Unit 10 of 11 · about 3 hours · implement
Weight transfer and differential tests between overlapping architecture variants
A variant you add to your decoder can be wrong in ways its own training loss will not show. When a variant contains the baseline as a special case, loading the same weights into both gives you an oracle that costs nothing to run and localizes the first mismatch.
You'll be able to
- List the parameter settings at which two architecture variants compute the same function, and load one set of weights into both to test it.
- Write exact differential tests for grouped-query against multi-head attention, a mixture of experts against a dense feed-forward network, latent against multi-head attention, and scaled against unscaled RoPE.
- Say which conversions are lossy, test what they must preserve instead, and set tolerances from the precision of the least precise operation in the path.
Covers
Read
In this order, only the parts listed
0 of 4 done
- GQA (arXiv:2305.13245v3)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)
Section 2.1 (checkpoint conversion by mean pooling), Section 2.2 (GQA-1 is MQA, GQA-H is MHA) and Figure 4 (mean pool, first head, random)
- Build a Large Language Model (From Scratch), companion bonus codeBuild a Large Language Model (From Scratch), Chapters 3 and 4
ch04/04_gqa/gpt_with_kv_mha.pyagainstgpt_with_kv_gqa.py, andch04/07_moe/gpt_with_kv_ffn.pyagainstgpt_with_kv_moe.py: diff each pair and list what changesThe pairs are written to compare memory, not to share weights. Writing the weight mapping is the exercise.
- DeepSeek-V2 (arXiv:2405.04434)DeepSeek-V2, Section 2.1 (Multi-head Latent Attention)
Section 2.1.1 and 2.1.2 (Equations 1 to 11) and Appendix C (full formulas of MLA), read for the mapping from multi-head weights to latent weights
- Roadmap-Final project: Decoder-Only Transformer StackDecoder-Only Transformer Stack
Architecture constraints (every component has an independent reference configuration) and Milestone C (match full and cached logits across MHA, GQA and MQA)
Focus on
- A special-case table is the unit of work. GQA with is MHA, and with is MQA. Copying each group's key and value weights to all its query heads turns GQA into an MHA that computes exactly the same function. An MoE whose experts are all copies of one dense feed-forward network equals it when the gate weights sum to 1 and nothing is dropped. MLA with a latent of width (no compression, no RoPE) equals MHA. RoPE scaling at equals the baseline. A gated scan with gate 1 equals causal linear attention.
- Load the same weights, not the same seed. Write one function per pair that maps the baseline state dictionary to the variant state dictionary, then compare logits and gradients. The first mismatch is usually a layout error:
repeatagainstrepeat_interleavegives the same shapes and a different function. - Test the lossy direction by what it must preserve. Mean pooling heads into groups changes the function, so do not assert equality with the original. Assert instead that the converted model equals an MHA whose heads inside each group are all set to the group mean.
- The tolerance belongs to the weakest link. A router that computes its softmax in float32 makes an otherwise float64 MoE-versus-dense test agree only to about 1e-8. Gates that you renormalize must sum to 1 to the precision of that softmax.
Common mistakes · 3
- Comparing two models built from the same seed instead of the same weights. Different module layouts consume random numbers in a different order, and the test fails or, worse, passes by luck of a symmetric initialization. Always build the variant by mapping the baseline's state dictionary.
- Demanding exactness where the variant is lossy or the gate does not sum to 1. Top-1 routing with a raw probability gate gives times the dense output by design, and mean-pooled heads are not the original heads. Write the expected relation, not the identity you wish held.
- Passing a shape check and calling the transfer done. Equal shapes hide wrong head order, wrong axis in the pooled mean and a missing scale. Compare logits and at least one gradient on inputs with nonzero positions and a causal mask.
Try it yourself
Closed-book, before checking anything
repeat in place of repeat_interleave, difference 2.32; MHA against mean-pooled GQA, 1.44 (not equal, as expected); NTK-aware base and position interpolation at , 0.0, with the YaRN temperature factor exactly 1; MHA against MLA with latent width and the up-projections set to the two halves of the identity, 0.0; the gated scan with gate 1 against causal linear attention, 1.8e-15. For the MoE with 6 identical experts and renormalized top-2 and top-3 gates, the difference to the dense network was 1.4e-8 and 1.9e-8, limited by the float32 router; with top-1 and the raw probability as gate, the output was the dense output times the selected probability (ratio 0.18 to 0.22).Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Which conversion between MHA and GQA is exact, and how do you build it?Answer
GQA to MHA. Copy each group's key and value projection rows to every query head in the group, in contiguous order, and keep the query and output projections. The MHA then computes the same attention as the GQA model. The other direction needs mean pooling plus training.
2.An MoE layer has 8 identical experts and top-2 routing with softmax over all experts followed by renormalization over the two selected. When does it equal the dense layer with the same weights?Answer
When no token is dropped, because then each token's output is the sum of two weights that add to 1 times the same dense output. With capacity pressure a dropped assignment removes part of the sum, and with unnormalized gates the output is the sum of the selected probabilities times the dense output.
3.What latent width makes MLA without RoPE reproduce an MHA layer, and what are the up-projections?Answer
, the full width of the keys and values together. The down-projection stacks the key and value projections of the MHA, and the key and value up-projections select the first and second half. Any narrower latent compresses and cannot reproduce arbitrary MHA weights.
4.Why is it wrong to test MHA against a mean-pooled GQA for equality, and what can you assert?Answer
Averaging heads changes the keys and values each query sees, so the function changes. Assert that the converted GQA equals an MHA whose heads in each group are replaced by the group mean, and that shapes, parameter counts and KV bytes are what the formulas say.
5.Your float64 MoE-versus-dense test agrees to 1e-8 and not 1e-14. Where do you look first?Answer
For operations inside the path that run in float32, such as a router computed in float32 for stability. The gate weights then sum to 1 only to about 1e-8. Either make the router dtype-aware for the test or set the tolerance to the router's precision.
Practice
- Differential tests for your chosen variant
Use the adapter pattern of
tests/adapters.py(run_multihead_self_attention_with_ropeandrun_transformer_lmload a weights dictionary into your module) as the template for the baseline-to-variant weight mapWrite the special-case tests for your variant from the list above, one seeded defect per test (
repeatforrepeat_interleave, a missing renormalization, the wrong pooling axis). Report the tolerance you used for each and why. The section mini-project builds on this: it asks for one tested variant on your decoder.
You're done when
For your variant you have a state-dictionary map from the baseline, an exact test in float64 at its special case, a stated expectation for the lossy case, and each test fails on its seeded defect.
Only when you can do this without notes.
Leads to
- Matched-parameter, matched-token and matched-compute comparisons and the decisive mechanism-risk experimentUse the tested variant in a matched-budget comparison.
- Complete language-model checkpoint state, atomic publication and corrupted-state handlingApply the same load-and-compare discipline to checkpoints.
Notes
Resources · 4 for this unit, 14 more in the 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. - 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.
- 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.
- 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.
Also in this 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.
- 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.
- 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. - 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.
- 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.