Unit 9 of 11 · about 4 hours · implement, measure

Activation and gradient scale diagnostics, and shape, mask, position and dtype property tests

Every architecture variant in this section can fail silently: a flipped mask, a position offset that drifts in float32, a norm that upcasts and spoils a gradient check. The tests and scale logs are what let you say a measured difference comes from the mechanism and not from a bug.

You'll be able to

  • Log per-layer activation norms, gradient norms and maximum attention logits in a decoder without retaining graphs, and summarize them with OLMo 2's growth exponent.
  • Write a property-test battery for a decoder variant (shape, causal prefix, position offset, padding, batch independence, dtype and finite-difference gradients) and show that each test fails on a seeded defect.
  • Choose a test tolerance from the dtype and the position offset instead of one fixed constant.

Covers

Activation and gradient-scale diagnostics across layers and sequence lengthsShape, causal, position-offset, dtype and long-context property tests
1

Read

In this order, only the parts listed

0 of 5 done

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

    Section 3.2, the paragraphs Gradient and activation growth (the growth exponent, Figure 5), Hyperparameter transfer across width (Figure 6) and Spike score (page 14)

  2. 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)

    Figures 2 and 4 as instrumentation designs (maximum attention logit per layer, output logit mean); the Figure 9 caption and Section 3.3 on predicting attention logit growth from scale

    You read Section 3.1 for the mechanisms. Here read only what each figure logs and how often. Section 3.3 tested one prediction from the small models (a 4.8B model at learning rate 1e-2 diverged, as the fit predicted): one confirmed case, not a guarantee for your run.

  3. CS336 Assignment 1 handoutCS336 2026 - Architectures and Attention Alternatives

    Section 7.2.3 (debugging tips: overfit one minibatch, monitor activation, weight and gradient norms; p. 40) and the model tests in tests/test_model.py

  4. Roadmap-Final project: Decoder-Only Transformer StackDecoder-Only Transformer Stack

    Milestone A (future-token intervention), Milestone D (the defect-injection list) and Failure-injection requirements

  5. CS336 Spring 2026, Lecture 3 slidesCS336 2026 - Architectures and Attention Alternatives

    Slides 52 to 56 (what the stability tricks protect)

2

Focus on

  • Log from hooks on detached tensors, every few steps, and keep the numbers as Python floats. Per layer: the root mean square of the residual stream, the gradient norm of one weight per sublayer, and the maximum attention logit. Per run: the mean of over output logits. A hook that keeps a tensor with its graph leaks memory, and one that calls .item() every layer every step adds synchronizations.
  • OLMo 2 summarizes growth with , where and are the average activation (or gradient) vectors at the first and last layer. A constant per-layer gain gives , so ideal is 0. It averages over documents and positions, so also compute it at several sequence lengths and note that it hides a profile that rises then falls.
  • Choose the oracle per property. Prefix invariance is exact in the same shapes (0.0 in the example). Position-offset invariance is exact in real arithmetic but not in floating point, because the rotation angle is the product of the position and the frequency, so its error grows with the offset. Padding invariance needs an attention mask for left padding. Gradient checks need a float64 path with no hard-coded float32 inside.
  • A test that cannot fail proves nothing. For each property, seed one defect (flipped mask, ignored offset, angles in float32, wrong group mapping, norm over the wrong axis) and check the test goes red, then remove it. The A1 tests compare outputs with stored snapshots of the baseline model. They pin the baseline against regression and do not test causality or offsets directly.
Common mistakes · 3
  • One tolerance for every test. In float32 the position-offset error is under 1e-6 at offset 0 and 5e-4 at offset 100000, so a fixed 1e-5 either fails a correct model at long offsets or is too loose to catch a defect at short ones. Set the tolerance from the offset and the dtype, and compare against a float64 reference.
  • A float64 gradient check through a stack that upcasts internally. In one toy decoder, a norm and a softmax that cast to float32 gave relative errors of 0.07 to 1.0 on the same entries that gave 1e-9 after the casts were made dtype-aware. The check measured float32 noise, not the gradient. Promote to at least float32 (torch.promote_types), not to exactly float32.
  • Calling padding handled because right padding passes. A causal mask alone makes right padding harmless. Left padding changes which keys are visible, so it needs an attention mask as well as shifted position ids.
3

Try it yourself

Closed-book, before checking anything

On a tiny decoder (vocabulary 64, width 32, 2 layers, 4 query heads, 2 KV heads, FFN width 64, RoPE, RMSNorm, random weights), implement the battery and run it. Labeled example, not a target (PyTorch 2.14.1, CPU, four runs with unseeded inputs): changing the last 12 of 24 tokens left the first 12 logits identical (difference 0.0) in float32 and float64; flipping the mask made the same test fail with differences of 2.0 to 2.7. Shifting all positions by 0, 1000, 4096 and 100000 changed float64 logits by 0 and then about 1e-14, 3e-14 and 1e-12, and float32 logits differed from the float64 reference by under 1e-6, about 5e-6, 2e-5 and 5e-4. Computing the angles in float32 inside a float64 model reproduced the float32 error at offset 100000 (about 5e-4), and the offset test caught it. Random content in right padding changed nothing (0.0); left padding with correct position ids but no attention mask changed the real tokens' logits by 1.6 to 2.7. Float64 finite-difference checks on entries of a key projection (step 1e-6, central differences) gave relative errors between 1e-9 and 6e-8. Your values will differ; the pattern to reproduce is exact zero, error that grows with the offset in float32, and every seeded defect going red.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Per-layer activation norm grows by a factor of 1.05 each layer in a 48-layer model. What is the growth exponent and what is the ratio of last-layer to first-layer norm?Answer

    and the ratio is . A small positive exponent compounds into an order of magnitude over depth.

  2. 2.Why can't a RoPE position-offset test demand exact equality in float32 at offset 100000, and what is the spacing of float32 numbers near that angle?Answer

    The angle is position times frequency, about for the fastest pair, and float32 numbers in are spaced apart. The angle is rounded, so cosine and sine change by up to a few thousandths. The offset-0 and offset-100000 logits cannot be equal, only close.

  3. 3.A batch is left-padded and the position ids are shifted to start at 0 on the first real token. Real-token logits still differ from the unpadded run. Why?Answer

    The pad tokens are still valid keys for every later query, because the causal mask only hides the future. Without an attention mask that hides the pad keys, they change the attention weights. Right padding is safe because the pads come after every real token.

  4. 4.Name two properties that an MoE layer with dropped tokens will violate, and the settings under which they hold.Answer

    Batch independence and causal prefix invariance can fail, because a token's output depends on the other tokens that share expert capacity. Both hold when capacity is at least the token count, so nothing is dropped. A fixed causal dropping rule restores causal prefix invariance, but batch independence also needs capacity counted per sequence rather than across the batch.

  5. 5.You see a finite-difference relative error of 0.4 on a single weight entry. List two causes to rule out before you suspect the backward pass.Answer

    Float32 operations inside the forward path (noise larger than the step times the gradient), and a step size or an entry whose gradient is near zero. Also check dropout and other randomness, and weight aliasing from expanded or shared tensors.

5

Practice

  • CS336 Assignment 1 model tests as a baseline, then your own battery

    test_transformer_lm, test_transformer_lm_truncated_input, test_rope, test_multihead_self_attention_with_rope run through tests/adapters.py

    These compare outputs with stored snapshots at atol 1e-4 or 1e-5, so they guard the baseline path. Then write the battery above for your variant, with one seeded defect per test. The section mini-project covers this battery and the per-layer scale log on your variant.

You're done when

Every property test passes on your baseline and variant, each goes red on its seeded defect, and you have a per-layer scale table (stream norm, gradient norm, maximum attention logit, growth exponent) for two depths or two sequence lengths.

Only when you can do this without notes.

Leads to

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

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

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

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.

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

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