Series in the AI archive · Overview

Suppose a model is about to generate the first token of its answer after reading a long paper. It has already processed the paper once. How much of that computation does it carry into the next step? How much does it have to consult again? Those two questions go a long way toward explaining how the decoder evolved after GPT-3.

There are three places to look inside the decoder. Position changes how the current token scores an earlier one. Attention determines what the model can read from the prefix and what it stores for future steps. The feed-forward block determines how the resulting representation is transformed. Modern models change these parts independently, often in the same model. GPT-3 · DeepSeek-V3

Follow one token through the decoder Link to heading

The tokenizer maps text to token IDs, and an embedding lookup maps each ID to a vector. A stack of decoder blocks updates those vectors. GPT-3 already used this general recipe in 2020. The changes below address the cost and flexibility of carrying it to different workloads. In a typical block, attention reads earlier positions and the feed-forward block transforms each position separately. Residual connections carry the input of each sublayer forward. An output projection maps the final representation at the last position to one logit per vocabulary item. Softmax gives a distribution for the next token. Once a token is chosen, it becomes part of the prefix for the next step. Transformer · GPT-3

Diagram source
flowchart TD
  A["Token IDs"] --> B["Token embeddings"]
  B --> C["Causal self-attention"]
  C --> D["Feed-forward transformation"]
  D --> E["Vocabulary logits"]
  E --> F["Choose the next token"]
  F --> G["Append to the prefix"]
  G --> A

The attention and feed-forward stages repeat at each layer. The diagram omits normalization and residual paths. Position information enters according to the architecture. The original Transformer had an encoder and decoder. Here we are following a decoder-only model, where causal self-attention operates on a single growing prefix. Transformer

Why the cache grows with the prefix Link to heading

Take one attention head. The input has $T$ rows, one per token, with $d_{\mathrm{model}}$ features in each row. Learned projections produce $Q$, $K$, and $V$, each with shape $T\times d_h$ in this example. The score matrix $QK^\top$ has shape $T\times T$. Row $i$ gives the scores for the query at position $i$ against all keys. We apply the causal mask before a row-wise softmax, then use the resulting weights to mix values. Transformer

$$ A=\operatorname{softmax}_{\mathrm{row}}\left(\frac{QK^\top}{\sqrt{d_h}}+M\right), \qquad O=AV, \qquad M_{ij}=\begin{cases} 0 & j\le i,\\ -\infty & j>i . \end{cases} $$

Here is a three-token example. Suppose the unmasked, scaled scores for token 2 against tokens 1 and 2 are $0$ and $\log 3$. The mask gives token 3 zero weight in that row. The two remaining exponentials are $1$ and $3$, so the output at position 2 is $\tfrac14 v_1+\tfrac34 v_2$. The dot products select the weights. The value vectors supply the information being mixed.

During generation, appending a token leaves earlier causal states unchanged for a fixed prefix and position scheme. The server can therefore reuse their keys and values. The new query still has to read the relevant keys and values. With dense attention, that includes the whole available prefix. The cache saves recomputation, while the work of consulting the prefix remains. This is the cost behind the changes that follow. KV-cache walkthrough · PagedAttention

Three ways to change attention Link to heading

RoPE changes the score. In rotary position embedding, each pair of query and key components is rotated by an angle proportional to its position. For one pair, let $R(i\theta)$ be the two-dimensional rotation at position $i$. Orthogonality gives $R(i\theta)^\top=R(-i\theta)$, and rotations add their angles. The score contribution becomes the following. RoFormer

$$ (R(i\theta)q_i)^\top(R(j\theta)k_j) = q_i^\top R(-i\theta)R(j\theta)k_j = q_i^\top R((j-i)\theta)k_j . $$

The query and key still encode content. The rotation gives their interaction an explicit dependence on relative position. Applying this across pairs at different frequencies gives the model multiple positional scales to work with. How well it uses distances beyond those seen in training remains an empirical question. RoFormer · Lost in the Middle

Grouped-query attention changes how much the server stores per token. Multi-head attention gives each query head its own key and value head. Multi-query attention shares one KV head across all queries. Grouped-query attention sits between them. Each group shares one KV head and retains distinct query heads. For a standard uncompressed cache with uniform layers, one sequence stores two tensors shaped $L\times T\times H_{\mathrm{KV}}\times d_h$. If each element takes $b$ bytes, the payload is therefore the following. Ainslie et al., EMNLP 2023

$$ \text{KV bytes}=2\,L\,T\,H_{\mathrm{KV}}\,d_h\,b . $$

In a hypothetical decoder with 32 layers, 32 query heads, head width 128, and FP16, 32 KV heads require 512 KiB per cached token. Eight KV heads require 128 KiB per token. At 8,192 tokens, the payload falls from 4 GiB to 1 GiB for one sequence, before allocator overhead. The fourfold saving follows directly from the head count. The wall-clock gain depends on the kernel and workload. The GQA paper reports quality near multi-head attention with speed comparable to multi-query attention in its uptraining experiments. Ainslie et al., EMNLP 2023

Latent and sparse attention change different parts of the cost. DeepSeek-V2’s multi-head latent attention compresses the KV representations for a token into a shared latent. In a simplified view, a down-projection stores $c_j=W_Dx_j$, and a head’s key and value are obtained through head-specific projections of $c_j$. For the key dot product, $q_i^\top W^K_h c_j=((W^K_h)^\top q_i)^\top c_j$. The server can transform the query once and score cached latents, avoiding materialization of each past head’s full key. The deployed architecture also keeps a positional key component with decoupled RoPE. The cache shrinks per token. Dense scoring still grows with the number of tokens consulted. DeepSeek-V2, §2.1

Sparse attention instead reduces how many detailed positions a query consults. DeepSeek-V4 combines selection over compressed history with more aggressively compressed summaries in its hybrid attention design. DeepSeek’s preview model card reports 27% of the single-token inference FLOPs and 10% of the KV cache of DeepSeek-V3.2 at a one-million-token context for V4-Pro. The FLOP comparison measures arithmetic, so a latency comparison would additionally need a serving implementation and hardware. Those are architecture-specific comparisons at that context length. To judge the trade-off, I would ask whether the model can still recover rare, exact evidence near different positions in the prefix at the same serving budget. DeepSeek-V4 model card · Lost in the Middle

Expert routing changes the weights a token uses Link to heading

After attention, a dense feed-forward block runs the same learned transformation at every position. In a sparse mixture-of-experts layer, a router scores several feed-forward networks, chooses a small set for the token, and combines their outputs. If the layer has $E$ equally sized experts and routes a token to $k$ of them, the token uses $k/E$ of that layer’s expert weights. The router, shared experts where present, and the rest of the model contribute separately. Switch Transformers · DeepSeek-V3

DeepSeek-V3 reports 671 billion total parameters and 37 billion activated per token. The first figure matters for storing and distributing the weights. The second helps explain which weights the forward pass uses for one token. Actual serving cost also depends on how tokens route during a batch and what communication the routing requires across devices. The practical comparison is between systems at a specified workload, with quality, latency, throughput, and hardware reported together. DeepSeek-V3 · Switch Transformers

What I would look for next Link to heading

A selective state-space model such as Mamba carries a recurrent state forward, so this part of inference has a state whose size is independent of prefix length for a fixed model. A different branch changes what can enter the sequence in the first place. Gemma 4, for example, describes a 12B variant that ingests raw audio and image patches. The useful comparison for long documents is how well each system preserves details that turn out to matter later, at a measured cost. I would test that by varying both evidence position and the number of distracting passages, then tracking exact evidence recovery, cache or state size, and latency. These are proposed measurements. Mamba · Gemma 4 · Lost in the Middle

The architecture defines how information can travel through the model. Part 2 follows the data and objectives that teach it which information to use, from next-token likelihood to instruction tuning, preferences, and verifiable outcomes.