Inference

Each new token reads every weight and the whole KV cache from memory. On one H100, Llama 2 13B gives one user at most 125 tokens a second and uses 0.3% of the GPU's math. A batch of users shares each read.

Pick a batch size. Watch one read of memory serve more users, until the cache no longer fits. Then give the model 8 key-value heads. Then we build it piece by piece: the cache, intensity, batching, paging, smaller caches, fewer bits and speculation.

You need the KV cache from Lecture 3 and the roofline from Lecture 5. We build the rest from zero.

Lecture 10 of Stanford CS336, Language Modeling from Scratch (Spring 2025, Percy Liang and Tatsunori Hashimoto). Previous: Lecture 9, Scaling Laws I. Next: Lecture 11, Scaling Laws II.

Share one read

The lecture's Llama 2 13B shape (40 layers, 40 heads of 128, MLP width 13,824), bf16, 1,024 tokens per sequence, one H100 SXM (3.35 TB/s, 80 GB). Step time is the lecture's bound: bytes read divided by bandwidth. 8 key-value heads is the lecture's what-if; the released 13B has 40. The time bar fills at an illustrative pace; its length and the read-out are the computed times.

Chapter 0

The Slow Token

Time one request in two phases and see why the answer takes 76 times longer than the question

You serve Llama 2 13B on one H100. A user sends a 1,024-token prompt and asks for 256 tokens back. The GPU reads the whole prompt in 27 ms. Then it spends 2.06 seconds writing the answer, about 8 ms per token.

Inference means running a fixed, trained model to answer prompts. It has two phases. Prefill runs every prompt token through the model in one pass, as training does. Decode then makes the answer one token at a time, because each token depends on the one before it.

Run one request

Top: prompt tokens enter in one pass. Bottom: answer tokens leave one per pass. Press Play, then drag the two lengths.

1,024
256

Roofline bounds for the lecture's Llama 2 13B on one H100 (989 TFLOP/s, 3.35 TB/s). Prefill counts the weight matmuls only. Each decode step reads the 26 GB of weights plus the cache so far. The times are computed; the chips are illustrative.

Why so different? Prefill multiplies each weight by 1,024 tokens at once, so the math units stay busy. Decode multiplies each weight by one token. The GPU still reads all 26 GB of weights for that one token. At 3.35 TB/s the read takes 7.8 ms, and the math takes 0.03 ms.

Prefill: 2 × 13.0 billion × 1,024 = 26.7 trillion FLOPs; at 989 trillion a second that is 27 ms, about 38,000 tokens a second. Decode: about 124 tokens a second. Per token, prefill runs 306 times faster.

The lecture names three numbers to watch:

Inference is not only chat. Every evaluation runs it. Thinking at test time multiplies it. Reinforcement learning samples millions of answers to score. Training is paid once; inference is paid on every token.

Symptom: a server reports thousands of tokens a second, but each user sees a slow stream.

Measure: split the time into TTFT (prefill) and seconds per answer token (decode).

Fix: treat them as two workloads with different limits. The rest of this lesson is about decode.

The road

  1. The KV cache: remember past keys and values instead of recomputing them.
  2. Arithmetic intensity: why decode sits far below the ridge.
  3. Latency and throughput: what a batch buys and what it costs.
  4. Continuous batching: refill a slot the moment it frees.
  5. PagedAttention: store the cache in small blocks, like an operating system.
  6. Smaller caches: GQA, MLA, shared layers and local windows.
  7. Fewer bits: quantization, outliers and pruning.
  8. Speculative decoding: guess cheaply, check exactly.
  9. Showcase: size a whole serving setup.
  10. Field guide: the numbers, the formulas in code, the checks.
Decoding Llama 2 13B on one H100 takes about 8 ms per token. What sets that time?

Chapter 1

The KV Cache

Keep each past token's keys and values, so a decode step runs one new token instead of the whole history

The simplest generator feeds the whole history back into the model for every new token. Each pass over T tokens does attention work that grows like T2, so T new tokens cost about T3. Almost all of it repeats.

In a decoder, a past token never sees the future. So its keys and values, in every layer, are the same at every later step. The model can store them once. That store is the KV cache: for every sequence, every past token, every layer and every key-value head, one key vector and one value vector.

Recompute or remember

Each row is one step; each cell is a token the step pushes through the model. Drag the number of new tokens, then switch the cache on.

12

An illustrative 8-token prompt. The cache bytes use the lecture's Llama 2 13B shape: 819 KB per token in bf16.

With the cache, a decode step computes a query, key and value for the new token only. It appends the new key and value, then reads all the past ones. Why not cache queries too? Attention needs a token's query only once, when that token is new.

How big is the cache? Call the number of layers L, the key-value heads per layer K, the numbers per head H, the tokens in the sequence S and the bytes per number b. The cache for one sequence holds:

Say it aloud

C equals two times L times K times H times S times b.

C
C the bytes of cache one sequence holds.
2
two one key and one value.
L
L the number of layers; each keeps its own cache.
K
K the key-value heads per layer: 40 in Llama 2 13B, 8 in Llama 2 70B.
H
H the numbers in one head's key: 128.
S
S the tokens in the sequence so far, prompt plus answer.
b
b the bytes per number: 2 in bf16.
In plain words

For each layer L, each key-value head K and each token S, store a key and a value of H numbers. Multiply the counts, then multiply by b bytes.

With numbers

Llama 2 13B (the lecture's shape): 2 × 40 × 40 × 128 × 1,024 × 2 = 839 MB per 1,024-token sequence, or 819 KB per token. Llama 2 70B (L = 80, K = 8): 1.34 GB per 4,096-token sequence. A batch of 64 such 13B sequences holds 53.7 GB of cache, twice the weights.

The cache trades memory for compute. For 1,024 prompt tokens and 256 new ones, the generator without it pushes 294,784 tokens through the model. With it, 1,279. Lecture 3 shows how sharing key-value heads (GQA) cuts K.

Symptom: each generated token takes longer than the one before, from the first token on.

Measure: log the tokens fed into the model per step. If it grows with the step, there is no cache.

Fix: feed only the new token and pass the cache back in (in Hugging Face, use_cache=True with past_key_values).

A model has 32 layers, 8 key-value heads of 128 numbers, and stores the cache in bf16. How many bytes does one token add?

Chapter 2

Arithmetic Intensity

Count FLOPs per byte for the MLP and for attention, and see why batching helps one and not the other

Lecture 5 gave the test. Arithmetic intensity is the FLOPs an operation does per byte it moves to or from GPU memory. An H100 does 989 trillion FLOPs and moves 3.35 trillion bytes a second, so its ridge is 295. Below 295 the GPU waits on memory.

Take one layer's MLP. Call the batch B, the new tokens per sequence T, the model width D and the MLP width F. The lecture's gated MLP has three D × F weight matrices and does three matmuls of 2BTDF FLOPs. In bf16:

Say it aloud

I-MLP equals six B T D F, over four B T D plus four B T F plus six D F. That is about B times T.

IMLP
I-MLP the MLP's FLOPs per byte.
6BTDF
six B T D F the FLOPs: three matmuls, each 2 FLOPs per multiply-add. B is the batch, T the new tokens per sequence, D the model width, F the MLP width.
4BTD + 4BTF
four B T D plus four B T F the bytes of activations: X read and the output written (2 bytes each, D wide), two F-wide results written.
6DF
six D F the bytes of weights: three D × F matrices at 2 bytes.
≈ B × T
about B times T what is left when B × T is much smaller than D and F, so the weights dominate the bytes.
In plain words

Each weight is read once and used once for every token in the batch, B times T tokens. So the FLOPs per byte is about the number of tokens processed together.

With numbers

Llama 2 13B, D = 5,120, F = 13,824. Decode (T = 1) with B = 1: I = 1.00. With B = 64: 63.3, still under the ridge. Prefill of one 1,024-token prompt (B = 1, T = 1,024): 866, above it.

Attention is different. Each sequence reads its own cache, so the batch shares nothing. Call the tokens already in the cache S. Attention reads Q and the cached K and V, and writes its output:

Say it aloud

I-attention equals S times T, over S plus T.

Iattn
I-attention attention's FLOPs per byte, with a fused kernel such as FlashAttention.
S
S the tokens attended to: the cache length.
T
T the new tokens: the prompt length in prefill, 1 in decode.
In plain words

Divide 4BSTD FLOPs by 4BSD + 4BTD bytes. The batch B and width D cancel, leaving S times T over S plus T.

With numbers

Prefill, S = T = 1,024: I = 1,024 × 1,024 / 2,048 = 512. Decode, T = 1: 1,024 / 1,025 = 0.999. Below 1 for any cache length and any batch.

Place both layers on the roofline

The MLP (purple) and attention (blue) on the H100 roofline. Pick a phase, then drag the batch.

1

Intensities from the two formulas with the Llama 2 13B widths, bf16, and the H100's dense bf16 peak and bandwidth. Attainable FLOP/s is min(peak, intensity × bandwidth).

The lecture's summary: prefill is compute-bound, decode is memory-bound. A bigger batch lifts the MLP toward the ridge while the batch fits in memory. Attention stays near 1.

Symptom: at long contexts, doubling the batch barely raises tokens per second.

Measure: the share of step time spent reading caches. Attention's intensity is about 1, whatever B is.

Fix: fewer cache bytes per token: Chapter 6 (architecture) and Chapter 7 (bits).

Why does a larger batch raise the MLP's intensity during decode but not attention's?

Chapter 3

Latency and Throughput

Price one decode step in bytes, and trade each user's speed for the server's total

If decode is memory-bound, a step's time is the bytes it reads divided by the bandwidth. The lecture makes this estimate, assuming compute and memory overlap perfectly and nothing else costs time.

Call the bytes of weights W, the cache bytes per sequence C (Chapter 1), the batch B and the memory bandwidth M. One step reads every weight once and every sequence's cache once:

Say it aloud

t equals W plus B times C, over M.

t
t the time of one decode step, in seconds. Each user gets one token per step.
W
W the bytes of weights: 13.0 billion parameters × 2 = 26.0 GB.
B
B the sequences decoded together.
C
C the cache bytes of one sequence: 0.839 GB at 1,024 tokens.
M
M the memory bandwidth: 3.35 × 1012 bytes per second.
In plain words

Add the weights W to B caches of C bytes each. Divide by the bandwidth M. The batch makes B tokens in that time, so the throughput is B divided by t.

With numbers

B = 64: t = (26.0 + 64 × 0.839) GB / 3,350 GB/s = 23.8 ms. Each user gets 1 / t = 42 tokens a second. The server makes 64 / t = 2,689.

Batch BMemory readStep tPer userThroughput
126.9 GB8.0 ms125 tokens/s125 tokens/s
6479.7 GB23.8 ms42 tokens/s2,689 tokens/s
256240.8 GB (does not fit in 80)71.9 ms14 tokens/s3,562 tokens/s

Trade latency for throughput

Throughput (pink) climbs with the batch; each user's speed (blue) falls. Drag the batch and the context; watch where the GPU's 80 GB runs out.

64
1,024

The lecture's bound for Llama 2 13B on one H100: t = (W + B × C) / M. We checked that the step's compute stays below its memory time at every point drawn.

Throughput grows 21 times from B = 1 to 64, then only 1.3 times more to 256, and 256 does not fit. Each step re-reads the weights, but the caches grow with B.

Two more levers, from the lecture. Run M copies of the model on M GPUs: latency stays the same and throughput grows M times. And TTFT is prefill, so use small batches for prefill and large ones for decode.

Symptom: the server runs out of memory as more users join, though the weights fit easily.

Measure: compare B × C with the memory left after W. At 1,024 tokens, 13B leaves room for 64 sequences.

Fix: a smaller C per sequence (Chapters 5 to 7), or cap the batch.

Using t = (W + B × C) / M with W = 26 GB and C = 0.84 GB, about what throughput does B = 32 give on an H100?

Chapter 4

Continuous Batching

Schedule the batch one step at a time, so a finished request's slot takes a new one at once

Training gets a neat block of tokens: batch by sequence length. Live traffic arrives ragged. Requests come at different times, and their answers have different lengths. The lecture lists three problems: waiting to fill a batch delays early requests, sequences share prefixes, and padding wastes work.

Static batching takes B requests, decodes until the longest one ends, and only then takes the next B. A 3-token answer holds its slot while a 14-token answer finishes. Its slot sits empty for 11 steps.

Continuous batching, from the Orca system (Yu et al., OSDI 2022), schedules at the level of one iteration. After every decode step, the server removes finished requests and adds waiting ones. The lecture calls this iteration-level scheduling.

Schedule ten requests on four slots

Each bar is one request in a slot; time runs right, one column per decode step. Pick a scheduler and press Play.

An illustrative workload: ten requests, all waiting at step 0, needing 6, 14, 3, 9, 4, 12, 5, 8, 2 and 7 decode steps. Prefill is not drawn.

Count the work. The ten requests need 70 token-steps. Static batching takes 33 steps, so its 4 slots are busy 70 / 132 = 53% of the time. Continuous batching takes 21 steps: 83% busy. The average request finishes at step 12.1 instead of 22.6.

One wrinkle. A batch is a single tensor, but these sequences have different lengths. Orca's answer is selective batching. The MLP, norms and projections act on each token alone. So the server lays all tokens end to end: lengths 3, 9 and 5 become one 17 × D matrix. Attention runs per sequence, because each has its own cache.

Symptom: short answers wait for long ones, and GPU slots sit idle at the end of each batch.

Measure: slot use = token-steps done / (slots × steps). Static batching on mixed lengths often lands near 50%.

Fix: iteration-level scheduling, as in Orca, vLLM, TGI and TensorRT-LLM.

In continuous batching, what happens when one request in a batch of 32 finishes?

Chapter 5

PagedAttention

Store each sequence's cache in small blocks anywhere in memory, so reserved space stops going to waste

Before vLLM, a server reserved one contiguous chunk of cache per request, sized for the longest answer it might give. Three kinds of waste follow. Slots reserved for tokens not yet made. Slots never used, if the answer ends early (internal fragmentation). Gaps between chunks too small for a new request (external fragmentation).

Kwon et al. (SOSP 2023) profiled these systems: only 20.4% to 38.2% of their cache memory held real tokens. Their fix, PagedAttention, borrows paging from operating systems. A sequence's cache lives in blocks of 16 tokens, vLLM's default. A block table maps each logical block to a physical block anywhere in memory. The server takes a new block only when the last one fills.

So the waste per sequence is the empty end of its last block. Call the tokens a sequence holds n and the block size 16:

Say it aloud

Blocks equals the ceiling of n over sixteen. Waste equals sixteen times blocks, minus n.

blocks
blocks the physical blocks the sequence holds.
⌈ ⌉
the ceiling of round up to the next whole number: a part-full block is still a block.
n
n the tokens in the sequence's cache.
16
sixteen the tokens per block, vLLM's default.
waste
waste empty token slots in the last block: always fewer than 16.
In plain words

Divide the n tokens by 16 and round up to get the blocks. The slots left over in the last block are the only waste, whatever the answer's length.

With numbers

The paper's OPT-13B holds 800 KB per token, so a 2,048-token reservation is 1.6 GB. An answer that ends at n = 300 wastes 1,748 slots, 85% of it. Paged: blocks = ⌈300 / 16⌉ = 19, waste = 304 − 300 = 4 slots, 3.3 MB.

Fit requests into the cache

Each cell is one token slot of cache. Warm cells hold real tokens; red cells sit reserved but empty. Switch the allocator and count who fits.

Illustrative: 1,024 slots and twelve waiting requests of 120, 40, 200, 75, 18, 150, 64, 33, 96, 90, 140 and 25 tokens. The server admits them in order until one does not fit. We scatter the paged blocks to show they need not touch.

Reserving 256 tokens a request fits 4 of the 12 and uses 42% of memory. Blocks of 16 fit 10 and use 87%. More sequences in memory means a bigger batch. vLLM reports 2 to 4 times the throughput of earlier systems at the same latency.

Blocks also allow sharing. Several samples from one prompt can point at the same physical blocks. When one sequence must change a shared block, vLLM copies it first: copy-on-write.

Symptom: the server admits few requests although most of the cache sits empty.

Measure: tokens stored / cache memory reserved. The vLLM paper measured 20.4% to 38.2% for older systems.

Fix: paged blocks with a block table, and prefix sharing with copy-on-write.

With blocks of 16 tokens, what is the most cache a sequence can waste?

Chapter 6

Smaller Caches

Change the architecture so each token stores fewer numbers: shared heads, a latent vector, shared layers, a local window

Memory is the bottleneck, so shrink the cache. These are lossy shortcuts: they change the model, so you train them in and check accuracy.

Grouped-query attention (GQA) keeps N query heads but only K key-value heads, each shared by N / K query heads (Lecture 3). The cache shrinks N / K times. The lecture's what-if: give Llama 2 13B 8 key-value heads instead of 40 at B = 64. Memory falls from 79.7 to 36.8 GB, the step from 23.8 to 11.0 ms, and throughput rises from 2,689 to 5,831 tokens a second. B = 256 now fits, at 69.0 GB and 12,432 tokens a second.

Multi-head latent attention (MLA), from DeepSeek-V2 (2024), caches one short vector per token instead of all the heads' keys and values. Call the heads nh, the numbers per head dh, the latent size dc and the size of an extra key for position dR. Per token and per layer:

Say it aloud

MLA stores d-c plus d-R numbers, versus two times n-h times d-h for MHA.

MLA
M L A multi-head latent attention: numbers cached per token, per layer.
dc
d-c the latent vector's size: 512 in DeepSeek-V2. The model rebuilds every head's key and value from it.
dR
d-R a small separate key that carries the RoPE position: 64. RoPE does not pass through the low-rank projection.
MHA
M H A multi-head attention: a key and a value for every head.
nh
n-h the attention heads: 128 in DeepSeek-V2.
dh
d-h the numbers per head: 128.
In plain words

MHA stores n-h keys and n-h values of d-h numbers. MLA stores one latent of d-c numbers and one position key of d-R numbers. Divide the two to get the saving.

With numbers

MHA: 2 × 128 × 128 = 32,768 numbers. MLA: 512 + 64 = 576. That is 57 times fewer. The paper notes it equals GQA with 2.25 groups, and reports MLA stronger than MHA in its tests.

Cross-layer attention (CLA, Brandon et al. 2024) shares keys and values across adjacent layers, as GQA shares them across heads; sharing between pairs halves the cache again. Local attention lets each token see only the last W tokens, so the cache stops growing with S. Local layers can lose long-range recall, so models interleave a few global layers. The lecture's example: Character.AI uses one global layer in every six, plus CLA.

Shrink the cache per token

Bars: cache per sequence for each design, on a log scale. Pick a design and drag the context to see who fits in 40 GB.

4,096

One DeepSeek-V2-sized shape for every bar (60 layers, 128 heads of 128, bf16), so only the design changes. The hybrid uses a 1,024-token window on 50 of 60 layers. Bars show memory, not accuracy.

Symptom: after switching to local or heavily shared attention, the model misses facts from early in a long prompt.

Measure: a long-context recall test (hide a fact far back, ask for it) before and after.

Fix: keep some global layers, or more key-value heads.

DeepSeek-V2's MLA caches 576 numbers per token per layer. Its heads would need how many under MHA, and what is the saving?

Chapter 7

Quantization and Pruning

Store each weight in fewer bits, keep the outliers safe, or cut the model down and repair it

Decode time is bytes over bandwidth, so fewer bytes per weight means faster steps. Quantization stores numbers in fewer bits:

For Llama 2 13B at B = 1, the weights shrink and the cache stays bf16. Step time goes from 8.0 ms in bf16 to 4.1 ms in int8 and 2.2 ms in int4.

The simplest scheme is absmax quantization. Call a real number x, the largest magnitude in its group m, and the stored integer q. For int8:

Say it aloud

q equals round of one hundred twenty-seven times x over m.

q
q the stored integer, from −127 to 127.
round
round of to the nearest whole number. This is where precision is lost.
127
one hundred twenty-seven the largest int8 magnitude used; 7 for int4.
x
x the real number: a weight or an activation.
m
m the largest absolute value in the group. To read q back, multiply by m / 127.
In plain words

Stretch the group so its largest value m lands on 127. Round each x to the nearest step. The step size is m / 127, so one big m makes every step coarse.

With numbers

With made-up numbers: fifteen values near ±0.3 (largest 0.66) and one outlier, 9.10. Then m = 9.10 and a step is 0.072, so the typical values use only −9 to 9 and err by 6.8% on average. Without the outlier, m = 0.66, a step is 0.0052 and the error is 0.42%.

Quantize a group with an outlier

Teal dots are the real values; pink ticks are what int8 or int4 brings back. Pick the bits, then keep the outlier in 16-bit.

Made-up values: fifteen ordinary numbers and one outlier of 9.10. Absmax quantization over the group. Error is the mean absolute error on the fifteen ordinary values, relative to their mean size.

Large models have such outliers. LLM.int8() (Dettmers et al. 2022) multiplies the feature dimensions with magnitudes of 6 or more, about 0.1% of them, in 16-bit. BLOOM-176B then fits on 3 A100s instead of 8, at 247 ms per token against bf16's 239. AWQ (Lin et al. 2024) scales up the 0.1% to 1% of weight channels that meet large activations before quantizing. Its 4-bit models use about 4 times less memory and run 3.2 to 3.3 times faster than 16-bit Hugging Face code.

Pruning cuts parts of a model, then repairs it with distillation. NVIDIA's Minitron (2024) scores layers, heads and channels on 1,024 calibration samples and removes the weak ones. Then it distills the original into the smaller model, with up to 40 times fewer training tokens than training from scratch.

Symptom: an int4 model gives garbage in some layers and is fine in others.

Measure: per layer, the ratio of the largest magnitude to the typical one. Big ratios crush the step size.

Fix: keep outliers in 16-bit (LLM.int8), scale salient channels (AWQ), or use smaller groups with their own scale.

Why does int8 weight quantization make decode faster even when the arithmetic is done in bf16?

Chapter 8

Speculative Decoding

Let a small model guess several tokens, check them all in one pass of the big model, and keep its exact distribution

A decode pass over five tokens costs about as much as a pass over one: for Llama 2 13B, 0.13 ms of math inside a 7.8 ms read. It also returns probabilities at every position. So checking tokens is cheaper than making them.

Speculative decoding (Leviathan et al. 2023; Chen et al. 2023) uses this. Call a small draft model's probabilities p and the big target model's q. Each round:

  1. The draft proposes k tokens.
  2. The target scores all k in one pass.
  3. Left to right, keep each token by the rule below.
  4. At the first rejection, draw a fix from the leftover max(q − p, 0), rescaled, and stop. If all pass, draw a bonus token from q.
Say it aloud

Keep of x equals the min of one, and q of x over p of x.

keep(x)
keep of x the chance to accept draft token x.
min
the min of the smaller of the two; a chance cannot pass 1.
q(x)
q of x the target's probability of x.
p(x)
p of x the draft's probability of x.
In plain words

If the draft under-sampled x, q(x) / p(x) is over 1, so keep x. If it over-sampled x, keep it q(x) / p(x) of the time; the leftover puts the missing mass back.

With numbers

The lecture's proof: q(A) = 0.3, q(B) = 0.7, p(A) = p(B) = 0.5. Keep A with 0.6, B always. The leftover (0, 0.2) rescales to (0, 1). A comes out 0.5 × 0.6 = 0.3; B comes out 0.5 + 0.5 × 0.4 = 0.7. Exactly q.

How many tokens does one target pass give? Call the chance that the target keeps a draft token the acceptance rate α. Leviathan et al. show α = Σ min(p, q): 0.8 in the example. A pass yields its run of kept tokens plus one. Assume every position has the same α, independently:

Say it aloud

E equals one minus alpha to the k plus one, over one minus alpha.

E
E the expected tokens per target pass.
α
alpha the acceptance rate.
k
k the draft tokens per pass.
In plain words

The first token always comes. The second comes if the target kept draft token 1, chance α. The third needs tokens 1 and 2, chance α squared, and so on to α to the k. E adds them: 1 + α + α2 + … + αk.

With numbers

α = 0.8, k = 4: E = 1 + 0.8 + 0.64 + 0.512 + 0.41 = 3.36 tokens per pass. Not k α + 1 = 4.2: that counts tokens after a rejection.

Speedup = E / (k c + 1), where c is a draft step's cost as a share of a target pass. An 8B draft for a 70B target: c ≈ 8 / 70 = 0.114, so 3.36 / 1.46 = 2.3 times.

Guess, then check

Four tokens, A to D; the target wants 50, 25, 15 and 10%. Run passes. Watch the run lengths match theory (yellow) and the output match the target.

0.80
4

A toy: the draft blends a poor guess (5, 10, 25, 60%) with the target. Positions are independent, as the formula assumes. The 0.11 draft cost is illustrative.

Chen et al. measured 2 to 2.5 times on Chinchilla 70B; Leviathan et al., 2 to 3 times on T5-XXL. The lecture pairs an 8B draft with a 70B target.

Symptom: speculation speeds up a quiet server but not a busy one.

Measure: checking k + 1 tokens multiplies the math by k + 1; at large batches the step turns compute-bound.

Fix: lower k, or speculate only at small batches (Chapter 9).

With acceptance rate 0.9 and k = 4 draft tokens, how many tokens does one target pass give on average?

Chapter 9

Showcase: Serve a Model

Choose a model, GPUs, a weight format, a cache design, a batch and speculation, and read off memory, speed and the limit

Every chapter in one tool. It sizes the cache (Chapter 1) and times a step as the slower of reading and math (Chapters 2 and 3). It adds fewer key-value heads (Chapter 6), fewer bits (Chapter 7) and speculation with k = 4 and α = 0.8 (Chapter 8). Continuous batching and paging let a real server keep the batch this full.

Size a serving setup

Top: memory against the GPUs' capacity. Middle: one step's read time and math time; the longer one wins. Bottom: what users see.

1
1,024

A roofline bound, not a measurement: each step takes the slower of reading memory and doing the math. We treat several GPUs as one, with memory, bandwidth and peak added and no communication cost: a best case. The cache stays bf16. The draft costs 0.1 of the target's weight read per step (illustrative). First token: prefill of the whole sequence at batch 1.

Things to try. Start on 13B at B = 1: 125 tokens a second, memory-bound (read 8.0 ms, math 0.03 ms). Switch to 70B. Its weights need 138 GB, which does not fit on one H100. Two H100s give 48.5 tokens a second. So does fp8 on one H100, at 69.3 GB; it holds a batch of 32 (1,345 tokens a second) but not 64.

Now speculate. On 13B at B = 1 each user goes from 125 to 302 tokens a second, 2.4 times. On 70B with 4 H100s at B = 256 the gain is only 13%. Checking 5 tokens per sequence multiplies the math by 5: 45.5 ms of math against 16.7 ms of reading.

Check yourself. Before you touch it: does 70B in int4 hold a batch of 64 on one H100? It needs 56.0 GB, so yes, and it makes 3,831 tokens a second.

Chapter 10

Field Guide

Keep the numbers, the formulas in code, and the order to try the fixes

Decode reads every weight and every cache once per token, so it waits on memory. Every fix moves fewer bytes per token or shares each read across more tokens. A bigger batch shares the weights; continuous batching and paging keep the batch full; GQA, MLA and local layers shrink the cache; quantization shrinks every byte. Speculative decoding turns several decode steps into one check, with no change to the output.

IdeaRule or numberWhy it matters
Two phasesprefill compute-bound, decode memory-bound13B: prompt at 38,000 tokens/s, answer at 124
KV cacheC = 2 × L × K × H × S × b13B: 819 KB per token; 70B: 1.34 GB per 4,096 tokens
IntensityMLP ≈ B × T; attention S T / (S + T)decode: B and about 1, against a ridge of 295
Step timet = (W + B × C) / M13B, B = 64: 23.8 ms, 2,689 tokens/s
Continuous batchingrefill slots after every steptoy: 33 steps to 21, slots 53% to 83% busy
PagedAttentionwaste < one block of 16older systems: 20.4% to 38.2% of cache used
GQAcache × K / N13B with 8 heads: B = 256 fits, 12,432 tokens/s
MLAdc + dR = 576 per token per layer57 times less than MHA's 32,768
Quantizationq = round(127 x / m)13B, B = 1: 8.0 ms (bf16), 4.1 (int8), 2.2 (int4)
SpeculationE = (1 − αk+1) / (1 − α)α = 0.8, k = 4: 3.36 tokens per pass

The formulas in code. We ran it. The cache is 0.839 GB. A step at B = 64 gives 42 tokens a second per user and 2,689 in all. 300 tokens fill 19 blocks with 4 slots empty. 200,000 speculative samples come out 30.05% A and 69.95% B, against the target's 30 and 70.

python
import numpy as np

def kv_bytes(L, K, H, S, b=2):            # one sequence's cache: a key and a value per layer, head, token
    return 2 * L * K * H * S * b

def decode_step(W, C, B, M=3.35e12):      # memory-bound bound: read weights once, every cache once
    t = (W + B * C) / M
    return t, 1 / t, B / t                 # seconds per step, tokens/s per user, tokens/s total

def blocks(n, bs=16):                      # PagedAttention: blocks held and empty slots wasted
    nb = -(-n // bs)
    return nb, nb * bs - n

def expected_tokens(alpha, k):             # tokens per target pass: 1 + alpha + ... + alpha^k
    return sum(alpha ** j for j in range(k + 1))

def spec_token(p, q, rng):                 # one draft token, checked exactly against the target q
    x = rng.choice(len(p), p=p)
    if rng.random() < min(1, q[x] / p[x]):
        return x                           # accepted
    r = np.maximum(q - p, 0)
    return rng.choice(len(q), p=r / r.sum())  # rejected: resample from the leftover

C = kv_bytes(L=40, K=40, H=128, S=1024)
print(C / 1e9)                                         # 0.839 GB per sequence
print([round(v, 4) for v in decode_step(2 * 13_015_449_600, C, 64)])   # [0.0238, 42.0231, 2689.4807]
print(blocks(300))                                     # (19, 4)
print(round(expected_tokens(0.8, 4), 2))               # 3.36
rng = np.random.default_rng(0)
p, q = np.array([.5, .5]), np.array([.3, .7])
out = [spec_token(p, q, rng) for _ in range(200_000)]
print(np.bincount(out) / len(out))                     # [0.30052 0.69948], the target's own distribution

Where it sits

The lecture's view: attention plus one-token-at-a-time generation is memory-bound by design. State-space models such as Mamba replace the growing cache with a fixed-size state, and hybrids keep a few attention layers for recall. Diffusion language models generate many tokens in parallel and refine them over several steps. Both trade some of what transformers do well for cheaper inference.

Keep going

Read next

The habit. Before you tune a server, write down three numbers: the bytes one decode step reads, the bandwidth, and the batch. Their ratio is your speed. Then ask which fix removes the most bytes per token.
A batch job runs a 70B model on 2 H100s and only cares about total tokens per second. What should it do first?

Now teach it: press Present or Teach. Explain why decode waits on memory, size a cache, and show why speculation keeps the target's distribution. Then go back to the instrument and predict, before you press it, whether B = 256 fits with 8 key-value heads.

Inference · Stanford CS336, Lecture 10
Previous: Scaling Laws I · Next: Scaling Laws II · Course site · Back to Gleams