Architecture and Numerics
Advanced architecture work matters only when the mechanism, numerics and comparison budget are controlled. This stage moves beyond assembling a standard decoder to reconstructing and testing one meaningful variant.
Section 2 of 11 · 11 units · about 46 hours
By the end you can Reconstruct one unfamiliar architecture mechanism from equations, add it to the tested decoder, pass shape, mask, position, precision and gradient checks, and attribute a measured difference under a fair parameter or compute contract.
Units
- Residual streams, pre-normalization, initialization and residual scaling with depth4h
- RMSNorm, LayerNorm, logit scale and precision hotspots in softmax and normalization4h
- Gated feed-forward width matching and parameter, activation and KV-memory accounting4h
- MHA, MQA and GQA trade-offs, and multi-head latent attention4h
- RoPE offsets, extrapolation failure, and position interpolation, NTK-aware scaling and YaRN5h
- Sparse, linear, recurrent and state-space sequence mixers, and a bounded Mamba-2 style layer5h
- Sparse MoE routing, expert capacity, dispatch and expert-parallel communication4h
- Load-balancing losses, router z-loss, dropped tokens and expert collapse4h
- Activation and gradient scale diagnostics, and shape, mask, position and dtype property tests4h
- Weight transfer and differential tests between overlapping architecture variants3h
- Matched-parameter, matched-token and matched-compute comparisons and the decisive mechanism-risk experiment5h
Build it
Mini project · about 16 to 22 hours
Decoder variant with numerical and mechanism controls
Extend lmlab with a tested decoder variant and a bounded architecture comparison. Establish numerical and weight-transfer correctness before training, then distinguish mechanism evidence from parameter, routing, context and tuning effects using your existing corpus on your GPU or a reduced CPU decoder.
- 1Extend
model/with your decoder from LLM Foundations and pass CS336 Assignment 1 model tests. Check frozen-batch objectives, norm and softmax gradients against float64 oracles; reconcile total/active parameters, FLOPs, saved activations and KV bytes with tensor inventories, hooks and analytical counts before training. - 2Choose a variant and reuse your weight maps and overlap tests: replicated GQA, uncompressed MLA, null RoPE scaling or gated-scan duality as applicable. Compare logits and gradients with the independent baseline or recurrence; retain lossy-conversion expectations and defect-catching regressions in
tests/. - 3Reuse your capacity-limited MoE layer independently of the chosen variant. Check dispatch and combine against a per-token loop, assignment conservation and dropped residuals; verify gate, balance and router z-loss gradients against hand algebra, retaining precision conventions and analytical communication payloads.
- 4Build the shape, causal-prefix, position-offset, padding, batch-independence, dtype and finite-difference battery; make every test reject a planted defect. Reuse initialization profiles across norm placements and depths; retain detached per-layer activation, gradient, attention-logit and growth summaries, with capacity-pressure exceptions tested separately.
- 5Freeze an architecture contract in
registry/: baseline, variant, null control and strongest simple alternative. Compare at matched tokens and declared parameter or compute budgets across paired seeds, retuning each arm equally; retain held-out records, resource counts, uncertainty and failed runs. - 6Run the bounded MoE balance, capacity and router z-loss campaign, changing controls separately at matched token and tuning budgets across paired seeds. Check language loss independently of auxiliary losses; retain per-layer loads, drops, entropy, logit scales and effects beside seed spread.
- 7Test the chosen mechanism's risk with a held-out recall, context-length or routing-pressure probe against the baseline. Retain adverse or unresolved regimes, fine-tuning status and alternative explanations; regenerate tables from raw records and reproduce a comparison from clean state before recommending an architecture.
What you hand in
- The
model/baseline and variant, reused MoE layer, property battery, weight maps and numerical oracles. - Count reconciliations, per-layer scale logs, MoE campaign and paired architecture comparisons with all attempts retained.
- Mechanism-risk evidence, clean reproduction transcript and a hardware-scoped architecture decision in
reports/.
How to check it
- Self-grade with the rubric below
- CS336 Assignment 1 model tests
Guard the baseline with model snapshots; add independent gradient, mask, position, transfer and dtype checks for the variant.
How it's graded
Numerical and transfer correctness
Pass: Your frozen-batch losses, gradients and transfer special cases match independent oracles before training. Tensor inventories reconcile parameter, operation, activation and KV counts; every property has a defect-catching regression.
Great: The first mismatching layer localizes a planted layout or precision fault, and the defense distinguishes lossy conversion from an implementation defect.
Routing evidence
Pass: Your loop and algebra oracles validate capacity, conservation, dropped residuals and auxiliary gradients. Paired campaigns retain per-layer load, entropy, drops and seed variation without assuming balance improves quality.
Great: A capacity-pressure counterexample explains a failed independence property, while the no-drop path still satisfies the exact equivalence contract.
Architecture attribution
Pass: Matched budgets, paired seeds, equal tuning, null and simple controls support a bounded claim. Raw evaluation, failed runs, mechanism-risk probes and clean reproduction remain linked to immutable run identities.
Great: An adverse or inconclusive regime changes the recommendation; an independent rerun reproduces the comparison and its strongest alternative explanation.
Resources
- CS336 2026 - Architectures and Attention AlternativesStanford University
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
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.
- RoFormer: Enhanced Transformer with Rotary Position Embedding (Su et al., 2021)Zhuiyi Technology
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.
- Build a Large Language Model (From Scratch), Chapters 3 and 4Sebastian Raschka / Manning
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
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
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
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.
- Extending Context Window of Large Language Models via Positional Interpolation (Chen et al., 2023) and YaRN (Peng et al., 2023)Meta AI; Nous Research
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
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
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
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
Extend the already-tested decoder with the chosen mechanism. Preserve its slow oracle, causal and position tests, generation behavior and model arithmetic.
- Modern LLM Notebook, Appendix B: From Parameters to MemoryWalking Labs
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
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.
- Switch TransformersGoogle Research
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
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
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
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.