Top-k Sampling

AI & Machine Learning Foundations beginner How AI Works 10 min read

Overview

Top-k sampling is a decoding strategy that restricts the model’s token selection to only the k most probable next tokens at each generation step. Instead of sampling from the full vocabulary of 30,000–100,000+ tokens, the model considers only the top k candidates, sets all other token probabilities to zero, and re-normalizes the remaining distribution before sampling.

This technique was introduced to solve a fundamental problem with unrestricted sampling: even with moderate temperature settings, there’s always a non-zero chance of selecting extremely low-probability tokens that produce nonsensical output. A token with 0.001% probability might be “xylophone” in the middle of a sentence about database design. Top-k eliminates these tail tokens entirely, creating a hard boundary on the pool of candidate tokens.

For AI engineers, top-k sampling is one of the three primary “knobs” for controlling text generation quality, alongside temperature and top-p (nucleus sampling). Understanding how these parameters interact — and when top-k is the right choice versus alternatives — is critical for tuning production LLM applications.

How It Works

The Algorithm Step by Step

Top-k sampling modifies the standard sampling process with a simple but effective filter:

  1. Generate logits: The model produces raw logit scores for every token in the vocabulary.
  2. Apply temperature: Logits are divided by the temperature parameter T (this step happens first in most implementations).
  3. Compute softmax: The scaled logits are converted to probabilities via the softmax function.
  4. Rank and truncate: Sort all tokens by probability in descending order. Keep only the top k tokens; set all others to probability 0.
  5. Re-normalize: Scale the remaining k probabilities so they sum to 1.0, creating a valid probability distribution.
  6. Sample: Randomly select one token from this truncated distribution, weighted by the re-normalized probabilities.
Key Concept

Top-k creates a hard cutoff at a fixed number of tokens. Regardless of how the probability mass is distributed, exactly k tokens are considered. This is both its strength (simplicity, predictability) and its weakness (inflexibility to varying distribution shapes).

A Concrete Example

Consider generating the next token after “The capital of France is”. The model produces probabilities for its full vocabulary. Here’s what top-k=5 does:

Full vocabulary (simplified to top 8):
Token       | Probability
------------|------------
"Paris"     | 0.72
"the"       | 0.08
"a"         | 0.05
"known"     | 0.04
"called"    | 0.03
"located"   | 0.02
"beautiful" | 0.01
"xylophone" | 0.0001
... (99,992 more tokens with tiny probabilities)

After top-k=5 filtering and re-normalization:
Token       | Original | Re-normalized
------------|----------|-------------
"Paris"     | 0.72     | 0.783
"the"       | 0.08     | 0.087
"a"         | 0.05     | 0.054
"known"     | 0.04     | 0.043
"called"    | 0.03     | 0.033

Tokens like “beautiful,” “located,” and “xylophone” are completely eliminated. The model will sample from only these 5 tokens, weighted by their re-normalized probabilities.

The Fixed-k Problem

The fundamental limitation of top-k sampling is that k is a fixed number, but probability distributions vary dramatically between generation steps. Consider two scenarios:

Scenario A — Confident prediction: After “The Eiffel Tower is located in”, the model is 95% confident the next token is “Paris.” With k=50, you’re including 49 tokens that collectively account for only 5% of the probability mass — unnecessary noise.

Scenario B — Uncertain prediction: After “I really enjoy eating”, many completions are plausible: “pizza,” “sushi,” “pasta,” “fruit,” “chocolate,” etc. The probability might be spread across 200+ reasonable tokens. With k=50, you’re cutting off many perfectly valid completions.

This inflexibility is why top-p (nucleus) sampling was developed as a dynamic alternative — it adapts the number of considered tokens based on how the probability mass is distributed.

Implementation in Code

Here’s how top-k sampling works in practice with the Hugging Face Transformers library:

# Using Hugging Face Transformers
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("gpt2")
tokenizer = AutoTokenizer.from_pretrained("gpt2")

input_ids = tokenizer("The future of AI is", return_tensors="pt").input_ids

# Generate with top-k sampling
output = model.generate(
    input_ids,
    max_new_tokens=50,
    do_sample=True,       # Enable sampling (vs greedy)
    top_k=40,             # Consider only top 40 tokens
    temperature=0.8,      # Moderate temperature
)

print(tokenizer.decode(output[0]))

And with the OpenAI API (note: OpenAI doesn’t expose top-k directly but some providers do):

// Google Vertex AI / Gemini API supports top-k directly
const response = await model.generateContent({
  contents: [{ role: "user", parts: [{ text: prompt }] }],
  generationConfig: {
    topK: 40,
    temperature: 0.8,
  },
});

Interaction with Temperature and Top-p

In the sampling pipeline, these parameters are typically applied in this order:

  1. Temperature — reshapes the full probability distribution
  2. Top-k — hard cutoff to the k most probable tokens
  3. Top-p — dynamic cutoff based on cumulative probability
  4. Sample — randomly select from the surviving tokens

When both top-k and top-p are applied, top-k acts as an upper bound on the number of tokens, and top-p further narrows within that set. For example, with k=100 and p=0.9, you’ll never consider more than 100 tokens, but if the top 20 tokens already cover 90% of the probability mass, only those 20 will be sampled from.

Practical Applications

Choosing the Right k Value

When to Use Top-k vs. Top-p

In modern practice, many engineers prefer top-p over top-k because it adapts to the distribution shape. However, top-k remains valuable in specific scenarios:

Comparing Decoding Strategies

Decoding Strategy Comparison

Greedy (k=1): Always picks top token. Fast, deterministic, but repetitive.
Beam Search: Tracks multiple sequences in parallel. Good for translation, slow for long-form generation.
Top-k Sampling: Samples from top k tokens. Simple, fixed candidate pool.
Top-p Sampling: Samples from smallest set covering p probability mass. Adaptive candidate pool.
Top-k + Top-p: Combines hard ceiling with dynamic narrowing. Most robust for production use.

Production Considerations

When deploying top-k sampling in production, keep these points in mind:

Key Takeaways

Further Reading