Lecture guide: Inference#
Lecturer: course staff · Course: Stanford CS336 Language Modeling from Scratch, Spring 2026, lecture 10 · Length: 1:26:00 Video: watch on YouTube Chapters that cite this lecture: 08. Inference
In one sentence: Percy Liang shows why generating text is memory-bound where prefill, as in training, is compute-bound, reads the latency and throughput of a model from the bytes it must move, and surveys the ways to move fewer: a smaller KV cache, smaller numbers, smaller models, speculative sampling and the systems tricks of a live server.
Before you watch#
The lecture applies the arithmetic intensity of lecture 2 and the memory hierarchy of the systems lectures to one decoding step, so those should be fresh. It is the middle of three lectures, between the two on scaling laws. Much of it follows the "scaling book" that Google engineers wrote about inference, some of whose figures the lecture borrows. The chapter Inference follows the lecture section by section.
The lecture, part by part#
0:00–5:16 Why inference matters#
The problem: a trained model, a prompt, and a response to produce as accurately and quickly as possible. It gets one lecture, yet it matters more all the time: chatting, code completion, agents, batch processing, evaluations that require generation, and training itself, since reinforcement learning generates rollouts to score. Training is a one-time cost, however large; inference is paid every day. Liang's figures: OpenAI's daily output is estimated at 8.6 trillion tokens, and DeepSeek V4, released earlier that year, was trained on 32 trillion, so in under four days the tokens generated exceed a frontier training run. Agents raise the stakes: most of their tokens are never read by a person, so tokens generated are simply compute spent, with no ceiling. A chatbot is fast enough once a human can read the stream; an agent never is. On the supply side: the closed API providers, providers of open-weight models, and open-source packages, among them vLLM as the go-to, SGLang, strong for agentic workloads, NVIDIA's TensorRT, fast but narrow, and llama.cpp for CPUs. In this book: Inference › Why this matters.
5:16–8:25 What fast means, and the one high-level bit#
Three metrics capture "fast". Time to first token is how long a user waits before anything appears, which matters for interactive use. Latency is how fast tokens stream for one query. Throughput is tokens per second across many queries, which matters for batch jobs over, say, a petabyte of data. The last two are related and often improve together, though a trade-off appears later. What determines them: in training all tokens are seen at once, since the sequence is one dimension of a large tensor, and the work parallelizes over it. Inference is autoregressive, so tokens are generated one at a time, and nothing parallelizes over the sequence. That is why inference is a very different workload and why it is hard to keep the compute busy. In this book: Inference › The core idea.
8:25–14:23 Notation, and a transformer block as tensor shapes#
The plan: the arithmetic intensity, throughput and latency of a transformer; then techniques that shrink the KV cache, quantize and prune; then speculative sampling and practical concerns. The notation is einops-like: B is the batch, T the sequence, D the model dimension, H the head dimension. In a product, dimensions shown in red contract: they appear in both operands and vanish from the result. Black dimensions appear in one operand and stay. Blue batching dimensions appear in both and stay. With that, a transformer block is drawn like a circuit, which Liang finds the crispest definition of a transformer: the shapes of every tensor and the dependencies. The block maps X through attention and an MLP. Projections produce queries, keys and values; N is the number of query heads, K the number of key-value heads, possibly fewer. The MLP is three products, gate, up and down; F is taken as 4D. The model dimension equals the head dimension multiplied by the number of heads, and in grouped-query attention the heads split into groups and heads per group. Two sequence symbols: s for input tokens, t for output tokens, equal in training, with t equal to one in generation. In this book: Inference › How it works, step by step.
14:23–20:34 Arithmetic intensity, reviewed#
Multiply a B × D matrix by a D × F matrix in BF16. Read the first matrix, 2BD bytes; read the second, 2DF; multiply, 2BDF FLOPs; write the result. Every read and write is quadratic and the product is cubic, which is where high arithmetic intensity comes from: FLOPs over bytes moved. Kept symbolic, the expression simplifies when B is much smaller than D and F: the intensity is about B, the analogue of the n over 3 of square matrices. The hardware's accelerator intensity is its FLOPs per second over its memory bandwidth. An operation above it is compute-bound, below it memory-bound; on an H100 this product is compute-bound for a batch above 295. With a single example the intensity is 1: the whole D × F matrix is read for 2DF FLOPs. That is the inference workload, thin tensors instead of full matrices. In questions, a student corrects the meaning of two symbols, K and G; the lecturer says he will fix the slide later. In this book: Inference › 1. Count one decoding step · Resource Accounting › 5. Find the bottleneck: arithmetic intensity.
20:34–25:08 The KV cache: prefill and generation#
Naive generation feeds the prompt to the transformer, samples a token, appends it and repeats. Since attention over the tokens so far is quadratic, each new token costs order t² and t tokens cost order t³. The repair rests on causality: in a causal transformer the activations of earlier positions do not change when tokens are appended. So the keys and values are stored in high bandwidth memory as a KV cache and reused between steps. There are two stages. Prefill processes the whole prompt, fills the cache and produces the first logits; generation then runs one token at a time, each step reading the cache and adding one key and one value. Formally the cache holds, for each of B sequences, each of S tokens, each layer and each head, one H-dimensional vector. Prefill is parallel like training; generation is sequential but no longer recomputes the past. In this book: Inference › 1. Count one decoding step.
25:08–35:05 Where generation hurts: the intensity of MLP and attention#
Count only the matrix products; the rest is little work and can be fused into them. The MLP, with s past tokens and t new ones, has the same form as the product above, and its intensity is about B times t: for prefill, large batches and long sequences are fine. In generation t is 1, so the intensity is B, which there means the number of concurrent requests: controllable in batch processing, unpredictable for a chatbot, a problem that continuous batching addresses later. Attention is the different story. Its FLOPs are B · s · t · D and its intensity is B-free, scaled by s · t over (s + t). In prefill, where t equals s, that is s over 2: workable for long sequences. In generation, with t equal to 1, it is s over (s + 1), which is below 1 against the 295 an H100 wants. The reason: every sequence passes through the same MLP weights, which are loaded once and reused, so a large batch pays; every sequence has its own KV cache, so a larger batch only adds independent, thin products, as poor as dot products. Prefill is compute-bound and generation is memory-bound, and attention during generation is the fundamental bottleneck of a transformer. In this book: Inference › 1. Count one decoding step.
35:05–44:00 A worked example: Llama 2 13B on an H100#
Because inference is memory-bound, time follows from the bytes to move. The configuration lists the sequence length, the model and MLP dimensions, the query and key-value heads, the head dimension, the layers, the vocabulary and the H100's bandwidth. Memory has two parts: the parameters, at 2 bytes each in BF16, and the KV cache, which is tokens times key-value heads times head dimension times layers, doubled for the key and the value and doubled again for BF16. The total is B times the cache of one sequence plus the parameters. Latency is that memory over the bandwidth; throughput is B over the latency. The parameter count comes out at 13 billion, a sanity check, and the cache at about 838 million bytes per sequence. So latency is linear in B, because the growing cache must be copied back and forth, and throughput rises with B toward an asymptote, as the parameters are shared by more sequences. At a batch of 1: 8 milliseconds per token and 124 tokens per second. A larger batch worsens latency and improves throughput, and the asymptote is never reached, because the cache exhausts the H100's memory; a B200 allows more, up to a limit. A batch is like a bus: everyone waits, then everyone rides. In this book: Inference › Worked example · Inference › 2. Batch requests, up to a point.
44:00–46:16 The trade-off, and time to first token#
Small batches give better latency and worse throughput; large batches the reverse; the choice of batch size decides which "fast" one gets. Parallelism is barely touched: M copies of the model leave the latency unchanged and multiply the throughput by M; the scaling book has more. Time to first token is the prefill time, since generation starts once prefill ends, so a small batch serves it and a large one serves throughput. In this book: Inference › 2. Batch requests, up to a point.
46:16–55:30 Shrinking the KV cache: grouped-query and multi-head latent attention#
The techniques run from architecture to systems. Memory is the bottleneck and the KV cache is a large part of it, larger than the parameters at a big enough batch. Grouped-query attention, seen before, computes one key and value per group of query heads: multi-head attention has as many groups as heads, multi-query attention has one group and, in his words, nobody uses it because it is really bad, and the balance lies between. The 2023 paper shows time per sample falling from multi-head to one group, with eight groups still cheap. The cache shrinks by the ratio of heads to groups. In the Llama example, with a batch of 64, several times fewer key-value heads cut the memory and improved latency and throughput together: the two are not always at odds; mainly the batch size sets them against each other. A batch of 256 that did not fit now fits: latency suffers a little, throughput rises in proportion. The paper's evaluations show little loss, but DeepSeek's later paper found that it does hurt, so anything that is not pure mathematics deserves a grain of salt. DeepSeek's multi-head latent attention keeps one key and value per token but compresses them: the activations are projected into a small number of latent dimensions, 512 against about 16,000 in V2, and the keys and values are reconstructed from it, so only the latent is cached. It conflicts with RoPE, which gets extra dimensions of its own. In DeepSeek's tables it is about as accurate as multi-head attention and better than grouped-query. In this book: Inference › 3. Shrink the KV cache.
55:30–59:10 Sharing across layers; sliding windows#
Cross-layer attention computes keys and values for a subset of the layers and lets the others reuse the previous layer's: sharing across layers what grouped-query attention shares across heads. The paper improves the Pareto frontier of accuracy against cache size. Sliding-window attention is old and natural: each generated token attends to the last K only, so the cache no longer depends on the sequence length, which suits long contexts, and the effective context is longer than the window because information travels down through the layers. Variants space the layers out or add attention to fixed global positions. The price is accuracy: this is no free lunch. Hybrid models interleave layers of full attention with local layers to balance accuracy against speed. In this book: Inference › 3. Shrink the KV cache.
59:10–64:29 Linear attention, and DeepSeek's compressed and sparse attention#
In questions, linear attention against sliding windows: linear methods keep a compressed representation of the whole history, the naive one a sum of keys and values, and Gated DeltaNet and Mamba compress while forgetting less. They have replaced sliding windows with good results, and full attention, sliding windows and linear attention can be combined, since sliding windows keep local detail at high resolution and linear attention gives broad summaries. For retrieval from a very long context a compressed history loses the needle, which is why hybrids keep some long attention; and in expressive power the recurrent layers exceed a sliding window, which can express nothing beyond its window. DeepSeek keeps inventing attention variants, whose acronyms he does not keep straight: a compressed attention that merges every M tokens into one, a sparse attention that scores positions with lightweight queries and keys to choose which to keep, and a more heavily compressed one. Diffusion models are the non-autoregressive alternative. In this book: Inference › 3. Shrink the KV cache · Attention Alternatives and Mixture of Experts › 5. Sparse attention.
64:29–68:00 Quantization#
Quantization is the systems view: lower precision, less memory, faster, if accuracy survives. Options run from BF16 down to 4-bit integers. Quantization-aware training quantizes and dequantizes during the forward pass, so that the weights adapt to the errors, at the price of large-scale training. Post-training quantization is the cheaper norm. The naive version chooses a scale and a zero point per tensor and works less well. GPTQ uses curvature information about the loss to quantize layer by layer and to push each layer's error into the weights not yet quantized. Activation-aware quantization observes that some activation channels are large and that the weights multiplying them matter more, so it keeps most columns at a few bits and gives a few important ones FP16. In this book: Inference › 4. Use smaller numbers · Quantization › 1. Know the number formats.
68:00–71:56 Pruning, and how to tell what matters#
Pruning is crude and works: an NVIDIA paper estimates which parts of a model matter, removes hidden units and whole layers, then heals the model with further training on the data or tasks of interest. A 15-billion-parameter model became an 8-billion one with little loss of accuracy and far less training than from scratch. The game in sum: reduce parameters or KV cache without hurting accuracy, either by training a faster architecture or by initializing it from the original model, a Frankenstein in his word, and repairing it with distillation. How to tell the important parts? Pass a calibration set through and look at the magnitude of activations; dead units sit near zero. What if everything is large? Empirically some channels are much larger than others, which is what makes these methods work. A unit that is always at a hundred has high mean and low variance and could be folded into a bias. In this book: Inference › 5. Use a smaller model · Pruning and Sparsity › Step 1: Choose the granularity.
71:56–76:56 Speculative sampling#
Everything so far was lossy. Speculative sampling is lossless and rests on an asymmetry: prefill checks a whole sequence in parallel and is compute-bound, so checking is much faster than generating one token at a time. A cheap draft model generates a few tokens, say four, and the target model verifies them all in one pass. The work is balanced: the draft model is memory-bound but small; the target is huge but runs a batch. In the video the tokens come in bursts. The algorithm, from several papers of the same period: sample K tokens from the draft model P, compute their logits under the target Q in parallel, and accept each with probability the minimum of 1 and Q over P; on a rejection, sample from the residual distribution and stop. It is rejection sampling that never comes back empty-handed: the proof, which he skips, shows that the output is an exact sample from the target. Too few draft tokens waste the target's parallelism and too many are rejected, so in this case three or four is the sweet spot. The draft model should be as close to the target as possible, so it is distilled, which makes the shrinking techniques above apply to it too: a reduced model that is good enough is served, and otherwise it drafts. In this book: Inference › 6. Check instead of generate: speculative sampling.
76:56–83:40 Dynamic workloads: continuous batching, selective batching, paging#
A live server receives requests at different times, with different prefixes and lengths, far from the tidy blocks of training. Orca, an early system, introduced continuous batching: each step decodes one token for every active sequence, a finished sequence is ejected and a new request is admitted, so the batch changes without pause. Lengths differ, and tensors want equal shapes. Selective batching leaves attention per sequence, since it depends on the length, but concatenates all sequences into one long sequence for the MLPs, which take up a lot of the FLOPs. PagedAttention, the core idea of vLLM at its start, addresses fragmentation: memory reserved up to a maximum output length sits unused inside a request, and gaps between requests go to waste. The systems people borrowed the operating system's answer: the cache of a sequence is cut into non-contiguous blocks, four tokens each in the example, tracked by indices. Requests that share a prefix share its blocks: a system prompt is cached once for everybody, and several responses to one prompt share the prompt's cache until their samples diverge, when a block is split: copy-on-write. In this book: Inference › 7. Run a server, not a loop.
83:40–1:26:00 Summary#
Inference matters greatly and differs from training although the model is the same: it is memory-bound, and dynamic in a live service. The techniques, quantization, new architectures, pruning with distillation and speculative sampling, share one principle, shrink the KV cache without hurting accuracy much, and systems ideas such as paging and speculative execution serve the live server. New architectures, state-space models, linear attention or diffusion, have, in his view, a huge potential: the KV cache and the way attention is built make the transformer, which was not designed for inference, an inference-unfriendly design. Hashimoto returns with the second lecture on scaling laws. In this book: Inference › Key takeaways · Inference › What the practitioners say.
What to take away#
- Prefill, like training, sees every token at once and is compute-bound; generation emits one token at a time, reads every weight for each one, and is memory-bound, so time is bytes moved over bandwidth.
- In prefill the MLP's intensity is about batch times sequence length and attention's about half the sequence length; in generation attention's intensity is below 1 whatever the batch, since each sequence has its own cache.
- Latency grows linearly with the batch and throughput rises toward an asymptote that memory limits keep out of reach; smaller batches serve latency and time to first token, larger ones throughput.
- A smaller KV cache improves both at once: grouped-query attention, multi-head latent attention, cross-layer sharing, sliding windows and hybrids, each a lossy change whose cost in accuracy has to be checked.
- Lower-precision numbers, pruning with repair, speculative sampling, which is lossless, and paging with prefix sharing complete the toolkit.
Sources#
- Percy Liang and the course staff, "Inference", Stanford CS336 Language Modeling from Scratch, Spring 2026: video.
- Course page: https://cs336.stanford.edu/.