Sampling: How LLM Selects Tokens
Briefly
Sampling is the process of selecting the next token from the probability distribution provided by the model. For more details, see the glossary.
Role of Sampling
At each generation step, an LLM calculates probabilities for all dictionary tokens. The sampling process selects one token from this distribution. The choice of strategy determines the nature of the generation: from deterministic to creative.
Main Strategies
Greedy Decoding
The token with the highest probability is selected. A deterministic method that yields the same result with the same input. Disadvantage: tendency to repeat and loop. For more details, see the glossary.
Top-k Sampling
The k tokens with the highest probability are selected from the distribution, then a random choice is made among them based on their probabilities. The parameter k controls diversity. For more details, see the article on top-p and top-k.
Top-p (Nucleus) Sampling
A minimal set of tokens is selected whose cumulative probability exceeds the threshold p. An adaptive method: fewer tokens are selected with sharp distributions, more with flat distributions.
Temperature
The temperature parameter scales logits before softmax. A lower T (< 1) sharpens the distribution, a higher T (> 1) flattens it. For more details, see the article on temperature.
Strategy Comparison
| Strategy | Determinism | Diversity | Control |
|---|---|---|---|
| Greedy | Full | Minimal | None |
| Top-k | Partial | Moderate | Parameter k |
| Top-p | Partial | Moderate | Parameter p |
| Temperature | Partial | High | Parameter T |
Combining Parameters
In practice, strategies are combined. A typical configuration is top-p = 0.9, temperature = 0.7. First, temperature is applied to logits, then top-p filters out low-probability tokens, and finally a selection is made.
import numpy as np
def sample_with_temperature(logits, temperature=1.0):
logits = logits / temperature
exp_logits = np.exp(logits - np.max(logits))
probs = exp_logits / np.sum(exp_logits)
return np.random.choice(len(probs), p=probs)
Impact on Quality
The choice of strategy depends on the task:
- Factual responses — low temperature (0.1–0.3), greedy or top-p with small p.
- Creative texts — high temperature (0.8–1.2), top-p = 0.95.
- Code — low temperature, strict constraints. For more details, see the structured generation.
Sampling is part of the broader decoding process decoding strategies. Methods like speculative decoding are used to speed up generation.