A repetition penalty lowers the scores of tokens already generated.
CTRL (Keskar et al., 2019) introduced the classic one: before the softmax, divide the logit of every token already generated by a penalty θ. With greedy decoding, the authors found θ ≈ 1.2 a good balance between truthful text and no repetition.
The trap is the sign. Hugging Face's penalty handles it the way the second line does. A few more details:
- It applies at most once per token, however often the token appeared.
- By default it counts the prompt too, so it can punish a name or a variable the answer has to repeat.
- vLLM's frequency and presence penalties subtract instead of divide, and count only generated text.
- Frequency grows with each repeat. Presence is one flat amount once a token appears.
- Both libraries apply their penalties before temperature and the filters.
A library runs it on a whole batch with no loop. logits.gather(-1, prev_ids) reads each row's past scores, torch.where lowers each one by its sign, and scatter writes them back. An id that appears twice writes the same lowered value twice, so it still counts once. That's level 4 of the practice.
In the editor, finish penalize(logits, seen, penalty). For each token id in seen, once each, divide a positive logit by penalty and multiply a negative one by it.