On this page
Feed an autoregressive language model the prefix The autumn light is across three requests. One run ends immediately with bright. Another produces fading fast. A third writes a fresh continuation every time. Identical weights, identical prompt, identical tokenizer: all that changed is the decoding code turning raw next-token scores (logits) into emitted tokens. Because each emitted token alters the conditioning context for every later step, decoding controls fluency, repetition, diversity, and schema validity.
Trace every strategy on one twelve-token row where each word is one token and eight rare tail tokens each hold 0.01 probability so the row sums to 1.00:
| Token | Probability | Plausible continuation |
|---|---|---|
bright | 0.45 | bright . |
fading | 0.30 | fading fast |
soft | 0.15 | soft gold |
pale | 0.02 | rare adjective |
| tail | 0.08 | eight rare tokens at 0.01 each |
Greedy decoding locks onto bright (0.45). Stochastic sampling can draw fading (0.30) into fading fast or soft (0.15) into soft gold. Top-p sampling at p = 0.90 retains bright, fading, and soft (0.45 + 0.30 + 0.15 = 0.90), renormalizing them to 0.500, 0.333, and 0.167. For low-latency serving, speculative decoding drafts tokens with a smaller model and verifies them in parallel with exact rejection sampling so the target distribution stays unchanged.[1]

fading alive, letting fading fast (0.270) outscore greedy's bright . (0.180).From logits to numerically stable probabilities
Softmax maps raw logits to probabilities. Calling exp(z) directly overflows FP16 above (max ≈ 65,504), FP32 above (max ≈ 3.4e38), and FP64 above . Subtracting leaves every ratio exact while keeping all exponents :[2]
The right-hand log-sum-exp form lets decoders sum log-probabilities across long sequences without underflowing to zero. Masked entries map cleanly to 0, while an all-masked vector must raise an error instead of returning NaN:
import numpy as np
def stable_softmax(logits) -> np.ndarray:
z = np.asarray(logits, dtype=np.float64)
if np.isnan(z).any() or np.isposinf(z).any():
raise ValueError("NaN and +inf are invalid logits")
if not np.isfinite(z).any():
raise ValueError("all tokens are masked")
w = np.exp(z - np.max(z))
return w / w.sum()
for dtype, hi in [(np.float16, 12.0), (np.float32, 90.0), (np.float64, 1000.0)]:
vec = np.array([hi, hi - 1.0, hi - 2.0], dtype=dtype)
with np.errstate(over="ignore", invalid="ignore"):
naive = np.exp(vec) / np.exp(vec).sum()
print(f"{dtype.__name__:7s} naive={naive.tolist()} | stable={stable_softmax(vec).round(3).tolist()}")
print("masked:", stable_softmax([2.0, -np.inf, 1.0]).round(3).tolist())
try:
stable_softmax([-np.inf, -np.inf])
except ValueError as exc:
print("all masked:", exc)float16 naive=[nan, 0.0, 0.0] | stable=[0.665, 0.245, 0.09]
float32 naive=[nan, nan, 0.0] | stable=[0.665, 0.245, 0.09]
float64 naive=[nan, nan, nan] | stable=[0.665, 0.245, 0.09]
masked: [0.731, 0.0, 0.269]
all masked: all tokens are maskedGreedy decoding and beam search
Greedy decoding picks the step-by-step argmax, . It costs after logits arrive, uses no randomness, and makes a clean baseline for classification or deterministic extraction. Its blind spot is myopia: by the chain rule , taking the step-one leader can miss a stronger full sequence. Here bright (0.45) splits across . (0.40), today (0.35), and now (0.25), while fading (0.30) concentrates on fast (0.90), so greedy locks into bright . (0.18) and misses fading fast (0.27). On long generations, greedy argmax also falls into verbatim repetition loops.[3][4]
Exhaustive search over paths is intractable. Beam search retains the top partial prefixes at each step, expands each survivor, sums log-probabilities, and prunes back to . Pruned prefixes never return, so width rescues fading fast (0.27) while discarding soft (0.15). Because each added token contributes a non-positive log-probability, raw sums reward short outputs that emit EOS early. Google's Neural Machine Translation (GNMT) system divided sequence log-probability by a tunable length factor:[5]
Setting restores raw log-probability; raising relieves penalty pressure on longer completions (counting tokens before EOS). Length-normalized scores can rise when a prefix adds a near-certain token, so early-stopping logic must not assume monotone decline.
import numpy as np
vocab = ["bright", "fading", "soft", "pale"]
first_probs = np.array([0.45, 0.30, 0.15, 0.02])
continuations = {
"bright": {".": 0.40, "today": 0.35, "now": 0.25},
"fading": {"fast": 0.90, "slowly": 0.10},
"soft": {"gold": 0.70, "gray": 0.30},
}
greedy_w1 = vocab[int(np.argmax(first_probs))]
greedy_w2 = max(continuations[greedy_w1], key=continuations[greedy_w1].get)
beam_idx = np.argsort(-first_probs, kind="stable")[:2]
step_two = sorted(
[(f"{vocab[int(i)]} {w2}", float(first_probs[i]) * p) for i in beam_idx for w2, p in continuations[vocab[int(i)]].items()],
key=lambda x: x[1],
reverse=True,
)
print(f"greedy: {greedy_w1} {greedy_w2} ({first_probs[0] * continuations[greedy_w1][greedy_w2]:.2f})")
print("beam top-2:", [(t, round(s, 3)) for t, s in step_two[:2]])
# GNMT length normalization (alpha = 0.6) flips short-sequence bias.
texts = ["bright.", "fading across hills now ."]
log_probs, lengths = np.array([-1.00, -1.08]), np.array([2, 5])
norm_scores = log_probs / (((5.0 + lengths) / 6.0) ** 0.6)
print("raw winner:", texts[int(np.argmax(log_probs))], "| length-norm winner:", texts[int(np.argmax(norm_scores))])
assert step_two[0][0] == "fading fast" and texts[int(np.argmax(norm_scores))] == "fading across hills now ."greedy: bright . (0.18)
beam top-2: [('fading fast', 0.27), ('bright .', 0.18)]
raw winner: bright. | length-norm winner: fading across hills now .Beam search excels on tightly conditioned tasks like translation, yet in open-ended dialogue maximizing likelihood favors generic clichés while holding up to divergent suffix paths in KV-cache memory.[3][6]
A summarization model decoded with beam width 8 emits terse one-line fragments. What should you inspect first?
Answer
Check length normalization (alpha), EOS token scores, early-stopping bounds, and maximum output limits before suspecting the weights. Unnormalized log-probability favors early EOS, and length-normalized scores can rise upon extension, breaking naive early-stop rules.
Temperature scaling
Stochastic sampling draws from the conditional distribution. Temperature divides raw logits before softmax:
Pairwise odds scale exponentially as : for , is 7.39x at , 54.60x at , and 3.79x at . Shannon entropy is monotone nondecreasing in : route temperature = 0 to an explicit greedy branch rather than dividing by zero,[7][8] and always scale every individual token before summing tail buckets (at , scaling all eight 0.01 tail tokens lifts combined tail mass from 8.0% to 21.07%):
| Token | |||
|---|---|---|---|
bright | 0.7785 | 0.45 | 0.3331 |
fading | 0.2015 | 0.30 | 0.2542 |
soft | 0.0200 | 0.15 | 0.1602 |
pale | 0.000024 | 0.02 | 0.0418 |
| eight-token tail | 0.000019 | 0.08 | 0.2107 |
| entropy (bits) | 0.86 | 2.09 | 2.75 |

Top-k, top-p, and min-p truncation
Even at moderate temperature, tens of thousands of unlikely tail tokens retain nonzero probability. Truncation filters cut that tail before sampling:
- Top-k retains only the highest-scoring tokens and renormalizes.[9] Its fixed integer ignores model certainty (
k = 50admits noise on sharp factual steps;k = 10clips valid choices on open prompts). - Nucleus (top-p) sorts probabilities descending and keeps the smallest prefix whose cumulative mass reaches : .[3] Size adapts automatically with entropy, though heating pushes mass into the tail and swells our
p = 0.90nucleus from3tokens to9. - Min-p retains tokens reaching at least fraction of the leader's probability: .[10] Applied after temperature, this equals , so higher still widens the window (and ordering min- before vs after changes survivors), while uniform ties retain all tokens and controlled reanalyses found no systematic win over well-tuned top-.[11]

top-k = 3 keeps three tokens in both regimes. top-p = 0.90 expands from two to five tokens on the flat curve, while min-p = 0.10 drops its cutoff from 7.2% to 4.0% and retains four tokens.import math
import torch
base_probs = torch.tensor([0.45, 0.30, 0.15, 0.02] + [0.01] * 8, dtype=torch.float64)
logits = torch.log(base_probs)
def nucleus_size(probs: torch.Tensor, p: float = 0.90) -> int:
sp, _ = torch.sort(probs, descending=True)
return int(((torch.cumsum(sp, dim=0) - sp) < p).sum())
for temp in [0.3, 1.0, 1.5]:
dist = torch.softmax(logits / temp, dim=-1)
h = float(-(dist[dist > 0] * torch.log2(dist[dist > 0])).sum())
print(f"T={temp}: bright={float(dist[0]):.4f}, tail={float(dist[4:].sum()):.4f}, H={h:.2f}b, top-p={nucleus_size(dist)}")
# Min-p before vs after T=2 on [0, -2, -4] with rho=0.1.
z = torch.tensor([0.0, -2.0, -4.0])
before = torch.nonzero(z >= z.max() + 1.0 * math.log(0.1)).flatten().tolist()
after = torch.nonzero(z >= z.max() + 2.0 * math.log(0.1)).flatten().tolist()
print(f"min-p before T=2: {before} | after T=2: {after}")
assert before == [0, 1] and after == [0, 1, 2]T=0.3: bright=0.7785, tail=0.0000, H=0.86b, top-p=2
T=1.0: bright=0.4500, tail=0.0800, H=2.09b, top-p=3
T=1.5: bright=0.3331, tail=0.2107, H=2.75b, top-p=9
min-p before T=2: [0, 1] | after T=2: [0, 1, 2]Penalties, grammar masks, and non-commuting pipelines
A multiplicative repetition penalty (commonly 1.1–1.2) breaks verbatim loops using a sign-aware rule once per distinct seen token ID: divide positive logits by and multiply negative logits by so every seen token drops.[12][7] Because sign-aware scaling is not shift-invariant, always apply it before subtracting max(z) for softmax stability, or centering flips positive scores to negative and can reverse the argmax winner:
import torch
def apply_repetition_penalty(logits: torch.Tensor, seen_ids: set[int], penalty: float = 1.2) -> torch.Tensor:
out = logits.clone()
idx = torch.tensor(sorted(seen_ids), dtype=torch.long)
out[idx] = torch.where(out[idx] > 0, out[idx] / penalty, out[idx] * penalty)
return out
raw = torch.tensor([2.4, -0.5, 0.7])
print("sign-aware [2.4, -0.5, 0.7]:", [round(float(v), 3) for v in apply_repetition_penalty(raw, {0, 1}, 1.2)])
scores = torch.tensor([2.4, 2.1, 1.2, 0.3])
names = ["bright", "clear", "warm", "pale"]
p_first = apply_repetition_penalty(scores, {0}, 1.2)
c_first = apply_repetition_penalty(scores - scores.max(), {0}, 1.2)
print("penalty first:", names[int(torch.argmax(p_first))], "| center first:", names[int(torch.argmax(c_first))])
assert int(torch.argmax(p_first)) == 1 and int(torch.argmax(c_first)) == 0sign-aware [2.4, -0.5, 0.7]: [2.0, -0.6, 0.7]
penalty first: clear | center first: brightAdditive frequency () and presence () penalties subtract directly using token counts: . Because all three operate on raw token IDs without syntax awareness, heavy values can suppress repeated code identifiers or required JSON keys.
Serving engines chain logit processors in a fixed order because stages do not commute: (1) logit biases and grammar masks, (2) history penalties before centering, (3) temperature == 0 greedy branch after checking that at least one finite logit remains, (4) temperature scaling, top-, stable softmax, top-/min-, renormalization, and PRNG draw, and (5) EOS, stop-string, and max_tokens checks.[7]
To enforce JSON Schema, regex, or SQL syntax, grammar-constrained decoding pairs generation with an automaton that masks every invalid token to before softmax.[13][14] Always mask invalid tokens before top-/top-/min-: if probabilities are [0.6, 0.3, 0.1] and only token 2 is legal, running top-p = 0.80 first drops token 2 and leaves an empty pool, whereas masking first renormalizes token 2 to 1.0. Remember also that syntax enforcement does not verify facts, and local step-by-step masking can distort full-sequence probabilities relative to conditioning on valid complete strings.[15][16] See Structured Outputs & Constrained Generation for compiled masks and grammar-aligned sampling.
![Three aligned stages of a production sampler pipeline on four candidate tokens: bright, clear, warm, and pale. Stage 1 shows raw logits [2.4, 2.1, 1.2, 0.3] with bright leading. Stage 2 applies repetition penalty theta = 1.2 to seen token bright, dropping it from 2.4 to 2.0 below clear (2.1) and flipping greedy argmax to clear. Stage 3 sorts softmax probabilities [0.404, 0.365, 0.164, 0.067] and plots cumulative mass crossing top-p = 0.90 at rank 3 warm (CDF 0.933), cutting pale (0.067).](https://assets.leetllm.com/v1/5aa47b9727aa/fundamentals/decoding-strategies-greedy-beam-nucleus/illustrations/_generated/production_sampler_stack_dark.png)
bright below clear (changing greedy output to clear), while top-p = 0.90 cuts pale and lets stochastic sampling draw from clear, bright, or warm.import random
import torch
def sample_next_token(logits: torch.Tensor, seen_ids: list[int], penalty: float, temperature: float, top_p: float, rng: random.Random) -> int:
adjusted = logits.clone()
if seen_ids:
idx = torch.tensor(sorted(set(seen_ids)), dtype=torch.long)
adjusted[idx] = torch.where(adjusted[idx] > 0, adjusted[idx] / penalty, adjusted[idx] * penalty)
if torch.isneginf(adjusted).all() or torch.isnan(adjusted).any():
raise ValueError("need at least one finite unmasked logit")
if temperature == 0:
return int(torch.argmax(adjusted))
probs = torch.softmax(adjusted / temperature, dim=-1)
sp, sidx = torch.sort(probs, descending=True)
keep = ((torch.cumsum(sp, dim=0) - sp) < top_p) & (sp > 0)
return rng.choices([int(i) for i in sidx[keep]], weights=[float(w) for w in sp[keep]], k=1)[0]
names = ["bright", "clear", "warm", "pale"]
logits = torch.tensor([2.4, 2.1, 1.2, 0.3])
print("greedy:", names[sample_next_token(logits, [0], 1.2, 0.0, 0.90, random.Random(0))])
print("sampled:", names[sample_next_token(logits, [0], 1.2, 1.0, 0.90, random.Random(0))])
scores = torch.log(torch.tensor([0.6, 0.3, 0.1]))
grammar_first = scores.masked_fill(~torch.tensor([False, False, True]), -torch.inf)
chosen = sample_next_token(grammar_first, [], 1.0, 1.0, 0.80, random.Random(0))
print("grammar-first token:", chosen)
assert chosen == 2
try:
sample_next_token(torch.full((3,), -torch.inf), [], 1.0, 0.0, 0.80, random.Random(0))
except ValueError as err:
print("empty pool rejected:", err)greedy: clear
sampled: warm
grammar-first token: 2
empty pool rejected: need at least one finite unmasked logitChoosing settings, runtime limits, and troubleshooting
Setting temperature = 0 removes randomness and seed fixes PRNG draws, yet batching and GPU floating-point reduction differences can still flip near-tied logits unless batch-invariant modes (VLLM_BATCH_INVARIANT=1) are active.[8][17] Hosted reasoning APIs frequently lock or ignore temperature and top_p while reasoning is enabled; rely on prompt grounding and structured schemas when sampling knobs are unavailable.[18][19]
Start sweeps from how much variance the task tolerates, changing one knob at a time on held-out prompts:
| Task | Temperature sweep | Sampler candidates | Primary metrics |
|---|---|---|---|
| Code generation | 0.0, 0.2, 0.5 | Greedy, top-p = 0.95 | Tests passed, format validity |
| Factual QA | 0.0, 0.2, 0.5 | Greedy, top-p = 0.90 | Grounded accuracy, unsupported claims |
| General dialogue | 0.3, 0.7, 1.0 | Top-p = 0.90, min-p = 0.10 | Helpfulness, repetition |
| Creative writing | 0.7, 1.0, 1.3 | Top-p = 0.95, min-p = 0.05 | Novelty, coherence |
| Symptom | Root cause | Fix |
|---|---|---|
NaN in custom softmax | Naive exp(z) overflowed FP16/FP32 | Subtract max(z) before exp (log-sum-exp) |
Crash at temperature = 0 | Divided logits by zero | Route T == 0 to greedy argmax before scaling |
| Generic chat with beam search | High likelihood favors boilerplate | Switch to calibrated sampling |
| Lower still hallucinates | Positive preserves token rank | Fix retrieval grounding or verification |
| Empty pool with JSON schema | Truncation ran before grammar mask | Apply masks before top-/top- |
| Drift after runtime swap | Processor order or tie-break differs | Verify logit-processor ordering |