Chapter 14 of 40 · ~20 min read & lab+75 XP
Chapter 14 · Generative AI

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.

What Is It?

Repetition Penalty, Presence/Frequency Penalties, and Min-P dynamically suppress already-used tokens and low-probability tail noise during generation.

Why Is It Required?

Autoregressive LLMs easily fall into infinite phrasing loops ('and the and the...') or hallucinate weird words at high temperatures; these guards keep outputs fluent.

Everyday Analogy: A gentle tap on the shoulder whenever a speaker starts repeating the exact same sentence over and over.
Why ML Engineers & Data Scientists Actually Need This

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!

ML / AI Engineer

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.

Data Scientist

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.

Interview & Debug Edge

Tricky Generative AI coding question: 'Implement Repetition Penalty in Python — and explain what breaks if you simply do logits[seen] /= penalty!'

Step 0 · Test Your Gut Before Any Math!

A previously generated token has raw logit z = −3.0, and repetition penalty is θ = 1.5. What should its penalized logit z' be?

What You Will Master in This Chapter
  • 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
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
θ>1\theta > 1Say aloud:“repetition penalty factor”
Plain-English Meaning
Multiplicative penalty applied to any token ID already present in the prompt/output history
Everyday Example
θ = 1.1 to 1.25 typical; 1.0 = off
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

Everyday Story First (Zero Math Yet!)

Look closely at Case A vs. Case B below — this single sign check is the #1 bug when engineers implement Repetition Penalty from scratch!

Sign-Aware Repetition Penalty (θ = 1.5): Why Negative Logits Multiply!Case A: Positive Logit (z > 0)z' = z / θ (e.g. +6.0 / 1.5 = +4.0)Dividing shrinks +6.0 down to +4.0✓ Probability DECREASES as intendedCase B: Negative Logit (z < 0)z' = z × θ (e.g. −2.0 × 1.5 = −3.0)Dividing −2.0/1.5 = −1.33 would BOOST it!✓ Multiplying pushes −2.0 down to −3.0!
Critical sign-aware rule in Keskar et al. (CTRL) Repetition Penalty: divide POSITIVE logits by θ (>1), but MULTIPLY NEGATIVE logits by θ so both move downward!

1. Multiplicative Repetition Penalty (Keskar et al. / Hugging Face / vLLM)

For every token ii that has already appeared in the context window, with penalty θ>1\theta > 1: zi′={zi/θif zi>0zi⋅θif zi≤0z'_i = \begin{cases} z_i / \theta & \text{if } z_i > 0 \\ z_i \cdot \theta & \text{if } z_i \le 0 \end{cases}

2. Additive Presence & Frequency Penalties (OpenAI API Style)

Instead of multiplying, subtract directly from logits using token occurrence count cic_i: zi′=zi−αpresence⋅I(ci>0)−αfrequency⋅ciz'_i = z_i - \alpha_{\text{presence}} \cdot \mathbb{I}(c_i > 0) - \alpha_{\text{frequency}} \cdot c_i

  • Presence Penalty (αp\alpha_p): Flat one-time nudge encouraging the model to introduce new topics.
  • Frequency Penalty (αf\alpha_f): Grows linearly with every repeat cic_i — strongly crushes verbatim loops!
Formula Anatomy · Click Any Colored Piece to Decode It
Anatomy of Additive vs. Multiplicative Penalties

z'_i = z_i − α_p·1(c_i > 0) − α_f·c_i

Presence Penalty (Flat)

Applied ONCE whether the token appeared 1 time or 50 times — promotes topic diversity.

In our example: α_p = 0.5 → −0.5 logit once
Put it together with real numbers: Caution: Setting θ > 1.3 on JSON or Python code can penalize structural tokens like ", ,, }, 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

Everyday Story First (Zero Math Yet!)

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!

Min-P Sampling: Dynamic Floor = p_min × p_max (p_min = 0.10)Min-P Floor = 0.10 × 0.60 = 0.0660%Paris18%France11%Europe4%cheese3%guitar2%moon
Min-P sets an adaptive probability threshold p_min · p_max: when the top token is 90% confident (p_max=0.9), weak 2% noise tokens are pruned cleanly even at high temperature!

Why Min-P Often Beats Top-P

At high temperature (T=1.4T = 1.4), 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 pmax⁡p_{\max}: Keep token i  ⟺  pi≥pmin⁡⋅pmax⁡\text{Keep token } i \iff p_i \ge p_{\min} \cdot p_{\max}

  • When the model is confident (pmax⁡=0.85p_{\max} = 0.85, pmin⁡=0.10p_{\min} = 0.10), any token below 8.5% is instantly pruned!
  • When the model is open-ended (pmax⁡=0.15p_{\max} = 0.15, pmin⁡=0.10p_{\min} = 0.10), the floor drops smoothly to 1.5%, preserving rich creative choices!
Animated Mini-Lab • 3.2

Min-P Dynamic Floor Sweeper (p_max = 62%)

Adaptive Cutoff = 0.10 × 0.62 = 6.2%
Python
62%
Rust
19%
Go
10%
COBOL
5%
potato
4%

3. Beam Search vs. Stochastic Sampling

Everyday Story First (Zero Math Yet!)

When should you use classic deterministic Beam Search instead of Top-P / Min-P sampling?

Deterministic Beam Search vs. Stochastic Nucleus / Min-P SamplingBeam Search (Tracks Top-B Paths)• Maximizes joint sequence log-prob Σ log p(y_t)• Best for: Translation, Whisper ASR, exact lookup• Pitfall: Generic, bland & repetitive in open chat!• Cost: B× larger KV-Cache & compute per stepStochastic Sampling (Temp + Top-P / Min-P)• Samples from calibrated, tail-pruned distribution• Best for: Chat, creative writing, Best-of-N coding• Natural human entropy + zero beam overhead• Pair with Presence/Repetition penalty for long outputs
Beam Search tracks the top-B highest-probability sequences (great for translation/ASR) but sounds repetitive in open chat — where stochastic sampling (Top-P / Min-P) shines.

Choosing the Right Decoding Strategy

  • Use Beam Search (B=4B = 4–88) 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!).
Walk Through With Me · Interactive Worked Example

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'}.

11. Token 'the' (seen, z = +3.0 > 0)Step 1 / 3

Positive logit → divide by θ\theta: +3.0/1.5=+2.0+3.0 / 1.5 = \mathbf{+2.0}.

Teacher's Note: Moved downward toward −∞ ✓
Pause & Check · Quick Intuition Pulse

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?

Try It YourselfStandard

Why can a strong Repetition Penalty (θ = 1.4) break JSON generation or Python code?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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 −∞-\infty 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!

Interactive Visual Lab
Lab Challenge: Toggle Repetition Penalty OFF vs. ON in the 60 FPS Loop-Breaker Animator to see how θ = 1.35 escapes a degenerate loop.
Interactive Animation • 3.2 Deep Lab

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.

θ = 1.35 (Active)
The

After 'sat' is emitted once, its positive logit (+4.5) is divided by θ = 1.35 → +3.33, allowing 'quietly' (+4.1) to win cleanly!

0%
Token 1 / 8
Intuition Takeaway: Sign-aware Repetition Penalty (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.
Where This Powers Real ML, Deep Learning & Generative AI

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.

Production NumPy & PyTorch Code Patterns
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())
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Dividing negative logits by θ > 1 in Repetition Penalty.
Best Practice: Always branch on sign: z / θ if z > 0 else z * θ!
Chapter Mastery Check (+75 XP)
Score: 0 / 2
1In sign-aware Repetition Penalty with θ = 1.5, how is a seen token with raw logit z = −2.0 transformed?
2What is the key difference between Presence Penalty and Frequency Penalty?

Apply What You Learned — Solve Matching Coding Problems