Techniqueadvanced
Repetition penalty
Also called frequency penalty, presence penalty.
Lower the logits of tokens that already occur in the output, by a factor or by an amount per occurrence, to curb loops.
A repetition penalty changes the logits of a language model before each decoding step so that tokens that already occur in the text become less likely. It fights the loops in which a decoder writes the same phrase again and again, which are common with greedy decoding and beam search on trained models. Two forms are in use. The scaling form of Keskar et al. 2019 (CTRL) divides the logit of each seen token by a factor ; libraries fix its sign problem by multiplying negative logits by in place of dividing them. The additive form, which commercial APIs expose as the frequency penalty and the presence penalty, subtracts an amount for each occurrence of a token and an amount for its first occurrence. Both are heuristics: the strength is tuned by hand, and a penalty that removes loops can also forbid repetitions that the text needs, such as names and function words.
In plain words
Models sometimes get stuck and say the same thing over and over. A repetition penalty makes a word less likely to be chosen again once it is already in the text. One kind cuts the score of a used word by a fixed factor. The other kind takes points off the score: some points the first time a word is used, and more points each time it is used again. A small penalty breaks loops. A large one also blocks words that a good text must repeat, such as names or "the".
When it applies
Use a repetition penalty with any decoder that works on next-token logits: greedy decoding, beam search, temperature sampling, top-k sampling and nucleus sampling. It applies before the temperature and the truncation. It is most useful where the decoder is deterministic and loops are likely, which is why CTRL used it with greedy decoding. Decide which tokens count as history: the generated tokens only, or the prompt as well. Libraries often include the prompt by default, which also penalizes words the user wrote.
The template
The history is the list of tokens so far, and is the number of times token occurs in it.
PENALIZE(z, history, form) ▷ z = next-token logits- 1
c ← the count of each token in history - 2
for each token j with c[j] > 0 do - 3
scaling: z[j] ← z[j] / θ if z[j] > 0, else z[j] · θ - 4
additive: z[j] ← z[j] − c[j] · α_f − α_p - 5
return z
Line L3 is the sign-aware scaling form, and line L4 the additive form with a frequency weight and a presence weight . A decoder uses one of the two lines, or both. The proof is in proofs/correctness.md: the sign-aware form never raises the logit of a seen token for , the plain division of CTRL can raise the probability of a seen token whose logit is negative, the additive form changes the odds of a token by exactly per occurrence and once, and only the additive form ignores a shift of all logits.
Classic examples
Breaking a greedy loop. A toy model gives the same logits for tokens a, b and c after every prefix, so greedy decoding writes a a a a a a. With the scaling form and it writes a b a a a a: after the first a, its logit drops to 1.333 and b wins once, but after that both a and b are seen, the penalty is the same for both, and a wins for good. With the additive form, and , it writes a a b a b c: the penalty grows with each use, so the tokens keep rotating.
The sign problem. For the logits with token 1 seen and , the plain division gives , which is larger than : the probability of the seen token goes up from 0.0420 to 0.0674. The sign-aware form gives and lowers it to 0.0159. Keskar et al. state only the division; the multiplication of negative logits is how libraries such as Hugging Face Transformers implement the CTRL penalty.
Two seen tokens. Even the sign-aware form does not always lower the probability of every seen token. For the logits with tokens 0 and 1 seen and , the new logits are , and the probability of token 1 rises from 0.0288 to 0.1327, because token 0 loses much more.
The offset of the logits. The logits and give the same distribution, since a softmax ignores a common shift. With token 0 seen and , the scaling form gives it probability 0.5050 in the first case and 0.5465 in the second. The additive form gives the same answer in both cases.
API penalties. OpenAI documents its frequency and presence penalties as on the logit . Since the change is an amount on the log scale, a frequency penalty of 0.4 on a token used three times divides its odds against an unused token by .
Variations
- Presence only. : a fixed cost for any token already used, however often.
- Frequency only. : a cost that grows with each use.
- A window. Count only the last tokens, so that words can come back after a while.
- No repeated n-grams. Forbid any token that would complete an n-gram already in the text, by setting its logit to . This is a hard rule, common in beam search for summarization.
- Negative penalties. or negative weights reward repetition, for example to make a model copy from its input.
- Similarity in place of identity. Contrastive search penalizes candidates whose hidden states are similar to the context, which also catches repetition with different words.
Pitfalls
- Dividing a negative logit. It rewards the token. Use the sign-aware form or the additive form.
- Logit offsets. The scaling forms act differently on logits that differ only by a constant, and a logit of exactly 0 is not changed at all. The additive form does not have this problem.
- Necessary repetition. Names, numbers, code identifiers and function words must repeat. A strong penalty makes the model swap in synonyms or misspell names. Prefer a mild penalty, a window, or excluding some tokens.
- The prompt counts. If the history includes the prompt, the model avoids the words of the question in its answer.
- Tokens, not words. The penalty works on subword tokens. A common subword shared by many words gets penalized for all of them.
- It treats a symptom. Loops come from the model and from searching for high-probability text (see inadequacy of the mode and exposure bias); the penalty changes the output, not the model.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Log-space arithmetic and semirings for the natural-language-and-speech pages.
Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.
The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:
PROB probabilities plus = + times = * zero = 0 one = 1
LOG log probabilities plus = log_add times = + zero = -inf one = 0
VITERBI log probabilities plus = max times = + zero = -inf one = 0
TROPICAL costs -log p plus = min times = + zero = +inf one = 0
LOG_COST costs -log p plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
BOOLEAN truth values plus = or times = and zero = False one = True
COUNTING path counts plus = + times = * zero = 0 one = 1
This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""
import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence
NEG_INF = float("-inf")
POS_INF = float("inf")
def safe_log(p) -> float:
"""Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
if p < 0:
raise ValueError("log of a negative number")
if p == 0:
return NEG_INF
return math.log(p)
def log_add(a: float, b: float) -> float:
"""Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).
log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
"""
if a < b:
a, b = b, a
if b == NEG_INF or a == POS_INF:
return a
return a + math.log1p(math.exp(b - a))
def log_sum(xs: Iterable[float]) -> float:
"""Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
xs = list(xs)
if not xs:
return NEG_INF
m = max(xs)
if m == NEG_INF or m == POS_INF:
return m
return m + math.log(math.fsum(math.exp(x - m) for x in xs))
def log_normalize(xs: Sequence[float]) -> List[float]:
"""Return the list x - log_sum(xs): log values whose exps sum to 1.
Raise ValueError if every value is NEG_INF (nothing to normalize).
"""
z = log_sum(xs)
if z == NEG_INF:
raise ValueError("every weight is zero")
return [x - z for x in xs]
def log_softmax(xs: Sequence[float]) -> List[float]:
"""Return log softmax(xs): the logits xs turned into log probabilities."""
return log_normalize(xs)
def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
"""Return the probabilities exp(x / temperature) / sum, computed stably.
The temperature must be positive. Logits of NEG_INF get probability 0.
"""
if not temperature > 0:
raise ValueError("the temperature must be positive")
m = max(xs)
if m == NEG_INF:
raise ValueError("every logit is -inf")
es = [math.exp((x - m) / temperature) for x in xs]
s = math.fsum(es)
return [e / s for e in es]
def argmax(xs: Sequence[Any]) -> int:
"""Return the first index of a largest value. Raise ValueError if xs is empty."""
if len(xs) == 0:
raise ValueError("argmax of an empty sequence")
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
@dataclass(frozen=True)
class Semiring:
"""A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""
name: str
plus: Callable[[Any, Any], Any]
times: Callable[[Any, Any], Any]
zero: Any
one: Any
idempotent: bool
def _add(a, b):
return a + b
def _mul(a, b):
return a * b
def _log_add_cost(a: float, b: float) -> float:
return -log_add(-a, -b)
PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)
def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring sum of xs, and sr.zero for an empty input."""
acc = sr.zero
for x in xs:
acc = sr.plus(acc, x)
return acc
def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring product of xs, and sr.one for an empty input."""
acc = sr.one
for x in xs:
acc = sr.times(acc, x)
return acc
repetition_penalty.py 52 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/repetition-penalty/. The authors are listed in prov/9K28B7.jsonl.
"""Three forms of the repetition penalty on next-token logits.
Tokens are integers 0 ... |V| - 1, the logits are a list of |V| floats, and
the history is the list of tokens so far (the prompt and the output, or
only the output; the caller chooses). Each function returns a new list of
logits and does not change its input. The code takes the logits of the
model as given; it does not run or train a network.
"""
from collections import Counter
from typing import List, Sequence
def ctrl_penalty(logits: Sequence[float], history: Sequence[int], theta: float) -> List[float]:
"""Divide the logit of every token in the history by theta, as written in CTRL.
With theta > 1 this lowers a positive logit but raises a negative one,
so on its own it can make a repeated token more likely.
"""
seen = set(history)
return [x / theta if j in seen else x for j, x in enumerate(logits)]
def scaled_penalty(logits: Sequence[float], history: Sequence[int], theta: float) -> List[float]:
"""The sign-aware scaling of common libraries: divide positive logits, multiply negative ones.
With theta >= 1 the logit of a token in the history never goes up.
"""
if not theta > 0:
raise ValueError("theta must be positive")
seen = set(history) # @line L1
out = list(logits)
for j in seen: # @line L2
out[j] = out[j] / theta if out[j] > 0 else out[j] * theta # @line L3
return out # @line L5
def additive_penalty(
logits: Sequence[float], history: Sequence[int], frequency: float, presence: float
) -> List[float]:
"""Subtract count * frequency + presence from the logit of every token in the history.
This is the form z_j - c_j * alpha_frequency - [c_j > 0] * alpha_presence.
"""
counts = Counter(history) # @line L1
out = list(logits)
for j, c in counts.items(): # @line L2
out[j] = out[j] - c * frequency - presence # @line L4
return out # @line L5
test_repetition_penalty.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/repetition-penalty/. The authors are listed in prov/9K28B7.jsonl.
import math
import random
from nlslog import argmax, softmax
from repetition_penalty import additive_penalty, ctrl_penalty, scaled_penalty
def test_identity_settings() -> None:
z = [2.0, -1.0, 0.0, 0.5]
h = [0, 1, 1, 3]
assert ctrl_penalty(z, h, 1.0) == z
assert scaled_penalty(z, h, 1.0) == z
assert additive_penalty(z, h, 0.0, 0.0) == z
assert additive_penalty(z, [], 1.0, 1.0) == z
def test_division_alone_raises_a_negative_logit() -> None:
z = [2.0, -1.0, 0.0]
before = softmax(z)[1]
after = softmax(ctrl_penalty(z, [1], 2.0))[1]
assert after > before
assert softmax(scaled_penalty(z, [1], 2.0))[1] < before
def test_sign_aware_scaling_never_raises_a_seen_token() -> None:
rng = random.Random(1)
for _ in range(300):
n = rng.randint(2, 8)
z = [rng.uniform(-5, 5) for _ in range(n)]
h = [rng.randrange(n) for _ in range(rng.randint(1, 5))]
theta = rng.uniform(1.0, 3.0)
p = softmax(z)
zz = scaled_penalty(z, h, theta)
q = softmax(zz)
for j in range(n):
if j in h:
assert zz[j] <= z[j]
else:
assert q[j] >= p[j] - 1e-12
if len(set(h)) == 1:
assert q[h[0]] <= p[h[0]] + 1e-12
# with two seen tokens, the weaker one can gain probability
z = [4.0, 0.5, 0.0]
p, q = softmax(z), softmax(scaled_penalty(z, [0, 1], 2.0))
assert abs(p[1] - 0.0288) < 1e-4 and abs(q[1] - 0.1327) < 1e-4
def test_additive_form_has_exact_odds_and_ignores_shifts() -> None:
rng = random.Random(2)
for _ in range(300):
n = rng.randint(2, 8)
z = [rng.uniform(-5, 5) for _ in range(n)]
h = [rng.randrange(n) for _ in range(rng.randint(1, 6))]
af, ap = rng.uniform(0, 1), rng.uniform(0, 1)
p = softmax(z)
q = softmax(additive_penalty(z, h, af, ap))
# the odds of j against i change by exp(-(c_j af + [c_j > 0] ap) + (c_i af + [c_i > 0] ap))
for i in range(n):
for j in range(n):
ci, cj = h.count(i), h.count(j)
cost = lambda c: c * af + (ap if c > 0 else 0.0)
want = math.log(p[j] / p[i]) - cost(cj) + cost(ci)
assert abs(math.log(q[j] / q[i]) - want) < 1e-9
c = rng.uniform(-50, 50)
q2 = softmax(additive_penalty([x + c for x in z], h, af, ap))
for a, b in zip(q, q2):
assert abs(a - b) < 1e-9
def test_scaling_forms_depend_on_the_offset_of_the_logits() -> None:
# the same probabilities, logits shifted by 3: the penalized results differ
z = [2.0, 1.0, 0.0]
shifted = [x - 3.0 for x in z]
assert max(abs(a - b) for a, b in zip(softmax(z), softmax(shifted))) < 1e-12
a = softmax(scaled_penalty(z, [0], 1.5))
b = softmax(scaled_penalty(shifted, [0], 1.5))
assert abs(a[0] - 0.5050) < 1e-4 and abs(b[0] - 0.5465) < 1e-4
# a logit of exactly 0 is not changed by the scaling forms
assert scaled_penalty([0.0, 1.0], [0], 5.0) == [0.0, 1.0]
def test_presence_counts_once_and_frequency_counts_each_time() -> None:
z = [1.0, 1.0]
assert additive_penalty(z, [0, 0, 0], 0.0, 0.5) == [0.5, 1.0]
assert additive_penalty(z, [0, 0, 0], 0.5, 0.0) == [-0.5, 1.0]
def test_greedy_loop_is_broken() -> None:
z = [2.0, 1.5, 1.0]
plain, pen = [], []
for _ in range(6):
plain.append(argmax(z))
pen.append(argmax(scaled_penalty(z, pen, 1.5)))
assert plain == [0] * 6
# the scaling counts presence only: once a and b are both seen, a wins again for good
assert pen == [0, 1, 0, 0, 0, 0]
add = []
for _ in range(6):
add.append(argmax(additive_penalty(z, add, 0.4, 0.0)))
# the frequency penalty grows with each use and keeps rotating the tokens
assert add == [0, 0, 1, 0, 1, 2]
def test_bad_theta() -> None:
try:
scaled_penalty([1.0], [0], 0.0)
except ValueError:
pass
else:
raise AssertionError("no ValueError")
Exercises
- Show that the plain division raises the probability of a seen token with a negative logit when it is the only seen token.
- Prove that the sign-aware form with never lowers the probability of an unseen token.
- Find logits and a history for which the sign-aware form raises the probability of a seen token.
- Show that the additive form gives the same distribution for and , and that the scaling form need not.
- For the toy model with logits , find the smallest at which the scaling form makes the second token b.
Proof: What the scaled and the additive repetition penalties do to the next-token distributionfull
We use the notation of the page. The logits are , the softmax is , the history is a list of tokens, is the number of times token occurs in it, and is the set of seen tokens. The three forms are:
- division (CTRL as written): for ;
- sign-aware scaling: if and otherwise, for ;
- additive: for all .
Unseen logits do not change. Let be the softmax of .
Lemma 1 (no change at the neutral settings). With , or with , or with an empty history, .
Proof. Each formula reduces to .
Lemma 2 (division can reward a repeated token). Let , and . Then .
Proof. when and . Raising one logit while the others stay fixed raises its probability, since grows with .
For the logits and the history , division by raises the probability of token 1 from 0.0420 to 0.0674, while the sign-aware form lowers it to 0.0159.
Lemma 3 (the sign-aware form). Let . Then (a) for every ; (b) for every unseen token ; (c) if , then .
Proof. (a) For , ; for , . (b) The numerator of an unseen token is unchanged, and by (a) the denominator does not grow. (c) Only changes, and it does not go up, so does not go up, as in the proof of Lemma 2.
Part (c) needs a single seen token. With two or more, a seen token can gain probability, because the other seen tokens can lose more. For the logits , the history and , the new logits are , and the probability of token 1 rises from 0.0288 to 0.1327.
Lemma 4 (the additive form changes the odds by a fixed factor). For any two tokens and ,
Proof. , and .
So with , every occurrence of in the history multiplies its odds against an unseen token by , and its first occurrence by a further , whatever the logits are.
Lemma 5 (shifts). Adding a constant to every logit does not change under the additive form. It can change under both scaling forms.
Proof. Under the additive form every also moves by , and the softmax ignores a common shift. For the scaling forms, take the logits and , which give the same , the history and . The first gives and ; the second gives and .
The logits of a model are defined only up to such a shift, so the strength of a scaling penalty depends on an arbitrary choice of the network, while the additive penalty does not. The tests check Lemmas 1 to 5 on random logits and on the examples above.
References
- Nitish Shirish Keskar, Bryan McCann, Lav R. Varshney, Caiming Xiong and Richard Socher, CTRL, a conditional transformer language model for controllable generation, arXiv 1909.05858, 2019, Section 4.1 (Sampling), the penalized sampling formula that divides the logits of tokens already generated by theta, and the advice that greedy sampling with theta of about 1.2 gives a good balance
- Hugging Face Transformers, RepetitionPenaltyLogitsProcessor, the class RepetitionPenaltyLogitsProcessor, which multiplies negative logits by the penalty and divides positive ones
- OpenAI API documentation, Advanced usage, the section Frequency and presence penalties, with mu[j] - c[j] * alpha_frequency - float(c[j] > 0) * alpha_presence
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 9K28B7 Edit this page History Report an error Markdown