QuiddityML

By · 5 November 2026 · 12 min read

LLM decoding strategies: greedy, sampling, top-k, top-p, and min-p

How greedy decoding, random sampling, top-k, top-p and min-p each pick the next token, what each one does to the output, and how to write all five in PyTorch.

A decoding strategy is the rule a language model uses to turn its predictions into text, one token at a time. A token is a whole word or a piece of a word. The model itself only gives a score to every token it knows, and the decoding strategy picks which one gets written. The same trained model can give one fixed answer or a different answer on every run, depending on this rule alone.

From training to generation

A language model reads the tokens so far and outputs one score for every token in its vocabulary. These raw scores are called logits. A higher logit means the model rates that token as a more likely next token.

During training, the data holds the real next token, and the loss pushes that token's logit up. During generation there is no real next token waiting in the data. The model still produces the same logits, and something has to choose a token from them. That choice rule is the decoding strategy.

Two panels from the same model and logits z: training feeds previous tokens through the model to logits and cross-entropy against a target token from the data, while inference feeds the logits into a choice rule that picks the next token and feeds it back.

Logits and probabilities

Softmax turns a vector of logits into probabilities that are all positive and add up to 1:

$$p_i = \frac{\exp(z_i)}{\sum_j \exp(z_j)}$$

Here $z_i$ is the logit of token $i$ and $p_i$ is its probability. For example, the logits 3.2, 1.4, 0.2 and -0.7 for cat, dog, sat and the become the probabilities 0.81, 0.13, 0.04 and 0.02.

Softmax keeps the order of the scores, so the token with the largest logit also has the largest probability. Here $\arg\max$ returns the position of the largest value:

$$\arg\max_v z_v = \arg\max_v \mathrm{softmax}(\mathbf{z})_v$$

A rule that only needs the top token can work on the logits directly. Rules that draw a token at random, or filter tokens by probability, need softmax first.

The logits 3.2, 1.4, 0.2 and -0.7 for cat, dog, sat and the becoming probabilities 0.81, 0.13, 0.04 and 0.02 in the same order, with greedy using argmax of the logits and sampling, filtering and sequence scoring using probabilities or log-probabilities.

The autoregressive loop

A model generates text one token at a time. Autoregressive means each chosen token is fed back in as the input for the next step. The model predicts a token, appends it to what it has so far, and uses that longer sequence to predict the next token.

The loop needs a token to start from and a token that ends it. Before anything has been generated there is no previous token, so the loop starts from BOS, a special beginning-of-sequence token. When the model picks EOS, the end-of-sequence token, generation stops. A maximum length stops the loop when EOS never comes.

In the picture below the model is a decoder that starts from a context vector $c$, which an encoder built from an input sentence, as in a translation model. H is the size of the decoder's state and V is the vocabulary size. At every step the decoder state gives V logits, softmax turns them into V probabilities, and one token is chosen.

Four decoder steps t = 1, 2, 3 and T, each going from a decoder state of size H to V logits, then V probabilities with a different shape at each step, then a chosen token y1, y2, y3 and yT, with each chosen token fed back into the next step.

Here is the loop in PyTorch for that encoder-decoder setup. A model with only a decoder runs the same loop, starting from the tokens of its prompt.

1def decode(encoder_output, tokenizer, model, max_len=50):
2    current_token = torch.tensor([[tokenizer.bos_id]])
3    hidden = encoder_output
4    generated = []
5 
6    for _ in range(max_len):
7        emb = model.embedding(current_token)
8        logits, hidden = model.decoder(emb, hidden)
9        next_token = logits.argmax(dim=-1)
10        generated.append(next_token.item())
11 
12        if next_token.item() == tokenizer.eos_id:
13            break
14        current_token = next_token
15 
16    return tokenizer.decode(generated)

current_token holds a token id, and the decoder reads vectors, so model.embedding looks the id up in an embedding table first. The line next_token = logits.argmax(dim=-1) is the choice rule. Every strategy in this post keeps the rest of the loop and changes only that line.

The encoder reading x1 to xS into a context c, and the decoder running bottom to top at each step: input token, state s_t, a Linear layer, probabilities, then the next token, which becomes the input of the next step, with the loop's code and an example distribution of the 0.36, cat 0.22, sat 0.14, on 0.09, mat 0.06 and EOS 0.02.

Since a chosen token becomes part of the input, one choice can affect the steps after it. Each strategy answers the same question at each step: given the current logits, which token becomes next_token?

Two related methods work differently from these rules. Temperature reshapes the probabilities before a rule runs, and beam search compares whole sequences instead of choosing one token at a time.

Logits at one position going into a panel that asks which token becomes next_token, with four answers: greedy takes the highest-probability token, random sampling draws from the full distribution, top-k, top-p and min-p filter before sampling, and temperature reshapes the distribution first, plus beam search below as a search over whole sequences.

Greedy decoding

Greedy decoding takes the single highest-scoring token at every step. In code it is the argmax line from the loop above.

For example, suppose the model's top candidates at the first step are cat at 0.38 and the at 0.31. Greedy writes cat. At the next step it picks sat at 0.49, then on at 0.52, and the output so far is "cat sat on".

Three greedy steps: cat 0.38 is picked over the 0.31, then sat 0.49 over is 0.21, then on 0.52 over in 0.20, building the output cat, cat sat, cat sat on.

Greedy is fast, and it gives the same output each time for the same input. That suits short factual completions and debugging runs. Its weakness is that it decides one step at a time. A token that looks best now can lead to weaker options later, and greedy never goes back to change it. Its output also tends to be bland, because the top token at each step is often a safe and common one.

Random sampling

Random sampling turns the logits into probabilities and draws one token, where each token's chance of being drawn equals its probability. Language often has several reasonable next tokens, and sampling keeps that spread instead of always taking the top one.

In the example below, "the" has probability 0.421 and "a" has 0.173. Sampling picks "the" about 42% of the time and "a" about 17% of the time, and it picks "sleeping" or "zebra" now and then. Three runs from the same distribution can give three different tokens.

A bar chart of six next-token probabilities, the 0.421, a 0.173, mat 0.082, on 0.041, sleeping 0.027 and zebra 0.015, then three runs drawing from it that land on the, mat and sleeping.

In PyTorch, sampling is two lines:

1probs = F.softmax(logits, dim=-1)
2next_token = torch.multinomial(probs, num_samples=1)

torch.multinomial draws num_samples token ids, each with a chance equal to its probability.

Sampling gives variety, which helps with creative text and brainstorming. The cost is control. A vocabulary has thousands of tokens with tiny probabilities, and together they still add up to a real chance, so plain sampling sometimes picks an odd token.

Top-k sampling

Top-k sampling keeps the $k$ highest-scoring tokens, drops the rest and samples from the tokens it kept. After the drop the kept probabilities no longer add up to 1. Dividing each one by their sum makes them add up to 1 again, which is called renormalizing.

For example, with $k = 5$ the five kept tokens have probabilities 0.34, 0.22, 0.14, 0.09 and 0.06, which add up to 0.85. Dividing each by 0.85 gives 0.40, 0.26, 0.16, 0.11 and 0.07.

A sorted bar chart where the top five bars 0.34, 0.22, 0.14, 0.09 and 0.06 are kept and a long tail of tiny bars is dropped, then the five kept bars renormalized to 0.40, 0.26, 0.16, 0.11 and 0.07.

In code, torch.topk(logits, k) returns two tensors: values, the $k$ largest logits, and indices, their ids in the vocabulary. Softmax over the kept logits gives the same numbers as renormalizing their probabilities. The draw picks a position among the kept tokens, so indices.gather maps that position back to a vocabulary id:

1def top_k_sample(logits, k):
2    values, indices = torch.topk(logits, k)
3    probs = F.softmax(values, dim=-1)
4    choice = torch.multinomial(probs, num_samples=1)
5    return indices.gather(-1, choice)

Top-k still samples, so it still gives variety, and the worst tail tokens are gone before the draw. Its weakness is that $k$ stays the same from step to step while the model's confidence changes. When the model is confident and only a few tokens fit, a large $k$ keeps weak tokens. When the model is unsure and many tokens fit, a small $k$ drops good ones.

Two panels: k = 6 on a peaked distribution keeps 0.918 of the probability, including three tail tokens under 0.08, and k = 3 on a flat distribution keeps only 0.45 and drops many reasonable tokens.

Top-p (nucleus) sampling

Top-p sampling, also called nucleus sampling, sets the size of the pool from the probabilities instead of using a fixed count. Sort the tokens from most to least likely and keep adding them until their probabilities add up to at least $p$, such as 0.9. Then renormalize the kept tokens and sample.

For example, take $p = 0.9$ and a confident distribution that starts 0.62, 0.19, 0.08 and 0.05. The first three add up to 0.89, which is still short of 0.9, so the fourth token joins and the pool has four tokens. An unsure distribution that starts 0.16, 0.13 and 0.11 needs twelve tokens to reach 0.9. The pool stays small when the model is confident and grows when it is unsure.

Two horizontal bar charts with p = 0.9: a confident distribution where the smallest prefix reaching 0.9 holds four tokens, 0.62, 0.19, 0.08 and 0.05, and an uncertain one where it holds twelve tokens from 0.16 down to 0.03.

In code, torch.sort returns the sorted probabilities and their original ids, and torch.cumsum gives the running total at each position:

1def top_p_sample(logits, p):
2    probs = F.softmax(logits, dim=-1)
3    sorted_probs, sorted_idx = torch.sort(probs, descending=True)
4    cum = torch.cumsum(sorted_probs, dim=-1)
5    keep = cum <= p
6    keep[..., 0] = True
7    keep[..., 1:] |= cum[..., :-1] < p
8    filtered = sorted_probs.masked_fill(~keep, 0.0)
9    filtered = filtered / filtered.sum(dim=-1, keepdim=True)
10    choice = torch.multinomial(filtered, num_samples=1)
11    return sorted_idx.gather(-1, choice)

keep[..., 0] = True keeps the top token in every row. The |= line also keeps the token where the running total crosses $p$, because the total just before it was still below $p$. ~keep flips the mask, masked_fill sets the dropped probabilities to 0, and dividing by the new sum makes the kept ones add up to 1.

Min-p sampling

Min-p sampling compares every token with the current top token. Let $p_{\max}$ be the highest probability at this step. With a setting $m$, called min_p in code, min-p keeps every token whose probability is at least $m \cdot p_{\max}$.

For example, with $m = 0.1$ and a top probability of 0.40, the cutoff is $0.1 \times 0.40 = 0.04$. The tokens at 0.40, 0.22 and 0.11 stay, and the tokens at 0.03 and 0.01 are dropped. When the top probability is only 0.12, the cutoff falls to 0.012 and only the 0.01 token is dropped.

Two panels with min_p = 0.1: high confidence with p_max = 0.40 has a cutoff of 0.04 that keeps 3 tokens and drops 2, and low confidence with p_max = 0.12 has a cutoff of 0.012 that keeps 4 tokens and drops 1.

When the model is confident, $p_{\max}$ is high, so the cutoff rises and weak tokens are removed. When the model is less confident, $p_{\max}$ is lower, so the cutoff falls and more alternatives stay. Min-p keeps the tokens that are competitive with the best one, instead of using a fixed count or a fixed total.

1def min_p_sample(logits, min_p):
2    probs = F.softmax(logits, dim=-1)
3    p_max = probs.max(dim=-1, keepdim=True).values
4    keep = probs >= (min_p * p_max)
5    filtered = probs.masked_fill(~keep, 0.0)
6    filtered = filtered / filtered.sum(dim=-1, keepdim=True)
7    return torch.multinomial(filtered, num_samples=1)

keepdim=True keeps p_max as a column with one value per row, so the comparison works on a whole batch of rows at once.

How the rules compare

The loop is the same for all five rules: produce logits, choose one token and feed it back in. The rules differ in which tokens they allow into the draw.

Rule Tokens it can pick Same output every run
Greedy the top token yes
Random sampling every token no
Top-k the k most likely no
Top-p the smallest set reaching p no
Min-p tokens at or above min_p * p_max no

On one distribution of 0.50, 0.25, 0.15, 0.07 and 0.03 the rules keep different tokens. Top-p with $p = 0.7$ keeps two tokens, because 0.50 + 0.25 = 0.75 already reaches 0.7. Min-p with $m = 0.2$ has a cutoff of 0.10, so it keeps three.

Temperature is a separate setting that changes the probabilities themselves before any of these rules runs. A low temperature makes the top tokens more likely and the output steadier, and a high temperature spreads probability out. The temperature post covers it with numbers.

One distribution of 0.50, 0.25, 0.15, 0.07 and 0.03 under five rules: greedy keeps 1 token, random keeps all 5, top-k with k = 3 keeps 3, top-p with p = 0.7 keeps 2, and min-p with min_p = 0.2 draws a cutoff at 0.10 that keeps 3.

All five rules in PyTorch

This script runs each rule 10,000 times on two made-up distributions over five tokens and prints how often each token was picked. The first distribution is unsure, with 0.50 at the top. The second is confident, with 0.90 at the top.

1import torch
2import torch.nn.functional as F
3 
4vocab = ["mat", "rug", "sofa", "floor", "moon"]
5unsure = torch.log(torch.tensor([0.50, 0.25, 0.15, 0.07, 0.03]))
6sure = torch.log(torch.tensor([0.90, 0.05, 0.03, 0.01, 0.01]))
7 
8def greedy(logits):
9    return logits.argmax(dim=-1, keepdim=True)
10 
11def sample(logits):
12    probs = F.softmax(logits, dim=-1)
13    return torch.multinomial(probs, num_samples=1)
14 
15def top_k_sample(logits, k):
16    values, indices = torch.topk(logits, k)
17    probs = F.softmax(values, dim=-1)
18    choice = torch.multinomial(probs, num_samples=1)
19    return indices.gather(-1, choice)
20 
21def top_p_sample(logits, p):
22    probs = F.softmax(logits, dim=-1)
23    sorted_probs, sorted_idx = torch.sort(probs, descending=True)
24    cum = torch.cumsum(sorted_probs, dim=-1)
25    keep = cum <= p
26    keep[..., 0] = True
27    keep[..., 1:] |= cum[..., :-1] < p
28    filtered = sorted_probs.masked_fill(~keep, 0.0)
29    filtered = filtered / filtered.sum(dim=-1, keepdim=True)
30    choice = torch.multinomial(filtered, num_samples=1)
31    return sorted_idx.gather(-1, choice)
32 
33def min_p_sample(logits, min_p):
34    probs = F.softmax(logits, dim=-1)
35    p_max = probs.max(dim=-1, keepdim=True).values
36    keep = probs >= (min_p * p_max)
37    filtered = probs.masked_fill(~keep, 0.0)
38    filtered = filtered / filtered.sum(dim=-1, keepdim=True)
39    return torch.multinomial(filtered, num_samples=1)
40 
41torch.manual_seed(0)
42rules = {
43    "greedy": greedy,
44    "sample": sample,
45    "top-k, k=3": lambda z: top_k_sample(z, 3),
46    "top-p, p=0.7": lambda z: top_p_sample(z, 0.7),
47    "min-p, 0.2": lambda z: min_p_sample(z, 0.2),
48}
49for label, logits in [("unsure", unsure), ("sure", sure)]:
50    print(label)
51    for name, rule in rules.items():
52        counts = [0] * len(vocab)
53        for _ in range(10_000):
54            counts[rule(logits).item()] += 1
55        print(f"  {name:13s}", " ".join(f"{w}={c / 10_000:.2f}" for w, c in zip(vocab, counts)))
1unsure
2  greedy        mat=1.00 rug=0.00 sofa=0.00 floor=0.00 moon=0.00
3  sample        mat=0.50 rug=0.25 sofa=0.15 floor=0.07 moon=0.03
4  top-k, k=3    mat=0.55 rug=0.28 sofa=0.17 floor=0.00 moon=0.00
5  top-p, p=0.7  mat=0.66 rug=0.34 sofa=0.00 floor=0.00 moon=0.00
6  min-p, 0.2    mat=0.55 rug=0.28 sofa=0.17 floor=0.00 moon=0.00
7sure
8  greedy        mat=1.00 rug=0.00 sofa=0.00 floor=0.00 moon=0.00
9  sample        mat=0.90 rug=0.05 sofa=0.03 floor=0.01 moon=0.01
10  top-k, k=3    mat=0.92 rug=0.05 sofa=0.03 floor=0.00 moon=0.00
11  top-p, p=0.7  mat=1.00 rug=0.00 sofa=0.00 floor=0.00 moon=0.00
12  min-p, 0.2    mat=1.00 rug=0.00 sofa=0.00 floor=0.00 moon=0.00

The logits here are the logs of the probabilities, so softmax gives the same probabilities back. On the unsure distribution, top-k and min-p keep the same three tokens and pick them in the renormalized proportions 0.55, 0.28 and 0.17. On the confident one, top-k still keeps three tokens and picks rug or sofa 8% of the time, while top-p and min-p keep only mat.

If the counts look wrong, print the kept mask or the kept ids first. A common bug in these functions is a mask that keeps the wrong tokens, or a position that never gets mapped back to a vocabulary id.

Which rule to use

Common mistakes

How language models are trained covers where the logits come from: next-token prediction and the cross-entropy loss. Temperature divides the logits by a number before softmax, which makes any sampling rule steadier or more varied. Beam search keeps several partial sequences at once and compares their total scores, which fixes the one-step view that greedy has.

QuiddityML teaches autoregressive decoding, greedy decoding, random sampling, top-k, top-p and min-p as separate concepts in the language models unit of its NLP track. The exercises include filling in the blanks of the top-p sampler, spotting the bug in a top-k sampler that returns positions instead of ids, and writing min_p_sample from scratch (QuiddityML).