Unit 1 of 11 · about 4 hours · explain, derive

Residual streams, pre-normalization, initialization and residual scaling with depth

A variant that changes norms, depth or initialization is judged against a baseline whose stream scale already depends on depth. You need the scale argument before you can tell a real architectural effect from a scale effect.

You'll be able to

  • Explain why a pre-norm block leaves an unnormalized residual stream, and what that does to the stream scale and the last-layer gradient as depth grows.
  • Derive the variance of the stream after independent residual branches and the branch scaling that holds it constant.
  • Compare two initializations by measuring activation and gradient norm growth across layers, and say which claims the measurement cannot support.

Covers

Residual-stream semantics, pre-normalization and depth stabilityInitialization, residual scaling and signal propagation with depth
1

Read

In this order, only the parts listed

0 of 4 done

  1. CS336 Spring 2026, Lecture 3 slides (architectures and hyperparameters)CS336 2026 - Architectures and Attention Alternatives

    Slides 10 to 13: pre-versus-post norm, the data, the two explanations (gradient attenuation, gradient spikes) and the double-norm layouts

    Stop at slide 13. The rest of the deck belongs to later units. The lecture has no initialization content; that comes from the OLMo 2 report below.

  2. On Layer Normalization in the Transformer Architecture (arXiv:2002.04745v2)On Layer Normalization in the Transformer Architecture (Xiong et al., 2020)

    Figure 1; Section 3.3 (Lemma 2 and Theorem 1, with the setting they assume); Section 3.4 and Figure 3 (empirical check)

    Skip Section 4. It is translation and BERT with a warmup comparison, not decoder language models.

  3. 2 OLMo 2 Furious (arXiv:2501.00656v3)OLMo 2 Open Model and Training Recipe

    Table 1 (page 5); Section 3.2 Model Initialization, including the growth exponent and Figures 4 to 6; Section 3.3.2 Reordered norm and QK-norm, Figure 7

  4. CS336 Assignment 1 handout (Spring 2026 repository)CS336 2026 - Architectures and Attention Alternatives

    Section 3.3.1 Parameter Initialization (p. 17) and the opening of Section 3.4 (p. 19); then Section 7.3, Ablation 1 and the problem (pre_norm_ablation) (pp. 42 to 43)

2

Focus on

  • A pre-norm sublayer reads a normalized copy of the stream but writes into the unnormalized stream. The stream is the embedding plus every earlier branch output, so its scale can grow with depth. A post-norm model renormalizes after every addition. Xiong Lemma 2 states exactly this for their setting: the expected squared norm is flat in depth for Post-LN and grows linearly for Pre-LN.
  • Theorem 1 bounds one thing: the gradient of the last FFN layer. It is independent of for Post-LN and shrinks like for Pre-LN. Lemma 3 gives the mechanism: the Jacobian of a normalization scales like , and is what differs. Read the assumptions before you trust the picture: initialization only, uniform attention (query and key weights zero), one head, square weight matrices and Gaussian inputs.
  • Two ways to hold the stream scale: scale each residual output projection by (two branches per block), or keep a fixed small standard deviation and rely on normalization. OLMo 2 dropped a depth-dependent scheme for a flat standard deviation of 0.02 and reports growth exponents closer to 0 for activations and gradients. That is one report on its own models with its own measurement, and it compares against OLMo-0424's layer-index scheme, not against uniform .
  • OLMo 2 changed several things as a package (reordered norm, QK-norm, z-loss, initialization). Section 3.3.2 says reordered norm and QK-norm 'in isolation' do not give good results, so the report cannot attribute the gain to any one of them.
Common mistakes · 3
  • Reading Theorem 1 as a layer profile. It bounds the last layer only. In the same toy at with post-norm, the FFN down-projection gradient norm was 0.156 at the last block and 6.1 at the first, the opposite order to 'gradients are large near the output', while the last-layer value stayed between 0.14 and 0.16 for (0.151, 0.141, 0.156) as the theorem says. Pre-norm gave 0.108, 0.049 and 0.022 at the last block. Measure the whole profile in your own model.
  • Treating the OLMo 2 stability result as evidence for one component. Its Table 1 and Section 3.3.2 describe a package, and Equation 2 in Section 2.1 writes where Table 1 and the Section 3.3.2 table use the intermediate state . Follow the table.
  • Calling a flat curve of stream norm 'stable'. The stream scale at initialization says nothing about training, and the final norm hides a growing stream from the output head. Compare the stream scale at several points in training before you claim a depth effect.
3

Try it yourself

Closed-book, before checking anything

Closed-book, derive the mean square of the stream after residual branches whose outputs are independent, zero-mean and each of variance , on an input of variance : . Scaling each branch by gives for every . Then, on your own pre-norm decoder with random token IDs and no training, record the stream mean square after every block for , with and without scaling the attention output projection and FFN down projection by . Labeled example, not a target: with a toy decoder (width 128, 4 heads, FFN width 344, RMSNorm, normal initialization with variance , 4 sequences of 64 random tokens, mean of 3 seeds, PyTorch 2.14.1 on CPU) the final mean square was 2.38, 10.6 and 56.7 for unscaled, and 1.14, 1.15 and 1.15 scaled. Growth in the unscaled runs was faster than linear in (the increment per sublayer rose from 0.17 to 0.30 to 0.43), so the independence assumption does not hold exactly. Expect the scaled values to stay flat and the unscaled ones to grow.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why does a pre-norm model need a final norm before the output head?Answer

    The stream is unnormalized and its scale depends on depth and position in training. Without a final norm the logits would carry that scale. The final norm restores a fixed scale before the head.

  2. 2. branch outputs are independent, zero-mean, each of variance , and are added to a stream of variance 1. What is the variance after the additions, and after scaling each branch by ? What changes if the outputs are perfectly correlated?Answer

    , and after scaling. If the outputs are perfectly correlated, the sum has variance , so growth is quadratic in and scaling no longer holds the scale.

  3. 3.Why does Theorem 1 give a last-layer gradient that falls like one over the square root of depth for Pre-LN but is flat for Post-LN?Answer

    The Jacobian of the final normalization scales like . In Pre-LN the squared norm of the stream grows linearly with , so the gradient shrinks like . In Post-LN the input to the normalization has a depth-independent norm.

  4. 4.A colleague says the OLMo 2 report shows depth-scaled initialization is worse than a flat standard deviation. What does the report actually compare?Answer

    A flat standard deviation of 0.02 against OLMo-0424's scheme, which scaled output projections by a factor that depends on the layer index. It measured growth exponents and spike scores in its own setup, alongside other changes. It does not test uniform scaling by one over the square root of twice the layer count.

5

Practice

  • CS336 Assignment 1: pre_norm_ablation

    Section 7.3, problem (pre_norm_ablation) (p. 43). The handout asks for a post-norm variant of your own block and a learning curve against pre-norm

    The handout budgets 0.5 B200 hours and gives no tests. Substitute the handout's TinyStories setup (4 layers, 16 heads, width 512, FFN width 1344) at its low-resource 40,000,000-token budget, or a smaller model on your own decoder. Keep tokens, data order, warmup and learning rate identical, use three seeds, and also record the highest learning rate at which each variant still trains. Add the per-layer stream and gradient norm profile at initialization for two depths. The section mini-project reuses that profile.

You're done when

You can derive the stream variance with and without scaling, and your own per-layer stream and gradient norms at initialization, for two depths and both norm placements, either agree with Theorem 1's last-layer claim or contradict it for a reason you can state.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 15 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) in stanford-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.

  • 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.

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_gqa and ch04/07_moe for one bounded variant. The printed chapters use GPT-2 parts (LayerNorm, GELU, absolute positions); the modern pieces live only in the bonus folders.

  • 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.

  • 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.ipynb and 13-moe.ipynb, and notebooks-en/part4-frontiers/27-long-context.ipynb and 30-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 of cs336-l04-linear-attention-duality or cs336-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 segsum reference), for a state-space alternative. Skip the full duality theory; compare against a linear-attention baseline in your own harness.

  • 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.

  • 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.