Interpretable
Module 2.5 · ~2.5h

Inference, Performance & Reliability

Sampling, KV caches, quantization, hallucination, and calibration — making models fast and trustworthy.

You'll be able to
  • Predict how temperature and top-p reshape the token distribution
  • Explain the KV cache and estimate its memory cost
  • Distinguish calibration failures from confabulation and design a small eval
Learn

From a distribution to a sentence

Everything up to now produced one thing: a probability distribution over the next token. Turning that into text requires a decision rule, and the choice of rule changes the output more than most people expect — same weights, same prompt, wildly different behavior.

The obvious rule is to take the most likely token every time (greedy decoding), or to search for the highest-probability sequence (beam search). Both are wrong, and the way they are wrong is one of the more interesting empirical facts about language models.

Key idea
Maximizing likelihood is the right training objective and the wrong decoding objective. Holtzman et al. (2019) showed that likelihood-maximizing decoders produce text that is “bland and strangely repetitive” — and that real human text is not the highest-probability continuation of itself. People are routinely surprising. Text that never surprises reads as broken.

The failure is self-reinforcing, which is what makes it dramatic. Once a phrase repeats, it becomes a strong contextual predictor of itself — the induction machinery you will meet in Part 3 — so its probability rises with every repetition. Greedy decoding on an open-ended prompt reliably falls into a loop it cannot leave.

degeneration
The characteristic failure of low-entropy decoding: repetition loops, bland hedging, and collapse onto a few high-frequency phrasings. It is not a bug in the weights — the same model sampled differently is fine.

So we sample. Three knobs, applied in this order:

  • Temperature TT divides the logits before the softmax: piezi/Tp_i \propto e^{z_i/T}. Below 1 it sharpens, above 1 it flattens. It reshapes the whole distribution and removes nothing.
  • Top-kk keeps the kk highest-probability tokens and zeroes the rest. Simple and blunt: kk is fixed whether the model is certain or not.
  • Top-pp (nucleus sampling) keeps the smallest set of tokens whose probabilities sum to at least pp. The cut is dynamic — a confident distribution keeps 2 tokens, an uncertain one keeps 200 — which is precisely Holtzman's contribution and why it became the default.

Whatever survives is renormalized to sum to 1 and sampled from. The widget below shows every step, including which rule killed which token.

Temperature and top-p interact, and the order matters
Temperature is applied to the logits first, so it changes the cumulative probabilities that top-pp then reads. Lowering TT shrinks the nucleus for free even at a fixed pp. Tuning both at once is why people end up with configurations they cannot explain; move one at a time. Note also that T=0T = 0 is not a temperature at all — implementations special-case it to mean greedy.
Learn

Making it fast: caches, drafts, and smaller numbers

Generating a token requires a forward pass over the whole context. Generating the next one requires a forward pass over the whole context plus one. Done naively, producing nn tokens costs O(n2)O(n^2) work that is almost entirely redundant — because attention at position tt needs the keys and values of every earlier position, and those never change.

KV cache
Store the key and value vectors for every token, in every layer, the first time they are computed. Each new token then computes only its own query, key, and value, and attends against the cache. Decoding drops from quadratic to linear time — at the cost of memory that grows linearly with context and is held for the entire request.
K,VTheK,VweatherK,VtodayK,VisK,Vsunnycached — never recomputednewthe new query attends to every cached key
Why the cache works: keys and values for past tokens are fixed once computed, because attention is causal — nothing later can change them. Only the new token's Q, K, V are computed each step, and its K and V are appended.

The cache is not a footnote. For a 70B-class model at a 128K context it runs to tens of gigabytes for a single request, which is why serving systems are designed around it: paged allocation so requests do not need contiguous blocks (vLLM's PagedAttention), and prefix sharing so a common system prompt is cached once for thousands of users. The calculator below makes the arithmetic concrete.

The architectural fix is grouped-query attention (GQA): let several query heads share one key/value head. Llama-3 70B has 64 query heads and 8 KV heads, cutting the cache by 8× for a small quality cost. Multi-query attention (MQA) is the extreme, with one KV head. Toggle the “70B without GQA” preset in the widget to see what this bought.

A second inefficiency is subtler. Decoding is memory-bandwidth bound, not compute bound. Producing one token requires reading every weight of the model from memory in order to do a handful of arithmetic operations on each. The GPU sits mostly idle waiting on memory. Two techniques exploit this.

speculative decoding
A small, cheap draft model proposes γ\gamma tokens; the large model verifies all of them in one forward pass (which costs about the same as verifying one, since it was bandwidth-bound anyway) and keeps the longest prefix that matches what it would have sampled. Leviathan et al. (2022) show the accept/reject rule leaves the output distribution exactly unchanged — it is a pure latency win, not an approximation, and they measured 2–3× on T5-XXL.

Quantization attacks the same bottleneck by making the weights smaller: store them in 8-bit or 4-bit instead of 16-bit, and you read a quarter as many bytes per token. What degrades is specific rather than uniform. Dettmers et al. found that transformers past a few billion parameters develop outlier features — a small number of dimensions with enormous magnitudes that dominate the layer's behavior and are destroyed by naive rounding. LLM.int8() keeps exactly those in 16-bit and quantizes the rest; later methods (GPTQ, AWQ) refine which weights are worth protecting.

What quantization actually costs
Perplexity barely moves, which is why the technique looks free on the headline metric. Aggregate benchmarks are dominated by the common cases the model handles easily. What degrades first is the long tail: rare facts, multi-step arithmetic, low-resource languages, and — relevant here — calibration. If you quantize, evaluate on the tail you care about, not on perplexity.
Learn

Confabulation, calibration, and knowing what you don't know

“Hallucination” gets used for two failures with different causes and different fixes. Separating them is most of the work.

calibration error
The model's confidence does not match its accuracy. It says 90% and is right 70% of the time. The model has the uncertaintyinternally and reports it badly. Measurable, and fixable by changing what you read out.
confabulation
The model produces a fluent, specific, entirely invented claim — a citation that does not exist, an API that was never shipped — with no internal signal that anything is wrong. Nothing to read out.

Kadavath et al. (2022) is the load-bearing result here, and it is more optimistic than the discourse suggests. Large models are well calibrated on multiple-choice and true/false questions when asked in the right format. They can be asked to propose an answer and then evaluate the probability P(True)P(\text{True}) that it is correct, with decent calibration and improvement as models scale. They can even be trained to predict P(IK)P(\text{IK}) — “do I know this?” — before answering, though calibration of P(IK)P(\text{IK}) transfers poorly to new task distributions.

Key idea
A well-calibrated model that hallucinates is not confused — it is being read out wrong. The uncertainty is present in the distribution; sampling one token at a time and rendering it as fluent prose is what discards it. Much of what looks like a knowledge failure is an interface failure.
perfectgap01accuracystated confidence
A reliability diagram. Perfect calibration is the diagonal. The curve below it is the usual shape: the model is overconfident everywhere, and the gap widens as stated confidence rises. The expected calibration error is the average vertical gap, weighted by how many predictions fall in each bin.

RLHF makes this worse in a specific and well-documented way. OpenAI's GPT-4 system card reported that the pre-RLHF base model was well calibrated on MMLU and the post-RLHF model was noticeably less so. That should be unsurprising after Module 2.3: humans prefer confident answers, so preference optimization pushes stated confidence up regardless of what the underlying distribution says. Alignment training and calibration are in direct tension.

Kalai et al. (2025) push the argument one step further and blame the scoreboard. Almost every benchmark grades binary — right or wrong — with no credit for “I don't know.” Under that rule, guessing strictly dominates abstaining whenever you have any information at all, exactly as it does for a student on a multiple-choice exam with no penalty for wrong answers. Models are optimized to be good test-takers, and we built a test that rewards bluffing. Their proposed fix is socio-technical rather than algorithmic: change the scoring of the benchmarks that dominate leaderboards.

Safety tie-in
This is why honesty is treated as a separate alignment property from helpfulness and harmlessness, and why it is the hardest of the three to train. Helpfulness and harmlessness can be scored by a rater reading the output. Honesty is a claim about the relationship between the output and the model's internal state — a model that asserts something it “believes” is false and one that asserts something it has no belief about are behaviorally identical from outside. That is the same wall you hit with chain-of-thought faithfulness in Module 2.4, and the same reason Part 3 goes looking inside.
Learn

Evals 101

An eval is a measurement instrument, and the failure modes are the ones every measurement instrument has: measuring something adjacent to what you meant, measuring something you already trained on, or measuring with less precision than your decisions require.

  • Multiple-choice benchmarks (MMLU, GPQA) are cheap, reproducible, and heavily contaminated by now. They also measure recognition rather than generation, and are graded binary — the scoring problem above.
  • Verifiable-answer benchmarks (GSM8K, HumanEval, SWE-bench) have real ground truth and are the best instruments we have, restricted to the domains where a checker exists — the Module 2.4 story again.
  • Human preference arenas (Chatbot Arena) measure what people like, which is genuinely useful and is also, as Module 2.3 established, precisely the signal that rewards confident formatting.
  • LLM-as-judge scales, and inherits every bias of the judge model, including a well-documented preference for its own outputs and for longer answers.
  • Red-teaming and behavioral evals target a specific hazard rather than average quality. This is where safety-relevant evaluation actually happens.
What makes a small eval good
Precision comes from a narrow question, not a large nn. A 10-item eval on one specific behavior, with a deterministic grader and a pre-registered pass criterion, will tell you more than a 1,000-item aggregate score you cannot interpret. Write down what result would change your mind before you run it. Report the binomial confidence interval — with 10 items, 8/10 and 6/10 are not distinguishable, and pretending otherwise is the most common eval mistake.

The deeper problem is Goodhart, one last time. Every eval that becomes important becomes a training target, whether deliberately (training on the benchmark) or structurally (the field selects for methods that score well on it). The half-life of a useful benchmark is short, and holding out an eval you never train on is worth more than any single number it produces.

Explore

Feel it: truncation and memory

The sampling playground uses one fixed illustrative distribution. Temperature is applied first, then top-kk, then top-pp, then what survives is renormalized — the same order as a real sampler. Every removed token is labeled with the rule that removed it.

Sampling: temperature, top-k, top-p
A fixed illustrative distribution for The weather today is… Temperature reshapes it, then top-k and top-p truncate it, then what survives is renormalized. Watch which rule kills which token.
tokenpcum %tallysunny25.8%26going15.6%41a12.8%54cold10.5%65nice8.6%73beautiful6.4%80warm5.7%85quite4.3%90the3.2%93perfect2.6%95rainy2.1%97absolutely1.3%99surprisingly1.0%100bananas0.3%100420.1%100
after temperature, before truncationfinal, renormalized
Surviving tokens: 15 of 15. Mass kept before renormalizing: 100.0%. Entropy 3.21 bits after temperature → 3.21 bits after truncation.

The calculator is the arithmetic every serving engineer runs before promising a context length.

KV cache memory calculator
Every token you have already generated leaves behind a key and a value vector in every layer, held for the whole request. This is what decides how many users fit on a GPU.
Cache precision
10 MB102 MB1.0 GB10.0 GB100.0 GB1.00 TB10.00 TB24 GB consumer GPU80 GB H1001K4K16K66K262K1.0Mcontext length (tokens)cache size

GQA: 64 query heads share 8 KV heads

2 × 80 layers × 8 KV heads × 128 dim × 2 B = 320.0 KB per token. At 131K tokens × batch 1, the cache is 40.0 GB — before any model weights. A 24 GB card holds 79K tokens of this cache; an 80 GB H100 holds 262K.

Things to try: (1) Set TT = 0.2 and draw fifty tokens — one token takes essentially all the draws. That is degeneration in miniature, and it is why greedy decoding loops. (2) Set top-pp to 0.90 and sweep temperature from 0.5 to 2.0, watching the nucleus size change without touching pp — a fixed top-pp is not a fixed vocabulary. (3) In the calculator, load Llama-3 70B at 128K, then hit “70B without GQA” and watch the line jump above the H100 reference. Then set batch to 32 with GQA back on: this is why context length is priced the way it is.

Practice

Problem set

The first three are arithmetic you should be able to do from memory by the end of this module — they come up constantly in real deployment conversations. The eval-design problem is the one worth doing slowly.

1.Nucleus sampling by handpencil & paper

Logits over six tokens: z=(2.0,  1.5,  1.0,  0.5,  0.0,  0.5)z = (2.0,\; 1.5,\; 1.0,\; 0.5,\; 0.0,\; -0.5). Use top-pp = 0.85.

(a) At T=1T = 1, how many tokens are in the nucleus, and what are their renormalized probabilities? (b) At T=0.7T = 0.7? (c) State in one sentence why top-pp is generally preferred to top-kk.

2.Will it fit?pencil & paper

A model has 80 layers, 64 query heads, 8 KV heads, head dimension 128, and an fp16 KV cache.

(a) How many bytes of cache per token? (b) At a 128K context and batch size 1, how many GB? (c) The model's weights are 140 GB in fp16 — what does that imply about serving 128K contexts on a single 8×H100 node (640 GB)? (d) How much does the answer to (a) change if the model used plain multi-head attention?

3.How much does speculation buy?pencil & paper

A draft model proposes γ\gamma tokens per round; each is accepted independently with probability α\alpha, and the first rejection ends the round (with one token still emitted from the target's corrected distribution). The expected tokens per round is

E[tokens]=1αγ+11α\mathbb{E}[\text{tokens}] = \frac{1 - \alpha^{\gamma+1}}{1 - \alpha}

Assume the draft model costs 5% of a target forward pass, and one round costs γ×0.05+1\gamma \times 0.05 + 1 target-equivalents.

(a) Speedup at α=0.8\alpha = 0.8, γ=4\gamma = 4? (b) At γ=8\gamma = 8 and γ=16\gamma = 16? (c) At α=0.5, γ=4\alpha = 0.5,\ \gamma = 4? (d) Why is the verification step nearly free?

4.Compute a calibration errorpencil & paper

A model answers 100 questions, bucketed by stated confidence:

  • conf ≈ 0.55 — 20 questions, 55% correct
  • conf ≈ 0.65 — 20 questions, 60% correct
  • conf ≈ 0.75 — 30 questions, 63% correct
  • conf ≈ 0.85 — 20 questions, 70% correct
  • conf ≈ 0.95 — 10 questions, 80% correct

(a) Compute the expected calibration error, ECE=bnbNaccbconfb\mathrm{ECE} = \sum_b \frac{n_b}{N}\,\big|\mathrm{acc}_b - \mathrm{conf}_b\big|. (b) Overall accuracy and mean confidence? (c) If you refuse to answer below 0.8 confidence, what accuracy do you ship, and at what coverage? (d) Is this model hallucinating?

5.Implement the samplercode

From raw logits, in NumPy or PyTorch, implement sample(logits, temperature, top_k, top_p) applying temperature, then top-kk, then top-pp, then renormalizing and sampling. No library sampling helpers.

Then verify, on a real small model (GPT-2 via HuggingFace):

  1. temperature=1e-6 reproduces greedy decoding exactly.
  2. top_p=1.0, top_k=None matches torch.multinomial on the full softmax, over 10,000 draws, within sampling error.
  3. Generate 200 tokens at temperature=0.3 from an open-ended prompt and count the longest repeated 5-gram. Compare against temperature=1.0, top_p=0.95.

Success check: check 3 shows visible degeneration in the low- temperature sample and none in the nucleus sample.

6.Design a 10-item evalexplore

Pick one behavior you actually care about and can grade mechanically. Good candidates: “refuses to invent a citation when asked for a source it does not have,” “says ‘I don't know’ on questions about events after its cutoff,” “does not change a correct answer when the user pushes back” (the sycophancy probe from Module 2.3).

Write down, before running anything:

  1. The exact 10 prompts.
  2. A deterministic grading rule — a regex, a string check, or an LLM-judge with a fixed rubric and a fixed judge model.
  3. Your prediction for each of two models.
  4. What result would change your mind.

Then run it against two models, three samples each at temperature 0, and report scores with binomial confidence intervals.

0 of 6 problems marked done
Check

Check yourself

1.
Greedy decoding produces repetitive text because…
2.
You set top-pp = 0.9 and then lower temperature from 1.0 to 0.6. What happens to the nucleus?
3.
A 70B model with GQA (80 layers, 8 KV heads, head dim 128, fp16) needs how much KV cache for one 128K-token request?
4.
Speculative decoding speeds up generation without changing output quality because…
5.
A model says “90% confident” and is right 70% of the time, with accuracy rising monotonically as stated confidence rises. This is best described as…
6.
Kalai et al. (2025) argue that hallucinations persist partly because…
7.
Your 10-item eval scores model A 8/10 and model B 6/10. The correct conclusion is:
Answer all 7 questions to submit.
Submit your answers to complete this check.
Go deeper

Go deeper

Holtzman is short and will change how you set sampling parameters forever. Kadavath is the one to read carefully — it is the most hopeful result in this module and the direct ancestor of honesty research.

EssentialThe Curious Case of Neural Text Degenerationpaper
Holtzman, Buys, Du, Forbes & Choi · 2019 · 40 min
The paper that gave us nucleus sampling. §2 has the figure that matters: human text sits nowhere near the model's per-token maximum, and its probability fluctuates wildly. §4 defines top-p. Read it before touching a temperature slider again.
EssentialLanguage Models (Mostly) Know What They Knowpaper
Kadavath, Conerly, Askell, et al. (Anthropic) · 2022 · 1.5h
Long but worth it. §2 on calibration for multiple-choice, §4 on P(True) self-evaluation, §5 on training a model to predict P(IK). The framing to carry forward: uncertainty is present internally and the problem is largely a readout problem — which is exactly the claim interpretability is positioned to test.
EssentialWhy Language Models Hallucinatepaper
Kalai, Nachum, Vempala & Zhang (OpenAI) · 2025 · 45 min
Argues hallucination originates as ordinary binary-classification error in pretraining and persists because binary-graded benchmarks reward guessing over abstention. Read §1 and the sections on evaluation scoring; the reduction arguments are skimmable. Pair it with the eval-design problem — it is the strongest case for why your grading rule is a values choice.
Fast Inference from Transformers via Speculative Decodingpaper
Leviathan, Kalman & Matias (Google) · 2022 · 35 min
Short and elegant. §2 has the accept/reject rule and the proof that the output distribution is unchanged — read that proof, it is half a page and it is the whole reason the technique is safe to deploy. §3 has the expected-token formula used in the problem set.
Efficient Memory Management for Large Language Model Serving with PagedAttention (vLLM)paper
Kwon, Li, Zhuang, et al. · 2023 · 45 min
What the KV-cache calculator implies for real systems. §3 on memory fragmentation is the motivation — naive contiguous allocation wastes 60–80% of cache memory. The virtual-memory analogy is the whole idea and it is well told.
LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scalepaper
Dettmers, Lewis, Belkada & Zettlemoyer · 2022 · 40 min
Read §3 on emergent outlier features. The interpretability-relevant finding is that past a few billion parameters, a tiny number of dimensions carry outsized magnitude and dominate the layer — a fact that shows up again in the superposition and residual-stream modules.
Transformer Inference Arithmeticblog
kipply (Carol Chen) · 2022 · 45 min
The reference for back-of-envelope inference math: KV cache size, memory-bandwidth versus compute bounds, why decoding is latency-bound and prefill is not. Keep it open the first few times you size a deployment; it is the source most people quietly reproduce.