• English
  • Beyond the classic transformer

    The transformer from chapter 6 has carried language models since 2017, but it has two expensive habits. Every new token reads the keys and values of every earlier token, and those keys and values pile up in a KV cache that grows with the conversation. And it writes text strictly one token per forward pass.

    Most recent architecture work attacks one of those habits. This chapter walks through the main ideas: shrinking the cache, replacing attention with a fixed-size memory, mixing the two, writing many tokens at once, and feeding the model things that are not text at all.

    Multi-head latent attention: compress the cache

    Chapter 10 showed two ways to shrink the KV cache: let several query heads share one key/value head (GQA), or let all of them share a single one (MQA). Sharing saves memory but throws away some of what separate heads could express.

    Multi-head latent attention (MLA), introduced with DeepSeek-V2 in 2024, compresses instead of sharing. For each token the model computes one small latent vector cc ("latent" means hidden: a compressed summary the model uses internally) and caches only that. When attention needs keys and values, it up-projects them from the latent for every head, multiplying by a matrix that makes the vector large again:

    ct=Wdown ht,kt(i)=WK(i) ct,vt(i)=WV(i) ctc_t = W_{\text{down}}\, h_t, \qquad k_t^{(i)} = W_{K}^{(i)}\, c_t, \qquad v_t^{(i)} = W_{V}^{(i)}\, c_t

    Here hth_t is the token's hidden vector, WdownW_\text{down} squeezes it into the latent, and each head ii has its own matrices WK(i)W_K^{(i)} and WV(i)W_V^{(i)} to rebuild its key and value. The sizes show the gain. In the model of the figure below, close to DeepSeek-V3, plain multi-head attention caches 2 × 128 heads × 128 numbers = 32,768 numbers per token in every layer. MLA caches a 512-number latent plus a 64-number position key: 576 numbers, about 57 times fewer.

    Rebuilding every key for every head at every step would be slow, but it is never needed. A key is only ever used in a dot product with a query, and q⋅(WKc)=(WK⊤q)⋅cq \cdot (W_K c) = (W_K^\top q) \cdot c: multiply the query by WK⊤W_K^\top once, and it can be compared with the cached latent directly. The value matrix folds into the output matrix the same way. Rotary positions (chapter 4) do not survive that folding, so MLA keeps a small extra key per token just for position.

    Figure 14.1 · What sits in the KV cache
    tokenclatent · cachedK, V · rebuilt on the fly
    Cached per token, per layer: 576 numbers
    one square = 256 numbers

    Store one small latent vector (plus a short position key). Keys and values for all 128 heads are up-projected from it when needed.

    KV cache for one 128k-token conversation

    Illustrative model close to DeepSeek-V3: 61 layers, 128 heads × 128 dims, 16-bit numbers.

    Switch the attention type and the context length. The squares show how many numbers each token leaves behind in every layer; the bars show the total for one conversation. MLA lands between GQA and MQA in size while keeping a separate view per head.

    With the settings above, a 128k-token conversation needs roughly 490 GB of cache with plain multi-head attention, about 31 GB with GQA, and under 9 GB with MLA. That difference decides how many users one GPU server can hold at once.

    State-space models: a memory that does not grow

    Attention keeps everything: to produce token 100,000 it looks back over 99,999 cached entries. A recurrent network does the opposite. It squeezes the past into a fixed-size state and updates that state once per token. Memory and work per token stay constant, however long the text gets.

    Classic RNNs (recurrent neural networks, the step-by-step design just described) lost to transformers for two reasons: they could not be trained in parallel, and they forgot too much. Modern state-space models (SSMs) such as Mamba (2023) fix both.

    • Selective updates. Each step is ht=Aˉt⊙ht−1+Bˉt xt,yt=Ct hth_t = \bar{A}_t \odot h_{t-1} + \bar{B}_t\, x_t, \qquad y_t = C_t\, h_t Here hth_t is the state after token tt (a short list of numbers), xtx_t is the token's input, ⊙\odot multiplies two lists number by number, and yty_t, the layer's output, is read out of the state through CtC_t. The decay Aˉt\bar{A}_t and the write strength Bˉt\bar{B}_t depend on the current token. With a one-number state and Aˉ=0.9\bar{A} = 0.9, each step keeps 90% of what was there, so after 10 filler words 0.910≈0.350.9^{10} \approx 0.35 of an old memory remains. An important word can get Aˉ≈0\bar{A} \approx 0 and a large Bˉ\bar{B}: forget that slot and write the new word in its place. In Mamba both come from one token-dependent number, the step size Δ: a large Δ means forget more and write more.
    • Parallel training. Each step is an affine map h↦a h+uh \mapsto a\,h + u (multiply by a number, then add one). Doing h↦a1h+u1h \mapsto a_1 h + u_1 and then h↦a2h+u2h \mapsto a_2 h + u_2 gives h↦(a2a1) h+(a2u1+u2)h \mapsto (a_2 a_1)\,h + (a_2 u_1 + u_2): again one multiply and one add. So neighbouring steps can be merged in pairs, all at once, then pairs of pairs, and so on. Because of that, the steps can be grouped in any order without changing the result (associativity), which lets a parallel scan process a whole training sequence in about log⁡2n\log_2 n rounds instead of nn sequential steps.
    Figure 14.2 · Growing cache vs fixed state
    The·cat·that·the·dog·chased·ran·up·the·tall·tree·and·sat·there·quietly.

    Attention: KV cache

    KVThe
    1 K/V entries · this token reads 1 cached entries

    State-space model: fixed state

    0.120.120.120.120.120.110.110.11
    8 numbers, always · this token reads 1 state
    Memory as the text grows
    tokens →KVSSM

    Training sees all 16 tokens at once: a parallel scan finishes the recurrence in 4 rounds (log₂ 16).

    1/16

    Both models read the first token. The attention model stores its key and value; the SSM writes it into its small state.

    Press play. On the left, every token adds a key/value row that every later token must read. On the right, a real (tiny) selective SSM updates its 8-number state: content words get a large Δ and change it a lot, function words barely touch it. The chart shows memory as the text grows.

    Linear attention reaches the same place from the other side. Drop the softmax from attention, and the output for a query qq becomes ∑i(q⋅ki) vi=q⊤(∑ikivi⊤)\sum_i (q \cdot k_i)\, v_i = q^\top \big(\sum_i k_i v_i^\top\big). The sum in brackets does not depend on the query, so it can be kept as one running matrix, updated once per token: St=St−1+ktvt⊤S_t = S_{t-1} + k_t v_t^\top. Again a fixed-size state. The price is that without softmax, attention can no longer focus sharply on a few tokens, which recent variants partly win back with gates. Mamba-2, RWKV, RetNet and Gated DeltaNet are all variations on "attention-like quality with a recurrent-sized memory". Mamba-2 is in fact built on the observation that a structured SSM and a form of linear attention compute the same thing.

    The catch is in the word fixed. A state of a few thousand numbers per layer cannot hold a 100-page document word for word. Pure SSMs are good at the gist and weaker at exact recall: copying a phone number from far back, or finding the needle in a long context.

    Hybrids: a few attention layers are enough

    So most new long-context designs keep some attention. A hybrid stack makes most layers cheap (recurrent, linear, or sliding-window attention) and spends full attention on a few. AI21's Jamba (2024) used one attention layer for every seven Mamba layers; several 2025 models from NVIDIA, Qwen and MiniMax follow similar ratios with different cheap layers. Google's Gemma models interleave local sliding-window attention with occasional global layers in the same spirit.

    Figure 14.3 · Mixing layer types
    recurrent / linear
    recurrent / linear
    recurrent / linear
    full attention
    recurrent / linear
    recurrent / linear
    recurrent / linear
    full attention
    recurrent / linear
    recurrent / linear
    recurrent / linear
    full attention
    recurrent / linear
    recurrent / linear
    recurrent / linear
    full attention
    recurrent / linear
    recurrent / linear
    recurrent / linear
    full attention
    recurrent / linear
    recurrent / linear
    recurrent / linear
    full attention
    full attention recurrent / linear
    6 of 24 layers use attention
    Memory for one sequence25%
    Work per new token25%
    Exact recall of a detail far backbest

    Relative, illustrative numbers. Memory and work are computed from layer counts; recall is a qualitative summary of published results.

    Choose a mix and a context length. Only the purple full-attention layers keep a KV cache that grows with the context, so memory and per-token work fall almost in proportion to how many you remove. Keeping even a few of them brings back most of the precise recall.

    Writing more than one token per pass

    The other expensive habit is decoding one token at a time. Speculative decoding already cheats by letting a small model guess ahead. Two newer ideas change the model itself.

    • Multi-token prediction (MTP). Extra output heads, trained alongside the normal one, predict the tokens at t+2t+2, t+3t+3, … from the same hidden state (the model's internal vector at that position). Training this way tends to help the model plan ahead, and at inference the extra heads become a built-in draft model: the next pass checks their guesses and keeps the ones that match. DeepSeek-V3 trains with one extra MTP module this way.
    • Diffusion language models. Instead of writing left to right, start from an answer of fixed length made entirely of [MASK] tokens. Each step predicts every masked position at once and commits the ones it is most confident about, much as image diffusion models sharpen noise into a picture. Research models such as LLaDA and commercial ones such as Inception's Mercury show this can reach competitive quality with far fewer passes.
    Figure 14.4 · Three ways to write a sentence
    0 forward passes
    1/13

    Autoregressive decoding: one forward pass, one token, strictly left to right.

    Forward passes to write 12 tokens
    Switch modes and press play. Autoregressive decoding needs one pass per token. Multi-token prediction drafts two tokens ahead and confirms them in the next pass; a wrong guess is replaced. Diffusion fills the easiest positions first and needs only four passes here. Pass counts are illustrative.

    Diffusion is not free: each pass processes the whole fixed-length answer, the length has to be chosen up front, and committing tokens in parallel can produce clashes a left-to-right model would avoid. Whether diffusion or autoregression wins at the largest scales is still an open question.

    Beyond text: images and audio as tokens

    A transformer does not care what its tokens mean, only that each one arrives as a vector. That is the whole trick behind multimodal models.

    • Images. A vision transformer (ViT) cuts an image into a grid of square patches, typically 14 or 16 pixels across, flattens each patch and multiplies it by a learned matrix. Each patch becomes one vector, a token like any other.
    • Audio. Speech is either encoded into vectors by an audio encoder, a network that turns sound into vectors (the approach popularized by Whisper) or turned into discrete audio tokens by a neural codec, a network that compresses sound into a short sequence of codes, typically a few dozen tokens per second of sound. Codec tokens can also be generated, which is how models talk back.
    Figure 14.5 · An image becomes tokens
    What·is·in·this·picture?
    1/4

    A 16×16 image. A real model sees something like 1024×1024 pixels.

    Step through it. The picture is cut into 16 patches, the patches join the text in one sequence, and a linear layer (one matrix multiplication) turns each one into a vector. The vectors here come from a fixed random matrix standing in for the learned one.

    There are two common ways to build such a model:

    ApproachHow it worksExamples
    AdapterTake a pretrained vision encoder (a network that turns images into vectors, such as CLIP) and a pretrained LLM, and train a small projector, a little network that maps image features into the LLM's embedding space.LLaVA and many open vision-language models
    NativeTrain one model on interleaved text, image and audio tokens from the start, often generating images and speech as well as reading them.Meta's Chameleon; most frontier assistants are described as natively multimodal

    Images are expensive: one high-resolution picture can turn into thousands of tokens, which is why vision models merge or average (pool) neighboring patches before they reach the language model. That cost leads straight back to the long-context and caching chapters.

    What's next

    None of these ideas replaces the core you have seen in this guide: tokens become vectors, layers mix information between positions, and training follows the gradient. They change how positions are mixed and how many tokens come out per pass. The other big frontier is not architecture at all but how models spend compute when they answer: reasoning trained with reinforcement learning, and working through long contexts full of tools, files and memory.

    Summary

    • MLA caches a small latent vector per token and rebuilds per-head keys and values from it, cutting the KV cache far below GQA.
    • State-space models and linear attention replace the growing cache with a fixed-size state: constant memory per token, but weaker exact recall.
    • Hybrids keep a few full-attention layers among many cheap ones and get most of both worlds.
    • Multi-token prediction and diffusion write several tokens per forward pass.
    • Multimodal models turn image patches and audio into tokens, so the same transformer reads them all.