Top-k and top-p: which tokens survive the cut?
Top-k 与 Top-p
Compare fixed-count and probability-mass cutoffs, crossing tokens, ties and temperature order.
top-k-top-pKeep two candidates, or keep enough probability?
Consider two four-token distributions. One is flat: every token has probability 0.25. The other is peaked: 0.85, 0.05, 0.05 and 0.05. Top-k with keeps two candidate indices in both cases. Nucleus sampling with threshold 0.8 keeps all four in the flat case but only the first in the peaked case.
The distinction is what the cutoff controls. Top-k specifies a candidate count. Top-p, also called nucleus sampling, specifies a minimum amount of original probability mass and lets the count change with context. Neither threshold says that a retained token is true, grammatical or useful.
Fan, Lewis and Dauphin use top-10 random sampling in their story-generation experiments. Holtzman and colleagues contrast fixed-k truncation with a dynamic nucleus, motivated by distributions that can be flat in one context and sharply concentrated in another. Their generation-quality findings belong to those experiments, not to every task or model.
Retain the token that reaches the threshold
Let be a normalized distribution over a finite vocabulary. Sort indices as from highest to lowest probability. Our implementation breaks equal-probability ties by original token index. For integer between one and vocabulary size:
This is an exact-size candidate set. Some implementations instead retain every logit at least as large as the kth largest logit, potentially keeping more than tied candidates. State which policy is used. A retained zero-probability index is never sampled, so candidate-set size and positive-probability support size can also differ.
For either truncation method, let be the selected set and its original mass. Sampling uses the renormalized distribution:
This is not uniform sampling from the retained indices unless their probabilities were equal. In the peaked opening example, top-2 becomes approximately , not .
For a nucleus threshold in , retain the shortest sorted prefix whose cumulative mass reaches or exceeds it:
With probabilities 0.6, 0.25 and 0.15 and threshold 0.7, the first entry is insufficient. Keep the second entry that crosses the threshold, giving retained mass 0.85 and probabilities . Keeping only entries whose cumulative sum remains below the threshold is the wrong boundary rule.
Truncation has a measurable effect even before generating any text. The total variation distance between the original and restricted distributions is:
The discarded region contributes mass . Inside the retained region, renormalization adds that same total mass, so the absolute differences sum to twice the discarded mass. Top-p therefore limits this one-step distribution change by , whereas top-k does not impose a fixed retained-mass guarantee. This bound concerns one conditional distribution, not a sequence-level quality metric.
Within retained positive-probability entries, relative odds are unchanged:
Temperature is different: it changes relative odds. The order can matter for nucleus sampling. Let square and renormalize probabilities, and let apply top-p at threshold 0.6. For :
Temperature first gives first-token probability , already above 0.6, so the nucleus contains one token. Nucleus first sees only 0.5 on that token, must retain the second as well, and later temperature cannot delete it mathematically. This is an actual counterexample, not a claim that the operations differ for every input.
Make tie and endpoint rules explicit
The complete NumPy program compares flat and peaked contexts, checks the crossing-token example and computes both operation orders. It does not draw a random sentence: the transformed distributions are the quantities under examination, so they can be verified exactly.
"""Exact-size top-k and minimal-prefix nucleus sampling, stable index tie policy."""
import json
import numpy as np
def distribution(p):
a=np.asarray(p,dtype=float)
if a.ndim!=1 or not len(a) or not np.isfinite(a).all() or (a<0).any() or not np.isclose(a.sum(),1,rtol=0,atol=1e-12):
raise ValueError('Normalized finite probabilities required')
return a/a.sum()
def order(p):return np.argsort(-p,kind='stable')
def restricted(p,ids):
out=np.zeros_like(p);out[ids]=p[ids]
if out.sum()<=0:raise ValueError('Selected set has no probability mass')
return out/out.sum()
def top_k(p,k):
p=distribution(p)
if type(k) is not int or not 1<=k<=len(p):raise ValueError('k must be an integer within the vocabulary')
ids=order(p)[:k]
return restricted(p,ids),ids.tolist()
def top_p(p,threshold):
p=distribution(p)
if not np.isfinite(threshold) or not 0<threshold<=1:raise ValueError('Threshold must lie in (0,1]')
ids=order(p);mass=np.cumsum(p[ids])
n=min(len(p),int(np.searchsorted(mass,threshold,side='left'))+1)
# At threshold one preserve every positive-probability token despite sum rounding.
if threshold==1:n=int(np.count_nonzero(p))
kept=ids[:n]
return restricted(p,kept),kept.tolist()
def temper(p,t):
p=distribution(p)
if not np.isfinite(t) or t<=0:raise ValueError('Positive finite temperature required')
out=np.zeros_like(p);keep=p>0;z=np.log(p[keep]);e=np.exp((z-z.max())/t);out[keep]=e/e.sum()
return out
def demo():
rows=[]
for name,p in [('flat',[.25]*4),('peaked',[.85,.05,.05,.05])]:
k,ki=top_k(p,2);n,ni=top_p(p,.8)
rows.append(dict(name=name,base=p,top_k=k.tolist(),top_k_ids=ki,top_p=n.tolist(),top_p_ids=ni))
p=np.array([.5,.3,.2]);a,ai=top_p(temper(p,.5),.6);truncated,ids=top_p(p,.6);b=temper(truncated,.5)
return dict(contexts=rows,crossing_example=top_p([.6,.25,.15],.7)[0].tolist(),
temperature_then_nucleus=dict(probabilities=a.tolist(),ids=ai),
nucleus_then_temperature=dict(probabilities=b.tolist(),ids=ids),
tied_k_ids=top_k([.4,.3,.3],2)[1],
scope='Token index breaks ties; exact-size k differs from inclusive logit-threshold implementations')
if __name__=='__main__':print(json.dumps(demo()))
The flat example’s top-2 keeps indices 0 and 1 and renormalizes to 0.5 each; its 0.8 nucleus retains all four. The peaked example’s top-2 retains original mass 0.9, while its nucleus retains mass 0.85 on just index zero and renormalizes that token to one.
At threshold one, every positive-probability token is preserved explicitly, avoiding accidental loss of a tiny positive tail from cumulative-sum rounding. For probabilities and threshold 0.5, the first token alone qualifies: the definition uses greater-than-or-equal, not strictly greater. With and , the stable tie rule selects indices zero and one.
The implementation sorts the whole vocabulary, requiring time and linear storage per step. More specialized selection procedures can avoid a full sort for top-k. These costs exclude the model forward pass and any device-transfer overhead. A mathematical distribution transformation is not by itself a high-performance generation implementation.
A probability cutoff is not a correctness filter
The model can assign a wrong answer high probability and a required technical term low probability. Truncation may then retain the error and remove the needed token. If the task requires a specific phrase or structured format, use and evaluate explicit constraints rather than assuming a nucleus threshold enforces them.
Parameter names alone are insufficient for reproduction. Record whether temperature runs before truncation, how ties are handled, whether top-k and top-p are combined, and what happens at endpoints. A policy that takes a nucleus after top-k renormalization uses different mass from a nucleus taken directly from the original distribution.
The one-step total variation identity does not mean a long generated sequence stays within the same distance. Different sampled prefixes produce different future distributions. Nor does a smaller distance establish better text. The cited papers evaluate generated outputs; this chapter isolates the sampler’s probability bookkeeping.
Reconstruct the retained distribution
- For with threshold 0.7, what are the nucleus and normalized probabilities? Answer: Keep the first two indices, with original mass 0.85. Their probabilities become and ; the third is zero.
- What is total variation distance in that example? Answer: 0.15, the discarded original mass. Renormalization increases retained mass by another 0.15 in the absolute-difference sum, whose half is 0.15.
- Must top-2 on probabilities 0.4, 0.3 and 0.3 include both tied 0.3 entries? Answer: Not under our exact-size rule: indices zero and one are kept. An inclusive kth-logit threshold would retain all three. Both conventions must be documented rather than silently interchanged.
- Why do the two operation orders differ in the displayed example? Answer: Squaring first moves the largest probability above the 0.6 cutoff, leaving one token. Truncating first retains two, and subsequent positive-temperature scaling keeps both positive.
Compare policies on matched contexts
Fan and colleagues give a concrete top-k generation setup; Holtzman and colleagues explain why a fixed count behaves differently on flat and peaked distributions and define nucleus truncation. Their original tasks motivate measuring both distribution shape and generated-text outcomes.
For a new system, retain the complete ordering of sampling operations in the experiment record. If a speculative decoder accelerates the policy, its acceptance correction must preserve these adjusted probabilities. For hard output requirements, continue to constrained decoding.
Make a prediction, then check
For probabilities .6, .25, .15 and top-p threshold .7, which entries remain?
Learning objectives
- Construct a minimal sorted prefix reaching the nucleus threshold.
- Explain renormalization and explicit tie policy.
- Demonstrate when temperature and nucleus truncation do not commute.
Prerequisites & connections
Explore related knowledge →References
- Hierarchical Neural Story Generation
Angela Fan; Mike Lewis; Yann Dauphin · 2018 - The Curious Case of Neural Text Degeneration — arXiv v2, ICLR 2020 text
Ari Holtzman; Jan Buys; Li Du; Maxwell Forbes; Yejin Choi · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author read Fan ACL2018 PDF5/6 section5.4 and Holtzman v2 PDF4–6 nucleus definition, renormalization and comparison. Six paired equations and four explained exercises. Original exact-size stable-tie top-k and minimal-prefix top-p, crossing-token, endpoint/full-support checks and actual noncommuting temperature0.5/nucleus0.6 counterexample. One-step TV bound not sequence quality; no generation benchmark.
- Single AI author read Fan ACL2018 PDF5/6 section5.4 and Holtzman v2 PDF4–6 nucleus definition, renormalization and comparison. Six paired equations and four explained exercises. Original exact-size stable-tie top-k and minimal-prefix top-p, crossing-token, endpoint/full-support checks and actual noncommuting temperature0.5/nucleus0.6 counterexample. One-step TV bound not sequence quality; no generation benchmark.
- Four computed SVG variants per topic;9 numeric/geometry tests and24 responsive cases passed. Eight final Chinese-mobile/English-desktop screenshots actually inspected. Full article acceptance recorded separately.
Source locations checked:
- Hierarchical Neural Story Generation · Visually read PDF5–6, especially section5.4: authors use top-10 random sampling and tune temperature for their story models. Not evidence of a universal best k or temperature. No story-model benchmark reproduced.
- The Curious Case of Neural Text Degeneration — arXiv v2, ICLR 2020 text · Visually read PDF4–6, sections3.1–3.3/equations2–4 and4.1 setup. Nucleus minimal prefix, truncation renormalization and temperature; reported quality is task/model-specific. No text generation experiment reproduced.
Related topics