Skip to content
King Jin

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:

  1. The model outputs logits.
  2. Logit processors adjust them first, for example repetition penalties or format constraints.
  3. Distribution shaping: temperature controls how sharp the distribution is.
  4. Candidate truncation: top-k or top-p cuts off the long tail.
  5. Selector: greedy, sampling or search picks one token.
  6. 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.

Logitsmodel outputProcessorspenalties,constraintsTemperaturereshape thedistributionTruncatetop-k, top-pSelectgreedy, sampleor searchAppendadd to contextnext token

Search and selection

Greedy decoding

At every step, pick the token with the highest probability:

xt=arg⁡max⁡iP(xt=i∣x<t)x_t=\arg\max_i P(x_t=i\mid x_{<t})

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 BB 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:

xt∼Categorical⁡(pt)x_t\sim\operatorname{Categorical}(p_t)

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.

MethodHow it worksWhat it solvesMain issue
Temperaturedivide the logits by TT, then softmaxcontinuous control over how sharp the distribution isdoesn't remove the tail; low temperature doesn't guarantee correctness
Top-kkeep only the kk most probable tokenscuts the tail at a fixed sizea fixed kk ignores the shape of the distribution
Top-pkeep the smallest set whose cumulative probability first reaches ppthe candidate pool grows or shrinks with the model's confidencethe same pp means different things for flat and sharp distributions

The temperature formula:

pi(T)=ezi/T∑jezj/Tp_i(T)=\frac{e^{z_i/T}}{\sum_j e^{z_j/T}}
  • T>1T>1: flatter distribution, more exploration.
  • T<1T<1: sharper distribution, more weight on high-probability tokens.
  • T=0T=0: 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:

logit′(i)=logit(i)−λ⋅count(i)logit'(i)=logit(i)-\lambda\cdot count(i)

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:

ct,i=∑t′<tαt′,ic_{t,i}=\sum_{t'<t}\alpha_{t',i}

If the current step attends heavily to positions that are already covered, the loss goes up:

Lcoverage=∑imin⁡(αt,i,ct,i)L_{coverage}=\sum_i\min(\alpha_{t,i},c_{t,i})

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:

score(y)=log⁡Pexpert(y)−αlog⁡Pamateur(y)score(y)=\log P_{expert}(y)-\alpha\log P_{amateur}(y)

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 α\alpha 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

MethodStrengthCostBest for
Greedyfast, stable, easy to reproducelocally optimal, often blandshort answers, baselines
Beam searchsearches several high-probability pathsheavy compute and KV cache, conservative outputtranslation, speech recognition
Samplingkeeps diversityvariance, long-tail riskopen-ended generation
Temperaturecontrols how much to exploredoesn't remove bad candidatesshaping the sampling distribution
Top-kcuts the tail simplyfixed pool size, not adaptivewhen you want a fixed pool size
Top-pcandidate set follows the model's confidencedepends on how well calibrated the distribution isgeneral open-ended sampling
Token penaltiesdirectly eases mechanical repetitioncan hurt repetition that's neededonce you've seen repetition
Coverage lossstops the model re-reading the sourcemostly limited to encoder-decodertraining for translation, summarization
Contrastive decodingsuppresses the clichés a weak model likestwo models at inferencecontrolled local inference experiments
Reranker / verifierjudges quality on the complete outputgeneration cost grows with NNcode, 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:

Ey<t∼Pdata[−log⁡Pθ(yt∣y<t,x)]\mathbb E_{y_{<t}\sim P_{data}} [-\log P_\theta(y_t\mid y_{<t},x)]

But at inference the prefix comes from the model itself:

y<t∼Pθy_{<t}\sim P_\theta

That sets off a chain:

  1. The training prefix distribution ≠ the inference prefix distribution.
  2. A model error changes the next input.
  3. The state drifts further from the training data.
  4. Errors can compound.

Mitigations

These methods tackle the train–inference mismatch to different degrees.

MethodHow it worksDirectly shrinks the mismatch?Main issue
Scheduled samplinggradually mixes model-generated tokens into trainingyesmixed prefixes are unnatural; early generated inputs are poor
Dataset aggregation / DAggercollects the model's own trajectories, has an expert label the right action after it drifts, merges them in and retrainsyesin NLG there's often no single expert continuation after drifting
Retrieval augmentationkeeps anchoring generation with external evidenceno, it mainly softens the consequencesthe model still uses its own generated prefix
Reinforcement learningoptimizes a sequence-level reward on the model's own full rolloutsyesreward 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:

  1. Let the model roll out on its own.
  2. Collect the states it reaches, or the prefixes where it went wrong.
  3. Have an expert label the correct next step from each of those states.
  4. Add the new examples to the dataset.
  5. 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:

max⁡θEy∼Pθ[R(y)]\max_\theta\mathbb E_{y\sim P_\theta}[R(y)]

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

OlderPPO for LLM Alignment →