Skip to content

Decoding Strategies: How LLM Chooses the Next Word

Summary

Decoding strategies determine how the model selects the next word from the probability distribution, impacting quality, diversity, and speed of generation. See also LLM.

Greedy Decoding

Greedy decoding selects the token with the highest probability at each step. This is a deterministic method: given the same input, the result is always the same. It is easy to implement and produces coherent text, but often leads to repetition and insufficient diversity.

import torch

def greedy_decode(logits):
    return torch.argmax(logits, dim=-1)

Beam search considers several hypotheses simultaneously. At each step, it keeps the beam_size best sequences by cumulative probability. This improves quality compared to greedy decoding but increases computational costs. See the article Beam Search for more details.

Parameter Description
beam_size Number of hypotheses to keep (usually 4–8)
length_penalty Penalty for length, regulates preference for short or long responses
early_stopping Stops when all hypotheses reach the end

Sampling

Sampling selects the next token randomly from the probability distribution. This allows for diverse responses but can lead to incoherence. Temperature and top-p/top-k are used for control.

  • Temperature — scales logits before softmax. The higher the temperature, the more uniform the distribution. See the article Temperature for more details.
  • Top-p — truncates tokens whose cumulative probability exceeds the threshold p. See the article Top-p and Top-k for more details.
import torch

def sample_with_temperature(logits, temperature=1.0):
    logits = logits / temperature
    probs = torch.softmax(logits, dim=-1)
    return torch.multinomial(probs, num_samples=1)

Strategy Comparison

Strategy Determinism Diversity Quality Speed
Greedy Decoding Yes Low Medium High
Beam Search Yes Low High Medium
Sampling No High Medium High
Sampling + top-p No Medium High Medium

Practical Recommendations

  • For tasks where accuracy is important (e.g., translation), use beam search.
  • For creative tasks (text generation, dialogue), use sampling with temperature 0.7–0.9 and top-p 0.9–0.95.
  • For deterministic responses (e.g., fact extraction), use greedy decoding or temperature 0.

Conclusion

The choice of decoding strategy depends on the task. Understanding the trade-offs between determinism, diversity, and quality helps tailor generation to specific requirements.