Unit 3 of 11 · about 4 hours · derive
Gated feed-forward width matching and parameter, activation and KV-memory accounting
Every later comparison in this section says 'at matched parameters'. A gated feed-forward network matches parameters and matmul FLOPs with its ungated baseline but not activation memory, and a rounded width does not even match parameters exactly. This unit gives you the accounting to state exactly what is matched.
You'll be able to
- Derive the gated feed-forward width that matches a two-matrix feed-forward network in parameters, and quantify what rounding the width does to the match.
- Derive per-block parameter counts, per-token KV bytes and saved-activation counts for a standard block and for one variant (SwiGLU, GQA), and say which of them a width match leaves unmatched.
- Count saved activations in your own block with autograd hooks and reconcile the count with the formula.
Covers
Read
In this order, only the parts listed
0 of 5 done
- GLU Variants Improve Transformer (arXiv:2002.05202v1)GLU Variants Improve Transformer (Shazeer, 2020)
Section 2 (Equations 4 to 6); Section 3.1 (hidden width 3072 reduced to 2048); Table 1 with its standard deviations at 65,536 steps
- CS336 Spring 2026, Lecture 3 slidesCS336 2026 - Architectures and Attention Alternatives
Slides 20 to 26 (activations and gated units), slides 36 to 41 (feed-forward to model-dimension ratio, the gated exception)
- CS336 Assignment 1 handoutCS336 2026 - Architectures and Attention Alternatives
Section 3.4.2 Position-Wise Feed-Forward Network, the SwiGLU definition (pp. 21 to 22) and Problem (
transformer_accounting) (pp. 27 to 28)You did parts (a) to (c) in LLM Foundations. Redo the arithmetic for a grouped-query, SwiGLU block instead of repeating them.
- 2 OLMo 2 Furious (arXiv:2501.00656v3)OLMo 2 Open Model and Training Recipe
Section 2.1, the SwiGLU bullet: hidden size about 8/3 of the model width, rounded up to a multiple of 128 (11,008 for the 7B model)
- Modern LLM Notebook, Appendix B: From Parameters to MemoryModern LLM Notebook, Appendix B: From Parameters to Memory
Section 1 (Parameters) and Section 2 (Activation Memory)
Section 2 lists the tensors a forward pass produces, not the tensors autograd saves, and omits two that a SwiGLU feed-forward network saves. Use it for the layout and recount with hooks. Stop before Section 3.
Focus on
- A gated feed-forward network has three matrices and an ungated one has two matrices, so equal parameters means and . Shazeer's Section 3.1 states the same match as 3072 to 2048 at : .
- Real configurations round the width. For the exact width is 10922.67 and OLMo 2 uses 11,008, so the gated block has 0.78% more parameters than a 4x ungated block. State the counted parameters of both variants in any comparison.
- Parameters and matmul FLOPs match; saved activations do not. For one token, an ungated GELU feed-forward network at width saves elements for backward (input, pre-activation, activation), while the gated one at width saves (input, two projections, the activated gate and the product).
- Shazeer's Table 1 reports means with standard deviations of 0.003 to 0.010 for four 65,536-step runs and single values at 524,288 steps. The 0.003 gap between GEGLU (1.633) and SwiGLU (1.636) at the longest run is smaller than that run-to-run spread. The setting is T5 span-filling with Adafactor and no dropout.
Common mistakes · 3
- Calling a width match a cost match. Equal parameters and equal matmul FLOPs leave saved activations and elementwise work different (about 1.3 times the saved elements here), and a recompute or fused-kernel policy changes the saved set again. Report which cost you matched.
- Recounting with the notebook's Section 2 recipe. It lists produced tensors, counts a feed-forward block as and rounds the gated block up to , after misstating its sum as (). Autograd also saves the activated gate and the gated product, and a count from hooks is the check.
- Reading the 8/3 rule as exact. Rounding the width to a multiple of 64, 128 or 256 changes the parameter count, and the 4x baseline in the A1 SiLU ablation matches the gated width only 'approximately'.
Try it yourself
Closed-book, before checking anything
torch.autograd.graph.saved_tensors_hooks, count unique saved non-weight tensors for at widths 384 (GELU) and 256 (SwiGLU), and match and elements per token (864 and 1120). The two modules both hold 73,728 parameters. Measured in PyTorch 2.14.1 eager mode, float32.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why is the matched gated width and not of something else?Answer
It is the same number: three matrices of must equal two matrices of , so . Equivalently the ungated width is reduced by a factor of 2/3.
2.A model with width 4096 uses a gated feed-forward width of 11,008. By how many parameters per layer does it differ from a 4x ungated network?Answer
against , so 1,048,576 more, about 0.78%.
3.A SwiGLU and a GELU feed-forward network have identical parameter counts. Which one saves more activations for backward, by how much, and why?Answer
SwiGLU, about 11.67d against 9d elements per token (1.3 times). It saves the shared input, both projections, the activated gate and their product, while GELU saves the input, the pre-activation and the activation.
4.Shazeer's Table 1 has GEGLU at 1.633 and SwiGLU at 1.636 after 524,288 steps. What can you conclude about their ranking?Answer
Nothing firm. The gap is 0.003, the 65,536-step runs have standard deviations of 0.004 and 0.010, and the longest runs are single values. The paper recommends SwiGLU on the whole table, not on that gap.
5.Per token and per layer, how many KV-cache bytes does a bfloat16 model with 8 KV heads of size 128 need, and what is the cache for one 8192-token sequence in a 32-layer model?Answer
bytes per token per layer. Over 32 layers and 8192 tokens that is bytes, exactly 1 GiB (1.07 GB).
Practice
- TensorTonic: Parameter-Matched SwiGLU Block
Free problem
cs336-l03-parameter-matched-swiglu, functionparameter_matched_swiglu(x, w_g, w_v, w_o, base_params)The three public cases check the selected width (a rounded , clamped to the weight pool), the parameter count and the output on small matrices. They do not check gradients or the activation memory. Add a test that counts saved tensors with hooks and compares it with your formula.
You're done when
You can state, for a block you choose, the parameter count, the per-token KV bytes and the saved-activation count of both the baseline and the variant, and your hook count agrees with the formula.
Only when you can do this without notes.
Leads to
- MHA, MQA and GQA trade-offs, and multi-head latent attentionApply the same accounting to the attention side: KV bytes for MHA, MQA, GQA and MLA.
- Matched-parameter, matched-token and matched-compute comparisons and the decisive mechanism-risk experimentUse the accounting to set up a matched-parameter comparison.
Notes
Resources · 4 for this unit, 14 more in the section
- CS336 2026 - Architectures and Attention AlternativesStanford University · primary
Study the Lecture 3 slides (
lecture_03.pdf, architectures and hyperparameters) and Lecture 4 slides (lecture_04.pdf, attention alternatives and mixture of experts) instanford-cs336/lectures, then implement the Assignment 1 Section 3.3 to 3.5 pieces (RMSNorm, SwiGLU, RoPE, causal attention, the pre-norm block) against its tests. Reconstruct every parameter and state equation before you change one mechanism. Keep GPUs, kernels and parallelism (Lectures 5 to 8) for their own tracks. - OLMo 2 Open Model and Training RecipeAllen Institute for AI · required
Read Section 2.1 (architecture), Section 3.2 (initialization) and Sections 3.3.1 to 3.3.3 (non-parametric norm to RMSNorm, reordered norm with QK-norm, z-loss) and Table 1, then find the same settings in a released configuration. The changes were adopted as a package, so the report cannot attribute stability to any single one.
- GLU Variants Improve Transformer (Shazeer, 2020)Google · support
Read Section 2 (the GLU family and SwiGLU) and Section 3.1 (hidden width cut from 3072 to 2048 so parameters match), then Table 1, where GEGLU edges out SwiGLU on the longest run. Check the matching arithmetic yourself.
- Modern LLM Notebook, Appendix B: From Parameters to MemoryWalking Labs · support
Appendix B Section 1 (parameters per block and per model, GQA and SwiGLU) and Section 2 (activation memory). Recount the activation tables with autograd hooks; the notebook lists produced tensors, not saved ones. Pin commit 979eecf.
Also in this section
- Build a Large Language Model (From Scratch), Chapters 3 and 4Sebastian Raschka / Manning · support
Use Chapter 3 (causal multi-head attention, pp. 50-91) and Chapter 4 (the GPT model, pp. 92-127) as the smallest runnable decoder, then the companion bonus folders
ch04/04_gqaandch04/07_moefor one bounded variant. The printed chapters use GPT-2 parts (LayerNorm, GELU, absolute positions); the modern pieces live only in the bonus folders. - On Layer Normalization in the Transformer Architecture (Xiong et al., 2020)Microsoft Research Asia · support
Read Figure 1 and Sections 3 and 4: why Post-LN gradients near the output are large at initialization and need warmup, and why Pre-LN does not. The analysis holds at initialization only and assumes uniform attention weights and Gaussian inputs there.
- GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (Ainslie et al., 2023) with Fast Transformer Decoding: One Write-Head is All You Need (Shazeer, 2019)Google Research · support
Read MQA Sections 2 and 3 (one shared key and value head to cut decoding memory traffic), then GQA Section 2 (grouped heads as the interpolation, mean-pooled uptraining with 5% of pretraining compute) and Table 1. Both report encoder-decoder results. MQA is at https://arxiv.org/abs/1911.02150.
- RoFormer: Enhanced Transformer with Rotary Position Embedding (Su et al., 2021)Zhuiyi Technology · required
Read Section 3: the rotation-matrix form of RoPE, why the attention score depends only on relative position, and the long-distance decay property. Base 10000 is the original choice; later models raise it.
- Extending Context Window of Large Language Models via Positional Interpolation (Chen et al., 2023) and YaRN (Peng et al., 2023)Meta AI; Nous Research · support
Read Position Interpolation Sections 2 and 3 (scale positions by the length ratio instead of extrapolating), then YaRN Section 3 (frequency-dependent interpolation and the attention temperature). Both still fine-tune. YaRN is at https://arxiv.org/abs/2309.00071.
- Small-Scale Proxies for Large-Scale Transformer Training Instabilities (Wortsman et al., 2023)Google DeepMind · support
Read Section 3.1: attention-logit growth and output-logit divergence reproduced in small models at high learning rates, and the QK-layernorm and z-loss fixes (Figures 1 to 4). It explains two of the OLMo 2 choices; transfer to a specific large run is argued, not proven.
- Modern LLM Notebook - Architecture FrontiersWalking Labs · support
Use
notebooks-en/part2-training/08-gpt2-to-modern-models.ipynb,11-mla-kv-cache.ipynband13-moe.ipynb, andnotebooks-en/part4-frontiers/27-long-context.ipynband30-efficient-attention.ipynb. Implement only the one variant selected for the checkpoint. - TensorTonic - Architecture and Attention AlternativesTensorTonic · support
Solve RMSNorm Forward Pass (
cs336-l03-rmsnorm-forward), Parameter-Matched SwiGLU Block (cs336-l03-parameter-matched-swiglu), Rotary Query and Key Embeddings (cs336-l03-rotary-query-key-embeddings), Causal Grouped-Query Attention (cs336-l03-causal-grouped-query-attention), Top-k MoE Router with Load Statistics (cs336-l04-topk-moe-router) and one ofcs336-l04-linear-attention-dualityorcs336-l04-mamba2-gated-state-scan. Add capacity and token-drop cases the router tests lack. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution. - Decoder-Only Transformer StackRoadmap-Final · support
Extend the already-tested decoder with the chosen mechanism. Preserve its slow oracle, causal and position tests, generation behavior and model arithmetic.
- Switch TransformersGoogle Research · depth
Use Equations 4 to 6 (the load-balancing loss), Figure 3 (capacity factors), Table 3 (smaller initialization for stability) and the Appendix F pseudocode as the deeper MoE reference. Reproduce only a tiny router experiment; full sparse pretraining belongs to later systems work.
- ST-MoE: Designing Stable and Transferable Sparse Expert Models (Zoph et al., 2022)Google · depth
Read Section 3 and Appendix B: the router z-loss in Equation 5, its coefficient 0.001 and the load-balance weight in Equation 6, and why update clipping stabilizes runs at a quality cost. Its setting is encoder-decoder T5.
- DeepSeek-V2, Section 2.1 (Multi-head Latent Attention)DeepSeek-AI · optional
Read Sections 2.1.1 to 2.1.4: low-rank joint key-value compression, decoupled RoPE and the cache comparison. The 93.3% cache reduction is against their own 67B model, not a portable ratio.
- Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (Dao and Gu, 2024)Princeton and CMU · optional
Read Section 1 and Sections 5 and 6, including Listing 1 (the
segsumreference), for a state-space alternative. Skip the full duality theory; compare against a linear-attention baseline in your own harness. - Deep Learning Tuning PlaybookGoogle Research · support
Read 'Identifying scientific, nuisance, and fixed hyperparameters' and 'Determining whether to adopt a training pipeline change or hyperparameter configuration' as the protocol for comparing architecture variants (per-arm learning rate, trial variance). Skip the batch-norm material. Last commit 2024; pin commit 7554a51.