What is Temperature, Top-p, and Top-k sampling?
Beginner · 2 min read · LLM Fundamentals
Open in study mode to save this question and track progressShort answer: Temperature scales raw logit values to control generation randomness; Top-k restricts token selection to the most probable tokens; Top-p (nucleus sampling) dynamic cuts off selection to the smallest set of cumulative probability tokens exceeding threshold .
Detail
LLM output generation converts raw unnormalized logit vectors into probability distributions over the vocabulary via Softmax:
| Parameter | Function | Value Range | Effect of Lower Value | Effect of Higher Value |
|---|---|---|---|---|
| Temperature () | Divides logits before Softmax | Deterministic, repetitive, focused ( equals greedy decoding) | Creative, chaotic, random | |
| Top- | Keeps top highest logit tokens | Cuts off low probability tail strictly | Includes broader vocabulary tokens | |
| Top- (Nucleus) | Truncates cumulative probability | Restricts candidates dynamically based on distribution steepness | Expands candidate set |
Example
PyTorch implementation of Top- (Nucleus) sampling filter:
python
import torch
def top_p_sampling(logits: torch.Tensor, top_p: float = 0.9, temp: float = 0.7) -> torch.Tensor:
logits = logits / temp
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cumulative_probs = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1)
# Remove tokens with cumulative probability above top_p threshold
sorted_indices_to_remove = cumulative_probs > top_p
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0
indices_to_remove = sorted_indices_to_remove.scatter(0, sorted_indices, sorted_indices_to_remove)
logits[indices_to_remove] = float('-inf')
return torch.multinomial(torch.softmax(logits, dim=-1), num_samples=1)Interview tips
- Highlight that for factual Q&A or JSON code generation, or is preferred, whereas creative brainstorming uses .
- Emphasize combining Top- and Temperature for balanced, non-repetitive responses.