Unlikelihood Training in Large Language Models: How Negative Candidate Loss and Sequence-Level Penalties Suppress Repetition Loops and Hallucinations
Autoregressive language models generate text by iteratively predicting the probability distribution of the next token conditioned on preceding tokens. While standard maximum likelihood estimation (MLE) via cross-entropy loss serves as the universal training objective across modern foundation models, it possesses a fundamental structural asymmetry: it exclusively maximizes the likelihood of target tokens appearing in the training corpus without explicitly penalizing degenerate, repetitive, or undesirable tokens.
Under greedy decoding and constrained sampling regimes, standard MLE-trained models frequently suffer from neural text degeneration. Once a model assigns slightly elevated probability to a previously emitted token or n-gram, self-attention mechanisms amplify the token's representation in subsequent steps, trapping the generator in inescapable repetition loops. Heuristic decoding methods, such as nucleus sampling, top-k filtering, and temperature scaling, mitigate this behavior at inference time by truncating the probability distribution, but they mask the pathology rather than resolving the distorted probability landscape learned by the neural network.
Unlikelihood training, introduced by Sean Welleck, Ilia Kulikov, Stephen Roller, Emily Dinan, Kyunghyun Cho, and Jason Weston, directly reformulates the training objective. By incorporating an explicit negative loss term that penalizes designated negative candidate tokens and repeating sequence rollouts, unlikelihood training reshapes the model's output distribution. This analysis examines the mathematical foundations of unlikelihood loss, derives its pre-softmax gradient dynamics, details token-level and sequence-level negative candidate construction, and traces its theoretical lineage to modern preference optimization frameworks like Direct Preference Optimization (DPO).
The Maximum Likelihood Pathology
Modern generative language models decompose the joint probability of a token sequence into an autoregressive product of conditional probabilities:
During standard pre-training and supervised fine-tuning, the parameter vector is optimized using Maximum Likelihood Estimation (MLE), implemented as empirical negative log-likelihood (cross-entropy) over a dataset :
where denotes the ground-truth target token at step , and represents the ground-truth prefix.
Standard Cross-Entropy (MLE):
Context: x_{<t} ───► Model Softmax ───► Maximize log p(x*_t)
(Other tokens implicitly suppressed via normalizer)
Unlikelihood Training (Joint Loss):
Context: x_{<t} ───► Model Softmax ───┬─► Maximize log p(x*_t) [Likelihood]
└─► Minimize log(1 - p(c)) ∀ c∈C [Unlikelihood]The Passive Suppression Weakness
Cross-entropy loss operates as a one-sided objective. When the model computes its predictive distribution via the softmax function over vocabulary logits :
the objective directly pushes up the logit $z_{x_t^}$ corresponding to the ground-truth token. Non-target tokens $k \ne x_t^$ are suppressed only indirectly through the normalizer .
This passive mechanism creates several structural failures:
- Probability Mass Leakage: If the training corpus exhibits high variance or noise, the model frequently distributes non-trivial probability mass across semantically irrelevant or degenerate tokens.
- Exposure Bias and Discrepancy: During training, the model is always fed ground-truth prefixes (teacher forcing). At inference time, the model conditions on its own prior generations . Small distributional shifts compound over long horizons, driving the model into out-of-distribution state representations.
- Attractor Loops: In high-dimensional transformer representations, self-attention circuits (particularly induction heads and associative key-value projections) naturally attend to tokens already present in the active context window. If the model emits a duplicate token during greedy or low-temperature decoding, that token increases the attention weight assigned to previous occurrences of the same token. This creates a positive feedback loop where the probability of repeating the token or phrase approaches 1.0, generating pathological repetitions such as "the company said the company said the company said..."
The Limits of Decoding Truncation
To prevent degenerate repetitions, practitioners commonly rely on stochastic decoding heuristics:
- Top-k Sampling: Restricts generation to the most probable tokens.
- Nucleus (Top-p) Sampling: Truncates the candidate pool to the smallest set of tokens whose cumulative probability exceeds threshold .
- Repetition Penalties: Artificially subtracts a fixed scalar from the logits of tokens present in the prompt context before computing the softmax.
While these heuristics prevent deterministic loops, empirical research demonstrates that they do not correct the underlying learned representation. Nucleus sampling often forces the model to sample from an erratic tail, increasing semantic incoherence and hallucination rates. Furthermore, in tasks requiring precise, deterministic outputs (such as code generation, mathematical deduction, and structured JSON parsing), stochastic sampling degrades task performance.
Unlikelihood training solves this problem at the parameter level, ensuring that greedy decoding itself produces non-degenerate, diverse text.
Mathematical Formulation of Unlikelihood Loss
Unlikelihood training augments the objective function by introducing a loss term that explicitly decreases the probability of an undesirable set of negative candidate tokens at step .
Let represent the predictive distribution over vocabulary given prefix . For any negative candidate token , the probability of the model not predicting token is:
The unlikelihood loss is defined as the negative log-probability of this complement event, summed over all negative candidates in :
Because , the complement is bounded in . Minimizing is equivalent to driving , which forces .

The Joint Objective
To maintain language modeling fluency and semantic validity while eliminating negative behaviors, unlikelihood loss is combined with standard maximum likelihood estimation via a weighting hyperparameter :
Across an entire sequence of length , the total unlikelihood objective is:
When , the objective reduces to standard cross-entropy. When , the loss penalizes both failure to predict the correct target and any positive probability allocated to negative candidates in .
Gradient Dynamics and Logit Penalization
The theoretical power of unlikelihood training becomes clear when analyzing the gradients with respect to the pre-softmax logits .
Let denote the logit for token , such that .
Standard MLE Gradient Derivation
For standard cross-entropy , the gradient with respect to logit is:
- For the ground-truth token ($i = x_t^$): $\frac{\partial \mathcal{L}_{\text{MLE}}}{\partial z_{x_t^}} = -(1 - p_{x_t^*})$, which pulls the logit up proportionally to the error.
- For all other tokens (): , which pushes the logit down proportionally to its current probability.
Unlikelihood Loss Gradient Derivation
Consider the unlikelihood loss for a single negative candidate : .
Using the chain rule:
The derivative of the loss with respect to probability is:
The derivative of the softmax probability with respect to logit is standard:
Multiplying these terms yields the exact logit gradient for unlikelihood loss:
Analyzing the Three Gradient Regimes
Combining the MLE and unlikelihood gradients for a single negative candidate and target token gives:
Evaluating this gradient across different token categories reveals the mechanism:
| Token Category | Index Condition | Gradient | Physical Effect on Logit | | :--- | :--- | :--- | :--- | | Ground-Truth Target | $i = x_t^$ (assuming $x_t^ \ne c$) | $-(1 - p_{x_t^}) - \alpha \left(\frac{p_c}{1 - p_c}\right) p_{x_t^}$ | Boosted upward force: Target logit increases faster when negative candidate probability is high. | | Negative Candidate | | | Direct hyperbolic suppression: Downward gradient scales linearly with , directly crushing the logit. | | Neutral Token | and | $p_i - \alpha \left(\frac{p_c}{1 - p_c}\right) p_i = p_i \left(1 - \alpha \frac{p_c}{1 - p_c}\right)$ | Adaptive redistribution: Gradient dampens, allowing probability mass to flow into neutral alternatives. |
The Hyperbolic Scaling Factor
The factor is the odds ratio of the negative candidate. As (the model assigns high confidence to a pathological token), .
This property ensures that:
- When the model assigns near-zero probability to an undesirable token, the penalty gradient is negligible, leaving normal language acquisition undistorted.
- When the model assigns high probability to a degenerate or repeating token, the gradient explodes, forcing immediate and severe parameter updates to suppress that mode.
Negative Candidate Construction Strategies
The effectiveness of unlikelihood training depends entirely on how the negative candidate set is defined. Researchers and practitioners employ three primary candidate selection paradigms.
Candidate Selection Strategies:
1. Token-Level Context Window:
Context: [The, cat, sat, on, the] ───► Target: [mat]
Candidate Set C_t: {The, cat, sat, on} \ {mat}
2. Sequence-Level Rollout (Self-Generated):
Prefix: [The robot reached] ───► Model Rollout: [for the wrench and the wrench and the wrench]
▲──────────▲──────────▲
Repeated 4-gram detected!
Sequence Candidates C_t: Set to tokens inside degenerate n-gram cycles.
3. Entity / Hallucination Masking:
Ground Truth Knowledge: {Founded: 1976}
Model Output: "Apple was founded in 1984" ──► C_t: {1984}1. Token-Level Recency Candidates
To prevent local token stuttering and immediate repetition loops during teacher-forced training, the negative candidate set is constructed from the preceding context tokens within a fixed history window , excluding the ground-truth target:
If a token appeared in the recent context but is not the valid continuation, its probability is pushed down. This forces the model to explore new vocabulary items rather than defaulting to recently activated lexical memory.
2. Sequence-Level Unlikelihood (Rollout Penalization)
While token-level unlikelihood reduces immediate token repetition, it suffers from a major constraint: it is computed over ground-truth prefixes . It never exposes the model to its own self-generated, multi-step degenerative trajectories.
To resolve sequence-level degeneration (such as repeating 4-grams or cyclic sentence structures), Welleck et al. introduced Sequence-Level Unlikelihood (Seq-UL):
- Prefix Sampling: Given a prefix , generate a continuation of length autoregressively using greedy decoding:
- Degenerate Span Identification: Scan the generated continuation for repeating -grams (typically 4-grams). If an -gram matches an identical -gram previously seen in the same continuation (where ), mark all tokens in the duplicate span as degenerate.
- Candidate Assignment: For each step , define the candidate set as the repeating token: .
- Sequence Unlikelihood Loss: Compute the unlikelihood loss over the self-generated sequence:
Sequence-level unlikelihood directly punishes the exact trajectories that the model's current weights produce under greedy rollout, closing the gap between teacher forcing and inference execution.
3. Factual Error and Toxicity Suppression
Beyond structural repetitions, candidate sets can be constructed dynamically to target semantic failure modes:
- Hallucination Mitigation: In retrieval-augmented generation, tokens generated by the model that contradict retrieved source documents can be added to .
- Toxicity and Safety Filtering: Toxic lexicons, leaked private keys, or disallowed behavioral sequences identified by red-teaming classifiers are dynamically converted into negative candidate sets during fine-tuning.
Theoretical Lineage: From Unlikelihood to Modern Preference Optimization
Unlikelihood training laid the algorithmic foundation for modern alignment methods that optimize language models using pairs of preferred and dispreferred text.
Evolution of Negative Loss Formulations:
1. Unlikelihood Training (2019):
L = -log p(x*) - α log(1 - p(c_neg))
2. Direct Preference Optimization (DPO, 2023):
L = -log σ( β log[π_θ(y_w)/π_ref(y_w)] - β log[π_θ(y_l)/π_ref(y_l)] )
▲─────────────────────────▲
Sequence-level unlikelihood
with reference KL anchor!
3. Negative Preference Optimization (NPO / Unlearning, 2024):
L = -log σ( -β log[π_θ(y_forget)/π_ref(y_forget)] )Direct Preference Optimization (DPO)
Direct Preference Optimization optimizes a policy directly on preference pairs (where is preferred and is dispreferred) without training an explicit reward model.
The DPO loss is formulated as:
Examining the second term inside the sigmoid:
Minimizing the DPO objective explicitly pushes down . DPO is mathematically equivalent to performing reference-anchored sequence-level unlikelihood training on the rejected response while simultaneously performing reference-anchored likelihood training on the chosen response .
Contrastive Preference Optimization (CPO) and Machine Unlearning
- Contrastive Preference Optimization (CPO): Applied extensively in machine translation and code reasoning, CPO adds an explicit negative unlikelihood penalty to prevent moderate-quality translation outputs from dominating the generation distribution.
- Negative Preference Optimization (NPO) and Machine Unlearning: In privacy preservation and safety scrubbing, models are trained to forget specific corpora (such as copyrighted books or toxic conversations). NPO applies unlikelihood objectives directly to the target forget-set tokens, using a reference model as a regularizer to prevent model collapse on unrelated distributions.
Empirical Benchmarks and Generative Properties
The impact of unlikelihood training on language generation has been extensively evaluated across standard corpora, including Wikitext-103, CC-News, and open-ended dialogue datasets.
Repetition and Diversity Metrics
Empirical evaluations measure text quality across three core dimensions:
- seq-rep-4: The percentage of generated 4-grams that repeat previously generated 4-grams within the same sequence (lower is better).
- Unique Tokens / Distinct-N: The proportion of distinct n-grams across the entire generation budget (higher is better).
- Perplexity (PPL): Token prediction loss on ground-truth evaluation sets (lower is better).
| Training Objective | Decoding Strategy | Perplexity (PPL) | seq-rep-4 (%) | Unique Tokens (100k) | Zipf Distribution Error | | :--- | :--- | :--- | :--- | :--- | :--- | | Standard MLE Baseline | Greedy () | 25.6 | 46.2% | 1,840 | 0.42 | | Standard MLE Baseline | Nucleus () | 25.6 | 12.8% | 9,450 | 0.28 | | Token-Level UL () | Greedy () | 26.2 | 11.4% | 7,820 | 0.19 | | Token + Seq UL | Greedy () | 26.8 | 1.2% | 14,210 | 0.08 | | Human Reference | N/A | N/A | 0.8% | 15,100 | 0.00 |
Data source: Welleck et al., ICLR 2020.
Key empirical findings include:
- Greedy Decoding Parity with Humans: Combining token-level and sequence-level unlikelihood training reduces 4-gram repetition from 46.2% to 1.2% under pure greedy decoding, closely matching human text distributions (0.8%).
- Preservation of Vocabulary Tail (Zipf's Law): Standard MLE models over-index on high-frequency head words during generation. Unlikelihood training restores the heavy-tailed Zipfian distribution of natural language by penalizing premature head-word reuse.
- Minimal Perplexity Penalty: When properly tuned (), unlikelihood loss introduces less than a 1.2-point increase in validation perplexity while eliminating degenerative collapse.
Implementation Details and Numerical Stability
Implementing unlikelihood training in PyTorch requires careful attention to numerical precision. Because modern models compute logits in float16 or bfloat16, calculating directly can suffer from catastrophic cancellation when or .
Numerically Stable Unlikelihood Formulation
Given log-probabilities , we must evaluate .
Using the mathematical identity:
In PyTorch, this is implemented natively via torch.log1mexp (or torch.log(-torch.expm1(log_p))):
import torch
import torch.nn as nn
import torch.nn.functional as F
class UnlikelihoodLoss(nn.Module):
"""
Computes Joint Maximum Likelihood and Unlikelihood Loss.
"""
def __init__(self, alpha: float = 1.0, ignore_index: int = -100):
super().__init__()
self.alpha = alpha
self.ignore_index = ignore_index
def forward(
self,
logits: torch.Tensor, # [batch_size, seq_len, vocab_size]
targets: torch.Tensor, # [batch_size, seq_len]
negative_mask: torch.Tensor # [batch_size, seq_len, vocab_size] (1 for negative candidates, 0 otherwise)
) -> torch.Tensor:
# Compute log-softmax over vocabulary
log_probs = F.log_softmax(logits, dim=-1) # [B, T, V]
# 1. Standard Cross-Entropy (MLE Loss)
mle_loss = F.nll_loss(
log_probs.view(-1, log_probs.size(-1)),
targets.view(-1),
ignore_index=self.ignore_index,
reduction='mean'
)
# 2. Numerically Stable Unlikelihood Loss: -log(1 - p_c) = -log1mexp(log_p_c)
# Clamping log_probs avoids -inf when p_c -> 1
clamped_log_probs = torch.clamp(log_probs, max=-1e-7)
unlikelihood_per_token = -torch.log1p(-torch.exp(clamped_log_probs)) # log(1 - exp(log_p))
# Apply negative candidate mask
masked_ul_loss = unlikelihood_per_token * negative_mask
# Normalize by total active negative candidates
num_candidates = negative_mask.sum().clamp(min=1.0)
ul_loss = masked_ul_loss.sum() / num_candidates
# Total Joint Loss
total_loss = mle_loss + self.alpha * ul_loss
return total_loss, mle_loss, ul_lossPractical Training Hyperparameters
When integrating unlikelihood objectives into pre-training or supervised fine-tuning pipelines:
- Warmup Phase: Train the model with standard MLE () for the first 10% of training steps to establish basic syntactic representations before enabling unlikelihood penalties.
- Alpha Scaling: Set . Setting often causes the model to over-suppress valid vocabulary items, leading to syntax degradation and increased validation perplexity.
- Rollout Frequency: During sequence-level unlikelihood fine-tuning, decoding rollouts at every optimization step is computationally expensive. Running greedy sequence rollouts on every 4th batch provides an optimal trade-off between training throughput and loop suppression.
Summary and Key Takeaways
- The Core Problem: Maximum likelihood estimation with cross-entropy is fundamentally one-sided: it rewards matching target tokens but fails to penalize degenerate, repeating, or hallucinated tokens.
- The Mechanism: Unlikelihood training introduces , providing an explicit downward gradient that scales hyperbolically with the odds ratio .
- Candidate Topologies: Token-level candidates penalize immediate lexical recency, while sequence-level candidates penalize multi-step repeating n-grams generated during model rollouts.
- Modern Lineage: Direct Preference Optimization (DPO), Contrastive Preference Optimization (CPO), and Machine Unlearning are direct extensions of sequence-level unlikelihood principles, using reference models to constrain negative probability shifts.
- Production Impact: Unlikelihood fine-tuning eliminates the need for aggressive stochastic sampling truncation during inference, enabling greedy and low-temperature decoding to produce fluent, non-repetitive text across structured and open-ended generation tasks.
Sources
- Neural Text Generation with Unlikelihood Training (Welleck et al., ICLR 2020 / arXiv:1908.04319)
- Direct Preference Optimization: Your Language Model is Secretly a Reward Model (Rafailov et al., NeurIPS 2023 / arXiv:2305.18290)
- The Curious Case of Neural Text Degeneration (Holtzman et al., ICLR 2020 / arXiv:1904.09751)
- Contrastive Preference Optimization for Out-of-Distribution Translation (Xu et al., ICML 2024 / arXiv:2401.08417)
- Negative Preference Optimization: From Unlearning to Safe Alignment (Zhang et al., 2024 / arXiv:2404.05868)



