Lesson 6.5 · 5 of 5 · 5 min read · Reviewed 24 Nov 2026
Frequency and presence penalties
By the end, you can
- Explain how frequency and presence penalties change token scores.
- Choose between a frequency, presence or repetition penalty for a task.
- Know which tasks should leave penalties off.
TemperatureTemperature: A sampling setting that controls randomness: lower values make output more predictable, higher values more varied., top-p and top-kTop-k: A sampling setting that limits the choice of next token to the k most likely tokens. (6.1, 6.2) reshape the next-token chart the same way at every step. Penalties are different: they look at what the model has already written and push those tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. down.
Why models repeat
Once a phrase is in the context, it becomes more likely to appear again, because the model is predicting text that fits what came before. Small and older models, long outputs and low temperature make this worse. You get loops like “easy to use, easy to clean, easy to store, easy to…”.
Three kinds of penalty
All three adjust the raw scores (logits) before temperature and samplingSampling: Choosing the next token from the model’s probability distribution, rather than always taking the most likely one..
| Penalty | Rule for a token already in the output | Grows with repeats? | Where you see it |
|---|---|---|---|
| Frequency | subtract penalty x count |
Yes | OpenAI-style APIs, many open-weight servers |
| Presence | subtract penalty once, if count > 0 |
No | Same APIs, usually beside frequency |
| Repetition | divide a positive logit by penalty (multiply a negative one) |
No | Hugging Face Transformers, llama.cpp, Ollama |
The repetition penalty comes from the CTRL paper. Typical values are 1.0 (off) to about 1.3. The additive pair in OpenAI-style APIs usually accepts values from -2 to 2, where 0 is off and negative values encourage repeats.
A worked example
LogitsLogits: The raw scores a model outputs for every token in its vocabulary before they are turned into probabilities. for the next token after “easy to use, easy to clean, easy to”, with counts of how often each token has appeared so far:
| Token | Logit | Count so far | Frequency 0.5 | Presence 0.5 |
|---|---|---|---|---|
| ” use” | 2.0 | 1 | 2.5 | 2.5 |
| ” clean” | 1.8 | 1 | 2.3 | 2.3 |
| ” store” | 2.6 | 0 | 2.6 | 2.6 |
| ” easy” | 2.4 | 3 | -0.1 | 0.9 |
Before any penalty, ” use” wins and the loop goes on. With either penalty, ” store” (never used) now has the top score. The frequency penalty hits ” easy” far harder because it has already appeared three times.
Picking one
| Goal | Setting |
|---|---|
| Stop the same phrase looping | Small frequency penalty, about 0.2 to 0.5 |
| Push the text towards new topics in brainstorming | Small presence penalty |
| A local model that gets stuck in loops | Repetition penalty about 1.1 |
| Extraction, classification, code, translation | Off |
When not to use them
Penalties do not understand meaning. They count tokensToken counting: Measuring how many tokens a request will use before sending it, for example with a token-counting endpoint.. That causes real damage when repetition is correct:
- Structured outputStructured outputs: Making a model return data that matches a defined schema, such as JSON with required fields and types.. JSON repeats
",:and field names on every line. A strong penalty breaks it. - Names and ids. A support reply must say “order 4821” as often as needed. A penalty may swap in a synonym or a wrong number.
- Code. Variable names repeat by design.
Penalties also count your prompt on some runtimes, not just the output. Check the docs for the runtime you use.
On Claude
The Claude Messages APIMessages API: The chat API endpoint that takes a list of messages and returns the next assistant message. doesn’t offer frequency, presence or repetition penalties, and current Claude models reject sampling settings too (6.1). Repetition there is a prompt problem: ask for variety explicitly (“use each selling point once”), give an example, or use a second pass to tighten the draft (chapter 15).
Common mistakes
- Turning penalties up to fix a vague prompt. Say what you want first; penalties are a last nudge.
- Changing penalty and temperature together. Change one at a time and compare on the same inputs.
- Using a large negative value to “encourage consistency”. It encourages loops, not consistency.
Key points
- Penalties lower the score of tokens that have already appeared in the output, before sampling.
- A frequency penalty grows with every repeat; a presence penalty is a flat cut once a token has appeared at all.
- Some runtimes use a multiplicative repetition penalty instead. Values near 1 are mild; large values damage grammar.
- Leave penalties off for extraction, code and anything that must repeat exact names. Not every API offers them; the Claude Messages API doesn't.
Break a repetition loop with penalties
Apply frequency and presence penalties to a toy model stuck in a loop and see what they fix and what they break.
You will have: A greedy generator with optional penalties, and printed outputs with no penalty, a frequency penalty and a too-strong penalty.
Steps
- Run the starter: greedy generation loops on 'easy to use'.
- Fill in penalised(): subtract frequency x count and presence (once) for every token already generated.
- Generate 12 tokens with no penalty, with frequency 0.5, and with frequency 2.0.
- Count distinct words in each output.
- Note what the strong penalty does to the product name that should repeat.
Done when
- No penalty: 'easy to use' repeats and the loop never ends.
- Frequency 0.5 gives 7 distinct words against 6 with no penalty.
- Frequency 2.0 gives 9 distinct words but mentions 'Atlas' only once, though a product name often should repeat.
Open in the Playground No API key needed.
Starter code (Python)
# Toy model: the next-token scores depend only on the previous token.
NEXT = {
"<s>": {"Atlas": 2.0, "easy": 1.0},
"Atlas": {"is": 2.0, "makes": 1.2},
"is": {"easy": 2.0, "light": 1.5},
"makes": {"cleaning": 1.5, "Atlas": 1.4},
"easy": {"to": 3.0, "and": 1.0},
"to": {"use": 2.0, "clean": 1.8, "store": 1.6},
"use": {",": 2.0, "Atlas": 1.9},
"clean": {",": 2.0, "Atlas": 1.9},
"store": {",": 2.0, "Atlas": 1.9},
",": {"easy": 2.0, "Atlas": 1.7, "light": 1.2},
"light": {"and": 1.5, ",": 1.0},
"and": {"easy": 1.5, "light": 1.0},
"cleaning": {"easy": 1.0},
}
def penalised(scores, counts, frequency, presence):
return scores # TODO: subtract frequency * count, and presence if count > 0
def generate(n, frequency=0.0, presence=0.0):
out, prev, counts = [], "<s>", {}
for _ in range(n):
scores = penalised(NEXT[prev], counts, frequency, presence)
prev = max(sorted(scores), key=lambda t: scores[t])
out.append(prev)
counts[prev] = counts.get(prev, 0) + 1
return out
print("no penalty:", " ".join(generate(12)))
Show a solution
NEXT = {
"<s>": {"Atlas": 2.0, "easy": 1.0},
"Atlas": {"is": 2.0, "makes": 1.2},
"is": {"easy": 2.0, "light": 1.5},
"makes": {"cleaning": 1.5, "Atlas": 1.4},
"easy": {"to": 3.0, "and": 1.0},
"to": {"use": 2.0, "clean": 1.8, "store": 1.6},
"use": {",": 2.0, "Atlas": 1.9},
"clean": {",": 2.0, "Atlas": 1.9},
"store": {",": 2.0, "Atlas": 1.9},
",": {"easy": 2.0, "Atlas": 1.7, "light": 1.2},
"light": {"and": 1.5, ",": 1.0},
"and": {"easy": 1.5, "light": 1.0},
"cleaning": {"easy": 1.0},
}
def penalised(scores, counts, frequency, presence):
out = {}
for tok, s in scores.items():
c = counts.get(tok, 0)
out[tok] = s - frequency * c - (presence if c > 0 else 0)
return out
def generate(n, frequency=0.0, presence=0.0):
out, prev, counts = [], "<s>", {}
for _ in range(n):
scores = penalised(NEXT[prev], counts, frequency, presence)
prev = max(sorted(scores), key=lambda t: scores[t])
out.append(prev)
counts[prev] = counts.get(prev, 0) + 1
return out
for label, f in [("no penalty", 0.0), ("frequency 0.5", 0.5), ("frequency 2.0", 2.0)]:
words = generate(12, frequency=f)
print(f"{label}: {' '.join(words)} | distinct={len(set(words))} | Atlas x{words.count('Atlas')}")
Finished the chapter? Take the chapter check.