Maps to: UC Berkeley EE 290/194 Scalable AI, Fall 2026 Lecture 4 (Sep 9, 2026), slides
lecture4.pdf(49 slides), Architectures to Break Bottlenecks: MoE, Latent KV, and Sparse (or Hybrid) Long-Context. Spring 2026 taught it as Lecture 3 (Jan 29, 2026). Recommended readings (course schedule): Hugging Face, Mixture of Experts Explained; W. Fedus, B. Zoph, N. Shazeer, Switch Transformers (2021); DeepSeek-AI, DeepSeek-V3 Technical Report (2024), for MoE and MLA at scale; B. Peng et al., YaRN: Efficient Context Window Extension of Large Language Models (2023). Other sources: DeepSeek-AI, DeepSeek-V2 (2024), where MLA was introduced; L. Wang et al., Auxiliary-Loss-Free Load Balancing Strategy for Mixture-of-Experts (2024); Kimi Team, Kimi K2 (2025); NVIDIA’s Nemotron-H and Nemotron 3 reports; DeepSeek-AI, DeepSeek-V3.2 (2025), for DeepSeek Sparse Attention; J. Yuan et al., Native Sparse Attention (2025); T. Dao and A. Gu, Transformers are SSMs (Mamba-2, 2024); J. Su et al., RoFormer (2021); S. Chen et al., Extending Context Window of Large Language Models via Positional Interpolation (2023). The model shapes come from the publishedconfig.jsonfiles of DeepSeek-V3, Kimi K2, Nemotron 3 Nano 30B-A3B and DeepSeek-V3.2, fetched 2026-10-31. Every number labelled measured comes fromcode/lecture04/on the author’s laptop; computed numbers come from the same code’s formulas. Code:code/lecture04/:arch_math.py(accounting),moe.pyandmla.py(PyTorch layers), and six demos. Reading time: ~2.5 hours for the prose; ~30 minutes for the demos.
0. How to read this lecture
0.1 Learning goals
From the slides. After this lecture you should be able to:
- Spot the right bottleneck: decide whether a workload is compute-limited or bandwidth/capacity-limited.
- Do the accounting for modern architectural knobs: estimate how MoE, MLA and sparse or hybrid designs change FLOPs and/or bytes moved.
- Explain the systems tax: routing and all-to-all for MoE, reconstruction compute for MLA, and cache and batching constraints for sparse attention.
- Choose interventions intentionally: match the constraint (FFN, KV or L²) to the architecture that directly changes the dominant term.
The slides add an important note, which this lecture also follows. The architectures covered are examples, not an exhaustive list, and nothing here needs memorizing. The goal is the tools to analyze future innovations, and to understand why labs make the choices they do.
0.2 Prerequisites and scope
- Prerequisites: Lectures 2–3: the roofline, arithmetic intensity (AI), the per-operator accounting of a decoder block, and the three headline bottlenecks (MLP compute, decode KV bandwidth, L² attention). Lecture 1’s KV-cache formula.
- Scope: one architectural answer to each bottleneck: mixture of experts, latent attention, sparse and hybrid long-context designs, plus the positional side of long context (RoPE scaling and YaRN). For each, what it changes in the roofline accounting and what it costs the systems stack.
- Not in scope today: how expert parallelism, context parallelism and the rest are implemented across GPUs (Lectures 5–6), MoE and attention kernels (Lecture 7), and training these models (Part II). The internals of state-space models are only sketched.
0.3 Section → code map
| Section | Idea | Code in code/lecture04/ |
|---|---|---|
| §2 | MoE: total vs activated parameters; real models; all-to-all; imbalance; decode weight traffic | arch_math.py, 01_moe_accounting.py |
| §2.6–2.7 | routing and load balancing in a trained MoE | moe.py, 02_moe_routing.py |
| §3 | KV sharing vs latent compression; MLA’s cache and decode intensity | 03_kv_compression.py |
| §3.5–3.6 | MLA’s equivalent computations, measured | mla.py, 04_mla_equivalence.py |
| §4 | sparse attention (DSA, NSA) on a task with known relevance | 05_sparse_attention.py |
| §4.6, §5 | hybrid stacks; attention FLOPs to 1M tokens; RoPE and YaRN | 06_hybrids_and_long_context.py |
0.4 Notation
As in Lectures 2–3: , , , , , , , , , , . New today:
| Symbol | Meaning |
|---|---|
| , , | routed experts, shared experts, routed experts activated per token (top-) |
| hidden width of one expert’s FFN | |
| , , | router score of expert for token , its combine weight (gate), the selected set () |
| , , | tokens dispatched to expert in a step; its routing bias; the bias controller’s step size |
| latent width of the routed payload in LatentMoE () | |
| , (written ) | MLA’s cached content-latent width and decoupled RoPE-key width |
| , | MLA’s cached latent and RoPE key for token |
| , | tokens (or blocks) selected per query in sparse attention; indexer heads |
| attention layers in a hybrid stack |
1. The framing: architectures change the terms inside the max
1.1 Three ways to change a roofline bound
For any workload, the first-order picture of Lectures 2–3 is
Lectures 2–3 asked which term binds and how kernels get close to it. This lecture changes the terms themselves, through the architecture:
- compute sparsity reduces FLOPs: do less math per token;
- state compression or sharing reduces bytes: move fewer bytes per token;
- long-context mechanisms reduce the effective term: avoid touching everything when is large.
The next lectures are about the parallelism interventions that change the same two quantities across GPUs. The main idea, in the slides’ words: modern large models are not just “bigger Transformers”. They are selective about where they spend compute and bandwidth.
1.2 Four meanings of “sparsity”
The word is overloaded, so the slides fix four meanings:
| kind | what is sparse | example | what changes |
|---|---|---|---|
| parameter sparsity | many parameters exist, but each token activates a small subset | MoE | FLOPs per token, communication |
| state compression / sharing | each token stores less (compression) or shares more across heads (sharing) | MLA; GQA/MQA | KV bytes, cache layout |
| computation sparsity | each query attends to a structured subset of past tokens or blocks | DSA, NSA | attention FLOPs, memory access pattern |
| architectural sparsity | not every layer is full attention; most are linear-time, constant-state sequence layers | hybrid stacks (Nemotron 3) | FLOPs and state across depth |
The taxonomy has a practical use. If you know which kind of sparsity a design uses, you can predict what will change (FLOPs, bytes, cache layouts or communication) before reading the paper’s benchmark table.
2. Mixture of experts: breaking the FFN bottleneck
2.1 Why the dense FFN is a bottleneck
A gated (SwiGLU) FFN maps to , with and . It has parameters and costs forward; with , that is and . Dense FFNs are efficient GEMMs (Lecture 2), but they couple capacity to per-token cost. Every parameter you add to make the model know more is multiplied, for every token, at training and at inference. Lecture 1 found the MLP holding 70–81% of a Llama 3 model’s parameters.
2.2 Decouple total capacity from activated compute
A mixture-of-experts (MoE, 混合专家) layer replaces the single FFN with many smaller expert FFNs of width :
- routed experts (路由专家), of which only the top- are active for any token;
- shared experts (共享专家), always active (optional but now common).
Per layer,
MoE adds a third axis to the scaling trade space: quality ≈ f(active compute, tokens, total capacity). The idea is old. Shazeer et al. (2017) put thousands of experts between LSTM layers; GShard (2020) and Switch Transformers (2021, top-1 routing) brought it to Transformers at scale. In 2024–26 it became the default for frontier open models.
2.3 The forward pass
One MoE layer in five steps:
- Router scores experts: a score for every expert and token .
- Top- selection: pick the set of experts with the highest scores.
- Dispatch: send each token’s activation to the GPUs that host its selected experts.
- Expert compute: each expert runs an ordinary gated FFN on the batch of tokens it received.
- Combine: the weighted sum of the selected experts’ outputs, plus the shared experts:
moe.py implements exactly these steps (step 3 is just indexing on one device).
2.4 Routing math
There are many router variants; two patterns cover most models.
- Classic softmax router: , , . The combine weights are proportional to over the selected set.
- Sigmoid-affinity router (DeepSeek-style): a learned expert embedding and . Each expert is scored independently, without competing in a softmax, and the gates are normalized only within the selected set: .
DeepSeek-V3’s config.json shows these choices: scoring_func: sigmoid, norm_topk_prob: true, a routed_scaling_factor of 2.5 on the routed sum, and group-limited routing (n_group: 8, topk_group: 4). The last restricts each token’s experts to 4 of 8 groups of experts, which bounds how many nodes one token’s all-to-all traffic can reach.
2.5 Pros and cons, if each expert lives on its own GPU
The slides pose this as a discussion question; here is an answer.
Benefits. Capacity grows without per-token FLOPs. A token touches only its experts, so per-token work is that of a much smaller dense model. Experts can specialize (§2.7). And each GPU stores only its own experts’ weights.
Downsides.
- Communication: every MoE layer needs an all-to-all to dispatch tokens and another to combine them (§2.8).
- Imbalance: a popular expert becomes a hot spot. Its GPU straggles, and everyone waits (§2.6).
- Memory: all experts must live somewhere, even though each token uses few. Total memory follows total parameters.
- Small per-expert batches: each expert sees only ~ tokens, which lowers its GEMMs’ arithmetic intensity (Lecture 2 §5.3).
- Decode: a batch touches many experts, so weight traffic grows with the batch (§2.9).
- Training stability and serving complexity both increase.
2.6 Load balancing is a throughput feature
If the router concentrates on a few experts, those experts become hot spots and their GPUs stragglers: the step time becomes “whoever is slowest”. With tokens sent to expert in batch , a rough utilization proxy is
If the maximum is much larger than the mean, you are paying for idle GPUs. In the slides’ words, in MoE imbalance is a throughput bug, and it affects quality too.
Demo 01 Part D simulates top-8 routing of 2,048 tokens over 256 experts (64 tokens per expert on average; computed):
| routing | utilization | dropped at capacity 1.0 | @ 1.25 | @ 2.0 |
|---|---|---|---|---|
| uniform (balanced in expectation) | 74.3% | 4.8% | 0.1% | 0.0% |
| skewed (popularity ∝ 1/√rank) | 13.3% | 22.7% | 16.9% | 8.7% |
Even perfectly uniform routing leaves the busiest expert with 1.35× the mean load, because random counts fluctuate. Each expert sees only ~64 tokens, and its maximum over 256 experts sits about three standard deviations above the mean. A skewed router is far worse.
Systems respond in two ways. The first is a capacity factor (容量因子): each expert processes at most tokens per step and the rest are dropped (they skip that expert). That caps the straggler but costs quality. The second is balancing mechanisms:
- Auxiliary balance loss (Switch Transformer): add to the loss, where is the fraction of assignments sent to expert and its mean router probability. It is minimized by uniform routing, but it competes with the language-modelling loss through the gradient.
- Routing-bias controller (DeepSeek-V3’s “auxiliary-loss-free” strategy, Wang et al. 2024): add an expert-specific bias to the scores for selection only, . After each step, if expert was overloaded and if it was underloaded. It is a feedback controller that pushes traffic away from hot experts without a large auxiliary-loss coefficient, and since the gates still use the unbiased scores, it does not distort the loss.
2.7 Routing in a trained MoE (demo 02)
Demo 02 trains small MoE layers (8 experts of width 32, top-2) on Cluster World: inputs from 16 Gaussian clusters with Zipf frequencies (30% down to 2%), where each cluster has its own linear map . The cluster of every sample is known, so we can measure specialization: the mutual information between the cluster and the chosen expert, normalized by the cluster entropy (maximum 0.88 with 8 experts). All results are measured, as the mean of 2 seeds:
| model | test MSE / Var(y) | utilization | busiest expert | dropped @ 1.25 | specialization |
|---|---|---|---|---|---|
| dense FFN, width 64 (= MoE activated) | 0.0262 | – | – | – | – |
| dense FFN, width 256 (= MoE total) | 0.0079 | – | – | – | – |
| MoE, softmax router, no balancing | 0.0035 | 61.9% | 20.2% | 4.6% | 0.77 |
| + aux loss 0.01 | 0.0035 | 63.2% | 19.8% | 5.2% | 0.77 |
| + aux loss 0.1 | 0.0037 | 71.8% | 17.4% | 2.1% | 0.78 |
| + bias controller | 0.0033 | 66.9% | 18.7% | 3.1% | 0.76 |
| MoE, sigmoid router, no balancing | 0.0042 | 46.8% | 26.9% | 15.3% | 0.70 |
| + bias controller | 0.0058 | 86.6% | 14.6% | 0.2% | 0.66 |
What survived the controls (the code README lists what did not):
- MoE wins big on this task, beating even the dense FFN with the same total width. The task is piecewise linear by cluster, which is exactly what conditional computation is made for. Real language is less clean; do not generalize the margin.
- No routing collapse happened without balancing. The busiest expert’s share (20–27% against a uniform 12.5%) mostly follows the data’s own Zipf skew, and no expert starved. The sigmoid router, whose experts do not compete in a softmax, is the more skewed of the two.
- Balancing works when it is strong enough. An aux loss at the common coefficient of 0.01 changed nothing; 0.1 raised utilization to 72% and halved the dropped tokens. The bias controller raised the sigmoid router from 47% to 87% utilization and cut its drops from 15% to 0.2%. It also oscillates (63–83% between checkpoints), as a fixed-step sign controller does.
- The quality cost of balance depends on how hard it pushes. For the softmax router every balanced variant stays within seed noise of the unbalanced one. Pushing the sigmoid router to 87% utilization raised the error from 0.0042 to 0.0058, well outside the seed range, and lowered specialization from 0.70 to 0.66. Forcing equal loads against skewed data trades quality for throughput, which is why production recipes tune it.
2.8 Case studies: DeepSeek-V3, Kimi K2, Nemotron 3 Nano
DeepSeek-V3 (, , , , ). One expert has M parameters, so one MoE layer holds B, while each token activates B (demo 01 Part A). A detail worth noticing: , exactly the width of the model’s own three dense FFN layers. So each token pays the same FFN compute as a dense layer, while the layer indexes 28.6× the capacity.
Whole models (demo 01 Part B; computed from config.json and checked against the checkpoints’ tensor totals):
| model | layers | experts | attention heads | total | activated / token |
|---|---|---|---|---|---|
| DeepSeek-V3 | 61 (3 dense) | 256 routed + 1 shared, top-8 | 128 (MLA) | 671.0 B (+ a 13.5 B MTP layer = 684,489,845,504, the checkpoint exactly) | 37.6 B (36.6 B without the input embedding; reported “37B”) |
| Kimi K2 | 61 (1 dense) | 384 routed + 1 shared, top-8 | 64 (MLA) | 1.03 T (within 3,416 of the checkpoint) | 32.9 B (31.7 B without the input embedding; reported “32B”) |
| Nemotron 3 Nano | 52 (23 Mamba-2, 23 MoE, 6 attention) | 128 routed + 1 shared (2× wide), top-6 | 32 (GQA, 2 KV heads) | 31.6 B (within 2,944) | 3.58 B; 3.23 B without the input embedding (reported “3.2B activated, 3.6B incl. embeddings”) |
Kimi K2 shows a common scaling move: keep the activated experts per token fixed () and increase the total (: 256 → 384). Total capacity grows by half, and the activated count even drops slightly, because K2 also halves the attention heads (128 → 64), cheaper at long context, and has only one dense layer. Nemotron 3 Nano shows MoE as a default efficiency tool even at small scale: 31.6 B total but only ~3.2 B activated, with , , 128 routed experts and 6 active. (The slides list ; the config has one shared expert of width .)
2.9 Expert parallelism: the routed payload
When experts live on different GPUs (expert parallelism (专家并行), Lecture 5), each MoE layer moves every token’s activation to its experts and back. The worst-case volume per layer is
Is that a lot? Compare it with the FLOPs it carries (demo 01 Part C, computed, H100):
| routed payload | bytes per token per layer | FFN FLOPs per byte sent | send over NVLink | send over a 400 Gb/s NIC | FFN compute |
|---|---|---|---|---|---|
| full width | 224 KiB | 3,456 | 510 ns | 4.59 µs | 801 ns |
| LatentMoE-style | 56 KiB | 13,824 | 127 ns | 1.15 µs | 801 ns |
An H100 does 2,199 FLOPs per byte its NVLink can move and 19,788 per byte one NIC can move. So inside a node, dispatch is roughly balanced with compute, while across nodes sending takes 5.7× longer than computing. The slides’ Nemotron 3 perspective follows: in practice MoE performance is often decided by movement as much as by GEMM efficiency. Small batches are weight-bandwidth-limited, and large batches can become communication-limited. LatentMoE routes and computes in a smaller latent dimension , so the payload becomes . Other answers are overlap, group-limited routing (§2.4) and topology-aware placement (Lecture 5).
2.10 The decode tax: a batch touches many experts
MoE saves FLOPs per token. Does it save bytes in decode? A decode step must read every expert that any token in the batch selected. With uniform routing, a batch of tokens touches on average
Demo 01 Part E (DeepSeek-V3, FP8 weights, computed):
| decode batch | experts touched (of 256) | MoE weight bytes per step | vs a dense FFN of the activated size |
|---|---|---|---|
| 1 | 8.0 | 396 MB | 1.0× |
| 8 | 57.4 | 2.57 GB | 6.5× |
| 64 | 222.4 | 9.84 GB | 24.8× |
| 1,024 | 256.0 | 11.3 GB | 28.6× |
At batch 1 a token reads only its 9 experts, the same bytes as a dense layer of the activated size. At batch 64 the step reads almost every expert. MoE saves FLOPs; in decode, its weight traffic grows with the batch until nearly every expert is read every step. That is why MoE serving spreads experts across many GPUs (each reads only its own) and runs large batches.
3. Latent attention: breaking the KV bottleneck
3.1 Two knobs that look similar but behave differently
At long context, decode is dominated by bytes of KV read per generated token (Lecture 2 §8). There are two clean ways to shrink them:
- Head-space sharing (GQA/MQA): store fewer KV heads, .
- Latent-space caching (MLA, 多头潜在注意力): store a different representation, a small latent per token, and reconstruct head-space tensors on demand.
GQA and MQA store the same kind of cache, just fewer heads; MLA stores something else. The slides’ cheat-sheet:
| mechanism | what is shared or compressed | decode-time KV bytes |
|---|---|---|
| MHA | nothing; each query head has its own KV head () | |
| GQA | query heads in groups share KV () | |
| MQA | one KV head () | |
| MLA | a latent content vector plus a small RoPE part |
GQA/MQA buy a factor (sharing); MLA buys an absolute shrink of the state per token (compression).
3.2 GQA/MQA, revisited: sharing sets decode intensity
Everything about the queries stays the same, , while , so KV bytes and decode bandwidth drop roughly linearly with . GQA/MQA optimize state and bandwidth; the attention outputs are still produced for all query heads, so they do not eliminate attention compute.
A consequence worth computing: in decode, every cached byte is used by query heads, so the attention core’s intensity is . Demo 03 Part B (computed, one layer, one sequence at 32k context):
| attention | FLOPs per byte of cache read | of the H100 knee |
|---|---|---|
| MHA | 1.0 | 0.3% |
| Llama-3-8B GQA (32 / 8) | 4.0 | 1.4% |
| Llama-3-70B GQA (64 / 8) | 8.0 | 2.7% |
| MQA (64 / 1) | 64 | 22% |
| DeepSeek-V3 MLA, absorbed (128 heads, one latent) | 243 | 82% |
The last row is §3.5’s surprise: MLA not only caches fewer bytes, it also uses each byte far more.
3.3 MLA: what is cached, and how K and V come back
For a token state , MLA computes and caches
and reconstructs each head’s content key and value, then appends the shared RoPE key:
The cache costs . DeepSeek-V3 uses and (kv_lora_rank, qk_rope_head_dim), 128 heads with 128-dim content keys and values, and also compresses its queries through a 1,536-dim latent (q_lora_rank).
Why the separate RoPE part? Rotary embeddings rotate keys by a matrix that depends on the key’s position. If the position were applied to , the rotation would sit between and , and the absorption trick of §3.5 would break. So position goes into a small, separately cached key shared by all heads: “decoupled RoPE”.
A subtle but important point. MLA intentionally decouples its internal dimensions. Standard attention often assumes ; if you blindly substitute that into MLA’s cache math, you get nonsense. MLA chooses , and the query latent separately, to trade off cache bytes per token, reconstruction compute and model quality.
3.4 Concrete KV math at L = 128k
The slides’ back-of-envelope uses a representative backbone (, , ). Standard MHA in BF16 would need 208 GiB per sequence. MLA with needs 8.4 GiB.
Demo 03 Part A widens the comparison (computed, BF16, per token and per 131,072-token sequence):
| model / attention | KV per token | per 128k sequence |
|---|---|---|
| Llama-3-8B, GQA-8, 32 layers | 128 KiB | 16.0 GiB |
| Llama-3-70B, GQA-8, 80 layers | 320 KiB | 40.0 GiB |
| DeepSeek-V3 if plain MHA (128 heads, K 192 + V 128 per head) | 4.77 MiB | 610 GiB |
| slides’ MHA yardstick | 1.67 MiB | 214 GiB |
| DeepSeek-V3, MLA | 68.6 KiB | 8.58 GiB |
| Nemotron 3 Nano (6 attention layers, 2 KV heads) | 6.00 KiB | 815 MiB (incl. 46.8 MiB of fixed Mamba state) |
DeepSeek-V3’s MLA cache is 71× smaller than the same model with plain MHA, and even 1.9× smaller than Llama-3-8B’s GQA cache, for a model 84× larger. In a 100 GB KV budget at 128k tokens, Llama-3-70B fits 2 sequences (4 with an FP8 cache), DeepSeek-V3 fits 10, and Nemotron 3 Nano 117 (demo 03 Part D). Sharing, quantization, compression and hybrid depth multiply.
3.5 The trade: reconstruction compute vs bytes saved, and absorption
MLA introduces extra compute: down-projecting to latents (in prefill and every generated token) and up-projecting latents to head-space inside attention. The slides frame it as the same move as FlashAttention, applied to decode state rather than to the score matrix: spend a little more compute, move a lot fewer bytes. Decode is bandwidth-bound, so cutting KV bytes by an order of magnitude can reduce latency more than the extra GEMMs increase it.
But “a little more compute” needs care. Rebuilding and for every cached token at every decode step is not a little: it costs FLOPs per cached token. For DeepSeek-V3 that is 33.6 MFLOP per cached token per layer per step, 120× the attention itself (demo 03 Part C). At 32k context, a naive decode step would take ≥ 1.11 ms per layer against ≥ 11.3 µs. The fix is weight absorption (权重吸收). Because ,
So fold into the query and into the output, and every head scores directly against the cached latents. No key or value is ever rebuilt. All 128 heads now read the same and , an MQA-like sharing pattern. That is why absorbed MLA decode reaches ~243 FLOPs per byte, 82% of the H100 knee, where GQA sits at 4–8: MLA saves bytes and raises intensity.
3.6 Measured: one cache, two computations, opposite trade-offs (demo 04)
mla.py implements a scaled-down MLA (, 16 heads, , , ) with four computations: prefill and decode, each naive (reconstruct) and absorbed. All measured:
- They agree. Naive decode = absorbed decode = the last row of prefill, to (fp32); naive and absorbed prefill agree to . The cache holds 160 numbers per token per layer instead of MHA’s 2,560 (16× smaller) and loses nothing: keys and values are a fixed linear function of the latent.
- Decode: absorb. The FLOP counter shows the naive path costing 16.7× (at ) to 55× (at ) the absorbed one. At the naive step takes 7.1 ms on the laptop and the absorbed one 0.89 ms (8× faster).
- Prefill: reconstruct. In a full prefill the per-query cost of absorbing (folding into each query, into each output) equals the per-key cost of reconstruction. Only the (query, key) pairs differ, and those are dearer in the latent space ( vs FLOPs per head). Measured, absorbed/naive grows from 1.02× at to 1.51× at , toward the closed-form limit 1.80×; for DeepSeek-V3’s dimensions the limit is 3.4×.
The rule: absorb in decode, reconstruct in prefill. A step that brings more than ~ new queries against a long cache (~171 for DeepSeek-V3) is already prefill-like; chunked prefill and speculative decoding live near that line. The slides’ “engineering reality” applies too. The win depends on kernel support (DeepSeek released dedicated MLA decode kernels), on cache formats, and on whether reconstruction can be fused or overlapped.
4. Sparse attention and hybrid stacks: breaking the L² wall
4.1 Why FlashAttention is necessary but not sufficient
FlashAttention-style kernels are IO-aware and avoid materializing the matrix in HBM (Lecture 2 §7.2; Lecture 7). That is essential, but it does not remove the quadratic dependence: the score matmul alone costs FLOPs. At –, that term dominates even with excellent kernels. Demo 06 computes one query’s attention cost at 1M tokens: 292 GFLOP per layer, for DeepSeek-V3.2-style attention. Something has to change, and the slides list three broad strategies:
- exact attention, better kernels: improve constants and IO, but stay ;
- sparse attention within a layer: compute attention on a structured subset (DSA, NSA);
- hybrid stacks across depth: linear-time, constant-state layers in most blocks, and only a few attention layers for global routing.
A useful mental model is to ask what set of past tokens a query can read: a recent window, the top- tokens or blocks chosen by relevance, compressed summaries of the past, or a constant-size state that summarizes everything.
4.2 DSA: retrieval inside attention
DeepSeek Sparse Attention (DSA), introduced with DeepSeek-V3.2, scores past tokens cheaply, then attends only to a small selected set. Its lightning indexer (闪电索引器) has small heads. For query token it computes a query-dependent head-gating vector
a non-negative match score per index head, , and their mixture
depends only on the query token and gates which cheap index heads matter for it. Then , and full attention runs only on the selected entries. It is a two-stage pipeline: (1) score all past tokens cheaply, (2) pay full attention for only of them. DeepSeek-V3.2’s config: index_n_heads: 64, index_head_dim: 128, index_topk: 2048, and the indexer runs in FP8.
What it changes in the L² term. The score matmul goes from to , linear in for fixed . The indexer is still quadratic, but very cheap per pair. With DeepSeek-V3.2’s shapes, one indexer pair costs 16.4 kFLOP and one absorbed-MLA attention pair 279 kFLOP: 17× less, and in FP8. Demo 06 Part B:
| context | full | DSA top-2048 (indexer share) | NSA | window 4096 |
|---|---|---|---|---|
| 4,096 | 1.14 GFLOP | 638 MFLOP (11%) | 499 MFLOP | 1.14 GFLOP |
| 131,072 | 36.5 GFLOP | 2.72 GFLOP (79%) | 2.71 GFLOP | 1.14 GFLOP |
| 1,048,576 | 292 GFLOP | 17.8 GFLOP (97%) | 18.7 GFLOP | 1.14 GFLOP |
By FLOPs alone DSA wins from about 2,200 tokens of context (exercise 7). At 1M tokens the indexer is 97% of its cost: a cheap scan per query has replaced an expensive one.
What it costs the systems stack (from the slides): an additional cached key buffer for the indexer, separate from the main KV/MLA cache; top- selection kernels and irregular memory access; batching complications, since prefill and decode have different indexer behaviour; and different cache formats and quantization for the different buffers.
Why DSA runs in an MQA-friendly way. Sparse attention reduces compute only if it also plays nicely with KV sharing and cache layouts. If different query heads (or different heads within a GQA group) select different tokens, the system must fetch the union of their selections. That can keep the math savings but erase the intended KV-traffic savings. The common implementation therefore runs DSA in an MQA-like mode, where each selected entry is shared by many queries, so “fetch once, use many times” still holds.
4.3 NSA: hierarchical sparse attention
Native Sparse Attention (NSA) starts from a failure mode of simple sparsity: dropping either global context or local detail. Its fix is hierarchical structure. For each query, attention runs along three paths:
- a sliding window for recent local context;
- token selection of important blocks, fine-grained;
- token compression into coarse block summaries, for global context.
A learned gating mechanism combines the three. The paper’s configuration, used in demo 06: a 512-token window, 16 selected blocks of 64 tokens, and one compressed token per 16 positions. Its attraction is a structured way to keep both “what just happened” and “what matters globally” without paying full .
4.4 Sparse attention on a task with known relevance (demo 05)
Theory says sparse attention is safe when relevance is sparse and the selector finds it. Demo 05 tests both on Needle World: 8,192 tokens, one shared K/V head and 8 query heads (DSA’s MQA mode). Each query’s heads point at 3 of 8 far-away “needle” tokens and at the 2 previous tokens. Full attention puts 54% of its mass on the 8 needles and 36% on the 2 previous tokens: sparse, and only partly local. Measured (mass kept = full attention’s probability on the selected tokens; output error = relative distance from the full-attention output):
| pattern | keys per query | mass kept | output error | FLOPs vs full |
|---|---|---|---|---|
| sliding window, w = 512 | 512 | 37.6% | 1.10 | 6% |
| sliding window, w = 2048 | 2,048 | 49.7% | 0.89 | 25% |
| NSA-style stand-in: window 512 + 16 blocks chosen by mean key | 1,473 | 52.3% | 0.86 | 18% |
| DSA-style stand-in indexer, top-2048 | 2,048 | 93.2% | 0.21 | 31% |
| oracle top-2048 (true scores) | 2,048 | 98.7% | 0.01 | 25% |
Four lessons:
- Windows cannot see far needles. They capture the local part and miss the rest, however wide they are.
- Token-level selection recovers far information. The DSA-style indexer keeps 93% of the mass at 31% of the FLOPs. It is a training-free stand-in: random low-dimensional projections of the queries and keys in place of DSA’s trained indexer.
- Recall is the risk. The same stand-in at keeps 67% (oracle 92%); at 1,024 it keeps 89%. If the indexer misses a needle, no later computation in that layer can recover it, which is the slides’ “recall risk”.
- Selecting blocks by their mean key fails here. Averaging 64 keys dilutes a single needle 64-fold in its block’s score, so the NSA-style stand-in keeps barely more than a window. Real NSA learns its compression and gates end to end; the untrained stand-in shows why that matters, not how well NSA works.
The union problem, measured (demo 05 Part C). If each head picks its own top-256 by true scores, the heads disagree enough that a query must read 1,022 distinct KV entries (4.0× k), for an output error of 0.048. One shared selection of 256 reads 256 entries, at an error of 0.065. At equal bytes, sharing wins: a shared top-1024 reads 1,024 entries for an error of 0.029. Select once per token, share across heads.
4.5 Hybrid stacks: pay the attention tax only a few times
Hybrid stacks (混合层堆叠) interleave attention with linear-time, constant-state sequence layers, such as state-space models of the Mamba family. A state-space model (状态空间模型) layer carries a fixed-size recurrent state through the sequence and updates it with each token, through input-dependent (“selective”) transitions in Mamba. Its cost per token does not grow with context, and its memory per sequence is constant. Mamba-2 (Dao & Gu 2024) also showed how to compute such layers with matmul-friendly chunked algorithms. What they give up is exact, random-access recall of arbitrary past tokens, so hybrids keep a few attention layers for global routing.
Nemotron 3 Nano is the slides’ example. Its config.json lists a 52-character hybrid_override_pattern: 23 Mamba-2 layers, 23 MoE FFN layers and only 6 attention layers. Two direct wins follow. In compute, most layers are rather than . In state, a KV cache exists only for the 6 attention layers. Demo 06 Part A (computed):
| context | Nemotron 3 Nano per sequence | of which fixed Mamba state | Llama-3-8B per sequence |
|---|---|---|---|
| 4,096 | 70.8 MiB | 66% | 512 MiB |
| 131,072 | 815 MiB | 5.7% | 16.0 GiB |
| 1,048,576 | 6.05 GiB | 0.8% | 128 GiB |
On one H100, Nemotron 3 Nano fits 10 sequences of 128k tokens next to its weights; Llama-3-8B fits 3, though Nemotron’s weights are 3.9× larger. The serving implication from the slides: a mixed state, a KV cache for the attention layers and an SSM state for the sequence layers, often with different kernel and quantization sensitivities. Averaged over depth, a 6-of-52 hybrid pays 11.5% of full attention’s cost at every context. Its attention layers are no cheaper; there are just fewer of them. The two ideas compose: sparse attention inside the few attention layers.
4.6 How to choose: DSA vs NSA vs hybrid stacks
| DSA | NSA | hybrid stacks | |
|---|---|---|---|
| mechanism | index → top- | window + select + compress, with gating | a few attention layers + many layers |
| use when | relevance is very sparse (a few far tokens matter); you want retrieval-like access at long | you need both local detail and global context; relevance is not extremely sparse | attention is too expensive across depth, not just within one layer; you can change the backbone and retrain |
| watch out for | recall risk (if top-k misses, the signal is lost); a serving tax (fast top-k, gathers, irregular reads) | tuning risk (too much compression blurs, too little is slow); more moving parts | global mixing risk (too few attention layers route information poorly); a mixed runtime (KV state + SSM state) |
| key knobs | , block size, kernels; group-consistent selection under GQA/MQA | window , selection budget, compression rate, gating stability | and placement; often GQA/MLA inside the kept attention layers |
5. The position side of long context: RoPE, interpolation and YaRN
Long context has a second problem besides cost: positions the model never saw. This part follows the course’s recommended YaRN reading.
5.1 RoPE in one paragraph
Rotary position embedding (Su et al. 2021) splits each query and key into pairs. It rotates pair of a vector at position by the angle , with frequencies . A rotated query at position dotted with a rotated key at position then depends only on . Demo 06 checks this numerically: at a fixed offset of 7, the dot product is 0.375901 at positions 7, 1,000 and 100,000. Each pair has a wavelength , the number of positions per full turn. For DeepSeek-V3’s 64-dim RoPE key with base 10,000, wavelengths run from 6 positions to about 47,000.
5.2 Why a model fails beyond its training length
During training on 4,096-token sequences, the high-frequency pairs (short wavelengths) turned many times. Every angle they can produce was seen, and they encode local order. The low-frequency pairs never completed even one turn, so beyond 4,096 tokens they produce angles the model has never seen, and attention degrades. Two simple fixes have opposite flaws:
- Position interpolation (PI) (Chen et al. 2023): divide every frequency by the extension factor , squeezing the long context into the trained range. Now even the high-frequency pairs rotate times slower, which blurs the local order they encoded.
- “NTK-aware” scaling (a 2023 community proposal): raise the base, . The lowest frequency then slows by the full factor and the highest is almost unchanged, with a smooth geometric transition in between.
5.3 YaRN: interpolate by parts
YaRN (Peng et al. 2023) makes the choice per frequency. With the original training length , compute how many turns each pair made during training, . Then:
- (many turns; local order): keep the frequency unchanged;
- (less than a turn; never saw the range): interpolate by the full factor ;
- in between: a linear ramp.
It also scales the attention logits by , because interpolation makes attention distributions flatter. DeepSeek-V3’s config uses exactly this: rope_scaling: {type: yarn, factor: 40, original_max_position_embeddings: 4096, beta_fast: 32, beta_slow: 1}. That gives = its max_position_embeddings. Demo 06 Part C (computed):
| pair | wavelength | turns in 4,096 tokens | PI divisor | NTK-aware divisor | YaRN divisor |
|---|---|---|---|---|---|
| 0 | 6 | 652 | 40 | 1.00 | 1.00 |
| 8 | 63 | 65 | 40 | 2.59 | 1.00 |
| 16 | 628 | 6.5 | 40 | 6.71 | 5.04 |
| 20 | 1,987 | 2.1 | 40 | 10.8 | 17.1 |
| 24 | 6,283 | 0.65 | 40 | 17.4 | 40 |
| 31 | 47,117 | 0.09 | 40 | 40 | 40 |
The 11 highest-frequency pairs (wavelength below 4096/32 = 128 tokens) are kept exactly, the 9 lowest-frequency pairs are interpolated by 40, and the rest are ramped. The logit scale is . Other recipes change the base instead: Llama 3 trains with a RoPE base of 500,000 to support long contexts. Every recipe is followed by continued training on long documents. Scaling positions makes long context possible; it does not by itself teach the model to use it.
6. Putting it together
6.1 One modern stack: the DeepSeek-V3 family
A useful way to read recent long-context models: each mechanism targets a different dominant term.
- MoE for the FFN bottleneck: routed capacity grows while activated compute stays bounded (256 routed experts, top-8).
- MLA for the KV bottleneck: cache a 576-number latent per token per layer (, ), reconstruct or absorb on demand.
- Sparse attention as a long-context add-on: DeepSeek-V3.2 adds the lightning indexer and top-2048 selection through continued training, to avoid paying full at extreme context.
Why this composition makes sense: you want to be selective along three axes at once, namely which FFN parameters, what decode state, and which past tokens.
6.2 One bottleneck, one knob
| pressure point | what you should change | typical architecture knobs |
|---|---|---|
| FFN compute and parameters | reduce activated FFN compute per token while increasing total capacity | MoE (top-), shared experts; LatentMoE (shrink the routed payload ) |
| KV cache / decode bandwidth | reduce the KV bytes streamed per generated token | GQA/MQA (); MLA (); hybrids (); KV quantization () |
| long-context | reduce how many keys each query touches, or reduce the number of attention layers | DSA/NSA (); hybrids (few attention layers, mostly layers) |
The common theme: all three are selectivity tricks. Select experts, select state dimensions, select tokens or layers.
6.3 The systems stack must support them
These architectures are fast only if the systems stack supports them:
- MoE: high-bandwidth all-to-all (expert parallelism), robust load balancing, good topology mapping. LatentMoE reduces the routed payload, easing expert-parallel bandwidth and latency.
- MLA: kernel support for latent cache formats and absorption/reconstruction; quantization that preserves quality.
- Sparse attention: fast top- selection kernels; cache layouts that work with continuous batching.
- Hybrids: runtime support for mixed state (KV + SSM), heterogeneous kernels and quantization.
The next lecture formalizes parallelism strategies (data, expert, sharded-state, tensor, pipeline, context) and how these architectures change the communication patterns.
7. Summary
- Architectures change the dominant term. MoE targets the FFN’s coupling of capacity and compute, MLA targets KV bytes, and sparse attention and hybrids target .
- MoE: total , activated . DeepSeek-V3 indexes 28.6× its dense FFN’s capacity at the same per-token FFN compute; 671 B total, ~37 B activated.
- MoE’s taxes: all-to-all (224 KiB per token per layer for DeepSeek-V3, cheap over NVLink and 5.7× compute over a NIC); stragglers (74% utilization even with uniform routing); weight traffic in decode that grows with the batch. Balancing (aux loss, bias controller, capacity factors) is a throughput tool with a quality price when pushed hard.
- KV knobs: sharing (GQA/MQA) buys ; compression (MLA) caches numbers per token per layer, 71× less than DeepSeek-V3 with MHA. Absorbed MLA decode reaches ~243 FLOPs/byte, near the knee. Absorb in decode, reconstruct in prefill.
- The L² wall: FlashAttention removes the bytes, not the arithmetic. DSA’s cheap indexer and top-2048 selection, or NSA’s window + select + compress, make attention per query linear in , with recall as the risk and union-free (shared) selection as the systems requirement. Hybrids keep attention in few layers, with constant SSM state elsewhere.
- Long-context positions: high RoPE frequencies already encode local order and must be kept; low ones must be interpolated. YaRN does both per frequency, with a logit temperature.
- The systems tax is the whole story. Routing, all-to-all, reconstruction GEMMs and cache layouts decide whether an architectural idea is a win.
8. Common pitfalls
- Counting MoE FLOPs from total parameters. 6N with N = 671 B overstates DeepSeek-V3’s training compute ~18×; use the activated count (and remember that MoE memory follows the total).
- Assuming balanced routing means no stragglers. Random counts make the busiest of 256 experts 1.35× the mean at 64 tokens per expert.
- Treating MoE as a decode-bandwidth win. At moderate batch, a decode step reads almost all experts.
- Substituting into MLA’s cache math. MLA’s dimensions are decoupled by design.
- Reconstructing K/V in decode, or absorbing in prefill: both are correct and both are the slow way.
- Judging sparse attention by FLOPs alone. Check recall (does the selector find what full attention would use?), and check that the selection is shared across the heads that read each KV entry.
- Applying position interpolation uniformly. It blurs the high frequencies that encode local order.
- Forgetting the hybrid’s fixed state. At short context, Nemotron 3 Nano’s Mamba state is two-thirds of its per-sequence memory.
9. Exercises
- MoE accounting. A layer has , , , , , with 3-matrix experts. Compute the total and activated FFN parameters, and the width of a dense FFN with the same activated size.
Answer
One expert: M. Total M; activated M, which equals a dense FFN of width ( M). The same design rule as DeepSeek-V3: (shared + active) × = the dense width.
- The routed payload. For that layer in BF16, how many bytes does one token send per MoE layer under expert parallelism (worst case)?
Answer
bytes = 96 KiB (dispatch + combine). The shared experts need no communication if they are replicated.
- MLA vs GQA. A 40-layer model uses MLA with , . What is its BF16 cache for a 65,536-token sequence, and how much smaller is it than a GQA-8 cache with head dimension 128?
Answer
MLA: bytes = 1.41 GiB. GQA-8: = 10.0 GiB, so MLA is 7.1× smaller.
- Decode intensity. What is the arithmetic intensity of a GQA decode-attention step with 64 query heads and 4 KV heads in BF16? How many query heads per KV head would you need to reach the H100 knee?
Answer
FLOPs/byte. Reaching 295 needs query heads per KV head in BF16. That is beyond any GQA configuration, but it is roughly what absorbed MLA achieves by letting all 128 heads share one 576-dim latent.
- Decode weight traffic. With 256 routed experts and top-8 routing, how many distinct experts does a decode batch of 16 touch per MoE layer, under uniform routing?
Answer
102: 16 tokens already make the step read 40% of the routed experts. With the shared expert that is 103 experts’ weights, what a dense FFN of the same activated size (9 experts’ worth, read once for the whole batch) would read. Real routers are skewed, which lowers this number somewhat.
- YaRN thresholds. A model trained at 8,192 tokens uses YaRN with , . Which RoPE pairs does it leave unchanged, and which does it interpolate fully?
Answer
Pairs whose wavelength is below tokens (more than 32 turns during training) are kept. Pairs whose wavelength exceeds 8,192 tokens (less than one turn) are interpolated by the full factor. Pairs in between get the ramp.
- When does DSA pay? With an attention pair cost of 279 kFLOP, an indexer pair cost of 16.4 kFLOP and , beyond what context length does DSA need fewer FLOPs per query than full attention?
Answer
2,180 tokens. The FLOP crossover is early. The practical one is later, because the indexer has its own cache, top- kernel and irregular gathers, and those costs are not FLOPs.
- Why share the selection? In demo 05, per-head selection at was more accurate than a shared selection of 256. Why does DSA still select once per token?
Answer
Per-head selections differ, so the KV entries a query must read are the union: 1,022 entries instead of 256. Decode is bandwidth-bound, so what matters is error per byte read, and at equal bytes the shared selection wins (top-1024 shared: error 0.029, against 0.048 for per-head top-256 with a 1,022-entry union). With MQA-style sharing, each selected entry is fetched once and used by every head.
10. The related assignment (concepts only)
There is no assignment specific to this lecture. Fall 2026’s A1 (performance engineering) continues alongside it, and A2 (pre-training) builds on the MoE and attention accounting. The concepts here feed directly into the research project: many of the course’s suggested directions are architectural, such as new sparse or hybrid layers, routing and balancing schemes, and KV formats. Their evaluation needs exactly today’s accounting: FLOPs and bytes per token, the systems tax, and a quality comparison at matched activated compute.
11. Research directions
- Balancing without a quality tax. Demo 02 found that pushing a router to high utilization can cost quality on skewed data. Controllers that target throughput (the straggler) rather than equal loads, or that adapt their step size, are open design space.
- Communication-aware MoE. LatentMoE, group-limited routing and topology-aware expert placement all attack the all-to-all. How do they trade against quality at fixed activated compute, and how do they change the best parallel layout (Lecture 6)?
- Absorption-aware serving. The absorbed/reconstruct decision depends on how many new queries a step brings (decode, chunked prefill, speculative decoding). Engines that pick the path per step, or kernels that blend them, are a natural systems project.
- Recall-aware sparse attention. Measure indexer recall on real long-context tasks, and design selectors whose misses are detectable (fall back to dense attention when unsure).
- How few attention layers are enough? For hybrids, where should the few attention layers go, and does sparse attention inside them compose with the SSM layers’ strengths?
12. Further reading
- Hugging Face, Mixture of Experts Explained (2023): the readable overview.
- N. Shazeer et al., Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer (2017); D. Lepikhin et al., GShard (2020); W. Fedus, B. Zoph, N. Shazeer, Switch Transformers (JMLR 2022, arXiv:2101.03961).
- DeepSeek-AI, DeepSeek-V2 (arXiv:2405.04434): MLA and decoupled RoPE. DeepSeek-V3 Technical Report (arXiv:2412.19437): MoE with aux-loss-free balancing, node-limited routing, MLA at 671 B. DeepSeek-V3.2 (2025): DeepSeek Sparse Attention.
- L. Wang et al., Auxiliary-Loss-Free Load Balancing Strategy for Mixture-of-Experts (arXiv:2408.15664).
- Kimi Team, Kimi K2: Open Agentic Intelligence (2025).
- NVIDIA, Nemotron-H (2025) and the Nemotron 3 Nano model card and report: hybrid Mamba–Transformer MoE.
- J. Yuan et al., Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse Attention (arXiv:2502.11089).
- T. Dao, A. Gu, Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (Mamba-2, arXiv:2405.21060).
- J. Su et al., RoFormer (arXiv:2104.09864); S. Chen et al., Positional Interpolation (arXiv:2306.15595); B. Peng et al., YaRN (arXiv:2309.00071).
13. Next lecture
Lecture 5 · Parallelism I: Data, Expert and Sharded-State Parallelism. Today’s architectures decided what each token computes and stores; next we decide where. We extend roofline thinking to many GPUs with communication as a third resource. We look at where a Transformer can be cut: along the batch (data parallelism), into experts (expert parallelism and its all-to-all, today’s routed payload), across the training state (ZeRO/FSDP). We cover the collectives that make each cut work (all-reduce, reduce-scatter, all-gather, all-to-all) and their α–β cost model.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| sparsity (parameter / state / computation / architectural) | 稀疏性(参数 / 状态 / 计算 / 架构) |
| conditional computation | 条件计算 |
| mixture of experts (MoE) | 混合专家 |
| expert / routed expert / shared expert | 专家 / 路由专家 / 共享专家 |
| router / gate / gating weight | 路由器 / 门控 / 门控权重 |
| top-k routing / softmax router / sigmoid affinity | top-k 路由 / softmax 路由器 / sigmoid 亲和度 |
| total vs activated parameters | 总参数 vs 激活参数 |
| dispatch / combine | 分发 / 合并 |
| expert parallelism (EP) / all-to-all | 专家并行 / 全对全通信 |
| routed payload / LatentMoE | 路由载荷 / 潜在空间 MoE |
| group-limited (node-limited) routing | 分组(节点)受限路由 |
| load balancing / hot spot / straggler | 负载均衡 / 热点 / 掉队者 |
| auxiliary balance loss / bias controller | 辅助均衡损失 / 偏置控制器 |
| auxiliary-loss-free balancing | 无辅助损失的负载均衡 |
| capacity factor / token dropping | 容量因子 / 丢弃 token |
| routing collapse / expert specialization | 路由坍缩 / 专家特化 |
| mutual information | 互信息 |
| head-space sharing (GQA / MQA) | 头空间共享(分组查询 / 多查询注意力) |
| latent-space caching / multi-head latent attention (MLA) | 潜在空间缓存 / 多头潜在注意力 |
| latent vector / down-projection / up-projection | 潜在向量 / 降维投影 / 升维投影 |
| reconstruction / weight absorption | 重建 / 权重吸收 |
| decoupled RoPE | 解耦旋转位置编码 |
| multi-token prediction (MTP) | 多 token 预测 |
| L² wall / long context | 二次方瓶颈 / 长上下文 |
| sparse attention / lightning indexer | 稀疏注意力 / 闪电索引器 |
| DeepSeek Sparse Attention (DSA) / Native Sparse Attention (NSA) | DeepSeek 稀疏注意力 / 原生稀疏注意力 |
| sliding window / token selection / token compression | 滑动窗口 / token 选择 / token 压缩 |
| recall risk | 召回风险 |
| union (of selections) | (选择集合的)并集 |
| hybrid stack / state-space model (SSM) / Mamba | 混合层堆叠 / 状态空间模型 / Mamba |
| constant state / mixed state | 常数大小状态 / 混合状态 |
| rotary position embedding (RoPE) / frequency / wavelength | 旋转位置编码 / 频率 / 波长 |
| extrapolation / position interpolation (PI) | 外推 / 位置插值 |
| NTK-aware scaling / YaRN | NTK 感知缩放 / YaRN |
| attention temperature (logit scale) | 注意力温度(logit 缩放) |
| continued training | 继续训练 |
| selectivity | 选择性 |