Text Generation: Sampling, Decoding, and Control
What You'll Learn
- 1Separate search based decoding from stochastic sampling
- 2Compute temperature softmax and nucleus cutoffs from raw logits
- 3Explain why maximum likelihood decoding produces bland, repetitive text
- 4Pick decoding settings that match the task and measure the tradeoff
Every generative model produces a distribution over the next token, and the decoder turns that distribution into a string. The choice matters more than most people expect: greedy search is deterministic and safe but repetitive, while sampling is diverse but can drift off topic. This lesson derives the temperature and nucleus arithmetic, then shows how to control output without retraining the model.
Search Versus Sampling
Greedy decoding takes the argmax at every step and commits early. Beam search keeps the highest scoring partial hypotheses and prunes back to , which raises likelihood but concentrates output on a narrow mode:
The second term is a plug-in control score, such as length or a classifier signal, so decoding becomes a constrained optimization problem rather than plain likelihood maximization. Search errors happen when the true best string was pruned at step 3, and they are the main reason a model with good perplexity still emits a flawed sentence.
Likelihood decoding has a known bias toward safe, generic text: each step multiplies in a factor below one, so long sentences with rare words sink, and short bland ones win. That is why creative and conversational systems sample instead of search.
Temperature and Top-k
Temperature rescales logits before the softmax. Letting be the raw scores:
At you get the model's own distribution. As approaches 0 the softmax sharpens toward the argmax and decoding becomes greedy; as grows the distribution flattens and outputs become surprising but incoherent. Top-k sampling truncates to the most likely tokens first and renormalizes, which keeps the tail from producing nonsense but fixes even when the model is confident.
Nucleus Sampling
Nucleus, or top-p sampling (Holtzman et al., 2019), picks the smallest token set whose cumulative probability reaches a threshold , then renormalizes over it:
The cutoff adapts automatically. When the model is confident, two or three tokens cover 80 percent of the mass and the nucleus is small; when it is uncertain, the nucleus widens, so one fixed behaves sensibly across contexts. Holtzman et al. show that open ended generation under fixed truncation degenerates into indefinitely repeated high frequency sequences, and that nucleus sampling avoids both the repetition and the tail noise.
| Strategy | Rule | Diversity | Typical failure | Use case |
|---|---|---|---|---|
| Greedy | argmax each step | low | loops | classification style output |
| Beam | keep top B paths | low to medium | short bland text | translation, summarization |
| Top-k | keep k best tokens | medium | fixed breadth | dialogue |
| Top-p | keep cumulative mass p | high | off topic drift | creative writing |
| Typical | match model entropy | high | slower to tune | long form drafting |
Control and Evaluation
Control comes from logit warping rather than retraining. A repetition penalty subtracts from logits already seen, a min length constraint forbids the end token, and classifier free guidance blends conditional and unconditional logits:
Evaluation has to match the intent. Task text is scored with task metrics, while free form text needs diversity measures such as distinct-n, the ratio of unique n-grams to total n-grams, plus a repetition rate and human review:
Worked Examples
Worked Code
"""Open ended generation with temperature and nucleus sampling."""
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
ids = tokenizer("The draft of the report", return_tensors="pt").input_ids
out = model.generate(
ids,
max_new_tokens=60,
do_sample=True,
temperature=0.8,
top_p=0.9,
pad_token_id=tokenizer.eos_token_id,
)
print(tokenizer.decode(out[0], skip_special_tokens=True))
"""Temperature and nucleus sampling from raw logits."""
import torch
import torch.nn.functional as F
def nucleus(logits, p=0.9, temperature=0.8):
logits = logits / temperature
probs = F.softmax(logits, dim=-1)
sorted_probs, sorted_idx = probs.sort(descending=True)
keep = sorted_probs.cumsum(-1) - sorted_probs < p
keep[0] = True
cut = sorted_probs * keep
cut = cut / cut.sum()
return sorted_idx[torch.multinomial(cut, 1)]
logits = torch.tensor([2.0, 1.0, 0.5, -1.0])
print("sampled index", nucleus(logits, p=0.8).item())
print("top-p tail", F.softmax(logits / 0.8, dim=-1).round(3).tolist())
Real-World Applications
- Conversational agents - Dialogue systems sample at between 0.6 and 0.9 with a nucleus of 0.9 so replies vary without drifting.
- Summarization - Beam search stays the default because a single high likelihood output is what the task wants.
- Code tools - Low temperature with constrained decoding keeps syntax valid while unit tests catch semantic drift.
- Creative tools - Writers raise temperature or widen for alternatives, then regenerate with a fixed seed for reproducibility.
đĄTune decoding against a human rubric
Common Mistakes
Using temperature 0 and sampling flags together
Fix: Temperature 0 collapses to greedy decoding, so diversity settings become dead configuration.
Comparing diversity across prompts
Fix: Distinct-n depends on prompt length and topic, so compare on a fixed prompt set.
Fixing top-k and top-p at once without a plan
Fix: Nucleus adapts to entropy, so prefer a tuned p and a large k unless you have measured otherwise.
Best Practices
- Log temperature, top-p, and seed with every generated response
- Report distinct-n and repetition rate next to task metrics
- Use beam search for single best outputs and sampling when variety is the product
Key Takeaways
- Greedy and beam search maximize likelihood, which biases output toward short generic text
- Temperature divides logits before the softmax, sharpening at low T and flattening at high T
- Nucleus sampling keeps the smallest set with cumulative mass p and adapts its width to model confidence
- Controls like repetition penalties and guidance operate on logits, so no retraining is required
Frequently Asked Questions
Why does greedy decoding loop?
The same high probability continuation stays on top, and the model has no incentive to move. Repetition penalties or sampling break the tie that greedy preserves.
What is a good starting point for open ended text?
Temperature 0.8 with top-p 0.9 and a large top-k ceiling. Move temperature first for diversity, top-p second for tail control.
Does beam search give better summaries?
Usually yes, because summarization rewards the single highest scoring string. Beam widths above 6 rarely help and often hurt through search error.
Interview Questions
Q1: Explain why nucleus sampling adapts better than top-k.
Top-k always keeps k tokens, so it is too narrow when the model is confident and too wide when it is uncertain, while nucleus keeps whatever set reaches cumulative mass p and widens with entropy.
Q2: How would you tune decoding settings in production?
Sample a fixed prompt set, collect human rankings against a rubric, fit a small grid over temperature and p, then freeze the chosen config with the seed logged for reproducibility.