Preventing LLM Loops: Repetition Penalty, Presence/Frequency & Min-P
Why LLMs fall into infinite repetition loops, the crucial sign-aware Repetition Penalty rule (divide positive, multiply negative!), Presence vs. Frequency penalties, Min-P dynamic pruning, and Beam Search vs. Sampling.
Repetition Penalty, Presence/Frequency Penalties, and Min-P dynamically suppress already-used tokens and low-probability tail noise during generation.
Autoregressive LLMs easily fall into infinite phrasing loops ('and the and the...') or hallucinate weird words at high temperatures; these guards keep outputs fluent.
Even frontier LLMs can get trapped repeating 'and the and the and the...' — sign-aware Repetition Penalty and Min-P are the exact safeguards that keep long generations crisp!
A classic bug in custom inference servers is dividing negative logits by θ > 1 (which accidentally BOOSTS repeated tokens!). Mastering the exact sign-aware formula avoids subtle production regressions.
Min-P (min_p = 0.05–0.10) has rapidly become the favorite sampler in local & open-weights serving (llama.cpp, vLLM, SGLang) because it stays coherent even at T = 1.2–1.5.
Tricky Generative AI coding question: 'Implement Repetition Penalty in Python — and explain what breaks if you simply do logits[seen] /= penalty!'
A previously generated token has raw logit z = −3.0, and repetition penalty is θ = 1.5. What should its penalized logit z' be?
- Implement sign-aware Repetition Penalty (CTRL / Hugging Face): z/θ for z > 0 and z·θ for z < 0
- Contrast multiplicative Repetition Penalty with OpenAI-style additive Presence Penalty (binary) and Frequency Penalty (count-scaled)
- Compute Min-P dynamic probability cutoffs (p_threshold = min_p · p_max) and explain why Min-P outperforms Top-P at high temperatures
- Decide when deterministic Beam Search beats stochastic sampling (translation/ASR) vs. when it degrades chat quality
Why do LLMs get stuck in loops? Because Transformer self-attention contains Induction Heads trained to copy patterns ([A][B] ... [A] → [B]). Once a model repeats a phrase twice, its own KV-Cache screams 'copy it a third time!' Repetition Penalty puts a small speed bump on every already-used token's logit, while Min-P sets a smart bouncer at the door: 'Only tokens at least 10% as plausible as the #1 choice may enter!'
1. Sign-Aware Repetition Penalty vs. Presence & Frequency Penalties
Look closely at Case A vs. Case B below — this single sign check is the #1 bug when engineers implement Repetition Penalty from scratch!
1. Multiplicative Repetition Penalty (Keskar et al. / Hugging Face / vLLM)
For every token that has already appeared in the context window, with penalty :
2. Additive Presence & Frequency Penalties (OpenAI API Style)
Instead of multiplying, subtract directly from logits using token occurrence count :
- Presence Penalty (): Flat one-time nudge encouraging the model to introduce new topics.
- Frequency Penalty (): Grows linearly with every repeat — strongly crushes verbatim loops!
z'_i = z_i − α_p·1(c_i > 0) − α_f·c_i
Applied ONCE whether the token appeared 1 time or 50 times — promotes topic diversity.
", ,, }, or def — causing syntax errors! Keep penalties gentle (1.0–1.1) for code/JSON.2. Min-P Sampling: Staying Coherent Even at High Temperature
Slide min_p in the interactive sweeper below to see how p_floor = min_p × p_max automatically adapts to the model's peak confidence!
Why Min-P Often Beats Top-P
At high temperature (), the long tail of 100,000 mediocre tokens gains mass, so Top-P = 0.90 starts letting bizarre words sneak in. Min-P anchors the threshold directly to the #1 token's probability :
- When the model is confident (, ), any token below
8.5%is instantly pruned! - When the model is open-ended (, ), the floor drops smoothly to
1.5%, preserving rich creative choices!
Min-P Dynamic Floor Sweeper (p_max = 62%)
3. Beam Search vs. Stochastic Sampling
When should you use classic deterministic Beam Search instead of Top-P / Min-P sampling?
Choosing the Right Decoding Strategy
- Use Beam Search (–) for tightly constrained sequence-to-sequence tasks with a single "right" phrasing: Machine Translation, Whisper Speech-to-Text (ASR), and OCR.
- Use Stochastic Sampling (Temperature + Top-P / Min-P) for chat, reasoning, coding, and creative writing, because human language does NOT maximize joint token probability (maximum-likelihood text sounds unnaturally dull and repetitive — the Degeneration Problem!).
Worked Example: Applying Sign-Aware Repetition Penalty (θ = 1.5)
Raw logits are {'the': +3.0, 'cat': +1.5, 'dog': -2.0} and previously seen tokens are {'the', 'dog'}.
Positive logit → divide by : .
Under Min-P sampling with min_p = 0.10, if the highest-probability token has p_max = 0.70, what is the minimum probability required for any other token to survive?
Why can a strong Repetition Penalty (θ = 1.4) break JSON generation or Python code?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
It is a hard rule that sets the logit to for any token that would complete a 3-gram already seen earlier in the output. Useful for summarization, but avoid it on code or factual entities that legitimately repeat!
Loop-Breaker Repetition Penalty Animator (θ = 1.0 vs. θ = 1.35)
Toggle Repetition Penalty ON vs. OFF to watch how penalizing previously emitted logits breaks degenerate repetition loops.
After 'sat' is emitted once, its positive logit (+4.5) is divided by θ = 1.35 → +3.33, allowing 'quietly' (+4.1) to win cleanly!
z/θ if z>0, z·θ if z<0) breaks attention copy-loops, additive Presence/Frequency penalties tune topic vs. count diversity, and Min-P (p_min · p_max) prunes noise cleanly even at high temperatures.Long-Form Writing & Roleplay Serving
Combines T = 1.0–1.2 with min_p = 0.05–0.10 and gentle frequency_penalty = 0.1 for crisp, non-repetitive multi-page outputs.
Whisper ASR & Neural Machine Translation
Uses Beam Search (beam_size = 5) with length normalization to find the globally highest-probability transcription.
import torch
import torch.nn.functional as F
# 1. HuggingFace-style Repetition Penalty (handles both positive & negative logits)
def apply_repetition_penalty(logits: torch.Tensor, seen_ids: list[int], penalty: float = 1.2) -> torch.Tensor:
out = logits.clone()
for tid in set(seen_ids):
out[tid] = out[tid] / penalty if out[tid] > 0 else out[tid] * penalty
return out
# 2. Min-P Filtering: drop tokens with prob < min_p * max_prob
def apply_min_p(logits: torch.Tensor, min_p: float = 0.05) -> torch.Tensor:
probs = F.softmax(logits, dim=-1)
cutoff = min_p * probs.max()
return logits.masked_fill(probs < cutoff, float("-inf"))
logits = torch.tensor([3.0, 2.5, 0.2, -1.0, -3.0])
penalized = apply_repetition_penalty(logits, seen_ids=[0], penalty=1.3)
filtered = apply_min_p(penalized, min_p=0.10)
print("After rep-penalty + min-p:", filtered.tolist())
θ > 1 in Repetition Penalty.z / θ if z > 0 else z * θ!