Skip to content

Top-p and Top-k Sampling

Abstract

Top-k and top-p — sampling strategies that limit the set of candidates for the next token to improve generation quality.

Why Are They Needed

During pure sampling from the full distribution, the model may choose a low-probability token, leading to incoherent text. Top-k and top-p cut off the 'tail' of the distribution.

Top-k

Select the k tokens with the highest probability, then re-normalize the probabilities. Example: k = 50 — only the 50 most probable tokens are considered.

Top-p (nucleus sampling)

Select the minimal set of tokens whose cumulative probability is not less than p. For example, p = 0.9 — tokens are taken until their cumulative probability reaches 0.9.

Comparison

Parameter Principle Advantages Disadvantages
Top-k Fixed number of tokens Simplicity Does not adapt to the distribution
Top-p Dynamic probability threshold Adaptability Slightly more complex to implement

Combining

Usually, both parameters are used: first, top-k cuts off the tail, then top-p refines. Recommended values: k = 40–50, p = 0.9–0.95.

Example

from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("gpt2")
tokenizer = AutoTokenizer.from_pretrained("gpt2")
inputs = tokenizer("The meaning of life is", return_tensors="pt")
outputs = model.generate(
    **inputs,
    do_sample=True,
    top_k=50,
    top_p=0.95
)
print(tokenizer.decode(outputs[0]))

Diagram

graph TD
    A[Full distribution] --> B[Top-k selection]
    B --> C[Top-p selection]
    C --> D[Sampling]