Key takeaways
- Generation runs in two phases. Prefill processes the whole prompt in parallel, is compute-bound, and sets the time to first token. Decode produces one token at a time, is limited by memory bandwidth, and sets the per-token latency.
- Thanks to the causal mask, an old token's k and v never change, so they can be stored in a KV cache. Each step only computes the new token, turning quadratic repeated work into linear work.
- Cache size =2×L×H×dh×T×B× bytes. Llama 2 7B needs 512 KB per token, and a handful of long conversations can need more memory than the model itself.
- Ways to shrink the cache: GQA and MQA (heads share K and V), MLA (compression), cross-layer sharing, sliding windows, and quantization.
- Batching raises throughput by making one trip of the weights serve many requests. Continuous batching keeps every slot busy; in training, packing plus block-diagonal masks cuts padding waste.
Why the first word always takes a moment
You type a question into a chatbot and hit Enter. There's a short pause, then the first word pops out, and after that the rest pour out quickly, one after another. Why the two different rhythms? And here's another puzzle: a single server is answering thousands of people at once. How does it keep up?
Last episode was about picking the next token. This one is about making generation fast and cheap, and the two key tricks are the KV cache and batching.
Two phases: prefill and decode
Prefill: the model takes your whole question and feeds all of its tokens in together, in a single forward pass. Every one of these tokens is already known, so they can all be processed in parallel. The GPU does one big matrix multiplication and its compute is kept fully busy, so this phase is compute-bound. The result of that one pass is the first token of the reply. The time from hitting Enter until it appears is the time to first token (TTFT).
Decode: from here on, the model can only produce one token at a time, because you can't know the next token until the previous one has been chosen. Generate one, append it, generate the next. Each step handles just one new token, so there's very little math, but every step still has to read all of the model's parameters out of GPU memory. So the bottleneck isn't slow math, it's slow memory reads: decode is memory-bound. The gap between two neighboring tokens is the per-token latency, and it sets how fast the text streams out.
|
Prefill |
Decode |
| Per pass |
whole prompt |
1 new token |
| Bottleneck |
compute |
memory bandwidth |
| Sets |
TTFT |
per-token latency |
Latency and throughput
There are two complementary ways to measure how "fast" inference is, and it's worth keeping them apart:
- Latency: how long it takes to finish a single request, in seconds. It answers "when I ask something, how long until I have the complete reply?"
- Throughput: how many tokens (or requests) the whole machine processes per unit time, counting all requests together, in tokens per second. It answers "how much work does this machine get done per second?"
A request's total latency is the time to first token plus the gaps between all the tokens after it. If the reply has N tokens and ttoken is the per-token latency:
latency=TTFT+(N−1)×ttoken
Plug in some numbers: a TTFT of 0.3 seconds, a per-token latency of 0.02 seconds, and a 200-token reply:
0.3+(200−1)×0.02=4.28 s
Watch out: TTFT is the first thing a user feels. However fast the rest is, if the first word takes ages to appear, the experience feels bad.
Now throughput. Serve one person at a time at 0.02 seconds per token, and throughput is 50 tokens per second. Batch 32 people's requests together and each step gets a little slower, say 0.025 seconds, but every step now produces 32 tokens at once. Throughput jumps to 1,280 tokens per second.
Intuition: Think of a restaurant. Latency is how long one diner waits between ordering and getting their food; throughput is how many diners the restaurant serves in an hour. To serve more diners, each one may have to wait a bit longer. Latency and throughput often trade off, and you'll see this again and again with batching.
No cache: redoing the same work every step
A quick reminder of attention (episode 7): in every layer, each token computes three vectors, a query q, a key k, and a value v. When a new token arrives, it uses its q to score the k of every earlier token, then uses those scores to take a weighted sum of their v's.
Now suppose there's no cache at all. The prompt is three tokens, "The fat cat", and we want to generate four more ("sat on the mat"):
| Step |
Tokens run through the model |
Count |
| 1 |
The fat cat |
3 |
| 2 |
The fat cat sat |
4 |
| 3 |
The fat cat sat on |
5 |
| 4 |
The fat cat sat on the |
6 |
In step two, the k and v for the first three tokens were already computed in step one, yet we compute them all over again, and every later step redoes the entire prefix. That's 3+4+5+6=18 computations, only 6 of them new: two thirds of the effort is wasted. If we store every k and v once it's computed, each step only handles the new token: 3+1+1+1=6 in total.
In general, without a cache, generating n tokens costs
1+2+⋯+n=2n(n+1)≈2n2
computations; with a cache, it's just n. With n=1000, that's 500,500 versus 1,000, a factor of 500. The longer the output, the bigger the gap.
Watch out: With a cache, the new token still attends to the entire history. But that only means reading k and v from the cache and doing dot products, which is far cheaper than running the whole prefix through the model again.
Why caching works: old k and v never change
Why are we allowed to reuse old keys and values? Once a new token joins, don't they change? The key is the causal mask: each token can only see itself and the tokens before it, never the ones after. Follow the chain:
- A new token arrives (say "on"). The attention matrix grows by one row and one column, and in every old row, that new column is masked out.
- So the old tokens' attention results don't change one bit, which means their output from this layer doesn't change either.
- The next layer's k and v are computed from exactly this output, so they don't change either.
- Keep going layer by layer: an old token's k and v never change, in any layer.
So what does the new token actually need to compute? Just the last row of the attention matrix: its own q, plus every k and v. An old token's q was used exactly once, in its own row, and is never needed again. That's why we cache only K and V, never Q.
As a formula, the new token's output for this layer is:
onew=softmax(dqK⊤)V
qK⊤ gives the new token's score for every token so far, itself included. Divide by d, apply softmax to turn scores into weights, and multiply by V. The K and V here are the entire history, straight from the cache.
The KV cache: one new column per step
So the fix is simple: as soon as a token's k and v are computed, store them and reuse them from then on. That storage is the KV cache. It trades memory for compute, and it's the cornerstone of fast inference.
- Prefill: the three prompt tokens are processed in one go, and their keys and values fill the first three columns of the cache.
- First decode step: the token we just generated, "sat", goes in as input. It computes only its own q, k and v, and appends its k and v as the fourth column. Its q is scored against all four keys, giving four attention weights, and those weights give a weighted sum of the four values: this layer's output.
- Every step after that: process the next token and append another column. The cache grows one column at a time.
Intuition: It's like reading a book where every page depends on what came before. Rather than rereading from page one each time, you jot down notes as you go (the cache) and just glance at them before reading the next page.
And don't forget: every layer has its own attention, so every layer keeps its own KV cache. A 32-layer model has 32 of them.
In code, the cache is allocated up front for the maximum length, with shape (batch, num_heads, max_seq_len, head_dim), and in practice it's stored inside the self-attention module (self.kv_cache). A single-token forward pass handles only the new token and reuses the cached K and V:
# Pre-allocate cache based on max_seq_len
kv_cache = [
{
'k': torch.zeros(batch, num_heads, max_seq_len, head_dim, device='cuda', dtype=torch.float16),
'v': torch.zeros(batch, num_heads, max_seq_len, head_dim, device='cuda', dtype=torch.float16),
}
for _ in range(num_layers)
]
# For attention, use cache[:, :, :position+1, :] as keys/values
def forward_with_cache(model, new_token, kv_cache, position):
"""
Instead of processing full sequence, process just the new token
and reuse cached K, V from previous positions.
"""
# Embed just the new token
x = model.embed(new_token) # (batch, 1, d_model)
for layer_idx, layer in enumerate(model.layers):
q, k, v = layer.qkv_proj(x).chunk(3, dim=-1)
# Update cache
kv_cache[layer_idx]['k'][:, :, position, :] = k.squeeze(2)
kv_cache[layer_idx]['v'][:, :, position, :] = v.squeeze(2)
# Attend over all cached positions
k_full = kv_cache[layer_idx]['k'][:, :, :position+1, :]
v_full = kv_cache[layer_idx]['v'][:, :, :position+1, :]
x = attention(q, k_full, v_full)
x = layer.ffn(x)
return model.lm_head(x)
Each decode step writes the new k and v into slot position, then takes the first position+1 slots and runs attention on them with the new token's q.
Watch out: Pre-allocating for the maximum length is easy to write, but most conversations never get that long, so the extra slots just sit there hogging GPU memory. That's why inference frameworks like vLLM use a technique called PagedAttention: the cache is cut into small pages, and each request only gets as many pages as it actually uses.
How big is the KV cache?
The KV cache trades memory for compute, so how much memory does it take? Count it out on a toy model first. One head stores a 4-dimensional k and a 4-dimensional v: 8 numbers. Two heads per layer make 16; two layers double it to 32. That's the cache for one token. Five tokens make 160 numbers, and at 2 bytes per 16-bit float, that's 320 bytes:
2×4×2×2×5=160,160×2 bytes=320 bytes
The general formula:
KV cache=2×L×H×dh×T×B×bytes
L is the number of layers, H the number of heads, dh the dimension per head, T the sequence length, B the batch size, and the last factor is bytes per number. The 2 at the front is there because we store both K and V. In other words, a standard multi-head attention cache scales as num_layers × num_heads × seq_len × head_dim × 2.
Now a real model, Llama 2 7B: 32 layers, 32 heads per layer, 128 dimensions per head, 2 bytes per number. For a single token:
2×32×32×128×2=524288 bytes=512 KB
Half a megabyte. A 4,096-token conversation: 512 KB times 4,096 is exactly 2 GB. Serve 16 of those at once and the cache comes to 32 GB, while the weights themselves are only about 13 GB. The cache is bigger than the model! On an 80 GB GPU, once you subtract the weights, a rough estimate leaves room for about 33 such conversations, at most.
Intuition: Total inference memory = model weights + KV cache + peak activations. With small batches and short sequences, the weights dominate; with big batches, the KV cache and activations both grow.
Why decode is slow: moving data costs more than math
Why is decoding memory-bound? Some rough math for Llama 2 7B on a single A100 GPU:
- Moving data: every parameter takes part in one multiply-add per generated token, so all 13 GB of weights have to travel from memory to the compute cores on every single step. The A100's memory bandwidth is about 2 TB per second, so one full trip takes around 6.5 milliseconds.
- Doing math: 7 billion parameters, one multiply-add each, is about 14 billion operations. The A100 can do roughly 312 trillion per second, so that takes only about 0.04 milliseconds.
The compute cores spend more than 99% of their time waiting for data. That's what memory-bound means. Prefill is a different story: one trip of the weights serves a thousand prompt tokens, so the math takes over 40 milliseconds (about 43), far longer than the 6.5 ms of data movement. Now the bottleneck is compute.
So what can we do about decoding? The weights have to make the trip anyway, so make each trip serve lots of requests: line up the new tokens from 16 users into one batch and multiply them together. One trip of the weights now yields 16 tokens. While conversations are short, each step takes almost exactly as long as before, but throughput goes up nearly 16 times. That's the fundamental reason for batching.
But one thing can't be shared: each sequence's own KV cache, which also has to be read in full on every step. With 16 conversations of 4,096 tokens, the cache totals 32 GB, more than the weights, and reading it becomes the biggest cost of each step (data movement stretches to about 22 ms).
Watch out: The size of the KV cache decides not only how many people you can serve at once, but also how fast every step runs.
Shrinking the KV cache
The cache takes up a lot of room. Can we shrink it? Look back at the formula: every factor is a place to attack.
Trick 1: heads share K and V (MQA and GQA)
- Multi-head attention (MHA): the standard setup, where every query head has its own K and V.
- Multi-query attention (MQA): all heads share one set of K and V, and each head keeps only its own q. The cache shrinks by a factor of
num_heads (down to one eighth with 8 heads), and inference gets faster and more memory-efficient.
- Grouped-query attention (GQA): split the heads into groups, and each group shares one set of K and V. It's the middle ground between MHA and MQA. With 8 heads in two groups, the cache shrinks to a quarter.
The catch: when heads share K and V, they all pull information from the same place, so each head loses some representational capacity, and model quality can drop.
Llama 3 8B does exactly this: 32 query heads, but only 8 KV heads. Compared with Llama 2 7B, which also has 32 layers and 128 dimensions per head:
Llama 2 7B:Llama 3 8B:2×32×32×128×2=512 KB2×32×8×128×2=128 KB
Exactly a quarter per token. So the H in the formula, strictly speaking, is the number of K and V heads. Lots of mainstream open models use GQA today.
Trick 2: compress into a latent vector (MLA)
The second trick comes from DeepSeek V2: multi-head latent attention (MLA). Instead of caching K and V themselves, with shape (seq_len, num_heads × head_dim), it caches one much smaller compressed (latent) vector, with shape (seq_len, latent_dim). At each decoding step, a matrix projects it back up to full size, rebuilding K and V for every head. Each head still has its own separate K and V; they're just compressed into one shared latent space and rebuilt from the same vector.
The numbers: DeepSeek V2 has 128 heads of 128 dimensions each. Done the standard way, each token in each layer needs 2×128×128=32768 numbers. MLA stores a 512-dimensional compressed vector plus a 64-dimensional position part, 512+64=576 numbers, about one fifty-seventh of the original.
Two costs:
- Inference needs an extra computation to project the latent vector back into K and V.
- It doesn't play nicely with RoPE from episode 8. RoPE's rotation depends on position, and with that rotation stuck in the middle, the math trick behind the compression stops working. So DeepSeek V2 sets aside 64 extra dimensions just to carry position information: that's the extra 64 in the 576.
Watch out: MHA → GQA → MQA is a spectrum: ever more memory-efficient, but with less capacity per head; GQA is the compromise in the middle. MLA takes a different road. Instead of sharing heads, it saves memory by compressing into a latent space, while each head keeps its own K and V.
Trick 3: share across layers
Cross-layer attention: let neighboring layers share one KV cache, and the L term in the formula is cut in half.
Trick 4: local attention (sliding window)
Local attention, also called a sliding window: instead of looking at the whole history, each token looks only at the most recent W tokens.
- In standard attention, every token looks at all the tokens before it, so compute grows with the square of the length (O(n2)) and the cache keeps growing.
- With a window, each of the n tokens does O(W) work, so compute is O(nW).
- Once a token falls out of the window, nobody will ever look at it again, so its k and v can simply be thrown away. The cache is capped at the window length W and becomes independent of sequence length. Mistral 7B, for example, uses a window of 4,096.
The price is that a token can't directly see anything further back. But as layers stack up, information still gets passed along, one window at a time, reaching further and further back. Many models also alternate local layers with global ones.
Trick 5: quantization
The most direct trick: store the numbers more cheaply. Going from 16 bits to 8 halves the cache; going to 4 bits leaves a quarter. The cost is a little precision. That's quantization, the topic of episode 16.
Summary: which factor each trick cuts
Regroup the formula as
L×(2×H×dh)×T×B×bytes
| Method |
Cuts |
| GQA / MQA |
heads H |
| MLA |
the whole 2×H×dh block |
| Cross-layer |
layers L |
| Sliding window |
length T (capped at W) |
| Quantization |
bytes per number |
MLA replaces the whole 2×H×dh block with one small compressed vector. And these tricks can be stacked on top of each other.
Batching, part 1: static and dynamic
Now batching. We saw that if decoding groups many requests into a batch, one trip of the weights serves everyone. The question is how to form the batches.
The simplest approach is static batching, also called traditional batching: gather a fixed number of requests, say 4, and start them together; only once the whole batch has finished do you move on to the next. Each request first does one prefill step, then decodes step by step until it's done.
Here's the problem. In the video's example, D needs only 3 steps and B only 4. After that their slots sit empty, waiting for the slowest request, A, to finish, while the next four requests, already waiting in line, lose 10 whole steps. Out of 72 cells, only 46 do real work: a utilization of just 64%. In an extreme case, one request generates 500 tokens and another only 10, and the short one sits idle for 490 steps.
One improvement is dynamic batching: instead of stubbornly waiting for a full batch, send it off as soon as it's full (say, 4 requests) or once a time limit runs out (say, 50 ms), whichever comes first. That fixes how long you wait to get started when requests trickle in slowly. But once the batch leaves, it's still all in together and all out together, so the idling problem remains.
Batching, part 2: continuous batching
A better approach is continuous batching. Instead of scheduling batch by batch, it schedules step by step: after every decode step, it checks again. Whoever has finished leaves, and the next request in the queue immediately takes the slot it freed, without waiting for the rest of the batch. The batch is always full, and the GPU never sits idle.
With static batching, the same 8 requests took 18 steps; with continuous batching, they're all done in 14. As long as requests are waiting, the slots stay almost always full. For requests waiting in line, the win is even bigger: E didn't finish until step 15 under static batching, and now it's done by step 8.
Intuition: Static batching is like a tour bus: it only leaves once it's full, and when people get off along the way, their seats stay empty. Continuous batching is like a subway: someone gets off, and someone else gets right on, so the car is almost always full.
The idea comes from a 2022 system called Orca, and today all the major inference frameworks, like vLLM, use it.
Selective batching: mixing prefill and decode
Continuous batching creates a new problem. A request that just joined has to do its prefill first, while the others in the batch are decoding. How do both phases fit into one batch? Selective batching handles it like this:
- Flatten all the tokens into one long row: for example, the 5 prompt tokens of the new request E, plus one decode token each for A, C and F.
- The linear layers and the MLP work on each token separately anyway, so they can all be done in one big matrix multiplication.
- Only attention has to be split up by sequence: each request uses its own q to look up its own KV cache.
Mixing them has a bonus: prefill is compute-heavy and decode is memory-bound, so together they use both the compute and the memory bandwidth more fully.
Batching in training: packing and attention masks
Batching isn't just for inference. In training and fine-tuning, the examples in a batch come in different lengths, which causes a similar kind of waste.
The traditional fix is to pad the shorter examples with a special PAD token until they're all the same length. Those padded positions still go through the computation, which is pure waste: in the video's three examples of length 8, with only 3, 2 and 3 real tokens, 16 of the 24 positions are padding.
Sequence packing lays several short examples end to end instead, joining them into one sequence close to the maximum length. 8 positions, and not one is wasted.
But there's a catch. With an ordinary causal mask, tokens from a later example can see the earlier examples through attention, so the examples leak into each other. The fix is to change the attention mask so each token can only see earlier tokens from its own example. The mask becomes a few small triangles lined up along the diagonal: a block-diagonal mask.
Another approach is token-budget batching, used mostly in fine-tuning. It starts from a simple fact: GPU memory use is set, roughly, by batch_size × sequence_length. So instead of fixing how many examples go in a batch, fix the total number of tokens: after padding to the longest example in the batch, the total must stay within the budget. Short examples? Pack in more. Long ones? Fewer. For instance 16 × 256, 8 × 512 and 4 × 1024 are all 4,096 tokens.
Recap
- Inference has two phases: prefill processes the whole prompt in parallel, is compute-bound, and sets the time to first token; decode goes one token at a time, is memory-bound, and sets the per-token latency. Keep latency (how long one request takes) apart from throughput (tokens per second for the whole machine).
- The causal mask means an old token's k and v never change, so they go in the KV cache, and each step computes only the new token: about n2/2 of repeated work becomes n. Cache K and V, never Q.
- Cache size =2×L×H×dh×T×B× bytes; Llama 2 7B needs 512 KB per token. The cache decides both how many users fit and how fast each step runs.
- To shrink it: GQA and MQA share K and V across heads, MLA compresses into a latent vector, cross-layer sharing cuts layers, sliding windows cap the length, and quantization cuts the bytes.
- Batching raises throughput by reusing the weights. Continuous batching keeps the slots full, and selective batching mixes prefill with decode. In training, packing with block-diagonal masks and token-budget batching cut padding waste.
One last clue: during decoding, most of the compute sits idle, and checking several tokens at once takes about as long as generating one. Can we take advantage of that? That's next episode: speculative decoding.