Unit 6 of 11 · about 5 hours · explain, implement

Sparse, linear, recurrent and state-space sequence mixers, and a bounded Mamba-2 style layer

Sub-quadratic mixers change the state the model carries, not just its cost. If you cannot say what the state can store, you cannot say what a hybrid gains or loses, and a speed claim hides the recall question.

You'll be able to

  • State, for softmax attention, sliding-window attention, linear attention, a gated state-space (Mamba-2 style) layer and a DeltaNet-style layer, the state size, the cost of training and of decoding one token, and what each cannot do.
  • Show that causal linear attention and a gated scalar state-space layer have identical parallel (masked-matrix) and recurrent forms, and implement a chunked version that matches the recurrence.
  • Explain why these mixers are different contracts, not drop-in replacements for attention, and what a fair hybrid comparison must hold fixed.

Covers

Sparse, linear, recurrent and state-space sequence mechanisms as distinct contractsA bounded Mamba-2 or gated state-space implementation
1

Read

In this order, only the parts listed

0 of 4 done

  1. CS336 Spring 2026, Lecture 4 slides (attention alternatives and mixtures of experts)CS336 2026 - Architectures and Attention Alternatives

    Slides 2 to 13: the local-plus-global toolkit, linear attention and its recurrent form, MiniMax M1, from linear attention to Mamba-2, Nemotron 3, gated DeltaNet, Qwen next, hybrid performance and sparse adaptation (DSA)

    Stop at slide 13; slide 14 starts mixture of experts. Slide 4 reorders without the causal mask, and slide 11 says there are few controlled ablations of hybrids.

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

    Slides 64 to 66 (sparse and sliding-window attention, interleaving full and local layers)

  3. Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (arXiv:2405.21060)Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (Dao and Gu, 2024)

    Section 1; Section 5.1 to 5.3 (scalar-identity SSMs, 1-semiseparable masked attention, the duality); Section 6 and Listing 1 (printed p. 21, the chunked SSD algorithm and segsum)

    Skip Sections 3 and 4 (the structured-matrix and kernel-attention theory) and everything after Section 7.1. Listing 1 uses rearrange from einops.

  4. Modern LLM Notebook: Efficient AttentionModern LLM Notebook - Architecture Frontiers

    Sections 2.1 to 2.9 (linear attention, its sharpness cost, SSMs, selective SSM, Mamba-2, Lightning Attention, hybrids)

    The code in 2.1 and in Homework 2 on vectorized linear attention is non-causal, and the 'fast' form in 2.1 reuses the quadratic normalizer. The Jamba row in 2.9 says '24 Mamba : 8 Attention' and 'one attention layer every 8 layers', which disagree.

2

Focus on

  • Write each mixer by its state. Softmax attention keeps the whole KV cache, which grows with length. Sliding-window attention keeps the last keys and values. Linear attention keeps , a matrix, and reads . A Mamba-2 style layer adds a scalar gate, . The DeltaNet rule can erase what a key already holds.
  • The duality is exact for the scalar-gate case. The recurrent form and the masked-matrix form with compute the same function, so you can train in the matrix or chunked form and decode with the recurrence. Section 5.1 states the result for a scalar times identity ; it is not a statement about every selective SSM.
  • A fixed state stores a bounded number of associations. With orthonormal keys the read returns each value exactly; a repeated key adds to the old value in linear attention (reading it returns the sum), while the DeltaNet rule overwrites it. Gates decide what is forgotten. Softmax attention can look up any earlier token, so recall is where hybrids keep a few full-attention layers.
  • The cost you quote must name the form. The reordering is valid without a causal mask. With the mask it becomes a scan, or chunks inside which you use the matrix form, as in Listing 1. FLOPs are linear in length for the scan, but the chunked algorithm is what makes it fast on matrix hardware.
Common mistakes · 3
  • Using the unmasked reordering for a decoder. For random with 6 tokens, and differ in every row but the last. Test the causal identity row by row, and test that changing a future token leaves earlier outputs unchanged.
  • Reading 'Transformers are SSMs' as 'any SSM equals attention'. The duality needs the scalar-gate structure, and the result says nothing about quality. A model with a fixed state compared with softmax attention at equal parameters can still fail recall tasks. Test with an associative-recall or copy task, not only loss.
  • Treating a hybrid's gain as an architecture result without controls. Slide 11 of Lecture 4 says there are few controlled ablations; a published hybrid changes layer ratio, depth, width and data together. Hold parameters, tokens and sequence length fixed and vary one thing.
3

Try it yourself

Closed-book, before checking anything

Closed-book, show that equals for , and extend it to the gated form with above. Then run the chunked algorithm of Listing 1 against a plain recurrence in float64 for , , 3 heads, head size 5, state size 4, log-gates with uniform in , chunk length 4. Outputs and final state should agree to about 1e-15 (1.8e-15 and 8.9e-16 in one run, PyTorch 2.14.1 on CPU), chunk lengths 4 and 8 should agree with each other, the masked-matrix form should agree with the recurrence, and splitting the sequence in two and passing the first final state as initial_states to the second call should reproduce the full run. Finally check the interference example: keys with values (the unit vectors of 3 dimensions). Reading gives in linear attention and under the DeltaNet rule with .
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Per head, what is the decoding state of softmax attention, sliding-window attention with window , and linear attention, and how does the per-token decoding cost scale in each?Answer

    Softmax attention: keys and values for all past tokens, cost per token. Sliding window: the last keys and values, . Linear attention: one matrix, , independent of .

  2. 2.For the gated recurrence , write the matrix with .Answer

    for and 0 otherwise. The product of gates is the 1-semiseparable mask , and in the paper's notation.

  3. 3.Why does the reordering of slide 4 not apply directly to a causal decoder?Answer

    The causal mask zeroes the entries above the diagonal of before multiplying by . The matrix sums over all positions, including future ones, so leaks the future. The causal version is a running sum, either a scan or a chunked algorithm.

  4. 4.A layer with state with has stored two associations with orthonormal keys. What does a third write with a new key do in linear attention and in the DeltaNet rule?Answer

    The new key lies in the span of the two existing ones, so its value adds into the same state entries. Reads of the old keys are perturbed in linear attention. The DeltaNet rule first removes what the new key already retrieves, which changes the old reads as well. A fixed state cannot keep more independent associations than its key dimension.

  5. 5.Name three things a hybrid-versus-attention comparison must hold fixed.Answer

    Parameters (or compute) counted from the actual models, training tokens and data order, and sequence length, plus the optimizer and learning-rate tuning budget for each arm. It also needs a recall-sensitive evaluation next to loss, and more than one seed.

5

Practice

  • TensorTonic: Parallel and Recurrent Linear Attention

    Free problem cs336-l04-linear-attention-duality, function linear_attention_duality(q, k, v)

    The three public cases check a scalar two-step sequence, orthogonal keys, and independent batches with unequal widths; the function returns both forms and the final state. There is no feature map or normalizer and no gate. They do not test the gated form. Extend your solution with a scalar gate and compare it with the Listing 1 oracle.

  • A bounded Mamba-2 style layer

    Listing 1 in Section 6; implement the chunked algorithm and a recurrent oracle, then wrap them in a layer with input projections to , , and a per-head gate

    Keep it small: no convolution and no gated normalization. Tests to write: chunk-length invariance, recurrence equality in float64, split-sequence equality with carried state, and future-token invariance. Optional: swap in your layer for half the attention layers of your decoder and compare under a matched contract.

You're done when

Your chunked scan matches the recurrence, the masked-matrix form and the split-sequence run in float64, and you can fill in a table of state size, training cost, decoding cost and recall behavior for five mixers.

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.

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

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

Also in this section

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

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

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

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

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