Chapter 6 · Inference and Efficiency¶
6.1 Decoding Strategies ★★¶
Greedy and beam search ★★¶
At each step the model outputs a probability distribution over the whole vocabulary for the next token, and the decoding strategy decides how to pick a token from it.
Greedy decoding always picks the most probable token. It is simple, deterministic and the cheapest, but it has two problems. First, it is short-sighted: being locally best at every step doesn't give the most probable sequence overall. For example, picking a word with probability 0.4 at the first step might force an awkward continuation, while another word with probability 0.3 might lead to a very smooth path. Second, in open-ended generation it easily falls into repetition loops: once a sentence has appeared, the model becomes more likely to repeat it, and greedy always takes the top choice, so the more it repeats, the more certain it becomes, and it keeps going in circles.
Beam search fixes greedy's short-sightedness: at each step it keeps the \(k\) partial sequences (beams) with the highest cumulative log-probability, extends each beam by one token, and picks the new top \(k\) from all candidates, until generation ends; it then outputs the highest-scoring complete sequence. Since log-probabilities are negative, longer sequences accumulate smaller totals, so beam search naturally favors short outputs and needs length normalization: in the formula, \(x\) is the input, \(y\) the generated sequence, \(|y|\) its length, and \(\alpha\) (usually 0.6–1.0) controls how strongly length is normalized.
Interview questions
- ★★ What are the problems with greedy decoding and beam search?
- ★ Why does beam search need length normalization?
Why beam search is rare in open-ended generation ★★¶
- The most probable text isn't the best text. Holtzman et al. (2019) found that human-written text is not what the model considers most probable: people regularly use surprising but highly informative words. Searching specifically for the most probable sequence tends to produce empty, generic, repetitive text. Beam search searches more thoroughly than greedy, so the problem gets worse; larger beams often give shorter, blander outputs.
- Low diversity. The \(k\) beams often differ by only a few words and are essentially the same answer, so they don't help when you want several different candidates.
- Expensive and hard to stream. It must maintain \(k\) sequences and their KV caches at once, and which beam wins isn't known until the end, so you can't show output to the user as it's generated.
- Little gain for today's chat models. After RLHF, the output distribution is already sharp, so beam search adds little. If you really want higher quality, sampling \(N\) candidates and choosing with a verifier or reward model (see Chapter 7, Section 7.3) works better.
Beam search is still a good fit for tasks with a nearly unique answer that is tightly constrained by the input, such as machine translation, speech recognition and very short structured outputs.
Interview questions
- ★★ Why is beam search rarely used for open-ended generation?
Temperature, top-k and top-p ★★¶
Sampling means drawing a token at random according to the distribution, which makes outputs more natural and varied. But sampling from the full distribution has a problem: the vocabulary has over a hundred thousand tokens, most with tiny individual probabilities, yet this "long tail" adds up to a sizable total. Over a few hundred tokens, you are almost certain to draw an absurd token at some step; and once drawn, the model treats it as fact and keeps writing, so everything after it drifts off. The three methods below all exist to control this.
Temperature divides each token's logit \(z_i\) by the temperature \(T\) before softmax. With \(T < 1\), gaps between scores are amplified and the distribution sharpens, so high-probability tokens are picked more often and output is more conservative; as \(T \to 0\) it becomes greedy. With \(T > 1\), the distribution flattens and low-probability tokens get more chances, so output is more varied and more error-prone; as \(T \to \infty\) it approaches uniform random over the vocabulary. \(T = 1\) is the model's original distribution. Temperature only reshapes the distribution; it never sets any token's probability to 0.
Top-k (Fan et al. 2018) keeps only the \(k\) most probable tokens, renormalizes and samples, cutting off the long tail directly. Its problem is that \(k\) is fixed and doesn't adapt to the shape of the distribution: when there are many reasonable next words (say, "Today I feel like eating _"), a small \(k\) cuts off reasonable choices; when the next word is nearly certain (say, "The United States of _"), most of the \(k\) candidates are junk.
Top-p (nucleus sampling, Holtzman et al. 2019) truncates by cumulative probability instead: sort tokens from most to least probable, keep the smallest set \(V_p\) whose cumulative probability reaches \(p\) (e.g. 0.9 or 0.95), and sample from it. When the distribution is flat, many tokens are needed to reach \(p\), so the candidate set grows on its own; when it's sharp, one or two tokens may suffice, so the set shrinks on its own. This adaptivity is exactly why it beats top-k.
In practice these are often combined: apply repetition penalties first (see below), then divide by the temperature, then apply top-k and top-p truncation, then sample (the order differs slightly between frameworks). (There is also min-p, which keeps only tokens whose probability is at least some fraction of the top token's probability.)
Interview questions
- ★★ How does temperature work, and what happens as \(T \to 0\) and \(T \to \infty\)?
- ★★ Why is top-p better than top-k?
Repetition penalty ★¶
The most direct fix for repetition loops is to lower the scores of tokens that have already appeared. The repetition penalty from CTRL (Keskar et al. 2019) rescales the logits of tokens already generated, with \(\theta > 1\) (commonly 1.1–1.3). Positive and negative logits are handled separately: dividing a positive logit by \(\theta\) makes it smaller, but dividing a negative logit by \(\theta\) would make it larger (closer to 0), so negative logits are multiplied by \(\theta\) instead. The frequency penalty and presence penalty in the OpenAI API are another form (right side of the formula): \(c_i\) is how many times token \(i\) has appeared; the frequency penalty \(\alpha\) subtracts in proportion to that count, so the more often a token appears, the more it's penalized; the presence penalty \(\beta\) subtracts a fixed amount once a token has appeared at all, nudging the model toward new content.
The cost is that it can't tell harmful repetition from necessary repetition: variable names in code, people's names, formatting symbols and common function words are supposed to recur, and a heavy penalty breaks code and makes prose awkward. So it's usually applied lightly, and avoided for code and structured output.
Interview questions
- ★ Why does the repetition penalty treat positive and negative logits differently, and what are its side effects?
When to use which ★★¶
| Scenario | Typical setting | Why |
|---|---|---|
| Extraction, classification, short factual answers | Greedy or \(T \approx 0\) | One correct answer; reproducible |
| Code or math with a standard (non-reasoning) model | Low \(T\) (0–0.3), optional top-p | Precision matters; a little randomness avoids loops |
| General chat assistant | \(T \approx 0.7\), top-p ≈ 0.9 | Natural and varied, with the tail cut off |
| Creative writing, brainstorming | \(T \approx 1\), top-p ≈ 0.95 | Diversity |
| Reasoning models with long CoT | \(T \approx 0.6\), top-p 0.95, no greedy (official advice for DeepSeek-R1, Qwen3) | Greedy tends to loop over thousands of tokens |
| Best-of-N, self-consistency | \(T \approx\) 0.7–1.0 | Samples must differ for voting or reranking to help |
| Translation, speech recognition | Beam search | Near-unique correct output, constrained by the input |
The general rule: the more a task has a single correct answer, the more you should reduce randomness; the more you need diversity, the higher the temperature can go. Two points deserve special attention. First, reasoning models: the official advice for both DeepSeek-R1 and Qwen3 is a temperature around 0.6 with top-p 0.95, and they explicitly advise against greedy decoding, because over long chains of thought of thousands of tokens, greedy easily falls into endless repetition. Second, when you need several candidates (best-of-N, self-consistency), you must use a fairly high temperature so the samples really differ; otherwise the \(N\) samples are nearly identical and voting or reranking becomes pointless.
Interview questions
- ★★ Compare greedy, beam search, top-k and top-p. When would you use each?
- ★ Why is greedy decoding discouraged for reasoning models?
-
★ Is the output always fully deterministic at temperature 0?
Not necessarily. In theory \(T = 0\) is greedy and should be deterministic. But in a real serving system, the same request is batched with different other requests each time, and with different batch sizes the order of floating-point sums inside GPU kernels can differ. Floating-point addition isn't associative, so the results differ slightly. When two tokens have very close logits, that tiny difference can flip the argmax, and the rest of the generation diverges completely. In MoE implementations with capacity limits, whether a token gets dropped can also depend on other requests in the same batch. Full reproducibility needs batch-invariant kernels or a fixed execution setup.
6.2 KV Cache Memory and PagedAttention ★★¶
The problem: wasted KV cache memory ★¶
The basics of the KV cache and how to estimate its size are in Chapter 1, Sections 1.3 and 1.5. In a serving system, model weights take a fixed amount of memory, and most of the rest holds the KV cache. So how many requests fit in the KV cache directly decides how many requests can run at once (the batch size), and therefore the throughput.
The difficulty is that you don't know in advance how long each request's output will be. Early systems pre-allocated a contiguous chunk of memory per request, sized for the maximum possible length. This wastes memory in three ways:
- Reservation waste: a request that will eventually produce 500 tokens holds all 500 slots from the start. Until generation gets there, those slots sit empty and no other request can use them.
- Internal fragmentation: space is reserved for the maximum length (say 2,048), but only 100 tokens are actually generated, and the rest is wasted.
- External fragmentation: after contiguous chunks of different sizes are repeatedly allocated and freed, memory is left with many small holes that add up to a lot but can't form one whole chunk.
Kwon et al. (2023) measured that in the systems of the time, only 20%–38% of KV cache memory actually stored token states.
Interview questions
- ★ Why does traditional KV cache allocation waste memory?
PagedAttention ★★¶
Request A, block size = 4 tokens
Logical blocks: [The cat sat on] [the mat and ...]
Block table: logical 0 → physical 7, logical 1 → physical 2
Physical memory: [ 0 ][ 1 ][A:1][ 3 ][B:0][ 5 ][ 6 ][A:0] ...
PagedAttention (Kwon et al. 2023, vLLM) borrows virtual-memory paging from operating systems. It splits each sequence's KV cache into fixed-size blocks (say 16 tokens each) that can live anywhere in GPU memory, with no need to be contiguous. Each sequence has a block table recording which physical block holds each logical block, just like an OS page table. During generation, a new physical block is allocated only when the current last block is full. The attention kernel is modified accordingly to read K and V from non-contiguous locations via the block table.
As a result, reservation waste and external fragmentation disappear, and internal fragmentation is limited to each sequence's last, partly filled block, bringing waste below 4%. The saved memory holds more requests, so batches get larger; the paper reports 2–4× higher throughput than systems such as FasterTransformer and Orca at the same latency.
Paging also enables sharing. Several sequences can point to the same physical block, managed by reference counts. For example, when sampling several answers to one prompt (parallel sampling), the prompt's KV cache is stored only once; different beams in beam search can also share their prefix. When a sequence needs to modify a shared block, it first makes its own copy (copy-on-write). This is also the foundation of prefix caching in Section 6.3. When memory runs short, some requests' blocks can be swapped out to CPU memory, or dropped and recomputed later (preemption).
The cost is that the kernel must address memory indirectly through the block table, which is slightly more complex than reading contiguous memory and adds a little overhead, negligible compared with the memory saved.
Interview questions
- ★★ What problem does PagedAttention solve, and how?
- ★ How does PagedAttention let several sequences share a KV cache?
- ★ What problem does FlashAttention solve, and what problem does PagedAttention solve?
6.3 Continuous Batching and Prefix Caching ★★¶
Why batching raises throughput ★¶
As Chapter 1, Section 1.3 explained, decode is limited by memory bandwidth: every step reads all the weights from memory but computes only one token per sequence. If \(B\) sequences decode together, the weights are read once and serve one token for each of the \(B\) sequences. The formula measures "how much compute per byte read" (arithmetic intensity): each token costs about \(2N\) FLOPs (\(N\) is the parameter count), and bf16 weights take \(2N\) bytes, so the intensity is about \(B\). A GPU's ratio of compute to bandwidth is usually one to a few hundred FLOPs per byte, so while \(B\) is small, enlarging the batch barely increases the time per step, and throughput grows nearly linearly until the system becomes compute-bound.
One caveat: each sequence's KV cache is its own, so unlike the weights it can't be read once for the whole batch. The longer the context, the larger the share of time spent reading KV cache, and the smaller the gain from a bigger batch; the memory taken by the KV cache also caps how large the batch can be. This is why KV cache memory management (6.2) matters so much.
Interview questions
- ★ Why does a larger batch raise decode throughput, and when does the gain shrink?
Continuous batching ★★¶
The simplest approach is static batching: gather a batch of requests and run them together until every sequence in the batch finishes, then start the next batch. The problem is that output lengths vary enormously: some requests end after 10 tokens, others need 2,000. Sequences that finish early just occupy their slots while waiting for the longest one, and new requests must wait for the whole batch to end before joining. The GPU is underused most of the time, and queueing latency is high.
Continuous batching (Orca, Yu et al. 2022, also called iteration-level scheduling) moves the scheduling granularity from "a batch of requests" to "each decode step": at the end of every step, finished sequences leave the batch immediately and free their KV cache, and queued requests join at the next step. New requests' prefill and old requests' decode can run in the same step: attention is computed per request, while the other per-token operations (linear layers, FFN) simply concatenate all tokens together. The batch stays full, throughput rises sharply, and new requests don't queue for long. It needs flexible memory management like PagedAttention to admit and release requests at any time. Inference frameworks such as vLLM, SGLang and TensorRT-LLM all use it by default.
It also creates a new problem: when a very long prompt joins, its prefill is so heavy that every request decoding in the same step has to wait, and the output stutters. Chunked prefill (Sarathi / Sarathi-Serve, Agrawal et al. 2023, 2024) splits a long prompt's prefill into chunks and processes one chunk per step alongside other requests' decodes. The work per step becomes more even, decode no longer stalls suddenly, and the compute that decode leaves unused gets filled by prefill.
Interview questions
- ★★ What is continuous batching, and why is it better than static batching?
- ★ Why does vLLM achieve much higher throughput than naive HuggingFace generate?
- ★ What is chunked prefill, and what problem does it solve?
Prefix caching ★★¶
Many requests share the same beginning: an application's system prompt, few-shot examples, the history of a multi-turn chat, an agent's tool descriptions, or several questions about the same long document. Because of the causal mask, a token's K and V depend only on itself and the tokens before it, so an identical prefix always produces an identical KV cache, and there's no need to recompute it every time. Prefix caching keeps the KV cache of prefixes already computed; when a new request starts the same way, it reuses that cache and only prefills the part that differs.
In terms of implementation, vLLM's automatic prefix caching computes a hash for each full block (determined by the block and all tokens before it), and new requests look up reusable physical blocks by hash. SGLang's RadixAttention (Zheng et al. 2023) organizes all cached token sequences in a radix tree, finds the longest common prefix, and evicts rarely used entries with an LRU policy.
The benefit: with a long shared prefix, both TTFT and prefill compute drop sharply. This is also why API providers charge less for cache-hit input tokens (prompt caching).
The limitation: a hit requires an exact token-by-token match starting from the very first token. If anything in the prefix changes, say the current time is placed at the start of the system prompt, every KV after it has to be recomputed. And because positional encoding (RoPE) makes K depend on position, the same text at a different position produces different KV and can't be reused. So when designing prompts, put the fixed content first and the changing content last.
Interview questions
- ★★ How does prefix caching work, and when does it hit?
- ★ Why does putting a timestamp at the start of the system prompt break prefix caching?
6.4 Speculative Decoding ★★¶
Core idea ★★¶
Speculative decoding (Leviathan et al. 2022; Chen et al. 2023) exploits the fact that decode is memory-bandwidth-bound: one forward pass of a large model takes about the same time for 1 token as for 5, because most of the time goes into reading the weights. So if the next few tokens can be "guessed" cheaply, the large model can check them all in a single forward pass. Concretely:
- A much smaller draft model \(q\) (e.g. a 1B model from the same family as a 70B target, which must use the same tokenizer) autoregressively generates \(\gamma\) candidate tokens \(x_1, \dots, x_\gamma\). The small model is fast, so this step is cheap.
- The prefix plus these \(\gamma\) candidates is fed into the target model \(p\) in one forward pass. Just like teacher forcing in training, a single forward pass yields the target model's distributions at all \(\gamma + 1\) positions at once.
- The candidates are accepted or rejected one by one from left to right (the rule is in the next subsection). At the first rejected position, that position is resampled from a corrected distribution and all later candidates are discarded; if all \(\gamma\) are accepted, one bonus token is sampled for free from the target's distribution at position \(\gamma + 1\).
So every forward pass of the target model produces at least 1 token (the same as ordinary decoding) and at most \(\gamma + 1\).
Interview questions
- ★★ How does speculative decoding work, and why is it faster?
The acceptance rule: why the distribution is unchanged ★★¶
Here \(p(x)\) is the target model's probability for token \(x\) and \(q(x)\) is the draft model's. The intuition: if \(p(x) \ge q(x)\), the draft "under-proposes" this token, so it's always accepted; if \(p(x) < q(x)\), the draft "over-proposes" it, so it's accepted only with probability \(p(x)/q(x)\), rejecting the excess.
Why does the output then follow the target distribution exactly? Compute it in two parts. First, the probability of outputting \(x\) via "the draft proposes it and it's accepted" is \(q(x) \cdot \min(1, p(x)/q(x)) = \min(p(x), q(x))\), which falls short of the target probability \(p(x)\) by \(\max(0, p(x) - q(x))\). Second, resampling from \(p'\) after a rejection fills exactly this gap: the total rejection probability is \(\sum_x \max(0, q(x) - p(x))\), which, since \(p\) and \(q\) both sum to 1, equals \(\sum_x \max(0, p(x) - q(x))\), the normalizer of \(p'\); so \(P(\text{reject}) \cdot p'(x) = \max(0, p(x) - q(x))\). The two parts add up to exactly \(p(x)\). Every position is handled this way: while all earlier candidates are accepted, the current position has exactly the prefix the target model would have produced itself; once a position is rejected and resampled, the later candidates were guessed from the old prefix and are all discarded. So by induction over positions, the whole sequence follows the target model's distribution.
So speculative decoding is lossless: it isn't an approximation; the output distribution is exactly the same as sampling token by token from the large model, just faster. With greedy decoding the rule simplifies to: accept the draft token if it equals the target model's argmax, otherwise replace it with the target's argmax.
Interview questions
- ★★ Write the acceptance rule of speculative decoding and explain why the output distribution matches the target model exactly.
Speedup and when it helps ★¶
\(\alpha\) is the probability that a candidate token is accepted; it measures how close the draft is to the target (\(\alpha = 1\) when they're identical). Assuming positions are independent, the expected number of tokens per target forward pass is given by the formula. For example, with \(\alpha = 0.8\) and \(\gamma = 4\) it's about 3.4. The real speedup must subtract the draft model's own cost and the extra compute of verifying several tokens, and is commonly 2–3×. Factors that affect it:
- How predictable the text is. When writing code, producing structured output or restating the input, the draft guesses right easily, \(\alpha\) is high and the speedup is large; open-ended creative writing has a much lower \(\alpha\).
- The choice of \(\gamma\). Too small, and each pass gains few extra tokens; too large, and most later candidates are rejected, so the draft's work is wasted.
- Batch size. Speculative decoding assumes the target model has spare compute. At large batch sizes the system is already close to compute-bound, so verifying extra tokens is no longer "free", and rejected tokens waste compute; the gain drops sharply and can even turn into a slowdown. So it suits low-batch, latency-sensitive serving best.
Interview questions
- ★ When does speculative decoding give little speedup?
Medusa and EAGLE ★¶
A separate draft model has its own hassles: you need a small model whose distribution is close to the target's and that shares its tokenizer, it takes extra memory, and the two models must be scheduled together in deployment. This led to methods where the target model "brings its own draft".
Medusa (Cai et al. 2024) adds several extra decoding heads on the target model's last hidden state: head \(k\) directly predicts the token \(k+1\) positions ahead. The top candidates from the heads are combined into a candidate tree, and tree attention (a special mask that lets each path in the tree see only its own ancestors) verifies all branches in one forward pass, picking the longest accepted path. The heads are lightweight and can be trained on a frozen backbone. By default Medusa uses a relaxed "typical acceptance" rule, trading a small distribution shift for a higher acceptance rate; to preserve the distribution exactly, it can use the rejection sampling above instead. Its weakness: all heads start from the same hidden state and predict later tokens without knowing what was actually sampled in between, so later heads are less accurate.
EAGLE (Li et al. 2024) uses a very light draft head (about one Transformer layer) that is autoregressive at the feature level: its input is the target model's top-layer features plus the tokens already sampled, and it predicts the next feature and token step by step. It uses the large model's rich features and also knows what was actually sampled, so its acceptance rate is much higher than Medusa's, and it uses the standard verification rule, so it's lossless. (Follow-ups EAGLE-2/3 raise acceptance further with dynamic candidate trees and multi-layer features; there is also prompt lookup, which copies n-grams from the context as candidates, and using DeepSeek-V3's MTP modules as the draft.)
Interview questions
- ★ How do Medusa and EAGLE differ from a separate draft model, and what are their weaknesses?
6.5 Quantization ★★¶
Quantization basics ★★¶
Quantization represents weights or activations with fewer bits. The formula is the most common symmetric quantization: \(b\) is the number of bits and \(s\) is the scale, which maps the largest absolute value in the group to the largest integer. Each number \(x\) is divided by \(s\) and rounded to an integer \(x_q\) for storage, then multiplied back by \(s\) at use time to get the approximation \(\hat x\). Each number's error is at most \(s/2\). (Asymmetric quantization adds a zero point, which suits data not centered at 0.)
The formula reveals the single most important fact about quantization: the scale is set by the largest value in the group. A single large outlier inflates \(s\), and all the normally sized numbers get only a few integer levels, losing a lot of precision. That's why granularity matters: per-tensor (one scale for the whole tensor) is simplest but most easily hurt by outliers; per-channel (one scale per output channel) and per-group (one scale per group of 64 or 128 weights) are finer and more accurate, at the cost of storing more scales and slightly more complex computation.
Why quantize?
- Save memory. A 70B model needs 140 GB in bf16 but only about 35 GB in INT4 (plus a few scales), so it fits on fewer GPUs.
- Speed up decode. Decode is memory-bandwidth-bound, so fewer bytes per weight cut the time to read weights almost proportionally, and generation gets faster.
- Speed up compute. When both weights and activations are quantized to INT8/FP8, low-precision Tensor Cores can be used, so the matrix multiplications themselves run faster.
Interview questions
- ★ How do per-tensor, per-channel and per-group quantization differ, and why is finer granularity more accurate?
PTQ vs QAT ★★¶
Post-training quantization (PTQ) quantizes an already trained model directly, with no further training. It usually needs only a tiny calibration set (a few hundred samples) to measure activation ranges or compensate for quantization error, and finishes in minutes to hours. At 8 bits PTQ is nearly lossless; 4-bit weight quantization with good methods (GPTQ, AWQ) keeps most of the quality; below that, quality drops noticeably.
Quantization-aware training (QAT) simulates quantization during training: in the forward pass, weights (or activations) are quantized and then dequantized (fake quantization), so the model "feels" the quantization error while training and learns weights that are robust to it. The difficulty is that the round function has zero derivative almost everywhere, so gradients can't flow back; the backward pass therefore uses the straight-through estimator (STE), treating round's derivative as 1 so the gradient passes straight through. QAT clearly beats PTQ at low bit widths (4 bits or fewer), at the cost of training compute and data. A middle ground is a short quantization-aware fine-tuning phase at the end of training (Gemma 3, for example, released QAT INT4 checkpoints).
Interview questions
- ★★ How do PTQ and QAT differ, and when is each appropriate?
- ★ In QAT, round isn't differentiable. How do gradients flow back?
Weight-only vs weight + activation ★★¶
| Weight-only (W4A16, W8A16) | Weight + activation (W8A8, FP8) | |
|---|---|---|
| What is low-precision | Weights only; dequantized to 16-bit inside the kernel | Weights and activations; the matmul runs in INT8/FP8 |
| FLOPs | Unchanged (16-bit matmul) | Run on faster low-precision Tensor Cores |
| Main benefit | Less memory and less weight traffic | Faster matmuls |
| Helps most | Decode at small batch (memory-bound) | Prefill and large-batch serving (compute-bound) |
| Main difficulty | Accuracy at 4 bits and below | Activation outliers |
| Representative methods | GPTQ, AWQ | LLM.int8(), SmoothQuant, FP8 |
Weight-only quantization (e.g. W4A16: 4-bit weights, 16-bit activations) dequantizes the weights back to 16-bit inside the kernel and then does an ordinary 16-bit matmul. So it doesn't reduce compute; it reduces memory and the amount of weight data read. It speeds things up clearly when bandwidth is the bottleneck (decode, small batches), but barely helps when compute is the bottleneck (prefill, large batches), where dequantization even adds overhead.
Quantizing both weights and activations (e.g. W8A8, in INT8 or FP8) runs the matmul directly on low-precision Tensor Cores, so the computation itself gets faster, with the biggest gains in prefill and large-batch serving. The hard part is activations: weights are fixed and can be carefully quantized offline, but activations change with every input, must be quantized on the fly, and LLM activations contain severe outliers (see below).
Interview questions
- ★ Does weight-only quantization speed up inference, and in which settings?
GPTQ and AWQ ★★¶
GPTQ (Frantar et al. 2022) quantizes layer by layer, aiming to keep each layer's output as close as possible to the original: \(W\) is the layer's weight, \(\hat W\) the quantized weight, and \(X\) the calibration inputs to this layer. It quantizes one column (input dimension) at a time: after each column is quantized, the error it introduced is spread onto the columns not yet quantized, using second-order information (the inverse of the Hessian \(H = 2XX^\top\)) to adjust their values and cancel the error (an idea from the classic Optimal Brain Surgeon). The intuition: input dimensions are correlated, so one weight's quantization error can be partly compensated by other weights related to it. GPTQ is efficient; the paper reports quantizing a 175B model to 3–4 bits in about 4 GPU hours. Its risk is some overfitting to the calibration data distribution.
AWQ (Lin et al. 2023) starts from a different observation: weights are not equally important, and protecting only about 1% of "salient" weights greatly reduces quantization error. Which weights are salient is decided by the size of the corresponding activations, not the weights themselves: errors in channels with large input activations get amplified the most. The most direct fix is keeping those weights in fp16, but mixed precision is hardware-unfriendly. AWQ uses scaling instead: multiply the salient channels' weights by \(s > 1\) and divide the corresponding activations by \(s\), which is mathematically equivalent. When the scaled-up weight is quantized, its absolute error stays about the same (since a group's scale is mostly set by the other weights), but that error is finally multiplied by an activation that is \(s\) times smaller, so its effect on the output shrinks. Each channel's \(s\) is found by a simple grid search on calibration data. AWQ needs no backpropagation and no column-by-column error reconstruction, so it depends less on the calibration data and generalizes better to other domains; it's widely used in practice.
Interview questions
- ★★ What are the core ideas of GPTQ and AWQ?
- ★ Why does AWQ judge weight importance by activation size rather than weight size?
Activation outliers and SmoothQuant ★★¶
Why are LLM activations harder to quantize than weights? LLM.int8() (Dettmers et al. 2022) found that once models reach about 6.7B parameters, systematic outliers appear in the activations: a few hidden dimensions (channels) have values far larger than the rest, and they show up in the same channels for almost every token and in most layers. With per-tensor INT8 activation quantization, the scale is inflated by these outliers, all the normal values get squeezed into one or two levels near zero, and model quality collapses. LLM.int8()'s fix is mixed-precision decomposition: compute the outlier channels separately in fp16 and the rest in INT8. Quality is preserved, but the kernel is complex and not fast.
SmoothQuant (Xiao et al. 2022) builds on a key fact: activation outliers are concentrated in fixed channels, while weights are smooth and easy to quantize. So part of the quantization difficulty can be "migrated" from activations to weights. For each input channel \(j\), choose a scaling factor \(s_j\): divide column \(j\) of the activations, \(X_{:,j}\), by \(s_j\) (shrinking the outlier channels) and multiply row \(j\) of the weights, \(W_{j,:}\), by \(s_j\) (compensating), leaving the matmul result unchanged. \(s_j\) is given by the formula, where \(\alpha\) (usually 0.5) controls how much difficulty is migrated: the larger \(\alpha\), the more goes to the weights. The scaling can be folded offline into the previous LayerNorm or linear layer, so it costs nothing at inference. Both activations and weights then become easy to quantize, enabling nearly lossless W8A8 INT8 inference. (Rotation methods such as QuaRot and SpinQuant go further, multiplying by orthogonal matrices to spread outliers across all channels, which allows 4-bit activations.)
Interview questions
- ★★ Why are LLM activations harder to quantize than weights, and how does SmoothQuant fix this?
KV cache quantization ★¶
With long contexts and large batches, the KV cache is often larger than the model weights (the example in Chapter 1, Section 1.5: one 8K sequence on Llama 3 8B needs 1 GB of KV cache). Weight-only quantization doesn't shrink the KV cache, so it must be quantized separately. Storing the KV cache in FP8 or INT8 halves both its memory and the data attention reads, so more requests or longer contexts fit, with essentially no quality loss; mainstream inference frameworks all support it.
Going down to 4 or 2 bits requires handling K and V according to their different properties. KIVI (Liu et al. 2024) found that keys have channel-wise outliers (some dimensions are large for every token), so keys should be quantized per channel, giving each channel its own scale; values have no such pattern, and the attention output is a token-weighted sum of values, so it's better to keep errors isolated per token, and values are quantized per token. The most recent tokens are usually kept in full precision, since they matter most for the current generation.
Interview questions
- ★ In KV cache quantization, why do keys and values use different granularities?
6.6 Serving Metrics ★¶
| Metric | Definition | Mainly driven by | Matters for |
|---|---|---|---|
| TTFT | Request arrival → first output token | Queueing + prefill (prompt length) | Perceived responsiveness |
| TPOT | Average time per output token after the first | Decode step time: batch size, model size, KV cache length | Streaming speed, long outputs |
| ITL | Gap between each pair of consecutive tokens (a distribution) | Decode step time plus stalls from prefills in the batch | Smoothness, tail latency (P99) |
| E2E latency | Arrival → last token | TTFT + all decode steps | Non-streaming use, agents |
| Throughput | Output tokens (or requests) per second per GPU | Batch size, memory efficiency | Cost |
| Goodput | Throughput counting only requests that meet latency SLOs | Both latency and throughput | Real serving capacity |
These are the most common metrics for an inference service. TTFT (time to first token) is the time from a request's arrival to its first output token, including queueing and the prefill of the whole prompt; the longer the prompt and the busier the system, the larger the TTFT. It decides whether the service feels responsive. TPOT (time per output token) is the average time per token after the first, set by how long each decode step takes; it decides how fast text appears when streaming. ITL (inter-token latency) is the gap between each pair of consecutive tokens. TPOT is its average, but ITL looks at the whole distribution, especially the tail (e.g. P99): if a long prompt's prefill cuts in, a few token gaps suddenly stretch and the user notices stutter, which the average hides. A request's end-to-end latency is roughly TTFT plus TPOT times the number of remaining tokens (\(n_{\text{out}}\) is the number of output tokens). Throughput is the number of tokens generated (or requests served) per second per GPU, which directly sets the cost.
Throughput and latency trade off, again because decode is bandwidth-bound: the larger the batch, the more sequences one read of the weights serves, so throughput rises; but each step does more compute and reads more KV cache, so each step gets slower and TPOT rises; with more requests competing, prefills also interfere with each other, worsening the tails of TTFT and ITL. So you pick an operating point based on the latency requirements (SLOs): a chat product must keep TTFT and TPOT within what users accept; offline batch jobs (synthetic data generation, evaluation runs) don't care about per-request latency and simply maximize throughput. Goodput (Zhong et al. 2024) combines the two by counting throughput only from requests that meet their latency SLOs, which better reflects a system's real serving capacity.
Different applications care about different things: a reasoning model generates thousands of tokens per answer, so TPOT dominates total time; an agent calls the model many times in a row with an ever-longer context, so TTFT and prefix caching become critical.
Interview questions
- ★★ What are TTFT and TPOT, and what mainly drives each?
- ★ Why do throughput and latency trade off?
- ★ How would you reduce TTFT? And TPOT?
6.7 Prefill-Decode Disaggregation ★¶
Prefill and decode have completely different bottlenecks (see Chapter 1, Section 1.3): prefill is compute-bound, decode is memory-bandwidth-bound. Running them mixed on the same GPUs makes them interfere: a long prompt's prefill makes every request decoding in the same batch wait, causing ITL spikes; conversely, protecting decode latency forces limits on batch or prefill size, wasting compute. The two phases also want different configurations: prefill benefits from more tensor parallelism to cut TTFT, while decode needs large batches and lots of memory for the KV cache. Chunked prefill (6.3) eases the interference, but it can't give the two phases different configurations.
Prefill/decode disaggregation puts the two phases on separate GPU pools: prefill instances only process prompts and compute the KV cache, which is then sent over a fast interconnect (NVLink or an RDMA network) to a decode instance that continues generating. Each pool can choose its own parallelism, hardware and instance count, tuned separately for TTFT and TPOT, so they no longer drag each other down, and goodput under latency SLOs is higher (DistServe, Zhong et al. 2024; Splitwise, Patel et al. 2023). Kimi's Mooncake (Qin et al. 2024) goes further and designs the whole serving architecture around the KV cache, and DeepSeek-V3's production deployment also separates prefill and decode into different deployment units (DeepSeek-AI 2024).
The costs: transferring the KV cache needs high bandwidth, and longer prompts mean more data to move; scheduling is more complex, since the load of the two pools must be balanced; and at small scale it's hard to keep both pools busy, which wastes resources. So it's mainly used in large deployments.
Interview questions
- ★ Why deploy prefill and decode separately, and what does it cost?
6.8 Efficient Long-Context Inference ★¶
As the context grows, inference cost grows in three directions: KV cache memory grows linearly with length, so fewer requests can be served at once; every decode step reads the whole KV cache, so the time per token grows linearly; and attention compute in prefill grows quadratically. Two families of methods that leave attention unchanged were covered earlier: storing less KV per token (MQA, GQA, MLA; see Chapter 1, Section 1.5) and KV cache quantization (6.5). The methods below change attention itself. (Positional encoding and context-length extension are in Chapter 2.)
Sliding window attention lets each token see only the most recent \(W\) tokens, so each layer's KV cache holds at most \(W\) entries and no longer grows with the context, and compute becomes linear. Information beyond the window isn't entirely lost: it can pass along indirectly as layers stack (the receptive field of \(L\) layers is about \(L \times W\)), but precisely recalling a detail from far back becomes hard. Mistral 7B used a sliding window; Gemma 2/3 interleave sliding-window layers with a few global attention layers, so most layers have a capped KV cache while the few global layers handle precise long-range retrieval.
Linear attention and state-space models (SSMs, e.g. Mamba) compress the whole history into a fixed-size state; each new token only updates this state, so neither compute nor memory grows with context length. This also answers the question left open in Chapter 1: why haven't they replaced softmax attention? Because a fixed-size state is a lossy compression of the history, and the longer the context, the harsher the compression; the model struggles to recover an exact detail from far back, such as copying a long passage or finding a phone number buried in a long document (Jelassi et al. 2024). Softmax attention keeps every token's K and V and can retrieve precisely at any time. So the mainstream approach today is hybrid architectures: most layers use linear attention or SSMs, while a few full-attention layers handle precise retrieval, as in Jamba, MiniMax-01 and Qwen3-Next. Most layers are then cheap with constant memory, while the model as a whole keeps its ability to recall precisely.
There are also methods that compress the KV cache directly at inference time, keeping only important tokens that receive a lot of attention (e.g. H2O, SnapKV); they need no retraining but are approximate and may discard information that only becomes useful later. And there is trainable sparse attention (e.g. NSA and DeepSeek-V3.2's sparse attention), where each token selects only part of the history to attend to.
Interview questions
- ★ Where are the bottlenecks in long-context inference, and what are the main optimization directions?
- ★ Why are linear attention and SSMs usually mixed with a few full-attention layers?