Inference
Why is writing an answer so much slower than reading a prompt, and what makes it cheap?
The part opens with a speed limit: to write one token a model reads every active weight, so tokens per second cannot beat the memory bandwidth divided by the bytes of weights, while the chip's arithmetic sits almost idle. On Part 17's roofline a prompt is a matrix product and a decode step a matrix-vector product, and the key-value cache is priced per token for multi-head, grouped-query and latent attention. A server answers by sharing each read among many conversations: batching trades speed against cost, continuous batching keeps the batch full, and pages and shared prefixes keep the memory full. The part then turns to exactness. Speculative decoding lets a drafter guess ahead and the big model check in one pass, and the acceptance rule min(1, p/q) with its leftover is proved to return the big model's distribution; two drafters are trained and timed. Quantization starts from Bennett's rounding error, meets outlier channels, and spends the error where it hurts least with SmoothQuant, GPTQ derived from Optimal Brain Surgeon, and rotations, down to the four-bit floats MXFP4 and NVFP4 and a quantized cache. FlashAttention computes attention in tiles with an online softmax and never writes its table. It ends with constrained decoding by an automaton's token mask and with what longer thinking and on-device models cost in late 2026.
What you need. Probability (total variation, expectations of geometric sums), a Lagrange multiplier, and Part 17's roofline and number formats.
- Mathematics and history
- speculative decoding, quantization (GPTQ, rotations, MXFP4/NVFP4), FlashAttention, paged KV, serving
- Models, data
- gpt-oss
What you will be able to do
Undergraduate
- Explain why a decode step is bound by memory bandwidth and a prefill by arithmetic, and compute the weight-only bound on tokens per second.
- Compute the bytes a key-value cache keeps per token from a model's layers, heads and head size.
Master's
- Prove that speculative sampling outputs the big model's distribution and accepts a draft with probability 1 - TV(p, q), and derive the expected tokens per pass.
- Derive the rounding error of a uniform quantizer and say when the prediction fails.
- Derive the online softmax and FlashAttention's memory traffic, and combine two chunks of keys exactly.
Research
- Derive the Optimal Brain Surgeon update and its error with a Lagrange multiplier, and explain how GPTQ applies it column by column.
- Show that a transformer with unit-gain RMSNorm is invariant to an orthogonal rotation of its residual stream, and explain why a rotation helps four-bit activations.
Engineering
- Size a server: choose a batch, a page size and a prefix cache from the context length, the memory and the price of a GPU-hour.
- Choose a weight format and a scale granularity (per tensor, per row, per block) for a target number of bits, and say what calibration data the method needs.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 15 min · Master's 51 min · Research 57 min · Engineering 28 min.
- 0One token at a timeUndergraduate3 min
- 1Prefill and decodeMaster's3 min
- 2The key-value cache, pricedUndergraduate4 min
- 3Batching: speed against costEngineering3 min
- 4Continuous batchingEngineering3 min
- 5Pages and shared prefixesEngineering3 min
- 6Guess ahead, check at onceMaster's3 min
- 7DraftersMaster's3 min
- 8Rounding errorUndergraduate4 min
- 9Outliers and SmoothQuantMaster's3 min
- 10GPTQ, from Optimal Brain SurgeonMaster's4 min
- 11Rotations: QuaRot and SpinQuantResearch3 min
- 12Four-bit floats: MXFP4 and NVFP4Master's3 min
- 13The cache in fewer bitsEngineering1 min
- 14FlashAttentionMaster's4 min
- 15Attention at serve timeEngineering2 min
- 16Constrained decodingUndergraduate3 min
- 17The frontier, late 2026Research3 min
- Recap, problems, and what comes nextAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
One token at a timeUndergraduate3 min
When a big model writes, it writes one token at a time. And to write each one, it has to read every single one of its weights. For an eight-billion-parameter model, stored as sixteen-bit numbers, two bytes each, that's about sixteen gigabytes, streamed from memory through to the chip, for one token. Then all of it again for the next one, and the next. How many bytes a second can flow from memory to the chip is the memory bandwidth: here, three point three five terabytes a second.
So memory sets a speed limit. Tokens per second can't beat the memory bandwidth divided by the bytes of weights: for Llama 3.1 8B on an NVIDIA H100, about tokens a second, before cache traffic and other overheads. And meanwhile the chip's arithmetic sits almost idle. Running a trained model to get answers, with no learning, just using it, is called inference; it's not part seven's variational inference. And inference is a problem of moving numbers, not multiplying them.
How did we get here? The transformer of 2017 already wrote one token at a time and kept the keys and values of what it had read, the cache of Part 15. In 2019 Noam Shazeer shared one set of keys and values among all the heads, to read less of it. In 2020 GPT-3 went on sale by the token, and the cost of a token became a business. 2022 was the year the ideas of this part arrived: FlashAttention, continuous batching, speculative decoding, and GPTQ's four-bit weights. In 2023, llama.cpp ran a big model on a laptop, and vLLM managed the cache in pages. Then DeepSeek compressed the cache itself, servers split reading from writing, and in 2025 OpenAI released gpt-oss with its experts in four-bit floats. Meanwhile the price of a token fell. A model at least as good as GPT-3 cost sixty dollars per million tokens in 2021, and fifteen cents per million input tokens in 2024: 400 times less.
This is Part 19 of AI, Built, the last part of the third act. In this part: why reading a prompt and writing an answer are different problems; how a server shares one model among many people; speculative decoding, proved exact; quantization, from rounding error to four-bit floats; FlashAttention, derived; and constrained decoding. Every one of them, measured on our own models, on this computer.
1Prefill and decodeMaster's3 min
A model with N parameters does about two N operations for every token it reads: one multiply and one add per weight. And every pass through the model reads every weight once: two N bytes in sixteen-bit numbers. When it writes an answer, a pass handles one new token per conversation. With B conversations in a batch, the intensity, operations per byte, is just B. When it reads a prompt, all T of its tokens go through in one pass, the way they do in training: that's called prefill, and its intensity is T. Part 17's roofline says an H100 only reaches full speed above about 295 operations per byte. A prompt of a thousand tokens is there. Writing for a single conversation, at an intensity of one, is not: decode is bound by memory.
We can watch this happen on this computer. Twelve weight matrices, Multiply a batch of B vectors through all twelve, and time it. The roofline predicts a floor: just reading the weights takes milliseconds, whatever B is, until the arithmetic catches up with the reading. So vectors per second climb from at a batch of one to at : times as much work out of the same weights.
Now our own model, the series' novels model, on the inference engine we wrote for this part. Prefill: one prompt, of T tokens, in a single pass. Decode: one new token for each of B conversations per pass. One conversation is written at 405 tokens a second; each step reads all 5.8 million weights, 9.4 gigabytes a second of them. The same model reads a 256-token prompt at 8,195 tokens a second: 20 times faster, because its tokens share the reading. Batching the decodes buys most of that back: 256 conversations at once get 2,766 tokens a second between them. But each of them now gets only 11. That trade, the speed of one against the work of all, is what a server is built around.
2The key-value cache, pricedUndergraduate4 min
Part 15 built the key-value cache: every token a model has read leaves a key and a value in every attention head of every layer, so that the next token can look back at it without recomputing. With L layers and n h heads of size d h, that's two L n h d h numbers per token. In 2019 Noam Shazeer let all the heads share one key and one value, and in 2023 grouped-query attention found the middle: n g groups, each shared by several query heads. In 2024 DeepSeek went further. Multi-head latent attention caches one compressed vector per token, of size d c, plus a small key that carries the rotary positions, and rebuilds every head's keys and values from it.
Here is what that means for real models. Llama 3.1 70B has 80 layers and 64 query heads of 128 numbers. Give each head its own key and value, and every token costs 2.6 megabytes. It uses eight groups instead, so a token costs 328 kilobytes, 8 times less. DeepSeek-V3's 128 heads, uncompressed, would cost 5 megabytes a token. With MLA, 70 kilobytes: 71 times less, about what grouped attention with 2.25 groups would keep. gpt-oss keeps 74 kilobytes, and our little model 12 kilobytes.
And the cache grows with every token of the conversation. On log scales, each model is a straight line: bytes per token times tokens. Compare the weights. Llama 3.1 70B's weights take 141 gigabytes. With grouped attention, one conversation's cache outgrows them at about 431 thousand tokens; with every head its own, at 54 thousand. And a server holds many conversations at once. One H100 has eighty gigabytes for all of it. gpt-oss bends its line differently: every other layer looks back only 128 tokens, so those layers' caches stop growing, and at 128 thousand tokens it keeps 2.0 times less than full attention everywhere would.
We measured the same thing on our model. A decode step, for batches of 1, 8 and conversations, each with to tokens already cached. Plot the time of a step against the bytes it has to read, and : every step moved between and gigabytes a second. At a batch of and tokens, the caches are megabytes, times the weights, and a step takes times as long as at tokens. Long conversations turn decoding into reading the cache: shrink it, as MLA does; look at less of it, as windows do; or store it in fewer bits, in chapter 13.
3Batching: speed against costEngineering3 min
Every server faces the trade from chapter one. Here it is for our model on this computer: each dot a batch size, its speed for one conversation across, its total work up. Alone, a conversation gets 405 tokens a second. Batched with 255 others, the computer writes 2,766 tokens a second in all, 6.8 times as many, but each conversation gets 11. Up and to the left is cheap; down and to the right is fast. A provider picks a point on this curve, and the price follows.
To see what this means for a real model on a real chip, model it with the roofline. A decode step reads the weights, W bytes, and every conversation's cache: c tokens at kappa bytes each. It can't go faster than the memory, beta. Nor faster than the arithmetic: two N B operations at P a second. And it all has to fit in memory, which caps the batch. The machine's time is shared, so the cost of a token is the price of a second divided by the tokens written per second. We use Llama 3.1 8B on one H100, at two dollars an hour: the rental price DeepSeek used to cost its own service. In 2022 Reiner Pope and colleagues at Google worked through this accounting for PaLM: the same weights, read faster or shared wider.
Here is what the model gives. Each line is a context length; along it, the batch grows from one, down and to the left, until memory runs out. With a thousand tokens of context, one conversation alone costs 2.69 dollars per million tokens. A batch of 416 brings that to 0.029: 94 times cheaper, while each conversation gets 4.4 times slower. Even then the chip does only 33 percent of the arithmetic it could. At 128 thousand tokens, 3 conversations fill the memory, and a token costs at least 3.74 dollars per million. That's why long contexts cost more, and why so much of this part is about shrinking the cache.
4Continuous batchingEngineering3 min
A server has many conversations to write at once, and they don't arrive together or end together. Until 2022 the usual way was static batching: gather a batch, prefill all the prompts, and decode until every answer in the batch is finished. A short answer leaves its slot idle while the longest one goes on, and new requests wait outside. In 2022 a team at Seoul National University proposed the fix, in a system called Orca: schedule at every step instead of every batch. When a conversation finishes, its slot goes to the next one waiting, at the very next step. Here are the same requests both ways, on this computer's measured costs: continuous batching finishes all of them in 9.6 seconds; static batches take 20.4.
With more traffic the difference is stark. We simulated a server on this computer's measured costs: 400 requests arriving at random, a second, with long-tailed lengths, like real chat. Static batches Continuous batching writes , times as many, And the wait for a first token: Serving systems have worked this way ever since.
Continuous batching has a cost of its own. When a new prompt joins, its whole prefill runs inside one step, and every conversation in the batch waits for it. In our simulation the median gap between two tokens of an answer is 13 milliseconds, but the longest is 182. In 2024 Sarathi-Serve cut prompts into chunks, and gave each step a budget: the decodes, plus as much prompt as fits. With chunks of 256 tokens, the longest gap falls to 59 milliseconds, 3.1 times shorter, for almost no change in the median.
There is another way to keep prompts from stalling answers: put them on different machines. Prefill is arithmetic and decode is memory, so in 2024 Splitwise and DistServe gave each its own GPUs, sending each prompt's cache across when it's done. DeepSeek serves V3 this way: prefill on units of GPUs, decode on units of . We tried it in the simulation: four workers that each do both, against one that prefills and three that decode.
5Pages and shared prefixesEngineering3 min
Where in memory should each conversation's cache go? Nobody knows how long an answer will be. Our toy scheduler restarts generation after preemption, and averages give every simulation step equal weight. So servers used to reserve, for every conversation, room for the longest answer allowed, here tokens. Most of it sits empty: in our simulated server, on average only percent of the memory holds a token, and it fits conversations at a time. In 2023 the vLLM team measured real systems keeping 20 to 38 percent. Reserving exactly the right length would need the future, and still splinters the memory as conversations come and go: percent. vLLM's answer came from operating systems: virtual memory. Cut the cache into pages of sixteen tokens, put each page anywhere, and keep a table of where they are. A conversation takes a page when it needs one. Now percent of the memory holds tokens, and conversations fit at once, times as many;
How big should a page be? On average a conversation leaves half its last page empty, so the waste is about half a page over the length of a conversation, here 479 tokens. Small pages waste little, but make a longer table to look up in every attention step. vLLM chose sixteen tokens: for our conversations, 1.5 percent of the memory wasted. Pages of 256 would waste 21.
Pages make one more thing possible: sharing. Most requests start with the same words: a system prompt, the instructions, the conversation so far. Their keys and values are the same every time, so compute them once, keep the pages, and point every request that starts that way at them. We simulated forty conversations of six turns, all opening with a 300-token system prompt. With room for a thousand tokens of prefixes, 19 percent of the prompt tokens needn't be computed again; with room for everything, 78 percent, because every turn repeats the conversation before it. On our model, a 256-token prompt takes 39 milliseconds to prefill; with its first 224 tokens already cached, 10: 4.1 times faster. SGLang kept these prefixes in a tree in 2023, and since 2024 DeepSeek has charged up to 90 percent less for input it finds in its cache.
6Guess ahead, check at onceMaster's3 min
Chapter one showed that decoding one conversation leaves the chip's arithmetic idle, while every pass reads all the weights. So let a small, fast model draft a few tokens ahead. Then the big model checks all of them in a single pass, the way it reads a prompt: one read of the weights for several tokens. Keep the drafts it agrees with; at the first disagreement, take the big model's choice and start again. Mitchell Stern, Noam Shazeer and Jakob Uszkoreit did this in 2018 for a model that always picks its likeliest token.
Sampling is harder: the big model doesn't have one answer, it has a distribution, and the drafts come from a different one. In late 2022, Yaniv Leviathan, Matan Kalman and Yossi Matias at Google found a rule that makes the output come out exactly right, and Charlie Chen's team at DeepMind found it too. Here are both guesses for the next character, on our own models: Part 13's transformer as the big one, a counting model on the last two characters as the draft. Accept a drafted character with probability p over q, capped at one: where the draft guesses a character too often, the excess is thrown out. If it's rejected, sample from what's left of p after taking q away: exactly where the draft guessed too rarely. Run the rule 200,000 times: the characters it writes are as close to p as sampling p itself.
Why is that exact? The rule writes x in one of two ways: x is drafted and accepted, or a draft is rejected and x is resampled. Drafted and accepted has probability q times the acceptance, which is the smaller of p and q. A rejection happens with probability one minus the sum of those minimums, which, since p sums to one, is the sum of what p has left over. And the resampling distribution is that leftover, normalized by the same sum. Multiply, and the sums cancel: the minimum plus the leftover is p. Whatever the draft, the token written has exactly the big model's distribution. The draft only decides how often a pass is saved.
One more check, on the novels model, with the small drafter we'll train in the next chapter. At one place in a held-out novel, we drafted two tokens at a time and let the rule run, times, keeping the first two tokens it wrote. The exact answer is known: the big model's probability of the first token, times its probability of the second given the first. In this finite-sample comparison, speculative sampling has total variation , against for direct sampling. Keep the drafts without checking, and you get the draft's distribution instead: .
7DraftersMaster's3 min
How much does it save? Call alpha the chance a drafted token is accepted, and pretend, for now, that each draft survives independently. Then the first i drafts all survive with chance alpha to the i. A pass writes token i plus one exactly when the first i drafts survive, and it always writes one, its own. So the expected tokens per pass is the sum of alpha to the i, from zero to k. A geometric series: one minus alpha to the k plus one, over one minus alpha. Drafting isn't free: if a draft step costs c passes of the big model, divide by one plus k c. Leviathan and colleagues derived exactly this.
Where does a draft come from? We trained two for the novels model, on this computer. The first is simply a small language model: two layers instead of six, trained on the same novels for minutes. The second follows EAGLE, from Yuhui Li and colleagues in 2024. Instead of a separate language model, it reads the big model's last hidden state, with the token just chosen, and predicts the next hidden state, which the big model's own output layer turns into a token. It is one block, trained for minutes with the big model frozen. As each trains, we measured its one-step distribution overlap at true held-out prefixes. Free-running acceptance is measured separately. The small model reaches ; the EAGLE head : .
Now the real thing: speculative sampling on twelve held-out openings, ninety-six tokens each. We count delivered tokens; any excess from the final pass is discarded. The formula counts all generated tokens, so this finite output budget can lower the measured dots. With four drafts per pass, the small model gets tokens out of each pass of the big model, and the EAGLE head . The lines are the formula, with alpha measured on the first draft.
And the clock? On this computer, For these ninety-six-token outputs, timings include prompt prefill and cache setup. On GPUs, where a pass of a few tokens costs about as much as a pass of one, published systems do better. Medusa adds extra heads to the model; EAGLE-3 reports up to six and a half times; and DeepSeek-V3 trains its own drafter during pretraining, the multi-token prediction module of Part 18, whose second token is accepted 85 to 90 percent of the time.
8Rounding errorUndergraduate4 min
Quantization is the other half of this part: store each number in fewer bits, and move fewer bytes. The simplest kind rounds every weight to the nearest of a set of evenly spaced levels, a step delta apart. The error e is at most half a step either way. If the weights are spread smoothly over many steps, the error is equally likely anywhere in that interval, and its mean square is the integral of e squared over delta. That gives delta squared over twelve, which W. R. Bennett of Bell Labs worked out in 1948, for speech and television sent as numbers. With b bits, symmetric about zero, the largest weight sets the step: delta is the maximum over two to the b minus one, minus one. With many levels, each extra bit approximately halves the step and quarters the error: about six decibels a bit. At low bit counts, use the exact step size above.
Does it hold for a real model? We rounded all the block weights of the novels model, with a scale for each row of each matrix, at two to eight bits, and measured the mean squared error. From bits up, the measurement and delta squared over twelve agree to within percent. The error reduction approaches a factor of four per bit as the bit width grows. At two bits the formula overestimates: most weights now fall inside the zero step, and their error is just their own small size, not spread over a whole step. The grey dots used one scale for a whole matrix: every error is larger, because one large weight anywhere sets the step for all the others.
Here is why the scale's reach matters. These are the weights of one matrix of our model: most within a narrow band around zero. With one four-bit scale for the whole matrix, its single largest weight sets the step, and most weights share a handful of levels near zero. A typical row's largest weight is 2.0 times smaller than the matrix's, so a scale per row puts the levels where that row's weights are. A scale per group of 32 or 64 weights goes further, for a few more bits of storage per group.
What the model loses: its loss on held-out novels, at each width and each kind of scale. At four bits it depends on the scales: one per matrix costs nats per token, one per row , one per 32 weights , for a nominal bits a weight, excluding padding. At three bits plain rounding starts to hurt, nats with a scale per row; at two, row-wise loss rises to from nats per token. Smaller groups need not lower loss at every width. Everything that follows is about doing better than plain rounding at three and four bits.
9Outliers and SmoothQuantMaster's3 min
Weights are only half of a matrix product. To use eight-bit or four-bit arithmetic, the inputs, the activations, have to be rounded too, every token, on the fly. In 2022 Tim Dettmers and colleagues found what makes that hard. From about six point seven billion parameters on, a few feature dimensions, around a tenth of a percent of them, carry values up to twenty times larger than the rest, in every layer. Our model is far smaller, but the effect is already there. These are the largest inputs each channel of one layer saw, on calibration text. The largest is 5.1 times the median. Round a token's activations with one scale, and those few channels set the step for all the others, which then get only a handful of levels.
SmoothQuant, from Guangxuan Xiao and colleagues at MIT and NVIDIA in 2022, moves the problem. A linear layer multiplies X by W. Divide channel j of the activations by a number s j, and multiply the same channel of the weights by it: the product is unchanged, and the division can be folded into the layer before, so it costs nothing at run time. Choose s j as the activation's range to the power alpha, over the weight's to the power one minus alpha. With alpha a half, both sides end up with the same range, the geometric mean of the two. The activations' outliers are smoothed into weights, which are rounded offline and can take it: across all channels of our layer, the largest activation goes from times the median to .
What does it buy on our model? At eight bits, nothing is needed: every method stays within nats of the full model. At six bits the costs appear. At four, plain rounding of every block input costs nats a token; ; and keeping the largest one percent of activation channels in full precision costs . This is an LLM.int8-inspired illustration; all block-linear weights remain eight-bit. Our outliers are mild, times the median rather than twenty, so there is less to smooth. Four-bit activations need something stronger: the next chapter but one.
10GPTQ, from Optimal Brain SurgeonMaster's4 min
Plain rounding treats each weight alone. But what matters is the layer's output. For a layer W, on real inputs X, the output's error is a sum over rows of a quadratic form in the rounding errors, with the matrix H. H is X times X transposed, the second moments of the inputs, estimated from a little calibration text. When two inputs move together, an error in one weight can be cancelled by nudging the other: moving along the valley of this quadratic is cheap, across it costly. So round a weight, then fix the damage with the weights not yet rounded.
The question is old. For this inverse-based derivation, take H positive definite. In GPTQ, a small diagonal damping term can regularize the calibration matrix before inversion. Fix weight q at its rounded value, and move all the others by delta to keep the output error, one half delta H delta, as small as possible. With a Lagrange multiplier, the optimum has H delta parallel to the direction of weight q. Solving: delta is the rounding error over the q-th diagonal entry of H inverse, times H inverse's q-th column. And the error that's left is the rounding error squared, over twice that diagonal entry. This is the Optimal Brain Surgeon of Babak Hassibi and David Stork, from 1993, which followed Yann LeCun's Optimal Brain Damage: they used it to prune networks. In 2022 Elias Frantar and Dan Alistarh used it to round.
Rounding one weight at a time, with the best update, is too slow for billions of weights. GPTQ, from Frantar, Ashkboos, Hoefler and Alistarh in 2022, makes three changes: round the columns in one fixed order, the same for every row; get every update from one Cholesky factorization of H inverse; and apply them in blocks. A 175-billion-parameter model took about four GPU-hours. Here it is on one row of a real layer of our model, at three bits. Each column is rounded, and its error is pushed onto the columns still to come. The grey outlines show the original weights. Over the whole layer, with every input to spread it across, GPTQ's error is , against .
A simpler idea came next. In 2023 Ji Lin and colleagues noticed that a weight matters in proportion to the size of its input. So multiply each input channel's weights by s before rounding, and divide the input by s, which folds away for free. The rounding error, relative to that channel, shrinks by s. AWQ makes s the average size of the channel's input, to a power alpha chosen on calibration text: activation-aware weight quantization. Across these runs, the mean chosen alpha over layers ranges from to . Our small AWQ variant brings little improvement here.
All three, on the whole model: every block matrix rounded, the loss measured on held-out novels, and GPTQ and AWQ each calibrated on three different samples of text. At four bits with a scale per 64 weights, rounding costs nats a token and GPTQ . At three bits with a scale per row, As for AWQ, Spending the error where the inputs don't look is what makes three and four bits usable.
11Rotations: QuaRot and SpinQuantResearch3 min
In 2024 Saleh Ashkboos, Dan Alistarh and colleagues found a way to make outliers go away instead of working around them. Start from the normalization before each layer, RMSNorm: divide a vector by its length, then multiply by a learned gain, gamma, which can be folded into the next weights. What's left divides by the length, and a rotation doesn't change lengths, so normalizing a rotated vector gives the rotated normalized vector. So rotate the whole residual stream by Q: every layer that reads it gets W times Q, every layer that writes to it Q transposed times W, and the embedding and the output head get Q too. The network computes exactly the same function. We checked on ours: the largest change in any logit is 2.5 times ten to the -5, rounding error.
Which rotation? Here is one token's input to a layer of our model, channel by channel. Its largest entry is times its typical size, on average over tokens. First fold the norm gains into the next weights, then apply a Hadamard matrix: entries of plus and minus one over root n, built by doubling, and applied in n log n steps, like a fast Fourier transform. Each output mixes all inputs equally, so a spike in one channel is spread across all of them. After both transformations, the average peak ratio is . This before-and-after includes gain folding as well as rotation.
Now the hard case: four-bit weights and four-bit activations, every block input rounded on the fly. Plainly, our model loses nats a token; SmoothQuant . Rotate first, the residual stream by a Hadamard matrix and the input of each feed-forward output by a random rotation, and .
Learning a rotation needs care, because a gradient step on a rotation matrix makes it something else. SpinQuant keeps it a rotation by construction. Write Q as the Hadamard matrix times the Cayley map of a skew-symmetric matrix A: every A gives a rotation, so A can be trained freely. We trained A on our model's loss with four-bit weights and activations, the rounding passed straight through for the gradient, starting from the Hadamard rotation. This curve uses the first sixteen held-out windows; the comparison bars use all forty-eight.
12Four-bit floats: MXFP4 and NVFP4Master's3 min
Part 17 met the smallest floating-point format in use, FP4, laid out as E2M1. One bit of sign, two of exponent, one of mantissa: sixteen codes, eight magnitudes. Zero and a half, then one and one and a half, two and three, four and six: within each power of two the gap is the same, and it doubles from one power to the next. On its own that covers zero to six. To store a model's weights, which are nothing like that size, each block of weights gets a scale, and the two formats of today's chips differ in exactly how.
MXFP4 comes from the Open Compute Project's microscaling standard of September 2023, written by AMD, Arm, Intel, Meta, Microsoft, NVIDIA and Qualcomm together. Here are thirty-two real weights from our model, a block. The block shares one scale, and the scale must be a power of two, stored as an eight-bit exponent, E8M0. The rule: the exponent of the block's largest weight, minus two, so that weight lands between four and eight: here two to the . Divide each weight by the scale, round it to the nearest E2M1 value, and keep its four-bit code: the middle row. Decoded, the last row. But E2M1 stops at six. Across our model, percent of the blocks have their largest value cut down this way: the price of a scale that can only be a power of two.
NVIDIA's NVFP4, on its Blackwell chips, changes two things. Blocks of sixteen, so one large weight spoils fewer neighbours. And the block's scale is itself a small float, eight-bit E4M3, with three bits of mantissa: it can put the block's largest weight at six much more closely, though rounding the scale can still cause clipping. E4M3 only spans a limited range, so one 32-bit scale for the whole matrix moves every block scale into it. The cost: four and a half bits a weight, against MXFP4's four and a quarter.
Which is better on our model? We emulate each format on the block weights, then measure loss on held-out novels. The storage rates are nominal: scales included, but padding and matrix-scale overhead excluded.
This is how a frontier-size open model fits on one chip. In August 2025 OpenAI released gpt-oss-120b: 117 billion parameters, five of them used per token, because most live in experts. The experts' weights are stored in MXFP4, and the rest in sixteen bits. Adding it up gives gibibytes, which matches the model card's . In sixteen bits it would be gigabytes; in four, it fits on a single eighty-gigabyte GPU. And four bits are moving into training itself: in 2026 Kimi K3 used MXFP4 weights and MXFP8 activations in quantization-aware training from the supervised fine-tuning stage onward.
13The cache in fewer bitsEngineering1 min
Chapters two and three showed that long conversations are dominated by the cache: one 128-thousand token conversation with Llama 3.1 70B keeps of keys and values. So round the cache too. But keys and values are different animals. Here is one head of our model over a stretch of text: the size of each key and value entry, channel by channel, token by token. So in 2024 Zirui Liu and colleagues, in KIVI, gave keys a scale per channel and values a scale per token, and stored both in two bits.
On our model, this is an offline, teacher-forced comparison, measured on held-out novels. The per-channel key scales see whole groups of thirty-two tokens, including later positions. Causal serving needs a separate experiment. At four bits, one scale per token costs . At three bits, one scale per token costs nats a token; KIVI's split . At two bits the differences grow: per token , rotated , KIVI .
14FlashAttentionMaster's4 min
Part 17 ended with FlashAttention, and promised its derivation. Here it is. A GPU has a large, slow memory, HBM, and a small, fast one on the chip, SRAM. The standard way to compute attention writes out the T by T table of scores, reads it back for the softmax and writes the probabilities, then reads those again to weight the values. For long inputs the table is enormous: at 128 thousand tokens, 32 gibibytes for a single head, and all that traffic leaves the arithmetic waiting. In 2022 Tri Dao and colleagues at Stanford showed how never to write it at all.
The key is the softmax. To compute it safely you subtract the largest score, so no exponential overflows, and divide by the sum: so it seems you need the whole row first. But you can go tile by tile, keeping a running maximum m. When a bigger score arrives, rescale the sum so far by e to the old max minus the new one, and add the new tile's terms. The output is kept the same way, unnormalized, and divided by the sum at the very end. Maxim Milakov and Natalia Gimelshein at NVIDIA published this online softmax in 2018. Here it runs on one real query of Part 13's transformer, tile by tile: watch the maximum jump, and the sum shrink to make room for it.
With that, the table is never needed. Take a block of queries and keep it in fast memory. Stream the keys and values through, tile by tile, small enough to fit beside it; compute each tile's scores, update the running max, sum and output, and drop the tile. Then the next block of queries. We checked it on the real attention of Part 13's transformer: the tiled result equals the plain formula to within rounding, in 64-bit and in 32-bit numbers.
How much traffic does that save? With M numbers of fast memory and heads of size d, a tile of keys and values holds M over 4 d of them. Keys and values are each read once. The queries and the running outputs are read and written once per tile of keys: T over B c times, about twelve T squared d squared over M numbers in all. The quadratic traffic term scales as T squared d squared over M, against T squared plus T d for the standard method. This is an order comparison: constants and tile boundaries determine the actual savings. The paper also rules out an asymptotic improvement uniformly across its SRAM range, d at most M at most T d. With an H100's shared memory, we counted the numbers moved, running the algorithm's loops: times fewer with heads of 128, times fewer with heads of 64. FlashAttention-2 in 2023 swapped the loops and trimmed the work between matrix products; FlashAttention-3, in 2024, overlapped data movement with arithmetic on Hopper GPUs, reaching 75 percent of the chip's peak.
15Attention at serve timeEngineering2 min
FlashAttention was built for reading prompts, where thousands of queries share each tile of keys. Decoding has one query per conversation, against a cache that may hold a million keys. FlashAttention hands each head's work to one of the GPU's multiprocessors. With one conversation and 32 heads, an H100 keeps 32 of its 132 busy: 24 percent. Flash-Decoding, from Tri Dao and colleagues in 2023, also splits the cache into chunks, attends to each in parallel, and combines the partial answers with the same trick as the online softmax: weight each chunk's output and sum by e to its max minus the overall max. With eight chunks per head, 97 percent of the chip has work. We checked the combination on Part 13's attention: exact to rounding. Its authors measured up to eight times faster generation at long contexts.
The other way to read less of the cache is to look at less of it. With full attention, every step reads the whole cache, and the read grows with the conversation. gpt-oss alternates: every other layer looks back only 128 tokens, so half the reading stops growing. At 128 thousand tokens it reads 2.0 times less. Gemma 3, in 2025, gave five layers in six a window of 1,024 tokens: 5.8 times less. And DeepSeek's sparse attention, in V3.2, keeps every token but lets a small, fast indexer choose 2,048 of them for each query. The indexer still glances at every token, through a few small eight-bit heads, but the main attention's read stops growing: 64 times less at 128 thousand. On our own model a window is easy to try: at 2,048 tokens, a decode step for eight conversations takes 32.2 milliseconds with full attention, and 6.5 with a window of 128. What it costs in quality depends on what the model learned to do with it: these models were trained with their windows.
16Constrained decodingUndergraduate3 min
Programs that call a model often need its answer in a fixed format: a record, a function call, a number. Our model was trained on novels, without training for this record format. Shown three records of guests at an inn, and asked for the next, it goes back to writing novels: Big models do far better, but 'usually' isn't good enough for a program.
The fix is to rule out format-violating tokens at each step. Finishing a record still needs enough generation budget. Write the format as a pattern, a regular expression, and compile it to an automaton: states, and the characters that move between them. Ours has states. But a model writes tokens, not characters, and a token can be several characters long. In 2023 Brandon Willard and Rémi Louf, in Outlines, built an index once, ahead of time: for every state, and every token of the vocabulary, run the token's characters through the automaton, and record whether it survives, and where it lands. For our -token vocabulary that took seconds. At the start only one token is allowed, the opening brace; inside a name, . Decoding then sets every disallowed token's probability to zero, a lookup per step.
With the mask, As for speed, Look at the names, though. The model has no idea what belongs in the field; the mask only rules out what can't. A mask fixes the form, not the sense. Grammars more complex than patterns, like JSON with nesting, need a stack as well, and XGrammar, in 2024, made those fast too.
Masking has a subtler flaw. Ask Part 13's character model to write one of five names after a line of The Maltese Falcon, and compare two things. The model's own odds for each whole name, renormalized over the five: what you'd get by sampling it again and again and keeping only those names. And what masking, letter by letter, actually samples. At the first letter, masking only asks how likely an S, an A or an E is, whatever word it would begin. So Effie gets 10 percent, though the model gives the whole name only 0.1. Locally sensible choices add up to a distorted answer. In 2024 Kanghee Park and colleagues showed how to sample from the true conditional instead.
17The frontier, late 2026Research3 min
Reasoning models, Part 28's subject, think in tokens, and every token is a decode step. In May 2025 DeepSeek's update to R1 lifted its score on a hard maths competition from 70 to 87.5 percent, and it did so partly by thinking longer: 23 thousand tokens a question instead of 12. What does length cost? Take chapter three's model of a GPU serving a model, and write answers of each length, with as many conversations as the memory holds. 1.9 times the tokens cost 3.6 times as much, because the caches grow, the batch shrinks, and every token gets dearer: from 0.22 to 0.41 dollars per million. Thinking longer is a decoding problem, and everything in this part is how it is made affordable.
Meanwhile the price of a token has collapsed. Take the cheapest OpenAI model at least as good as the original GPT-3: sixty dollars per million tokens in 2021, twenty after a cut in 2022, two for the ChatGPT model in 2023, fifteen cents for GPT-4o mini in 2024. That's 400 times in about three and a half years, 5.6 times a year. Epoch AI, tracking many benchmarks, found the price of a fixed level of ability falling between nine and nine hundred times a year, depending on the task. Some of that is this part's methods, some is Part 17's hardware, and some is smaller models trained on more data, as Part 12 described.
Chapter one's speed limit also says who can run these models. Divide a device's memory bandwidth by the bytes a token reads. A laptop with Apple's M5, at 153 gigabytes a second, can write at most tokens a second with gpt-oss-20b, whose MXFP4 experts and sixteen-bit non-expert weights make each token read about gigabytes; an H100, . That is why four-bit formats and experts matter for running models at home, where llama.cpp started in 2023, and why Apple's on-device model, in 2025, was trained for two-bit weights. And the split between prefill and decode is reaching the hardware: in September 2025 NVIDIA announced Rubin CPX, a GPU with cheaper memory and plenty of arithmetic, for the long-context work of reading prompts, which it said would ship by the end of 2026.
Recap, problems, and what comes nextAll tracks2 min
Let's take stock. Reading a prompt is arithmetic and writing an answer is reading memory, so a server batches the writing, and the price of a token follows from the batch it can afford. Continuous batching keeps the batch full, and pages keep the memory full. A drafter guesses ahead and the big model checks in one pass, preserving the same output distribution. With uniform in-cell error and no clipping, mean squared rounding error is delta squared over twelve; GPTQ and rotations spend it where it hurts least, and four-bit floats store it compactly. And FlashAttention never writes its table down.
All of this comes back. Generating images one pixel at a time, and the race to take fewer steps, are Parts 20 and 21. Reasoning models think in tokens that decoding pays for, Part 28; agents run long contexts and many calls with shared prefixes, Part 29. The outlier channels of chapter nine are a clue to what the directions inside a model mean: Part 30 shows a network packing more features than it has dimensions. And Part 31 asks how to trust what comes out.
Here are six problems to try, from the drafter's formula to Flash-Decoding's combination. Pause here, and work through them; full solutions are in this part's notes.
Next time, the fourth act begins: generation. Before diffusion, there were four ways to make a model that invents: one pixel at a time, through a learned code, as a game between two networks, or by bending space itself. Part 20: four ways to generate.
To go further, the vLLM and FlashAttention papers are good places to start. Thanks for watching, and see you in Part 20.
Where it goes next. Generating images one pixel at a time and the race to take fewer steps are Parts 20 and 21. Reasoning models pay for their thinking tokens at decode time in Part 28, and agents run long contexts with shared prefixes in Part 29. The outlier channels of chapter 9 return in Part 30 as a clue to superposition, and Part 31 asks how far the output can be trusted.
Key results
The part's results in one place, for revision.
Try it
Lab 19 · Faster, and exactly the same: speculative sampling and FlashAttention
Draft 200,000 tokens from a wrong distribution q, accept each with probability min(1, p/q) and resample rejections from what is left of p: check that the output has distribution p, that a draft is accepted with probability 1 - TV(p, q), and that a pass writes (1 - a^(k+1))/(1 - a) tokens. Then compute attention in tiles with the film's code and compare it, and its memory traffic, with the plain T x T table.
python -m videos.ai.labs 19
needs numpy, scipy, matplotlib · download lab19.py ·
source on GitHubTV(p, q): how wrong the draft is 0.1962
TV(output, p): speculative sampling 0.0041 (sampling noise alone: about 0.0031)
TV(output, p): drafts kept unchecked 0.1985
drafts accepted 0.8029 1 - TV(p, q) = 0.8038
tokens per pass, k = 4 drafts measured 3.390 (1 - a^5)/(1 - a) = 3.387
tiled attention against the table largest difference 4.0e-15 split in 5 chunks 2.2e-15
numbers moved at T = 65,536 standard 1.72e+10 tiled 8.54e+09 (2.0x fewer)
Checking a draft with min(1, p/q) and resampling from the leftover returns exactly the big model's distribution, so the draft only decides how many tokens a pass writes. Tiled attention returns the same output to rounding error, and at long lengths it moves fewer numbers than writing the table.
The code (105 lines; it asserts its own result)
"""Lab 19: speculative sampling and tiled attention, two ways to go faster that leave the answer exactly the same."""
import numpy as np
from videos.coursekit import labs
from videos.ai.ai19 import attn # the film's online softmax, FlashAttention tiles and traffic counts (numpy)
TITLE = "Faster, and exactly the same: speculative sampling and FlashAttention"
GOAL = ("Draft 200,000 tokens from a wrong distribution q, accept each with probability min(1, p/q) and resample "
"rejections from what is left of p: check that the output has distribution p, that a draft is accepted with "
"probability 1 - TV(p, q), and that a pass writes (1 - a^(k+1))/(1 - a) tokens. Then compute attention in "
"tiles with the film's code and compare it, and its memory traffic, with the plain T x T table.")
TASKS = [
"Replace the leftover distribution by p itself (resample a rejected draft from p). How far, in total variation, "
"does the output move from p?",
"Give a draft step a cost of c = 0.05 passes and plot the speed-up (1 - a^(k+1)) / ((1 - a)(1 + kc)). Which k is "
"fastest at this lab's acceptance rate?",
"Shrink the fast memory M passed to attn.io_flash_counted until tiled attention moves more numbers than the "
"standard method. How does that M compare with d^2?",
]
V, N, KMAX = 12, 200_000, 8
def speculative(p, q, n, rng):
"""n tokens by speculative sampling: (tokens, accepted flags)."""
draft = rng.choice(len(p), size=n, p=q)
accept = rng.random(n) < np.minimum(1, p[draft] / q[draft])
left = np.maximum(0, p - q)
out = np.where(accept, draft, rng.choice(len(p), size=n, p=left / left.sum()))
return out, accept
def tv(a, b):
return 0.5 * np.abs(a - b).sum()
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. one token: the output is p, whatever the draft
p = rng.dirichlet(np.full(V, 0.6))
q = 0.55 * p + 0.45 * rng.dirichlet(np.full(V, 0.6)) # a drafter that is partly right
out, accept = speculative(p, q, N, rng)
emp = np.bincount(out, minlength=V) / N
unchecked = np.bincount(rng.choice(V, size=N, p=q), minlength=V) / N
alpha = 1 - tv(p, q)
noise = np.sqrt(V / (2 * np.pi * N)) # roughly the TV between p and N of its own samples
lab.row("TV(p, q): how wrong the draft is", f"{tv(p, q):.4f}")
lab.row("TV(output, p): speculative sampling", f"{tv(emp, p):.4f} (sampling noise alone: about {noise:.4f})")
lab.row("TV(output, p): drafts kept unchecked", f"{tv(unchecked, p):.4f}")
lab.row("drafts accepted", f"{accept.mean():.4f} 1 - TV(p, q) = {alpha:.4f}")
assert tv(emp, p) < 4 * noise, "the output has the big model's distribution"
assert tv(unchecked, p) > 0.5 * tv(p, q) > 4 * noise, "unchecked drafts do not"
assert abs(accept.mean() - alpha) < 0.005, "acceptance = 1 - TV(p, q)"
# 2. k drafts per pass: tokens written until the first rejection, plus the big model's own token
passes = 40_000
ok = rng.random((passes, KMAX)) < alpha
measured, formula = [], []
for k in range(1, KMAX + 1):
first_no = np.where(ok[:, :k].all(axis=1), k, np.argmin(ok[:, :k], axis=1))
measured.append(first_no.mean() + 1)
formula.append((1 - alpha ** (k + 1)) / (1 - alpha))
lab.row("tokens per pass, k = 4 drafts", f"measured {measured[3]:.3f} (1 - a^5)/(1 - a) = {formula[3]:.3f}")
assert np.abs(np.array(measured) - formula).max() < 0.06, "expected tokens per pass"
# 3. attention in tiles: the same numbers, without the table
T, d = 96, 16
Q, K, Vv = (rng.standard_normal((T, d)) * 2 for _ in range(3))
plain = attn.plain_attention(Q, K, Vv)
err_flash = np.abs(attn.flash_attention(Q, K, Vv, Br=8, Bc=12) - plain).max()
one, _ = attn.split_kv_decode(Q[-1], K, Vv, splits=5)
err_split = np.abs(one - plain[-1]).max()
lab.row("tiled attention against the table", f"largest difference {err_flash:.1e} split in 5 chunks {err_split:.1e}")
assert err_flash < 1e-12 and err_split < 1e-12, "the online softmax is exact"
Ts = np.array([1024, 4096, 16384, 65536])
d_h, M = 128, 100_000 # numbers in a head, numbers of fast memory
std = np.array([attn.io_standard(int(t), d_h) for t in Ts], float)
fla = np.array([attn.io_flash_counted(int(t), d_h, M) for t in Ts], float)
assert all(attn.io_flash_counted(int(t), d_h, M) == attn.io_flash_formula(int(t), d_h, M) for t in Ts)
lab.row(f"numbers moved at T = {Ts[-1]:,}", f"standard {std[-1]:.2e} tiled {fla[-1]:.2e} ({std[-1] / fla[-1]:.1f}x fewer)")
assert np.all(fla < std) and std[-1] / fla[-1] > std[0] / fla[0] > 1, "the saving grows with length"
lab.note = ("Checking a draft with min(1, p/q) and resampling from the leftover returns exactly the big model's "
"distribution, so the draft only decides how many tokens a pass writes. Tiled attention returns the "
"same output to rounding error, and at long lengths it moves fewer numbers than writing the table.")
fig, ax = labs.figure(2, size=(11, 4.2))
w = 0.27
order = np.argsort(-p)
for j, (vals, color, name) in enumerate(((p, labs.GOLD, "the big model's p"), (emp, labs.BLUE, "speculative sampling"),
(unchecked, labs.RED, "drafts, unchecked"))):
ax[0].bar(np.arange(V) + (j - 1) * w, vals[order], w, color=color, label=name)
ax[0].set(title=f"{N:,} tokens: the output's distribution", xlabel="token (sorted by p)", ylabel="probability")
ax[0].set_xticks(range(V))
ax[0].legend()
ks = np.arange(1, KMAX + 1)
for a_, color in ((0.6, labs.GREY), (0.9, labs.PURPLE)):
ax[1].plot(ks, (1 - a_ ** (ks + 1)) / (1 - a_), color=color, lw=1.2, ls="--", label=f"formula, a = {a_}")
ax[1].plot(ks, formula, color=labs.GOLD, label=f"formula, a = {alpha:.2f} (this draft)")
ax[1].plot(ks, measured, "o", color=labs.BLUE, label="measured")
ax[1].set(title="Tokens written per pass of the big model", xlabel="drafts per pass k", ylabel="tokens per pass")
ax[1].legend(loc="upper left")
lab.fig = fig
return lab
Now change it
- Replace the leftover distribution by p itself (resample a rejected draft from p). How far, in total variation, does the output move from p?
- Give a draft step a cost of c = 0.05 passes and plot the speed-up (1 - a^(k+1)) / ((1 - a)(1 + kc)). Which k is fastest at this lab's acceptance rate?
- Shrink the fast memory M passed to attn.io_flash_counted until tiled attention moves more numbers than the standard method. How does that M compare with d^2?
Problems, with solutions
Try each problem before opening its solution.
1. Tokens per pass. With each draft accepted independently with probability α, show that a pass writes (1 − α^{k+1})/(1 − α) tokens on average. For α = 0.8 and a draft step costing c = 0.05 passes, which k is fastest?
Solution
The pass writes token i + 1 (i = 0 … k) exactly when the first i drafts are all accepted, which has probability α^i (the i = 0 term counts the guaranteed first output token). By linearity, E[tokens] = Σ_{i=0}^{k} α^i = (1 − α^{k+1})/(1 − α). A round costs one pass plus k draft steps, 1 + kc, so the speed-up is S(k) = (1 − α^{k+1}) / ((1 − α)(1 + kc)). With α = 0.8, c = 0.05: S(1) = 1.71, S(2) = 2.22, S(3) = 2.57, S(4) = 2.80, S(5) = 2.95, S(6) = 3.04, S(7) = 3.08, S(8) = 3.09, S(9) = 3.08: k = 8 is fastest, though anything from 6 to 10 is within 2%.
2. Exactness. Show that speculative sampling outputs x with probability exactly p(x), and that a draft is accepted with probability 1 − TV(p, q).
Solution
x is output if it is drafted and accepted, probability q(x) min(1, p(x)/q(x)) = min(p(x), q(x)), or if some draft is rejected and x is resampled from r(x) = (p(x) − min(p(x), q(x)))/Z with Z = Σ_y (p(y) − min(p(y), q(y))). The rejection probability is 1 − Σ_y min(p(y), q(y)) = Z, because Σ_y p(y) = 1. So P(x) = min(p, q) + Z · (p − min(p, q))/Z = p(x). The acceptance probability is β = Σ_y min(p(y), q(y)); since min(a, b) = (a + b − |a − b|)/2 and p and q both sum to one, β = 1 − ½ Σ_y |p(y) − q(y)| = 1 − TV(p, q). Ratios p(x)/q(x) are needed only for sampled drafts, where q(x) > 0. If Z = 0, p = q and rejection never occurs, so no residual distribution is needed.
3. Rounding error. Assuming uniform in-cell error and no clipping, derive E[e²] = Δ²/12. For fixed positive absmax A, symmetric signed step Δ_b = A/(2^{b−1} − 1) and b ≥ 2, derive the reduction from b to b + 1 bits and its large-b limit.
Solution
Under the assumed uniform-cell model, e is uniform on [−Δ/2, Δ/2]: E[e²] = (1/Δ) ∫{−Δ/2}^{Δ/2} e² de = (1/Δ)(2/3)(Δ/2)³ = Δ²/12. With b bits over a fixed range, the model predicts E_b/E{b+1} = [(2^b − 1)/(2^{b−1} − 1)]². Its decibel reduction is 20 log₁₀[(2^b − 1)/(2^{b−1} − 1)], tending to 20 log₁₀ 2 = 10 log₁₀ 4 ≈ 6.02 dB as b grows. For example, 3 → 4 bits predicts 49/9, about 7.36 dB. Clipping, changing ranges and nonuniform in-cell occupancy can invalidate the prediction for measured weights.
4. A cache. A model has 48 layers and 8 key-value heads of 128 in 16 bits. How many bytes does its cache keep per token, and at what context does one conversation's cache weigh 60 GB?
Solution
Keys and values: 2 × 48 × 8 × 128 numbers × 2 bytes = 196,608 bytes, 192 KiB, per token. 60 × 10⁹ / 196,608 ≈ 305,000 tokens. With every one of, say, 40 query heads keeping its own key and value it would be five times as much, and the cache would weigh 60 GB at about 61,000 tokens.
5. Optimal Brain Surgeon. Let H be real symmetric positive definite. Minimize ½ δᵀHδ subject to e_qᵀδ = ŵ_q − w_q: derive the update and the error it leaves.
Solution
The Lagrangian ½ δᵀHδ − λ(e_qᵀδ − (ŵ_q − w_q)) has gradient Hδ − λe_q = 0, so δ = λH⁻¹e_q. The constraint gives λ e_qᵀH⁻¹e_q = λ[H⁻¹]_qq = ŵ_q − w_q, so λ = (ŵ_q − w_q)/[H⁻¹]_qq and δ = ((ŵ_q − w_q)/[H⁻¹]_qq) H⁻¹e_q. The error is ½ δᵀHδ = ½ λ² e_qᵀH⁻¹HH⁻¹e_q = ½ λ²[H⁻¹]_qq = (w_q − ŵ_q)² / (2[H⁻¹]_qq). Positive definiteness makes this the unique constrained minimum. GPTQ updates still-unquantized columns using rows of an upper Cholesky factor U with H⁻¹ = UᵀU, after damping the input second-moment matrix as needed.
6. Combining two chunks. Two chunks of keys give (m₁, ℓ₁, o₁) and (m₂, ℓ₂, o₂), where m is a chunk's largest score, ℓ = Σ e^{s_j − m} and o = Σ e^{s_j − m} v_j over the chunk. Combine them into exact attention.
Solution
With M = max(m₁, m₂), the full sums are L = e^{m₁−M} ℓ₁ + e^{m₂−M} ℓ₂ and O = e^{m₁−M} o₁ + e^{m₂−M} o₂, because e^{s_j − M} = e^{s_j − m_i} e^{m_i − M} for every j in chunk i; attention is O/L. The rule is symmetric in the two chunks and associative (combining a third with the result gives the same M, L and O as any other order), so the chunks can be processed in parallel and reduced in any order: Flash-Decoding. Each rescaling exponential e^{m_i − M} ≤ 1, avoiding exponential overflow. Associativity holds in exact arithmetic; floating-point reduction order can change rounding.
Notes and sources
Glossary
| English | 中文 |
|---|---|
| inference, serving | 推断,服务(部署) |
| prefill, decode | 预填充,解码 |
| key-value cache (KV cache) | 键值缓存(KV缓存) |
| multi-head, multi-query, grouped-query attention (MHA, MQA, GQA) | 多头注意力,多查询注意力,分组查询注意力 |
| multi-head latent attention (MLA) | 多头潜在注意力(MLA) |
| batch, batch size | 批,批大小 |
| throughput, latency | 吞吐量,延迟 |
| time to first token (TTFT), time between tokens | 首个词元的等待时间,词元之间的间隔 |
| static batching, continuous batching | 静态批处理,连续批处理 |
| iteration-level scheduling | 迭代级调度 |
| chunked prefill | 分块预填充 |
| disaggregated serving (prefill and decode on separate workers) | 预填充与解码分离部署 |
| paged attention, page, block table | 分页注意力,页,块表 |
| fragmentation (internal, external) | 碎片(内部,外部) |
| preemption | 抢占 |
| prefix caching, radix tree | 前缀缓存,基数树 |
| speculative decoding, speculative sampling | 推测解码,推测采样 |
| draft model, drafter, target model | 草稿模型,起草器,目标模型 |
| acceptance rate | 接受率 |
| EAGLE head, Medusa heads | EAGLE头,Medusa头 |
| total variation distance | 总变差距离 |
| quantization, round to nearest | 量化,就近舍入 |
| scale (per tensor, per row, per group) | 缩放因子(每张量,每行,每组) |
| step size Δ | 步长Δ |
| calibration data | 校准数据 |
| activation outliers, outlier channels | 激活离群值,离群通道 |
| W8A8 (8-bit weights and activations) | W8A8(8比特权重和激活) |
| SmoothQuant, migration strength α | SmoothQuant,迁移强度α |
| Optimal Brain Damage, Optimal Brain Surgeon | 最优脑损伤,最优脑外科 |
| GPTQ, AWQ (activation-aware weight quantization) | GPTQ,AWQ(激活感知的权重量化) |
| salient weights | 显著权重 |
| Hadamard matrix, rotation | 哈达玛矩阵,旋转 |
| computational invariance | 计算不变性 |
| Cayley map, skew-symmetric matrix | 凯莱映射,反对称矩阵 |
| crest factor (peak over typical) | 峰值因子(峰值与典型值之比) |
| E2M1, E4M3, E8M0 | E2M1,E4M3,E8M0 |
| MXFP4, NVFP4, shared exponent, clamping | MXFP4,NVFP4,共享指数,截断 |
| KV-cache quantization; per-channel, per-token | KV缓存量化;按通道,按词元 |
| online softmax, running max, running sum | 在线softmax,当前最大值,累计和 |
| IO complexity | IO复杂度 |
| Flash-Decoding, split-KV, log-sum-exp | Flash-Decoding,KV切分,对数求和指数 |
| occupancy | 占用率 |
| sliding-window attention, sparse attention, indexer | 滑动窗口注意力,稀疏注意力,索引器 |
| constrained decoding, structured output | 约束解码,结构化输出 |
| finite automaton, regular expression, token mask | 有限自动机,正则表达式,词元掩码 |
| grammar-aligned decoding | 语法对齐解码 |
| test-time compute, thinking budget | 测试时计算,思考预算 |
| price per million tokens | 每百万词元的价格 |
| on-device inference | 端侧推断 |
About this partfrom its README
Part 19 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan
and the syllabus); the last part of Act III, the Transformer Era. How a trained model is run for
millions of people: why reading a prompt and writing an answer are different problems on the roofline, what the
key-value cache costs, how a server batches, schedules and pages, how speculative decoding writes several tokens per
pass and stays exact, how weights, activations and caches are rounded to eight, four and three bits, how
FlashAttention avoids its table, and how decoding is constrained to a format. Local experiments use the series' own
models: the novels model (explainer.ai.novels) on this part's inference engine (engine.py), and Part 13's character
transformer. Measurements are distinguished from analytical bounds, fitted simulations and cited published figures.
Two drafters are trained here, and their training is
replayed on screen; so is the learning of a rotation, SpinQuant-style.
- One token at a time. Writing a token reads the active weights: the weight-only bound is tokens per second ≤ bandwidth / weight bytes (an H100 and Llama 3.1 8B in 16 bits, published figures), before cache and other traffic. How we got here, 2017–2026: the key-value cache, multi-query attention (Shazeer 2019), GPT-3 sold by the token, FlashAttention, Orca, speculative decoding and GPTQ (2022), llama.cpp and vLLM (2023), MLA and disaggregated serving (2024), gpt-oss in MXFP4 and DeepSeek's sparse attention (2025); OpenAI's price for a GPT-3-class model, 2021–2024.
- 1. Prefill and decode. FLOPs 2N per token, bytes 2N per pass, intensity B for a decode batch and T for a prompt; H100's ridge (Part 17). Measured: an 805 MB stack of weight matrices multiplied by batches of 1–512 vectors (GEMV becoming GEMM) against the roofline's floor; the novels model's prefill and decode throughput.
- 2. The key-value cache, priced. 2 L n_h d_h per token (MHA), 2 L n_g d_h (GQA, Ainslie et al. 2023), L (d_c + d_R) (MLA, DeepSeek-V2 2024); Llama 3.1 70B, DeepSeek-V3 and gpt-oss-120b from their configurations; the cache against context length and against the weights; measured decode time against the bytes a step reads.
- 3. Batching: speed against cost. The measured trade between speed per conversation and total throughput; a roofline model of Llama 3.1 8B on an H100, memory capping the batch, at the 2 USD per GPU-hour DeepSeek costed its service at (DeepSeek-V3.2 2025); cost per million tokens against speed, at 1k–128k context; Pope et al. (2022).
- 4. Continuous batching. Static batches against iteration-level scheduling (Orca, Yu et al. 2022), simulated with this machine's fitted step costs: a Gantt chart of slots, throughput, time to first token; prefill stalls and chunked prefill (Sarathi-Serve 2024); prefill and decode on separate workers (Splitwise, DistServe 2024; DeepSeek-V3's deployment; Mooncake).
- 5. Pages and shared prefixes. The cache's memory reserved at the maximum, contiguous first-fit, or paged (vLLM, Kwon et al. 2023), simulated: memory holding tokens, conversations at once; waste against page size; prefix caching on multi-turn chats (SGLang 2023; DeepSeek's context caching 2024) and its measured prefill saving. The paging toy restarts generation after preemption; it does not recompute an already-confirmed output prefix. Its occupancy averages weight simulation steps equally, rather than elapsed time. Published vLLM gains are separate results from the cited paper.
- 6. Guess ahead, check at once. Blockwise parallel decoding (Stern, Shazeer & Uszkoreit 2018); speculative sampling (Leviathan, Kalman & Matias 2022; Chen et al. 2023): the rule min(1, p/q) and the leftover max(0, p − q), proved exact; checked on Part 13's transformer (200,000 samples) and on the novels model's next two tokens (60,000 runs; total variation against direct sampling and against unchecked drafts).
- 7. Drafters. The expected tokens per pass (1 − α^{k+1})/(1 − α) and the speed-up with draft cost c, derived; a two-layer drafter and an EAGLE-style head (Li et al. 2024) trained here, with teacher-forced held-out overlap replayed through training; separate free-running runs on 12 held-out openings, delivering 96 tokens each: delivered tokens per pass against the iid formula, acceptance conditional on reaching each depth, and greedy decoding. Excess tokens from the final pass are discarded. Timing on four openings includes prompt prefill and cache setup; Medusa, EAGLE-3, DeepSeek-V3's MTP module (Part 18).
- 8. Rounding error. E[e²] = Δ²/12 derived (Bennett 1948), about 6 dB per added bit in the fixed-range, high-resolution, no-clipping approximation; checked on all the novels model's block weights; one matrix's histogram with per-tensor and per-row levels; loss against bits for a scale per tensor, row, 64 and 32 weights.
- 9. Outliers and SmoothQuant. LLM.int8()'s emergent outliers (Dettmers et al. 2022); our model's channel ranges; SmoothQuant (Xiao et al. 2022) derived; W8A8, W8A6, W8A4: plain, smoothed, and an LLM.int8()-inspired exemption for the largest one percent of activation channels. Their block-linear weights remain quantized; this is not the full mixed-precision LLM.int8() implementation.
- 10. GPTQ, from Optimal Brain Surgeon. The layer-wise objective with H = XXᵀ; Optimal Brain Damage (LeCun, Denker & Solla 1990) and Optimal Brain Surgeon (Hassibi & Stork 1993) derived with a Lagrange multiplier; Optimal Brain Compression (2022) and GPTQ (Frantar et al. 2022): one row's column-by-column update animated; AWQ (Lin et al. 2023); all three at 4 and 3 bits on three calibration sets.
- 11. Rotations: QuaRot and SpinQuant. After folding learned norm gains into following weights, unit-gain RMSNorm with its ε term commutes with orthogonal rotations; computational invariance (QuaRot, Ashkboos et al. 2024), checked; an activation comparison including both gain folding and a Hadamard rotation; W4A4 plain, smoothed, Hadamard, random rotations, and a rotation learned through the Cayley map (SpinQuant, Liu et al. 2024), its training replayed.
- 12. Four-bit floats: MXFP4 and NVFP4. E2M1 (Part 17); MXFP4 (OCP 2023) bit by bit on 32 of our weights: the E8M0 shared exponent, the codes, clamping above 6; NVFP4 (NVIDIA 2025): blocks of 16, an E4M3 scale and a tensor scale; block-linear weights emulated in each format against 4-bit integers. The NVFP4 comparison uses the same 16-weight groups and E4M3 scale format, with numerical scales chosen for each element range. Storage rates are nominal, excluding padding and tensor-scale overhead; embedding and output head remain FP32. gpt-oss-120b's 60.8 GiB recomputed from its model card; Kimi K3's MXFP4 weights (Part 18).
- 13. The cache in fewer bits. Keys' outlier channels against values; KIVI (Liu et al. 2024): keys per channel, values per token; the cache at 8 (integer, FP8), 4, 3 and 2 bits, per token, KIVI, and Hadamard-rotated. The local loss comparison is offline and teacher-forced: key scales see whole 32-token groups. It illustrates quantization granularity, rather than a causal KIVI server with residual buffering. Causal serving is a separate experiment.
- 14. FlashAttention. The standard method's HBM traffic; the online softmax (Milakov & Gimelshein 2018) derived and run on one real query of Part 13's transformer; tiles (Dao et al. 2022), checked exact on Part 13's attention; the IO complexity Θ(T²d²/M) derived and counted by running the loops, for an H100's shared memory; FlashAttention-2 (2023) and -3 (2024).
- 15. Attention at serve time. Flash-Decoding (Dao, Haziza, Massa & Sizov 2023): split-KV with log-sum-exp combination, checked; occupancy of an H100 at batch 1; sliding windows (gpt-oss, Gemma 3) and DeepSeek's sparse attention (V3.2): cache read per decode step against context; a window measured on our model.
- 16. Constrained decoding. A prompted record format tested on 200 unconstrained and 200 constrained samples; the pattern compiled to an automaton and a token index (Outlines, Willard & Louf 2023); sample validity checked and generation timed in ordered runs, including repeated prompt prefill and cache setup; XGrammar (2024); masking distorts the distribution (Park et al. 2024), shown on Part 13's character model.
- 17. The frontier, late 2026. Thinking longer (DeepSeek-R1-0528: 12k → 23k tokens per AIME question) costed with chapter 3's model; prices per token over time (OpenAI list prices; Epoch AI 2025); bandwidth bounds on laptops and GPUs (Apple M5, M5 Max, H100) for on-device models (Apple's 2-bit model, gpt-oss-20b, Llama 3.1 in 4 bits), and our model's measured speed against its bound; Rubin CPX.
- Recap, where this comes back (Parts 20, 21, 28, 29, 30, 31; Part 30's superposition picture), the problem set, Part 20's teaser, references.
Run from the repo root:
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- The roofline (from Part 17) applied: GEMV vs GEMM; prefill vs decode.
- Continuous batching; paged KV; prefix caching; disaggregated serving.
- Speculative decoding: exactness proved, the expected-accepted formula; EAGLE and MTP drafters.
- Quantization: Δ²/12, outliers, SmoothQuant, GPTQ from Optimal Brain Surgeon, AWQ, rotations (QuaRot, SpinQuant).
- MXFP4/NVFP4 bit layouts (gpt-oss).
- KV quantization.
- FlashAttention 1–3: online softmax, tiling, IO complexity; FlashDecoding.
- Constrained decoding via automaton masks.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
1. 每次前向传播写出的词元数。 设每个草稿以概率 α 被独立接受,证明一次前向传播平均写出 (1 − α^{k+1})/(1 − α) 个词元。若 α = 0.8,起草一步的代价 c = 0.05 次前向传播,k 取多少最快?
解答
当且仅当前 i 个草稿全部被接受时(概率 α^i),这次前向传播写出第 i + 1 个词元(i = 0 … k;i = 0 那一项计入总会输出的 第一个词元)。由期望的线性,平均词元数 = Σ_{i=0}^{k} α^i = (1 − α^{k+1})/(1 − α)。一轮的代价是一次前向传播加 k 步起草, 即 1 + kc,所以加速比 S(k) = (1 − α^{k+1}) / ((1 − α)(1 + kc))。α = 0.8,c = 0.05 时:S(1) = 1.71,S(2) = 2.22, S(3) = 2.57,S(4) = 2.80,S(5) = 2.95,S(6) = 3.04,S(7) = 3.08,S(8) = 3.09,S(9) = 3.08:k = 8 最快,不过 6 到 10 都在 2% 之内。
2. 精确性。 证明推测采样输出 x 的概率恰好是 p(x),并证明一个草稿被接受的概率是 1 − TV(p, q)。
解答
x 被输出有两种途径:被起草并被接受,概率是 q(x) min(1, p(x)/q(x)) = min(p(x), q(x));或者某个草稿被拒绝,再从 r(x) = (p(x) − min(p(x), q(x)))/Z 中重采样出 x,其中 Z = Σ_y (p(y) − min(p(y), q(y)))。拒绝的概率是 1 − Σ_y min(p(y), q(y)) = Z,因为 Σ_y p(y) = 1。所以 P(x) = min(p, q) + Z · (p − min(p, q))/Z = p(x)。接受的概率是 β = Σ_y min(p(y), q(y));由 min(a, b) = (a + b − |a − b|)/2,且 p、q 各自求和为 1,得 β = 1 − ½ Σ_y |p(y) − q(y)| = 1 − TV(p, q)。 只需在被采样的草稿上计算 p(x)/q(x),此时 q(x) > 0。若 Z = 0,则 p = q,不会发生拒绝,也就无需残差分布。
3. 舍入误差。 假设单元内误差均匀且无截断,推导 E[e²] = Δ²/12。对固定绝对值上界 A > 0,采用步长 Δ_b = A/(2^{b−1} − 1) 的对称有符号量化,b ≥ 2,求从 b 比特增加到 b + 1 比特的误差降低倍数及其在 b 很大时的极限。
解答
在所假设的单元内均匀误差模型下,e 在 [−Δ/2, Δ/2] 上均匀分布: E[e²] = (1/Δ) ∫{−Δ/2}^{Δ/2} e² de = (1/Δ)(2/3)(Δ/2)³ = Δ²/12。给定固定范围时,该模型预测 E_b/E{b+1} = [(2^b − 1)/(2^{b−1} − 1)]²。因此误差降低 20 log₁₀[(2^b − 1)/(2^{b−1} − 1)] 分贝;b 增大时趋近 20 log₁₀ 2 = 10 log₁₀ 4 ≈ 6.02 分贝。例如,3 → 4 比特预测降低 49/9 倍,约 7.36 分贝。截断、变化的范围和 不均匀的单元内分布,都可能使实际权重的测量偏离这一预测。
4. 一个缓存。 一个模型有 48 层,8 个键值头,每个 128 维,用 16 比特存储。每个词元的缓存有多少字节?上下文多长时,一段对话的 缓存重达 60 GB?
解答
键和值:2 × 48 × 8 × 128 个数 × 2 字节 = 196608 字节,即每个词元 192 KiB。60 × 10⁹ / 196608 ≈ 30.5 万个词元。如果比如 40 个查询头每个都有自己的键和值,缓存会是 5 倍,大约 6.1 万个词元就达到 60 GB。
5. 最优脑外科。 设 H 为实对称正定矩阵。在约束 e_qᵀδ = ŵ_q − w_q 下最小化 ½ δᵀHδ:推导更新量,以及它留下的误差。
解答
拉格朗日函数 ½ δᵀHδ − λ(e_qᵀδ − (ŵ_q − w_q)) 的梯度为 Hδ − λe_q = 0,所以 δ = λH⁻¹e_q。代入约束得 λ e_qᵀH⁻¹e_q = λ[H⁻¹]_qq = ŵ_q − w_q,于是 λ = (ŵ_q − w_q)/[H⁻¹]_qq,δ = ((ŵ_q − w_q)/[H⁻¹]_qq) H⁻¹e_q。误差是 ½ δᵀHδ = ½ λ² e_qᵀH⁻¹HH⁻¹e_q = ½ λ²[H⁻¹]_qq = (w_q − ŵ_q)² / (2[H⁻¹]_qq)。正定性保证这是唯一的约束最小值。 GPTQ 在需要时对输入二阶矩矩阵加阻尼,再利用满足 H⁻¹ = UᵀU 的上三角 Cholesky 因子 U 的各行,对尚未量化的列依次更新。
6. 合并两段。 两段键分别给出 (m₁, ℓ₁, o₁) 和 (m₂, ℓ₂, o₂),其中 m 是这一段里最大的分数,ℓ = Σ e^{s_j − m}, o = Σ e^{s_j − m} v_j(对这一段求和)。把它们合并成精确的注意力。
解答
令 M = max(m₁, m₂),完整的和是 L = e^{m₁−M} ℓ₁ + e^{m₂−M} ℓ₂,O = e^{m₁−M} o₁ + e^{m₂−M} o₂,因为对第 i 段里的每个 j, e^{s_j − M} = e^{s_j − m_i} e^{m_i − M};注意力就是 O/L。这个规则对两段是对称的,也满足结合律(再合并第三段,无论什么顺序, 得到的 M、L、O 都一样),所以各段可以并行计算,再以任意顺序归约:这就是 Flash-Decoding。每个重缩放指数 e^{m_i − M} ≤ 1, 避免了指数计算的上溢。结合律在精确算术下成立;浮点归约顺序可能改变舍入误差。
Build the film
python -m videos.ai.ai19.compute # the part's numbers, into .cache/ai19
python tools/build.py ai19 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai19 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai19. Setup: see the course page. Source of these notes: the README and the scenes' narration.