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.
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
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.
Top: prompt tokens enter in one pass. Bottom: answer tokens leave one per pass. Press Play, then drag the two lengths.
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.
Chapter 1
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.
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.
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:
C equals two times L times K times H times S times b.
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.
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).
Chapter 2
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:
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.
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.
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:
I-attention equals S times T, over S plus T.
Divide 4BSTD FLOPs by 4BSD + 4BTD bytes. The batch B and width D cancel, leaving S times T over S plus T.
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.
The MLP (purple) and attention (blue) on the H100 roofline. Pick a phase, then drag the batch.
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).
Chapter 3
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:
t equals W plus B times C, over M.
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.
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 B | Memory read | Step t | Per user | Throughput |
|---|---|---|---|---|
| 1 | 26.9 GB | 8.0 ms | 125 tokens/s | 125 tokens/s |
| 64 | 79.7 GB | 23.8 ms | 42 tokens/s | 2,689 tokens/s |
| 256 | 240.8 GB (does not fit in 80) | 71.9 ms | 14 tokens/s | 3,562 tokens/s |
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.
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.
Chapter 4
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.
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.
Chapter 5
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:
Blocks equals the ceiling of n over sixteen. Waste equals sixteen times blocks, minus n.
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.
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.
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.
Chapter 6
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:
MLA stores d-c plus d-R numbers, versus two times n-h times d-h for MHA.
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.
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.
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.
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.
Chapter 7
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:
q equals round of one hundred twenty-seven times x over m.
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 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%.
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.
Chapter 8
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:
Keep of x equals the min of one, and q of x over p of x.
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.
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:
E equals one minus alpha to the k plus one, over one minus alpha.
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.
α = 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.
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.
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).
Chapter 9
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.
Top: memory against the GPUs' capacity. Middle: one step's read time and math time; the longer one wins. Bottom: what users see.
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
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.
| Idea | Rule or number | Why it matters |
|---|---|---|
| Two phases | prefill compute-bound, decode memory-bound | 13B: prompt at 38,000 tokens/s, answer at 124 |
| KV cache | C = 2 × L × K × H × S × b | 13B: 819 KB per token; 70B: 1.34 GB per 4,096 tokens |
| Intensity | MLP ≈ B × T; attention S T / (S + T) | decode: B and about 1, against a ridge of 295 |
| Step time | t = (W + B × C) / M | 13B, B = 64: 23.8 ms, 2,689 tokens/s |
| Continuous batching | refill slots after every step | toy: 33 steps to 21, slots 53% to 83% busy |
| PagedAttention | waste < one block of 16 | older systems: 20.4% to 38.2% of cache used |
| GQA | cache × K / N | 13B with 8 heads: B = 256 fits, 12,432 tokens/s |
| MLA | dc + dR = 576 per token per layer | 57 times less than MHA's 32,768 |
| Quantization | q = round(127 x / m) | 13B, B = 1: 8.0 ms (bf16), 4.1 (int8), 2.2 (int4) |
| Speculation | E = (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
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.
lecture_10.py).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.