
28 July 2026
Decoding Strategies and Exposure Bias
This post merges two sets of class notes I wrote up at the end of July. The first half covers how a language model turns its probability distribution over the next token into actual text, which is the job of decoding strategies. The second half covers the gap between training and inference that comes from generating one token at a time, known as exposure bias.
NLP splits roughly into NLU (understanding) and NLG (generation). In NLG, the more open-ended the task, the more reasonable outputs there are, and the less sense it makes to treat "the single most probable string" as the whole goal.
The two kinds of generation task also tend to use different architectures:
- Conditional tasks such as translation and summarization usually use an encoder-decoder: the encoder reads the full input bidirectionally, and the decoder reads that representation through cross-attention.
- Open-ended generation usually uses a decoder-only model, which keeps predicting the next token from the context so far.
This is a common pairing, with no hard rule behind it. An encoder-decoder can do open-ended generation, and a decoder-only model can translate and summarize.
From logits to the next token
An LLM only produces a distribution over the vocabulary for the next token. Which token actually gets picked is up to the decoding strategy. The model outputs logits, and the decoding strategy decides how to modify, truncate, search or sample that distribution. One decoding step usually goes in this order:
- The model outputs logits.
- Logit processors adjust them first, for example repetition penalties or format constraints.
- Distribution shaping: temperature controls how sharp the distribution is.
- Candidate truncation: top-k or top-p cuts off the long tail.
- Selector: greedy, sampling or search picks one token.
- The chosen token is appended to the context, and we go back to step 1 for the next one.
There can also be an extra step at the sequence level: generate complete candidates first, then let a reranker or verifier pick one.
Search and selection
Greedy decoding
At every step, pick the token with the highest probability:
It's fast and stable, which makes it a good baseline. The downside is that the best choice at each step doesn't add up to the best sentence, an early mistake can't be undone, and long outputs tend to get bland or repetitive.
Beam search
At every step, keep the highest-scoring candidate sequences and extend each of them. It spends extra compute to approximately find a complete string with higher probability.
It suits low-entropy tasks with a narrow output space, such as translation and speech recognition. In open-ended generation, the highest-likelihood path is often overly safe and template-like, and the beams tend to converge on each other.
Sampling straight from the distribution
Vanilla sampling, also called multinomial sampling, draws directly from the model's full distribution:
It keeps many valid ways of saying something. The trouble is the long tail of the vocabulary: each of those tokens has a tiny probability, but there are so many that together they still hold a sizable share of the probability mass, so you can draw a token that is clearly wrong. That's why top-k and top-p cut off the tail before sampling.
Shaping and truncating the distribution
These methods usually don't make the final pick. They control the shape of the distribution before sampling.
| Method | How it works | What it solves | Main issue |
|---|---|---|---|
| Temperature | divide the logits by , then softmax | continuous control over how sharp the distribution is | doesn't remove the tail; low temperature doesn't guarantee correctness |
| Top-k | keep only the most probable tokens | cuts the tail at a fixed size | a fixed ignores the shape of the distribution |
| Top-p | keep the smallest set whose cumulative probability first reaches | the candidate pool grows or shrinks with the model's confidence | the same means different things for flat and sharp distributions |
The temperature formula:
- : flatter distribution, more exploration.
- : sharper distribution, more weight on high-probability tokens.
- : the formula is undefined; many implementations special-case it as greedy.
A top-p example: with probabilities 0.45, 0.30, 0.15, 0.06, 0.04, top_p=0.9 keeps the first three tokens (they sum to exactly 0.9), renormalizes them to about 0.50, 0.33, 0.17, and samples from those.
Reducing repetition
Repetition can come from token-level preferences, or from reading the same input position over and over. Here are a few classic fixes.
Penalizing tokens already seen
Push down the logit of any token that has already appeared:
A presence penalty only checks whether the token has appeared; a frequency penalty grows with the number of times it has appeared; a repetition penalty applies a scaling correction whose exact form depends on the implementation.
It's simple and works at inference time with no retraining. But it can't tell whether a repeat is legitimate, so it can hurt names, code, math symbols and technical terms.
Coverage loss
Coverage loss is mainly used for translation and summarization with an encoder-decoder. It tracks how much cross-attention the decoder has already given to each source position:
If the current step attends heavily to positions that are already covered, the loss goes up:
What it reduces is "translating the same piece of input several times". It's mainly a training objective, so unlike a sampling parameter you can't just switch it on at inference for a decoder-only model.
Contrastive decoding
Run an expert model alongside a weaker amateur model:
Things both models like, such as "very very very", cancel out, while candidates the expert clearly prefers get a higher score. The cost is a second model and more inference compute. In the original paper the two terms are simply subtracted, and is a cutoff that first drops tokens the expert itself finds too unlikely; the weighted form above is a common variant.
Don't confuse contrastive decoding with contrastive search. The first uses two models, an expert and an amateur. The second usually uses a single model and adds a degeneration penalty based on hidden states to its probabilities. They are different algorithms.
Re-ranking and verifiers
Per-token probabilities don't always tell you how good a complete answer is. Another route is to generate several complete candidates first, then re-rank them with a reward model, rules, tests or a verifier:
sampling / search → N complete candidates → reranker / verifier → final answer
This fits code, math and other high-value tasks, but cost and latency usually grow with the number of candidates.
Is the maximum-likelihood string reasonable?
For open-ended tasks, usually not. Human text comes from an uncertain distribution with many equally valid ways of saying things. Always chasing the single maximum-likelihood string is mode seeking: it tends to produce safe, ordinary, low-information text that doesn't represent the distribution as a whole.
This habit of "hugging the high-probability modes" can serve as a weak signal for detecting AI-generated text, but it can't reliably tell you who wrote something.
Decoding methods side by side
| Method | Strength | Cost | Best for |
|---|---|---|---|
| Greedy | fast, stable, easy to reproduce | locally optimal, often bland | short answers, baselines |
| Beam search | searches several high-probability paths | heavy compute and KV cache, conservative output | translation, speech recognition |
| Sampling | keeps diversity | variance, long-tail risk | open-ended generation |
| Temperature | controls how much to explore | doesn't remove bad candidates | shaping the sampling distribution |
| Top-k | cuts the tail simply | fixed pool size, not adaptive | when you want a fixed pool size |
| Top-p | candidate set follows the model's confidence | depends on how well calibrated the distribution is | general open-ended sampling |
| Token penalties | directly eases mechanical repetition | can hurt repetition that's needed | once you've seen repetition |
| Coverage loss | stops the model re-reading the source | mostly limited to encoder-decoder | training for translation, summarization |
| Contrastive decoding | suppresses the clichés a weak model likes | two models at inference | controlled local inference experiments |
| Reranker / verifier | judges quality on the complete output | generation cost grows with | code, math, complex tasks |
Training and inference see different prefixes
Decoding is about picking tokens one at a time at inference. That "one at a time" brings its own problem: exposure bias. It's the difference in prefix distribution between teacher-forced training and autoregressive inference: during training the model only ever sees true prefixes, but at inference it has to keep writing on top of its own predictions, mistakes included.
During training the model always walks along the answer key. At inference, from the first mistake onward, it can wander into context it has never seen. A mistake changes the distribution of the inputs that follow, so errors build on one another instead of staying independent.
Teacher forcing
I mentioned teacher forcing in From RNN to Seq2Seq: during training, the decoder is fed the true previous token at each step. It only gets the true history; the token it's supposed to predict is never handed to it in advance.
If the target sentence is I love learning, one training example can be shifted right like this:
Input: <BOS> I love
Target: I love learning
One forward pass computes all three predictions at once:
<BOS> → predict "I"
<BOS> I → predict "love"
<BOS> I love → predict "learning"
The full true sequence already exists, and the causal mask stops each position from peeking at later tokens, so a Transformer can compute every position in parallel.
Student forcing: autoregressive inference
At inference there's no answer key, so the model has to feed the token it just generated back into the context:
generate token 1 → put it back in context → generate token 2 → put it back in context → ...
Say the target is I love learning, but the model generated I like:
- Teacher forcing: the next step still predicts "learning" from the true prefix
I love. - Student forcing: the next step carries on from the model's own prefix
I like.
"Student forcing" usually means running free, feeding the model's own predictions back autoregressively. It describes how inputs are fed, and has nothing to do with the model architecture.
Distribution mismatch
Training optimizes:
But at inference the prefix comes from the model itself:
That sets off a chain:
- The training prefix distribution ≠ the inference prefix distribution.
- A model error changes the next input.
- The state drifts further from the training data.
- Errors can compound.
Mitigations
These methods tackle the train–inference mismatch to different degrees.
| Method | How it works | Directly shrinks the mismatch? | Main issue |
|---|---|---|---|
| Scheduled sampling | gradually mixes model-generated tokens into training | yes | mixed prefixes are unnatural; early generated inputs are poor |
| Dataset aggregation / DAgger | collects the model's own trajectories, has an expert label the right action after it drifts, merges them in and retrains | yes | in NLG there's often no single expert continuation after drifting |
| Retrieval augmentation | keeps anchoring generation with external evidence | no, it mainly softens the consequences | the model still uses its own generated prefix |
| Reinforcement learning | optimizes a sequence-level reward on the model's own full rollouts | yes | reward design, stability, cost, credit assignment |
Scheduled sampling
Early in training, use mostly true tokens; later, raise the share of tokens the model generated itself:
Early: 90% gold + 10% generated
Later: 30% gold + 70% generated
The intuition is to let the model gradually learn to handle the states its own mistakes lead to. But discrete sampling can't pass gradients directly, and a mixed prefix may look neither like human text nor like a full model rollout. It isn't the default in modern LLM training.
Dataset aggregation
A DAgger-style loop:
- Let the model roll out on its own.
- Collect the states it reaches, or the prefixes where it went wrong.
- Have an expert label the correct next step from each of those states.
- Add the new examples to the dataset.
- Retrain and repeat.
The key difficulty for NLG: once the model drifts from the reference, there are usually several reasonable ways to continue, so the expert label is no longer unique.
Retrieval augmentation
RAG adds reliable material to the current context:
model context + retrieved evidence → next-token generation
It can cut down on accumulating factual errors and topic drift, but it doesn't change the fact that inference runs on the model's own prefix, so it isn't a direct fix for exposure bias.
Reinforcement learning
RL lets the model generate its own complete trajectories, then updates it by a sequence-level reward:
The training data comes from rollouts of the current (or nearly current) policy, so it's closer to the states the model actually meets at inference. The costs: rewards are hard to design, training is expensive, reward hacking can happen, and when a whole answer gets a low score it's hard to pin that on specific tokens.
RLHF is one framework for feeding that kind of signal back to the policy. I wrote about PPO, the update algorithm commonly used inside it, in PPO for LLM Alignment.
References
- Hugging Face Transformers: Generation
- Holtzman et al., The Curious Case of Neural Text Degeneration
- Li et al., Contrastive Decoding: Open-ended Text Generation as Optimization
- See et al., Get To The Point: Summarization with Pointer-Generator Networks
- Bengio et al., Scheduled Sampling for Sequence Prediction with Recurrent Neural Networks
- Ross et al., A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning