Transformers & attention, section 3 of 4, 6h

What modern models actually do differently

By the end: You can read a current model's config and say what each named component changes about cost and quality.

  • Grouped-query and multi-query attention, and the cache arithmetic
  • Sliding-window and local attention
  • Rotary position embeddings and context extension
  • SwiGLU and RMSNorm
  • Mixture of experts: total against active parameters
  • FlashAttention, which is exact

New to transformers & attention? Earlier models read a sentence one word at a time, in order, carrying a running summary forward — which made them slow to train and forgetful across long passages. The transformer threw that out and used attention instead: when handling any one word, the model looks at every other word in the input at once and decides which of them matter here. The word "it" can look straight back at the noun it refers to, however far away that noun is. Why it matters

Open the config of any open-weights model released recently and you will find a dozen names that no introduction to transformers mentions: grouped-query attention, RoPE scaling, SwiGLU, a router and an expert count. This section goes through them one at a time and says what each changes about memory, speed or quality, with the arithmetic where there is arithmetic. It is the difference between knowing how a transformer works and being able to read what someone is actually shipping.

The model in the paper is not the model you will serve#

The 2017 architecture is the one most explanations still teach: multi-head attention, learned absolute position embeddings, a GELU feed-forward layer, layer normalisation. Every one of those has been replaced in the models being served today. Interviewers ask for the replacements by name, because each is a decision with a cost attached rather than a detail.

Grouped-query attention#

Multi-head attention gives every query head its own key and value heads. Keys and values are what the KV cache stores, so the cache grows with the number of heads. Grouped-query attention keeps all the query heads and lets several of them share one key and value head. Multi-query attention is the same idea taken to a single shared pair for the whole layer.

32 query heads, 32 KV heads   multi-head        full cache
32 query heads, 8 KV heads    grouped-query     cache / 4
32 query heads, 1 KV head     multi-query       cache / 32

KV cache per token = 2 x layers x kv_heads x head_dim x bytes

32 layers, 8 KV heads, head_dim 128, 16-bit   ->  128 KiB per token
the same model with 32 KV heads               ->  512 KiB per token
The cache shrinks by exactly the ratio of query heads to key and value heads. The weights barely change size.

On a served model the cache, not the weights, is usually what caps how many requests fit on a card. Dividing it by four divides the memory cost of concurrency by four, or buys four times the context length for the same memory. This is the single change that made long context affordable, and it is why an 8B model can serve dozens of 8k conversations on one GPU.

The quality cost is small and real, and it grows as sharing gets more aggressive. Multi-query attention loses more and was reported to be less stable to train, which is why grouping, commonly eight key and value heads, is the compromise nearly everyone settled on.

Sliding-window and local attention#

Restrict each position to the last w tokens instead of the whole prefix. Cost per layer becomes linear in sequence length rather than quadratic, and the cache only has to hold w tokens per layer no matter how long the conversation gets.

What it costs is direct reach. Information still travels further than the window, because each layer moves it another w positions, so a stack of L layers reaches about L times w. What is lost is precise retrieval: a single token far outside the window cannot be attended to directly, which is exactly what a long-context lookup needs. Models that use it usually interleave, putting a few full-attention layers among many windowed ones so at least some layers can see everything.

Rotary position embeddings#

Attention treats its input as a set, so position has to be supplied from outside. Early models added a learned vector per position. That has two problems: the table has a fixed number of rows, so there is no vector at all for a position beyond the training length, and it encodes where a token sits rather than how far apart two tokens are.

RoPE rotates each query and key vector by an angle proportional to its position index. The dot product of a rotated query with a rotated key then depends only on the difference between the two positions, so relative distance falls out of the arithmetic instead of being learned. Nothing is added to the values and no table has to be sized in advance.

Extending context afterwards means changing the rotation frequencies so the angles a longer sequence produces stay inside the range the model saw in training. Position interpolation scales them down uniformly; the NTK-aware and YaRN variants scale them unevenly across frequency bands, leaving the high frequencies that carry local order alone. All of them work to a point, and all of them cost some quality, most visibly on precise retrieval inside the stretched range.

A context number in a config is not a measurement

If a model advertises a long context because someone changed the RoPE scaling and nothing else, the model can read that far and may not be able to use it. Test retrieval at the far end of the claimed window before believing the number.

SwiGLU and RMSNorm#

The feed-forward layer used to be an up-projection, an activation such as GELU, and a down-projection. SwiGLU does the up-projection twice, passes one copy through a swish activation and multiplies the two elementwise, so one path gates the other. That is three matrices where there were two, so the hidden width is cut to roughly two thirds to keep the parameter count level. The gate lets the layer suppress channels per token, and it measures slightly better for the same budget. There is no deeper story than that.

RMSNorm drops the mean subtraction from layer normalisation: divide the vector by its root mean square and apply a learned scale, with no shift. One less reduction over the vector, marginally less arithmetic, and no measurable quality cost, which is why it has become the default.

Mixture of experts#

The feed-forward layer is split into many separate experts, and a small router sends each token to one or two of them. The others do nothing for that token. The model gets far more parameters without the compute per token rising to match.

Dense model       8B total parameters      8B active per token
Sparse model    120B total parameters      5B active per token

compute per token    follows the active count
memory to serve      follows the total count

Mixture of experts saves compute, not memory

Every expert has to be resident, because the router may pick any of them for the next token. If you sized the GPU from the active parameter count, you have under-provisioned it by the ratio of total to active, and the model will not load at all.

The other costs are load balancing, which needs an auxiliary term in the loss to stop the router sending nearly everything to a few favoured experts, and communication: when experts are spread across devices, every token's routing decision becomes an all-to-all exchange.

FlashAttention#

Standard attention computes the full matrix of scores for every pair of positions, writes it to GPU memory, reads it back for the softmax, writes it again, and reads it once more to multiply by the values. On a long sequence that matrix is enormous, and moving it is what takes the time rather than the multiplying.

FlashAttention never writes it. It walks over blocks of queries and keys small enough to sit in on-chip memory, keeps a running maximum and sum so the softmax can be accumulated block by block, and builds the output as it goes. The backward pass recomputes the blocks it needs instead of storing them.

It is exact. The output matches standard attention to floating-point noise, it performs slightly more arithmetic rather than less, and the entire win is memory traffic. It also makes attention memory linear in sequence length rather than quadratic, which is what let context windows grow at all. If it appears in a list beside sparse and linear attention as another approximation, that is the thing to correct.

Where people go wrong

Revising the 2017 architecture and describing that in an interview. Nothing in production runs plain multi-head attention with learned absolute positions and a GELU feed-forward layer, and naming what replaced each part, and what it bought, is what is being tested.

If this comes up in an interview

What is grouped-query attention and why does it matter?

Several query heads share one key and value head instead of each having its own. The KV cache shrinks by exactly that ratio, so a model with 32 query heads and 8 key and value heads has a quarter of the cache. Since the cache rather than the weights usually caps concurrency, that is four times the requests or four times the context for the same memory. Quality drops slightly, and more so for multi-query attention with a single shared pair, which is why eight is the usual compromise.

Then they push further

You need more concurrency still. What next?

Quantize the cache, cap context length, use an engine that allocates cache in pages so nothing is reserved and wasted, and consider a model with windowed attention layers, where the cache stops growing past the window.

Does it make the weights smaller too?

Only slightly. The key and value projection matrices shrink by the same ratio, but they are a small share of a layer's parameters. The cache is where the saving is.

What gets marked up. Strong answers give the ratio and connect it to concurrency rather than to speed. Saying it makes the model faster without mentioning the cache misses the point.

Why did rotary position embeddings replace learned absolute positions?

A learned table has a fixed number of rows, so there is nothing for a position beyond the training length, and it encodes absolute position when what attention needs is relative distance. RoPE rotates queries and keys by an angle proportional to position, so their dot product depends only on the gap between them. Extending context means rescaling those frequencies, which works to a point and costs some retrieval quality.

A model card says 120 billion total parameters and 5 billion active. What does that tell you about serving it?

It is a mixture of experts: a router picks a couple of experts per token, so compute per token is that of a 5 billion parameter model while all 120 billion must sit in memory. It will be cheap per token and expensive to host. Sizing the GPU from the active figure is the standard mistake.

Then they push further

What is harder about training it?

Keeping the router balanced, which needs an auxiliary loss term or the router collapses onto a few experts, and the all-to-all communication when experts live on different devices.

Is FlashAttention an approximation?

No. It computes exactly the same attention, tiling the work so blocks fit in on-chip memory and using a running softmax so the full scores matrix is never written to GPU memory. It does slightly more arithmetic and far less memory traffic, which is the whole speedup, and it makes attention memory linear in sequence length.

Build this: Open the config of two recent open models. For each, work out the KV cache per token from the layer count, key and value head count and head dimension, then recompute it as if every query head had its own. Note which uses RoPE scaling, which uses windowed layers, and whether the parameter count is total or active.

This is one section of Transformers & attention, 26 hours across 4 sections. Read it in full to get the whole topic in order.

Stop 26 of 50 on the AI Engineer route

0 of 50 topics done · 0h behind you, 603h to go

Next on this routeFine-tuningWhen prompting is not enough, and it usually is.18h

What you have marked done is stored in this browser only. It does not reach a server, and clearing site data will clear it.