Shelves / AI and ML Foundations
AI·157
LLM Decoding
Turning next-token distributions into text: greedy decoding and its repetition loops, sampling with temperature, top-k, top-p (nucleus) and min-p truncation implemented from scratch and composed in the order inference engines use, repetition, frequency and presence penalties, logit bias, stop sequences and end-of-turn tokens, maximum tokens and finish reasons, beam search with length normalisation and why chat models rarely use it, seeds and the limits of determinism, constrained and structured decoding, speculative decoding for speed, best-of-n and self-consistency, and recommended settings for extraction, chat, code and creative tasks.
Start here: turning probabilities into text
The model gives probabilities; something else must choose the next token. That choice, called decoding, changes the output's character more than people expect. Always picking the most likely token (greedy) is safe but dull and loops. Sampling picks randomly in proportion to the probabilities, with knobs: temperature sharpens (below 1) or flattens (above 1) the distribution; top-k keeps only the k most likely tokens; top-p (nucleus) keeps the smallest set whose probabilities add up to p.
The same model, six ways
Two measures of the output: distinct-2 (the share of adjacent token pairs that are unique; low means repetitive) and how surprised the model itself is by the text it produced (its own loss; high means it wandered into improbable territory):
greedy: distinct-2 0.73 repeated 4-grams 9% own loss 2.44
"A cache stores the same programs (chapter 21). Experiment 3: the same programming the same programming …"
temperature 0.7: distinct-2 0.92 repeated 4-grams 2% own loss 3.27
"… Rust, Zig, Go, … Zig, and Go, Go, Zig, Rust, Go, Rust, Zig, Rust …"
temperature 1.0: distinct-2 0.98 repeated 4-grams 0% own loss 4.21
temperature 1.5: distinct-2 1.00 repeated 4-grams 0% own loss 6.27
"… processizing) during keep traffic keys (nowatures even") at t performance cocept"
top-k 20, T=1.0: distinct-2 0.94 repeated 4-grams 0% own loss 3.13
"A cache stores (chapter 245). 3. Provents the browser's JDB: The same model needs every test, …"
top-p 0.9, T=1.0: distinct-2 0.96 repeated 4-grams 0% own loss 3.97
Greedy decoding fell into a loop ("the same programming the same programming"): once a phrase becomes likely, repeating it makes it more likely still. Temperature 1.5 avoided repetition entirely and produced invented non-words (own loss 6.27, close to random). Top-k and top-p cut off the long tail of unlikely tokens, keeping variety without the nonsense; they sit between the extremes, which is why most products default to something like temperature 0.7–1.0 with top-p 0.9–0.95. (This tiny model's text is crude at any setting; with a large model the same trade-offs appear as "boring and repetitive" versus "creative but unreliable".)
Which setting for which job
| Task | Typical decoding |
|---|---|
| extraction, classification, code completion, factual answers | greedy or low temperature (0–0.3) |
| general assistant replies | temperature ≈ 0.7, top-p ≈ 0.9 |
| brainstorming, creative writing | higher temperature (≈ 1.0) with top-p |
| structured output (JSON) | low temperature plus constrained decoding that only allows tokens valid in the schema |
How deep to go in LLM decoding
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain greedy decoding, sampling, temperature, top-k and top-p |
| L2 | Choose decoding settings for a task and make outputs reproducible |
| L3 | Implement the samplers, explain repetition, beam search, penalties and min-p |
| L4 | Diagnose bad generations (loops, drift, invalid JSON) and fix them with decoding changes |
| L5 | Design generation strategies: constrained decoding, speculative decoding, self-consistency |
| L6 | Build high-throughput generation systems (batching, speculative and parallel decoding) |
The decoding problem
At each step the model gives a probability distribution p over the vocabulary for the next token (chapter 156). A decoding strategy chooses which token to emit. The choice controls the balance between:
- Quality / correctness: pick high-probability tokens.
- Diversity / creativity: sometimes pick less likely tokens.
- Degeneration: pure maximisation can loop ("I think that I think that…"); pure random sampling from the full distribution wanders into the low-probability tail and produces nonsense.
All strategies below operate on the logits of the last position, step by step.
Greedy decoding
Always pick argmax p. Deterministic (up to numerical effects) and cheap.
- Good for short, well-determined outputs: classification labels, extraction, short factual answers.
- Prone to repetition loops in long open-ended text, because once a phrase becomes likely, repeating it keeps it likely.
- Not globally optimal: the highest-probability sequence may begin with a token that isn't the single most likely first token.
Temperature
Divide logits by T before softmax: p_T = softmax(z / T) (chapter 147).
- T → 0: approaches greedy.
- T = 1: the model's own distribution.
- T > 1: flatter, more random; usually degrades quality quickly.
Temperature reshapes the distribution but doesn't remove the tail: at T = 1, thousands of tail tokens with tiny probabilities can together carry meaningful mass, so occasional bizarre tokens appear. Truncation methods fix that.
Top-k sampling
Keep only the k most likely tokens, renormalise, sample. Simple, but a fixed k is wrong in both directions: when the model is confident (one plausible token), k = 50 still admits 49 bad ones; when many continuations are plausible, a small k cuts good options.
Top-p (nucleus) sampling
Keep the smallest set of most-likely tokens whose cumulative probability reaches p (e.g. 0.9), renormalise, sample (Holtzman et al., 2019). The candidate set adapts to the model's confidence: tiny when the distribution is peaked, large when it's flat.
Min-p sampling
Keep tokens whose probability is at least min_p × (probability of the top token) (e.g. min_p = 0.05). Scales the cut-off with confidence; works well at higher temperatures and is supported by many open-model inference engines.
Implementing the samplers
import numpy as np
def softmax(z):
z = z - z.max(); e = np.exp(z); return e / e.sum()
def apply_temperature(logits, T):
return logits / max(T, 1e-6)
def top_k_filter(logits, k):
if k <= 0 or k >= len(logits): return logits
kth = np.partition(logits, -k)[-k]
return np.where(logits < kth, -np.inf, logits)
def top_p_filter(logits, p):
if p >= 1.0: return logits
order = np.argsort(-logits)
probs = softmax(logits[order])
cum = np.cumsum(probs)
keep_sorted = cum - probs < p # keep tokens until cumulative mass first reaches p
keep = np.zeros_like(logits, dtype=bool); keep[order[keep_sorted]] = True
return np.where(keep, logits, -np.inf)
def min_p_filter(logits, min_p):
if min_p <= 0: return logits
probs = softmax(logits)
return np.where(probs >= min_p * probs.max(), logits, -np.inf)
def sample_next(logits, rng, temperature=1.0, top_k=0, top_p=1.0, min_p=0.0):
if temperature == 0:
return int(np.argmax(logits)) # greedy
z = apply_temperature(np.asarray(logits, float), temperature)
z = top_k_filter(z, top_k)
z = top_p_filter(z, top_p)
z = min_p_filter(z, min_p)
return int(rng.choice(len(z), p=softmax(z)))
vocab = ["Paris", "the", "a", "located", "known", "home", "one", "France", "big", "banana"]
probs = np.array([0.50, 0.20, 0.10, 0.06, 0.05, 0.04, 0.02, 0.015, 0.01, 0.005])
logits = np.log(probs)
kept = lambda z: [vocab[i] for i in np.where(np.isfinite(z))[0]]
kept(top_k_filter(logits, 3)) # ['Paris', 'the', 'a']
kept(top_p_filter(logits, 0.9)) # ['Paris', 'the', 'a', 'located', 'known']
kept(min_p_filter(logits, 0.1)) # p ≥ 0.05 → ['Paris', 'the', 'a', 'located', 'known']
rng = np.random.default_rng(0)
from collections import Counter
Counter(vocab[sample_next(logits, rng, temperature=1.0, top_p=0.9)] for _ in range(10_000))
# ≈ Paris 55%, the 22%, a 11%, located 6.6%, known 5.5%; 'banana' never appears
Engines apply penalties, temperature and truncation in a defined order (commonly: logit processors and penalties → temperature → top-k → top-p → min-p → sample); details differ by engine, so the same parameter values can behave slightly differently across providers.
Repetition control
| Control | Mechanism | Typical use |
|---|---|---|
| Repetition penalty (multiplicative, e.g. 1.1) | Divide positive logits (multiply negative ones) of tokens already present | Open-model engines (Hugging Face, llama.cpp) |
| Frequency penalty (additive, e.g. 0.0–1.0) | Subtract α × (count of the token so far) | OpenAI-compatible APIs; discourages verbatim repetition proportionally |
| Presence penalty (additive) | Subtract β once if the token has appeared at all | Encourages new topics |
| No-repeat n-gram | Forbid any n-gram from occurring twice | Summarisation with beam search |
| DRY / similar samplers | Penalise extending sequences that repeat earlier text | Long-form creative generation |
Penalties are blunt: they also penalise legitimately repeated tokens (variable names in code, JSON keys, a person's name), so keep them low or off for structured outputs.
def apply_penalties(logits, generated_ids, repetition=1.0, frequency=0.0, presence=0.0):
z = logits.copy()
counts = Counter(generated_ids)
for tok, c in counts.items():
if repetition != 1.0:
z[tok] = z[tok] / repetition if z[tok] > 0 else z[tok] * repetition
z[tok] -= frequency * c + presence
return z
Logit bias directly adds a value to chosen tokens' logits: −100 effectively bans a token; positive values favour labels in classification prompts.
Stopping
Generation ends when one of these happens; APIs report it as a finish/stop reason:
- The model emits its end-of-turn / end-of-sequence token (natural end).
- A stop sequence appears in the output (e.g. "\n\nUser:",
</answer>, or a closing code fence). The engine checks decoded text, since a stop string may span several tokens; the stop text is usually excluded from the returned output. - Max tokens reached: the output is truncated. Always check the finish reason: a JSON object cut off at max tokens is invalid; a "length" finish means raise the limit, shorten the task or continue.
- A tool call is emitted and the application must run it (chapter 168).
def generate(step_fn, prompt_ids, max_tokens, stop_strings, detok, eos_id, **sampling):
ids, out_text = list(prompt_ids), ""
rng = np.random.default_rng(sampling.pop("seed", None))
for _ in range(max_tokens):
tok = sample_next(step_fn(ids), rng, **sampling)
if tok == eos_id: return out_text, "end_turn"
ids.append(tok); out_text += detok(tok)
for s in stop_strings:
if s in out_text: return out_text[:out_text.index(s)], "stop_sequence"
return out_text, "max_tokens"
Beam search
Keep the B best partial sequences (by total log-probability) at each step, expand each with the top candidates, keep the best B overall; at the end return the highest-scoring finished sequence.
- Finds higher-likelihood sequences than greedy; standard for machine translation, speech recognition, summarisation with encoder-decoder models, where there is roughly one right output.
- Needs length normalisation: sums of log-probabilities favour short outputs; divide by length^α (α ≈ 0.6–1.0).
- For open-ended chat, high-likelihood text is bland and repetitive ("the beam search curse"); sampling produces more human-like text. Beam search also multiplies compute by B and doesn't stream naturally, so chat APIs generally don't offer it.
import heapq
def beam_search(step_logprobs, start, beam=2, max_len=5, eos=None, alpha=0.7):
beams = [(0.0, [start])] # (cumulative logprob, tokens)
finished = []
for _ in range(max_len):
candidates = []
for score, seq in beams:
for tok, lp in step_logprobs(seq).items():
candidates.append((score + lp, seq + [tok]))
beams = heapq.nlargest(beam, candidates, key=lambda c: c[0])
finished += [b for b in beams if b[1][-1] == eos]
beams = [b for b in beams if b[1][-1] != eos]
if not beams: break
pool = finished or beams
return max(pool, key=lambda c: c[0] / len(c[1]) ** alpha) # length-normalised
table = {("<s>",): {"The": -0.4, "A": -0.9, "Some": -2.3},
("<s>", "The"): {"cat": -1.5, "dog": -2.1}, ("<s>", "A"): {"cat": -0.3, "new": -1.9},
("<s>", "Some"): {"cats": -0.2}}
step = lambda seq: table.get(tuple(seq), {"</s>": 0.0})
beam_search(step, "<s>", beam=2, max_len=3, eos="</s>") # (-1.2, ['<s>', 'A', 'cat', '</s>'])
Determinism and seeds
- Temperature 0 (greedy) is the most repeatable setting, but outputs can still vary between runs: batched inference changes the order of floating-point additions (non-associative), different hardware or kernels give tiny logit differences, and MoE routing can flip on near-ties. Some engines offer batch-invariant "deterministic" modes at a throughput cost.
- A seed makes sampling repeatable only when everything else (model version, engine, batch composition) is identical; many APIs treat it as best-effort.
- Design systems to tolerate variation: validate outputs, retry on failure, evaluate with multiple samples (chapter 175), and pin model versions for reproducibility.
Constrained and structured decoding
To guarantee machine-readable output, mask logits at each step so only tokens consistent with a grammar remain valid: a JSON Schema, a regex, an enum of labels, a context-free grammar (SQL, a DSL). Implementations (Outlines, XGrammar, llguidance, llama.cpp GBNF, and providers' "structured outputs" modes) precompile the grammar into an automaton over the tokenizer's vocabulary. Chapter 167 covers schemas, validation and failure handling.
Faster decoding: speculative decoding
Decoding is memory-bandwidth-bound: verifying several tokens costs about the same as generating one. Speculative decoding:
- A cheap draft (a small model, extra prediction heads such as Medusa/EAGLE, n-gram lookup from the prompt) proposes k tokens.
- The large target model scores all k positions in one forward pass.
- Accept the longest prefix consistent with the target's distribution (with a rejection-sampling rule that keeps the output distribution exactly the target's); resample at the first rejection.
Speed-ups of 2–3× are common when the draft agrees often (code, structured text, repetitive outputs). Inference engines (vLLM, SGLang, TensorRT-LLM) support it (chapter 166).
Using multiple samples
- Best-of-n: sample n candidates, choose with a scorer (reward model, unit tests, a verifier, an LLM judge).
- Self-consistency: sample several reasoning paths, take the majority answer; improves maths and logic accuracy at n× cost.
- Rejection sampling for data generation: keep only samples that pass checks (chapter 158, 164).
Recommended settings
| Task | Settings |
|---|---|
| Extraction, classification, structured output | Temperature 0–0.2, structured outputs/constrained decoding, no penalties, explicit max tokens |
| Factual Q&A, RAG answers | Temperature 0–0.5, top-p 0.9–1.0 |
| Code generation | Temperature 0–0.4 for single answers; higher (0.6–0.8) with best-of-n plus tests |
| Conversational assistant | Temperature 0.5–1.0, top-p ≈ 0.9–0.95 (or the provider's defaults) |
| Creative writing, brainstorming | Temperature 0.8–1.2 with top-p 0.95 or min-p 0.05–0.1; mild presence penalty |
| Reasoning models | Often fixed or recommended sampling settings from the provider; control the thinking budget rather than temperature |
Adjust one of temperature or top-p at a time, and evaluate on your own task: defaults chosen by providers are usually sensible starting points.
Lab: samplers implemented and compared
The chapter 156 model (2.2 M parameters, validation loss 4.227) on the lab machine's CPU. generate() is about 15 lines: compute logits for the last position, apply the decoding rule, sample with a seeded torch.Generator, append, repeat (no KV cache; the context is cut to the last 128 tokens). Prompt "A cache stores", 100 new tokens, seeds 0–2.
Experiment 1: six decoders
logits = logits / temp
if top_k: v, _ = logits.topk(top_k); logits[logits < v[-1]] = -inf
if top_p:
p, ix = logits.softmax(-1).sort(descending=True)
keep = p.cumsum(0) - p < top_p # include the token that crosses p
mask = full_like(logits, -inf); mask[ix[keep]] = 0; logits = logits + mask
next = torch.multinomial(logits.softmax(-1), 1, generator=g)
| Decoder | distinct-2 | Repeated 4-grams | Model's loss on its own output |
|---|---|---|---|
| greedy | 0.73 | 9% | 2.44 |
| T = 0.7 | 0.92 | 2% | 3.27 |
| T = 1.0 | 0.98 | 0% | 4.21 |
| T = 1.5 | 1.00 | 0% | 6.27 |
| top-k 20 | 0.94 | 0% | 3.13 |
| top-p 0.9 | 0.96 | 0% | 3.97 |
The "own loss" column is a useful sanity number: at T = 1.0 with no truncation, the model's loss on its own samples (4.21) matched its validation loss on real text (4.23), as it should, since it's sampling from its own distribution; greedy text was far more predictable than real text (2.44) and T = 1.5 far less (6.27). Real human text sits in between, which is the observation behind nucleus sampling (Holtzman et al., 2019, "The Curious Case of Neural Text Degeneration").
Experiment 2: speed without a KV cache
120 tokens in 0.6 s (198.7 tokens/s), context capped at 128 tokens
Each step re-ran the whole (up to 128-token) context through the model. With a KV cache, each step processes only the new token and attends to stored keys and values, turning per-token cost from O(context) forward passes into O(1) passes plus attention over the cache. For a 128-token context and a 2 M-parameter model it barely matters; for a 100,000-token context it is the difference between usable and not.
Experiment 3: beyond sampling
| Technique | Idea | When |
|---|---|---|
| repetition / frequency penalties | lower logits of tokens already used | long-form generation that loops |
| min-p | keep tokens with probability ≥ p × the top token's | adaptive truncation, robust at higher temperature |
| beam search | keep the k best partial sequences | translation, short constrained outputs; poor for open-ended text |
| constrained decoding | mask tokens that would violate a grammar or JSON schema | structured output, tool calls |
| speculative decoding | a small draft model proposes tokens; the big model verifies several at once | lower latency with identical output distribution |
Try it yourself
- Add min-p (0.05) and compare with top-p 0.9 at temperature 1.3.
- Implement a repetition penalty (divide logits of seen tokens by 1.2) for greedy decoding and remeasure distinct-2.
- Implement beam search with width 4 and compare its text and own-loss with greedy.
- Constrain generation to the digits 0–9 and a closing bracket, and generate "Order [" completions.
Revision sheet: LLM decoding
Key ideas
- Decoding turns next-token distributions into text; it's separate from the model and has large effects.
- Greedy: deterministic, repetitive, loops; beam search: high-likelihood but bland for open-ended text.
- Sampling with temperature (sharpen/flatten), top-k (fixed count), top-p (cumulative mass), min-p (relative threshold); applied in that order in most implementations.
- Penalties: repetition, frequency and presence penalties.
- Constrained decoding for grammars and JSON schemas; logit bias for steering specific tokens.
- Speed: KV cache, batching, speculative decoding, quantisation (Volume 15).
- Reproducibility: seeds, but batching and hardware can still change results; temperature 0 isn't always bit-exact on GPUs.
Numbers to remember
- Lab: greedy distinct-2 0.73 with 9% repeated 4-grams; T = 1.5 own-loss 6.27 (near random).
- Lab: at T = 1.0 the model's loss on its own samples (4.21) ≈ its validation loss (4.23).
- Common defaults: T 0.7–1.0, top-p 0.9–0.95; T ≈ 0 for extraction.
Pitfalls
- High temperature for factual or structured tasks.
- Greedy for long open-ended text (loops).
- Parsing free-form text when constrained decoding is available.
- Assuming temperature 0 guarantees identical outputs across runs and hardware.
- Over-penalising repetition so needed words (names, terms) can't repeat.
Glossary
- Logit: pre-softmax score.
- Nucleus sampling: top-p sampling.
- Beam width: number of partial sequences kept in beam search.
- Speculative decoding: draft-then-verify generation.
- Constrained decoding: masking invalid tokens at each step.