Unit 2 of 11 · about 4 hours · derive, measure
RMSNorm, LayerNorm, logit scale and precision hotspots in softmax and normalization
Most numerical failures in a decoder sit in three places: the norm, the attention softmax and the output softmax. A variant that changes any of them changes where precision is lost, so you need to know each hotspot before you attribute a loss difference to the mechanism.
You'll be able to
- Derive RMSNorm from LayerNorm, state when they coincide exactly, and derive the RMSNorm Jacobian .
- Derive the z-loss gradient and explain why cross-entropy alone cannot control the logit offset that z-loss controls.
- Find the precision hotspots in a block (squares, exponentials, long accumulations) and measure each against a float64 reference at a stated dtype and shape.
- Reproduce attention-logit growth in a small model and show what QK-norm does to it.
Covers
Read
In this order, only the parts listed
0 of 4 done
- CS336 Spring 2026, Lecture 3 slidesCS336 2026 - Architectures and Attention Alternatives
Slides 14 to 19 (LayerNorm versus RMSNorm, why RMSNorm, dropping bias terms); slides 52 to 56 (stability: softmax hotspots, output z-loss, QK-norm, logit soft-capping)
Slide 15 asks whether 'RMSNorm is faster because it has fewer operations' makes sense and slide 16 answers with data movement. Treat that as a claim to test, not a result.
- CS336 Assignment 1 handoutCS336 2026 - Architectures and Attention Alternatives
Section 3.4.1 RMSNorm (pp. 19 to 20, the upcast to float32) and Section 3.4.4 softmax and masking (pp. 23 to 24)
- 2 OLMo 2 Furious (arXiv:2501.00656v3)OLMo 2 Open Model and Training Recipe
Section 3.3.1 (nonparametric LayerNorm to RMSNorm), Section 3.3.3 Z-Loss and Figure 8 (a fused and a plain implementation give the same forward value and different backward behavior), Table 1
Section 3.3.3 writes the z-loss term as while Table 1 lists the weight as . Take the coefficient from the training configuration you reproduce, not from either.
- Small-Scale Proxies for Large-Scale Transformer Training Instabilities (arXiv:2309.14322v2)Small-Scale Proxies for Large-Scale Transformer Training Instabilities (Wortsman et al., 2023)
Section 3.1 (3.1.1 attention logit growth and 3.1.2 output logit divergence), Figures 1 to 4
Stop before Section 3.2. The muParam, warmup and depth experiments belong to later units.
Focus on
- LayerNorm is RMSNorm applied to the mean-centered input. The two agree exactly when the feature mean is zero (same and gain, no bias). Add a constant to every feature and LayerNorm does not change, while RMSNorm rescales and keeps the offset. Dropping the mean removes one reduction and the bias parameter, and the claim that this makes the model faster is about memory traffic, not FLOPs.
- The Jacobian of a normalization is times a projection, so gradients through a norm scale like one over the input scale. That is the mechanism behind Xiong's Lemma 3 and behind the learning-rate sensitivity in Wortsman et al.
- Softmax is invariant to adding a constant to all logits, so cross-entropy is flat along that direction and nothing stops the offset from drifting. z-loss, with , adds a gradient times the softmax along it. QK-norm bounds the attention logits directly: after per-head RMSNorm with unit gains each query and key has norm , so before the gains.
- Name each hotspot with its failure. Squares in float16 overflow when , because exceeds the float16 maximum 65504. bfloat16 keeps the float32 range but has 8 bits of precision, so logits in are rounded to multiples of 0.5. Naive sequential accumulation stalls once the running sum reaches 256 in bfloat16. Library reductions and fused norm kernels accumulate in a wider type, so you must check your own code, not the library's.
Common mistakes · 3
- Testing a hotspot through the library function instead of your own code. In the check above
torch.nn.functional.rms_normis safe in float16, andtorch.ones(10000, dtype=torch.bfloat16).sum()gives 9984 (a rounded result of a wider accumulation), but a Python loop adding ones in bfloat16 stops at 256. The hand-written norm and reduction in your block are what can fail. - Claiming QK-norm 'fixes' attention logit growth without a baseline run at the same learning rate. Wortsman et al. show growth at high learning rates in small models and relate it to the quadratic dependence of logits on parameter norms; they call that a hypothesis. Run both variants at several learning rates.
- Trusting a fused z-loss kernel. OLMo 2 Figure 8 shows a fused implementation and a plain PyTorch one that agree in the forward pass and diverge in the backward pass, and the report suspects precision. Compare gradients, not only the loss value.
Try it yourself
Closed-book, before checking anything
x.pow(2).mean() gives inf and the normalized row is all zeros. After x.float() the entries are 0.2086 and 62.59. torch.nn.functional.rms_norm on the same float16 input returns finite values because the library upcasts.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.When do LayerNorm (no bias) and RMSNorm give the same output, and what happens to each when you add a constant to every feature?Answer
They agree when the input already has zero mean over the feature axis, with the same and gain. Adding a constant leaves LayerNorm unchanged, because it subtracts the mean. RMSNorm still divides by the new root mean square, so the constant remains in the output at a different scale.
2.Why can't cross-entropy alone stop all the logits from drifting upward together, and what does z-loss add?Answer
Cross-entropy depends only on logit differences, so adding to every logit leaves the loss and its gradient unchanged while rises by . The term is not shift-invariant and adds the gradient , which pulls toward 0.
3.After per-head RMSNorm with unit gains, what is the largest possible attention logit ?Answer
. Each normalized vector has root mean square 1, so norm , and Cauchy-Schwarz bounds the dot product by . Learned gains multiply the bound, so the observed maximum can exceed .
4.An activation vector in float16 has largest entry 200. Is a hand-written RMS computation safe? What if the entry is 260?Answer
At 200 the square is 40000, below the float16 maximum 65504, so the square is finite. At 260 the square is 67600, which overflows to
inf, and every output of that row becomes 0. The threshold is 256 because .5.Two runs differ only in whether QK-norm is on, and the QK-norm run reaches a lower loss at one learning rate. What else must hold before you credit QK-norm?Answer
Several seeds at that learning rate, a learning-rate sweep for both variants (the best learning rates may differ), and the same data order and token budget. A single run at one learning rate cannot separate the mechanism from learning-rate sensitivity.
Practice
- TensorTonic: RMSNorm Forward Pass
Free problem
cs336-l03-rmsnorm-forward, functionrmsnorm(x, g, epsilon)The three public cases check two rows with unit gain, a learned gain of
[2, 0.5], and an all-zero row. They do not test float16 or bfloat16 inputs or gradients. Add your own tests: a float16 row with an entry above 256, and a float64 reference. - CS336 Assignment 1:
rmsnormProblem (
rmsnorm), Section 3.4.1; implementrun_rmsnormintests/adapters.pyand passtest_rmsnormIf you passed this earlier, rerun it after adding the float16 test above.
- Attention-logit growth with and without QK-norm
Reproduce the idea of Figure 2 on a model of a few million parameters or fewer: track the maximum layer-0 attention logit during training at four learning rates, with and without QK-norm
Labeled example, not a target: 4-layer pre-norm decoder, width 128, 4 heads, FFN width 344, a byte-level text corpus, batch 16 by 128 tokens, AdamW with betas 0.9 and 0.95, no weight decay, 20 warmup steps, 400 steps, one seed, PyTorch 2.14.1 on CPU. The maximum layer-0 logit seen was about 45, 1,000, 14,000 and 360,000 at learning rates 0.003, 0.01, 0.03 and 0.1 without QK-norm, and about 10, 14, 19 and 29 with it; a rerun with the same seed moved the values without QK-norm by up to a quarter. Use three seeds on your own data and report the spread.
You're done when
You can derive the Jacobian and the z-loss gradient from a blank page, and you have a table of your own measurements: one row per hotspot, with dtype, shape and error against float64, plus the attention-logit curves with and without QK-norm.
Only when you can do this without notes.
Leads to
- Activation and gradient scale diagnostics, and shape, mask, position and dtype property testsTurn these measurements into dtype and scale tests on your decoder.
- Mixed precision, loss scaling, nonfinite handling and gradient-clipping placementSee how loss scaling, nonfinite handling and clipping interact with the hotspots found here.
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) 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.
- 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.
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.
- 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.
- 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. - 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.