C.W.K.
Stream
Lesson 08 of 12 · published

Decoding Strategies: Greedy, Beam, Top-k, Top-p

~12 min · decoding, sampling

Level 0Token
0 XP0/94 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

The model produces logits at every step. Decoding turns those logits into a chosen next token. Five common strategies, each with different bias/variance tradeoffs.

Greedy

Always pick the highest-probability token. Deterministic, fast, repetitive. Good for classification or where the answer is unambiguous; bad for creative text.

Beam search

Maintain k partial sequences ("beams") at each step. At every step, expand each beam by all possible next tokens, score each candidate, keep the top k. Better than greedy for translation and structured output, but expensive (k× compute) and tends to produce overly bland text on open-ended tasks.

Top-k sampling

Restrict the candidate set to the k highest-probability tokens, renormalize, sample. Adds randomness while filtering tail noise. k=40 is common.

Top-p (nucleus) sampling

Restrict to the smallest set of tokens whose cumulative probability exceeds p. Adapts dynamically: when one token dominates, the set is small; when uncertainty is high, more tokens enter. p=0.9 is the typical default.

Temperature

Scale logits by 1/T before softmax. T=0 is greedy. T<1 sharpens, T>1 flattens. T=0.7 is a common default for chat. (Next lesson covers temperature in detail.)

Code

Top-p sampling in 8 lines·python
def sample_top_p(logits, p=0.9, temperature=1.0):
    logits = logits / temperature
    sorted_logits, sorted_idx = logits.sort(descending=True)
    probs = F.softmax(sorted_logits, dim=-1)
    cumulative = probs.cumsum(dim=-1)
    cutoff = cumulative > p
    cutoff[..., 1:] = cutoff[..., :-1].clone()
    cutoff[..., 0] = False
    sorted_logits = sorted_logits.masked_fill(cutoff, float('-inf'))
    next_idx = sorted_idx.gather(
        -1, torch.multinomial(F.softmax(sorted_logits, dim=-1), 1)
    )
    return next_idx

External links

Exercise

Generate 5 completions of the same prompt with each strategy: greedy, beam search (k=4), top-k (k=40), top-p (p=0.9), each at temperature=0.7. Read them. Which one feels best for a chat-like prompt? For a factual prompt? For a code prompt?

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.