Skip to Content
Chapter 5

Modern variants: What’s in a frontier model

Tomas Reimers 19 minute read

If you diff GPT-2 (2019) against a frontier open model like DeepSeek-V3  (2025), the shocking thing is how little the skeleton changed: embeddings, attention, MLPs, residual stream, next-token head. But the config file grew some new fields, and each one is a response to a specific pressure — almost always either the cost of the MLPs or the cost of the KV cache (the stored keys and values of earlier tokens — defined mid-chapter).

So let’s do the diff by hand, starting from Chapter 3’s fully-itemized GPT-2 — 12 blocks of (2.4M attention + 4.7M MLP) ≈ 85M, plus 38.6M of embeddings = 124M — and upgrading one config field at a time, redoing the arithmetic after each change:

  1. Mixture of experts makes the MLPs — the majority of the parameters — sparse: huge total knowledge, small per-token cost.
  2. Attention variants — grouped-query and latent attention (GQA, MLA) — shrink the KV cache, the data structure that dominates inference memory.
  3. RoPE (rotary position embeddings) and systems tricks stretch the context window from GPT-2’s 1,024 tokens toward a million.
  4. Multimodality turns out to require almost nothing new: convert everything into tokens and reuse the whole machine.

By the end, the little model from Chapter 3 will read, field for field, like a frontier config.

Mixture of experts: sparse MLPs

Start with the MLPs, because that’s where the parameters are: 4.7M of each GPT-2 block’s 7.1M — two-thirds. Chapter 4 said more parameters mean lower loss; the tension is that in a dense model every parameter you add makes every token more expensive, because all the weights run all the time. Your brain doesn’t work this way: French cooking stays off while you debug a segfault.

Mixture of experts (MoE) makes the MLP sparse. Instead of one MLP per block, have many (8 to 256 in practice), the “experts,” plus a small learned router: a linear layer that reads the token’s vector from the residual stream, scores every expert (a softmax, so the scores are weights that sum to 1), and sends the token through only the top-k (often 2 to 8). The chosen experts’ outputs are combined as a weighted sum, using the winners’ router weights renormalized to sum to 1 (for the figure’s last token, output=0.62⋅expert2(x)+0.38⋅expert5(x)\text{output} = 0.62 \cdot \text{expert}_2(x) + 0.38 \cdot \text{expert}_5(x)) and written back to the stream. The weighted sum is what makes routing trainable: a top-k pick is discrete, with no derivative — but the router’s probabilities sit inside the output as multipliers, so gradients flow back through them and the discrete pick rides on a differentiable score:

'the'routerexpert 1 (MLP)0.14expert 2 (MLP)0.06expert 3 (MLP)0.34expert 4 (MLP)0.03expert 5 (MLP)0.09expert 6 (MLP)0.02expert 7 (MLP)0.28expert 8 (MLP)0.05×0.55×0.45out
token 'the' arrives at the MoE layer and hits the router first
Mixture of experts, top-2 routing: a learned router (a small linear layer plus softmax) scores all experts and sends each token to its best two. All 8 MLPs' parameters exist — that's total parameters, what the model knows — but each token only pays for 2: active parameters. Router scores shown are real softmax outputs of the illustrated logits.

Now upgrade GPT-2 and redo Chapter 3’s arithmetic. Replace each block’s single 4.7M-parameter MLP with 8 experts of the same shape, route top-2:

  • Total parameters: each block is now 2.4M attention + 8 × 4.7M experts ≈ 40M; times 12 blocks plus embeddings ≈ 520M. The model knows 4× more.
  • Active parameters: each token runs 2.4M attention + 2 × 4.7M chosen experts ≈ 12M per block; times 12 blocks plus the 38.6M embeddings ≈ 180M across the model. Each token pays only ~1.5× the dense cost (per-token FLOPs track the parameters a token actually touches — Chapter 4’s 2 FLOPs per weight).

That asymmetry — 4.2× the knowledge for 1.45× the per-token compute — scales: DeepSeek-V3 has 671B total parameters but only ~37B active per token. GPT-4-class knowledge at mid-size-model FLOPs. First scaled by Google’s Switch Transformer  and pushed into the open by Mixtral , MoE is now effectively universal at the frontier.

The catch is engineering. The router is trained end-to-end like every other weight, and left alone it will happily collapse onto a few favorite experts — a rich-get-richer loop: a slightly-preferred expert gets more tokens, trains more, gets preferred more, until most experts are dead weight. The standard fix is to make imbalance part of the loss: add an auxiliary term that grows when routing is uneven, so gradient descent itself trades a sliver of prediction quality for spreading tokens out. And because experts are sharded across GPUs, every MoE layer is also a network hop: tokens physically travel to their experts and back (Chapter 10).

One demystification: despite the name, experts don’t specialize into “the biology expert.” The Mixtral team checked: expecting topical clustering across code, math, and biology documents, they found routing essentially uniform across domains. What they found instead was syntactic and token-level specialization: one expert consistently catching whitespace and indentation in code, others gravitating to numbers, punctuation, or particular keywords, with consecutive tokens often routed to the same expert. In hindsight the result makes sense twice over. The router chooses per token, per layer (hundreds of independent decisions per token in DeepSeek-V3), so there is no single place where “this is a biology question” could even be decided. And the load balancer actively fights topical specialization. If one expert owned biology, every biology paper would swamp it, and the auxiliary loss would push the traffic apart. “Expert” is a term of art for a shard of MLP capacity; the specialization that survives training is the kind spread evenly through text — syntax — and nobody assigned it.

The load-balancing loss, concretely.

The Switch Transformer’s version, still the canonical one. For each expert ii, measure two things over a batch: fif_i, the fraction of tokens actually routed to it, and PiP_i, the router’s average probability on it. Add to the training loss:

Laux  =  α⋅nexperts⋅∑i fi⋅Pi\mathcal{L}_{\text{aux}} \; = \; \alpha \cdot n_{\text{experts}} \cdot \sum_i \, \tip{fraction of tokens routed to expert i}{f_i} \cdot \tip{average router probability on expert i}{P_i}

A product of two quantities that each sum to 1 is minimized when both are spread uniformly — collapse onto one expert and the term spikes, so the gradient pushes the router’s scores apart. (fif_i is a count, not differentiable, which is why PiP_i is in the product: the gradient flows through the probabilities.) The coefficient α\alpha is kept small (~0.01): enough pressure to keep every expert alive, not enough to override genuinely useful routing. DeepSeek-V3 went a step further with auxiliary-loss-free balancing: instead of a loss term, each expert gets a bias added to its routing score only, nudged up when the expert is underused and down when overloaded, rebalancing the traffic without distorting the gradients at all.

Taming the KV cache: GQA, MQA, MLA

Next, attention — but the problem isn’t the attention weights (2.4M per block; they’re cheap). It’s a fact from Chapter 3 that was harmless at GPT-2’s size: every head in every layer produces, and must keep, its own keys and values for every token. Our GPT-2 runs 12 heads of 64 dimensions per layer, each with its own small Wq,Wk,WvW_q, W_k, W_v.

The bill arrives at generation time. Each new token’s query must search the keys, and fetch the values, of every earlier token, in every head, in every layer. Chapter 3’s spreadsheet showed why those never need recomputing: a finished column is finished forever, so each token’s K/V are computed once and stored in the KV cache. (The cache kills the redundant projection work; the query-against-every-stored-key comparisons remain, which is why long context stays expensive below.)

Storage isn’t free: the cache has to live in GPU memory, next to the weights, for as long as the conversation does. Put a price on it. Each cached token stores one key vector and one value vector per head, per layer — and in Chapter 3’s multi-head attention, the heads’ K/V together span the full model width. In half-precision (2 bytes per number):

bytes  =  2×nlayer×nkv×dhead×2\tip{cache bytes per token of context}{\text{bytes}} \; = \; \tip{a key and a value}{2} \times \tip{number of layers}{n_{\text{layer}}} \times \tip{number of KV heads}{n_{\text{kv}}} \times \tip{dimensions per head}{d_{\text{head}}} \times \tip{bytes per number in half precision}{2}

For our GPT-2 (12 layers, 12 heads of 64 dimensions): 2×12×12×64×2=372 \times 12 \times 12 \times 64 \times 2 = 37 KB per token — at its 1,024-token context, a trivial 38 MB. Nobody at OpenAI lost sleep over this in 2019. Now scale it to Llama 3 70B’s shape (80 layers, 64 heads of 128 dimensions), pretending for the moment that every head caches its own K/V, as in Chapter 3: 2×80×64×128×2=2.62 \times 80 \times 64 \times 128 \times 2 = 2.6 MB per token — and a single 128K-token conversation needs 2.6 MB × 131,072 ≈ 340 GB (more than four 80-GB H100s) for one user’s cache. Since inference speed is mostly set by bytes moved through memory (Chapter 10), the KV cache directly limits context length, batch size, and cost: it grew from rounding error to the most expensive object in the datacenter.

The fixes form a progression: keep all 64 query heads, but let them share a smaller set of K/V heads — each query head still asks its own question through its own WqW_q, but several search over the same keys and values, computed by one K/V head:

MHA8 query heads8 K/V heads cached1 per query — cache ×1GQA8 query heads2 K/V heads cachedgroups share — cache ÷4MQA8 query heads1 K/V head cachedeveryone shares — cache ÷8
Sharing means pointing several query heads at the same keys and values. Every query head keeps its own W_q — its own taste in what to look for — but the K/V it searches over is computed (and cached) once per group. Only the bottom row is cached, so shrinking it shrinks the cache proportionally. Drawn with 8 query heads; Llama 3 70B runs the same pattern at 64 queries over 8 K/V heads.

Since only the K/V heads are cached (queries are used once and discarded — nothing ever looks back at a query), nkvn_{\text{kv}} is the only head count in the cache formula, and shrinking it shrinks the cache proportionally:

  • Multi-query attention  (MQA): one K/V head shared by all query heads. The formula’s nkvn_{\text{kv}} drops 64 → 1: cache shrinks 64×; quality dips (the GQA paper measures the gap).
  • Grouped-query attention  (GQA): the compromise — groups of query heads share K/V heads. Llama 3 70B runs 64 query heads against 8 KV heads: 8× smaller cache, negligible quality loss. This is today’s default.
  • Multi-head latent attention (MLA): DeepSeek’s move, and a departure from head-sharing — store only a small learned compression of all the heads’ keys and values (in DeepSeek-V2 , a 576-dimensional latent per token per layer, where its 128 heads of dimension 128 would otherwise cache 2×128×128=32,7682 \times 128 \times 128 = 32{,}768 — a 57× compression) and decompress on the fly. That spends compute to save memory: backwards for training, where compute is the binding cost (Chapter 4), exactly right for generation, where the arithmetic units idle waiting on memory (Chapter 10 makes this precise).
MHA64 KV heads — one per query head (the Chapter 3 default)2.5 MB/tok · 320 GB @ 128K
GQA8 KV heads, each shared by 8 query heads (Llama 3)320 KB/tok · 40 GB @ 128K
MQA1 KV head shared by all 64 query heads40 KB/tok · 5 GB @ 128K
MLAone 576-dim compressed latent per token (DeepSeek)90 KB/tok · 11 GB @ 128K
KV cache per token of context, computed for Llama 3 70B's real shape (80 layers, head dim 128, fp16). The progression MHA → GQA → MQA/MLA is the industry whittling down its most expensive data structure: at a 128K-token context, vanilla attention would need a third of a terabyte per sequence.

A model card that advertises some attention variant is almost always really announcing KV-cache economics.

Long context: RoPE and its stretching exercises

Frontier context windows went from GPT-2’s 1,024 tokens to 1M+ in about five years. Two things had to happen.

First, positions had to generalize. Chapter 3’s answer to word order (and GPT-2’s) was to add a learned position vector to each embedding: position 7 gets the position-7 vector, stored in a 1,024 × 768 table (0.8M parameters of our ledger). That table is two problems in one: the model has never seen a vector for position 5,000, and “these tokens are 3 apart” (what attention actually cares about) is only represented indirectly. RoPE (Rotary Position Embedding ), today’s standard, deletes the table entirely (our ledger’s one negative line item: −0.8M parameters, replaced by a formula with none). It encodes position by rotating each query and key vector by an angle proportional to its position. The trick is what rotation does to attention scores. Rotation preserves length, and a dot product depends on lengths and the angle between — so when query and key rotate together, each by its own position’s angle, absolute positions cancel and only the difference survives. The score sees content plus relative offset, never “position #4,821” — relative position, baked into the geometry:

key, pos 2query, pos 53θkey at 2, query at 5 — gap of 3key, pos 6query, pos 93θboth shifted +4 — same gap, same score=
RoPE: rotate each query and key by an angle proportional to its position (here θ per step). Attention scores are dot products, and a dot product depends only on the angle between two vectors — so the score for 'query 3 positions after key' is identical wherever the pair sits. Position becomes relative, baked into the geometry.

RoPE in coordinates, and why it stretches.

Pair up the dimensions of each query and key (a dd-dimensional vector becomes d/2d/2 little 2D planes) and rotate the pair in plane ii at position mm by angle mθim\theta_i, where the frequencies θi=10000−2i/d\theta_i = 10000^{-2i/d} range from fast (a big angle per position step) to extremely slow (thousands of positions per degree). Why have both? Because heads have two opposite kinds of job:

  • Some matching needs the exact nearby offset to matter: a head tracking “the token right before me” must score offset 1 differently from offset 2, which takes a fast plane, where one step swings the angle sharply; in a slow plane, offsets 1 and 5 look almost identical.
  • Other matching needs distance not to matter: “find the definition of this variable from 3,000 tokens back” is a content match that must survive any offset. That takes a slow plane, which barely moves over 3,000 steps; in a fast plane, 3,000 steps is hundreds of full revolutions, and the scrambled phase would destroy the match.

And the full geometric spread is needed because any single frequency aliases (angles wrap around, so many different offsets land on the same angle) while many frequencies together pin offsets down unambiguously. It’s exactly a clock: the second hand alone can’t distinguish 3:00:15 from 4:00:15, the hour hand alone can’t distinguish 3:00:15 from 3:00:45; together they’re unambiguous.

The whole vector rotates — no dedicated “position slot,” every dimension carrying content and every pair spinning at its own speed (the slowest planes are so nearly frozen they behave like an unrotated region in practice). (A few “partial rotary” implementations rotate only a fraction of the dimensions; standard RoPE rotates everything.) Because the encoding is a formula rather than a lookup table, it extends to unseen positions. Context-extension methods like YaRN  work by rescaling those frequencies so a model trained at 8K positions can operate at 128K after a comparatively cheap fine-tune (done in “mid-training” — Chapter 7). This is why long context arrived as point releases rather than retrains.

An objection: Chapter 2 established that directions carry meaning — so doesn’t rotating a vector by its position scramble its meaning? Three facts dissolve it. First, RoPE never touches the residual stream: it rotates only the queries and keys inside an attention head, in the instant before their dot product; the values, the stream, and everything the MLP reads are unrotated. Second, queries and keys rotate together, so what the score sees is content plus relative angle; the comparison geometry survives even as absolute directions spin. Third, the model learns WqW_q and WkW_k with the rotation already in place (a fixed, known transform) and learns to exploit it: position-blind matching gets parked in the nearly-frozen slow planes, position-sensitive work in the fast ones. The rotation isn’t something the model fights; it’s a coordinate system the model grows into.

Second, the quadratic had to be survivable. Attention still compares every token to every token — at 1M tokens, that’s 101210^{12} score pairs per head per layer, naively materialized as a terabyte-scale matrix. FlashAttention  computes exact attention but reorders the computation so the big seq×seq score matrix never materializes in slow GPU memory. It’s a pure systems win that every frontier stack now ships (the full why belongs to Chapter 10). On top of that, long-context models interleave sliding-window layers: most layers attend only to a local window of recent tokens, and only some layers attend globally. (Information still crosses windows: stacked local layers each carry it one window further, and the occasional global layer is the long-range relay.)

A consumer warning from the evals world: “supports 1M tokens” means the model runs at 1M tokens. Whether it can actually use information spread across that window (measured by needle-in-a-haystack tests — hide one fact in a long document, ask for it back — and multi-hop retrieval evals) is a separate and often disappointing question — see Chapter 9.

The little diffs: norms and activations

Two renames remain before our upgraded GPT-2’s config reads fully modern — and since Chapter 3 gave normalization a single clause, here is what it actually is.

Start with the job. The residual stream is pure accumulation — every attention step and MLP adds, nothing scales back down — so stack 80 blocks and magnitudes drift, and drift compounds through every weight matrix. Too large and activations and gradients blow up, too small and they fade out (Chapter 3’s vanishing-gradient aside, at depth 80). Normalization is the thermostat. Before each block reads the stream, rescale the token’s vector to a standard size, so every block at every depth sees inputs in the same predictable range.

LayerNorm, the 2017 original, does it per token: take the vector’s dd entries, subtract their mean, divide by their standard deviation, then let the model re-scale each dimension with learned parameters (the ⊙\odot below is elementwise multiplication):

LayerNorm(x)  =  γ⊙x−μσ+β\mathrm{LayerNorm}(x) \; = \; \tip{a learned per-dimension gain}{\gamma} \odot \frac{x - \tip{the mean of the vector's d entries}{\mu}}{\tip{the standard deviation of those entries}{\sigma}} + \tip{a learned per-dimension shift}{\beta}

RMSNorm is what a decade of ablations (remove-one-component-and-remeasure experiments) left standing: it turns out the mean-subtraction and the shift β\beta barely matter, so drop them — just divide the vector by the root-mean-square of its entries and apply the learned gains. Same stabilizing effect, cheaper to compute. Modern models also move where the norm sits: the 2017 transformer normalized after each residual addition (post-norm); modern models normalize the copy of the stream being fed into attention or the MLP and leave the stream itself untouched (pre-norm) — preserving the clean additive highway from Chapter 3’s residual-stream section, which improves training stability at depth.

SwiGLU (Swish-Gated Linear Unit) replaces ReLU inside the MLPs. Recall Chapter 1’s ReLU: max⁡(0,x)\max(0, x), a hard on/off gate. SwiGLU makes the gate learned and smooth: the MLP’s expansion layer produces two projections instead of one (call them the content and the gate), and the output is their elementwise product, content⊙SiLU(gate)\text{content} \odot \mathrm{SiLU}(\text{gate}), where SiLU(x)=x⋅sigmoid(x)\mathrm{SiLU}(x) = x \cdot \mathrm{sigmoid}(x) (the sigmoid linear unit, a.k.a. Swish — that’s the “Swi”; sigmoid is Chapter 1’s 0-to-1 squash) is a smooth ramp:

GPT-2's MLP: ReLUxexpand768 → 3072ReLU: negatives → 0contract3072 → 768outThe modern MLP: SwiGLUxcontent768 → 2688gate768 → 2688SiLU: a smooth ramp⊙elementwise ×contract2688 → 768out
The MLP, before and after. GPT-2's version: expand, clip negatives to zero (ReLU — a hard gate), contract. SwiGLU's version: the expansion produces two projections; the gate side passes through SiLU (a smooth ramp that dips slightly below zero — the curves drawn are the real functions) and multiplies the content side elementwise, deciding per dimension how much gets through. The two projections are why the expansion shrinks from 4d to ~3.5d: same total parameters, one extra decision.

One pathway proposes what to write; the other decides, per dimension and per token, how much of it gets through. The second projection is also why Llama’s intermediate_size is ~3.5dd rather than Chapter 3’s 4dd: SwiGLU needs three matrices where ReLU needed two (2×d×4d=8d22 \times d \times 4d = 8d^2 weights before; 3×d×e3 \times d \times e now). So keeping the 8d28d^2 budget exactly would shrink the expansion to e=8d2/3d≈2.7de = 8d^2/3d \approx 2.7d; Llama rounds up to 3.5dd, spending a bit extra. SwiGLU wins consistently and nobody is quite sure why. The paper that established it  ends, verbatim: “We offer no explanation as to why these architectures seem to work; we attribute their success, as all else, to divine benevolence.”

Neither change alters the story of the machine: the field ran a decade-long ablation study, and these won.

Reading a real config file.

The ledger we’ve been keeping is the config file. Llama 3 70B’s, annotated:

{ "hidden_size": 8192, // d — the residual stream width (Ch. 3) "num_hidden_layers": 80, // blocks in the stack (Ch. 3) "num_attention_heads": 64, // query heads (Ch. 3) "num_key_value_heads": 8, // GQA: 8 KV heads shared 8 ways (this ch.) "intermediate_size": 28672, // MLP expansion (~3.5d, SwiGLU-adjusted) "vocab_size": 128256, // tokenizer size (Ch. 2) "rope_theta": 500000, // RoPE base frequency (this ch.) "max_position_embeddings": 131072 // context window }

A MoE model adds num_experts and num_experts_per_tok — total vs. active, in config form. After this chapter, every line of every model card should parse — and you can rerun Chapter 3’s parameter count on any of them.

Multimodality: everything becomes a token

Frontier models see images, hear audio, and increasingly emit both — and required almost no new machinery to do it. The recipe is to convert other modalities into tokens and reuse the entire apparatus:

  1. A vision encoder (a Vision Transformer , ViT) chops the image into a grid of patches (16×16 pixels each in the original), flattens each patch, and treats it exactly like a token embedding. No convolutions; the same blocks as Chapter 3, usually without the causal mask (it’s an encoder: the whole image is already on the table, nothing is predicted left-to-right, so no mask is needed — the encoder lineage, mask-free cousin of the decoder stack we’ve been building).
  2. A small adapter projects the encoder’s output vectors into the language model’s embedding space.
  3. The LLM proceeds as if the image were a few hundred words it had read. (CLIP , Contrastive Language-Image Pretraining, supplied the standard vision encoder — trained so an image’s vector lands near its caption’s, leaving the adapter a mere change of coordinates. Audio follows with a speech encoder.)
imageflatten +projectdescribethis:…patch tokens (16 of them)text tokensone sequence, same transformer
A Vision Transformer eats an image the only way a transformer eats anything: as a sequence. The image is chopped into a grid of patches (16×16 pixels in the original ViT; 4×4 patches shown), each patch is flattened and projected to an embedding vector — exactly one 'token' — and the sequence continues as if the image were words.

An image is two-dimensional, though, and the flattening step destroys that: patches are laid out in reading order, so the patch directly above this one is now just “sixteen positions back,” indistinguishable from any other neighbor. How does the model know the grid? The same way the transformer knew word order: it doesn’t, until you tell it — attention is a set operation (Chapter 3), so spatial structure arrives as position information. The original ViT did the laziest possible thing: a learned position vector per patch slot, exactly like GPT-2’s position table, with no 2D-ness built in — and training discovered the geometry anyway: plot which position embeddings resemble which and a clean 2D grid emerges, each patch most similar to its true spatial neighbors (one of the paper’s best figures). Modern vision stacks make the structure explicit instead — giving each patch a (row, column) coordinate pair and encoding the two axes separately, e.g. 2D RoPE (recall RoPE rotates independent 2D pairs of dimensions; here some pairs rotate by row and others by column). That matters for the same reason RoPE beat the position table in text: formulas generalize to image sizes the table never saw.

Early multimodal systems bolted encoders onto finished LLMs; current frontier models are natively multimodal — trained on mixed text/image/audio streams from the start. The transformer was never a language model. It is a sequence model, and prose, code, screenshots, and speech all reach it the same way: as sequences of embeddings.

The transformer’s quadratic attention keeps inspiring challengers — most prominently state-space models like Mamba , which are, with real irony, a modernized recurrence: constant-size state and linear-time inference — the very design attention replaced in Chapter 3’s opening. They now match transformers at moderate scale, and ideas from them show up in production as hybrids: a few attention layers among many linear-time layers. The transformer’s real moat is nine years of tooling, kernels, and hardware co-evolution — watch the challengers without reorganizing your mental model around them.

Step back and look at what we built. We took Chapter 3’s 124M-parameter GPT-2 and, field by field: made its MLPs sparse (520M total, 180M active), shared its KV heads (cache ÷8), swapped its position table for rotations (context extendable), renamed its norms and activations, and taught it to eat pixels. At no point did we touch the skeleton. That is the state of the art: the 2017 architecture, relentlessly cost-optimized.

Something should be nagging you about this chapter, though. We counted every parameter and never once said what any of them does. We know the shapes of all the containers and nothing about the contents — half a billion numbers whose dimensions we chose and whose values we can’t read. Surely someone has tried to look inside? The next chapter is about the people who did, and what they found there.

Further reading

Last updated on