LLM Internals Lab

Multi-Head Attention

The whole model

One forward pass, from text to the next token. Click any part, or step through it.

    Attention up close

    Every head of the attention sublayer, and the computation inside one of them.

    KV cache per token, per layer

    Values stored per token for 16 query heads of dimension 128, the head layout of DeepSeek-V2-Lite. GQA uses 4 groups; MLA a 512-dim latent plus a 64-dim rotary key; DSA adds a 128-dim index key.

    During generation the KV cache, more than the arithmetic, limits how long a context or how large a batch fits in GPU memory, and reading it back slows every new token. That is why these variants exist.

    MQA shrinks the cache the most but can cost quality. GQA recovers most of that quality at close to MQA's speed (Ainslie et al., 2023). DeepSeek reports MLA outperforming MHA in its ablations while caching about as much as GQA with 2.25 groups.

    The two newer designs attack the growth with length itself. Gated DeltaNet replaces the cache with a fixed-size memory, so Qwen3-Next keeps a per-token cache in only 12 of its 48 layers. Sparse attention still stores every token, but each new token reads only the 2,048 that its indexer selects, so the work per token stops growing with the context.

    * Gated DeltaNet stores nothing per token. Each layer keeps one fixed-size state instead: 16 heads × 128 × 128 = 262,144 values at the sizes compared here, however long the context.

    Dimensions come from the official config files of ; Qwen Sparse Attention figures from the LMSYS write-up and the published Qwen3.8-Flash-Next config. No weights are loaded: the diagrams show structure and tensor shapes, not activations, and every score, weight and logit drawn is illustrative unless a pop-up says it was computed. Cache sizes assume 16-bit values. Equations are typeset with Temml (MIT) in Latin Modern Math (GUST Font License).

    Every mechanism shown here is also runnable PyTorch in llm_lab/reference (attention, MLA, Gated DeltaNet, both sparse indexers, the eight decoding methods), tested to give the same logits as Hugging Face transformers.

    Sources