Apply repetition, frequency and presence penalties to logits

Small models love to loop. Inference servers expose three knobs to discourage repeats: a multiplicative repetition penalty and additive frequency and presence penalties, all based on the tokens generated so far.

Write apply_penalties(logits, generated, repetition_penalty, frequency_penalty, presence_penalty). logits is a 1-D float array over the vocabulary, generated is a list of token ids. Let c[t] be how many times token t appears in generated. For every token with c[t] > 0:
1. Repetition penalty: if logit > 0, divide it by repetition_penalty; otherwise multiply it by repetition_penalty.
2. Then subtract frequency_penalty * c[t] + presence_penalty.
Tokens never generated are unchanged. Return the new float array (do not modify the input).

Signaturedef apply_penalties(logits, generated, repetition_penalty, frequency_penalty, presence_penalty)

Example

logits = [2.0, -1.0, 0.5], generated = [0, 1, 1], penalties (2.0, 0.1, 0.5) gives [0.4, -2.7, 0.5].

Understand the idea

Small models often loop on the same words. Inference servers offer three knobs that push down tokens already generated. The repetition penalty is multiplicative: it must always make a repeated token less likely, so a positive logit is divided by the penalty and a negative logit is multiplied by it. The frequency penalty subtracts more for each repeat, and the presence penalty subtracts a flat amount once a token has appeared at all. Worked example: logits [3, -2, 1], generated [0, 0, 1], repetition 1.5, frequency 0.2, presence 0.3. Token 0 (count 2): 3 / 1.5 = 2, then 2 - (0.2 * 2 + 0.3) = 1.3. Token 1 (count 1): -2 * 1.5 = -3, then -3 - (0.2 + 0.3) = -3.5. Token 2 never appeared, stays 1. Result [1.3, -3.5, 1]. Rule: for each token with count c > 0, apply the sign-aware repetition penalty first, then subtract frequency * c + presence; return a new array without changing the input. These are the same settings exposed by most hosted LLM APIs.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleapply_penalties([2.0, -1.0, 0.5], [0, 1, 1], 2.0, 0.1, 0.5)
  • Sample 2: nothing generatedapply_penalties([1.0, -2.0, 3.0], [], 1.3, 0.2, 0.4)
  • Test 3: negative logit repeatedapply_penalties([-0.5, 1.5, -3.0, 0.0, 2.2], [2, 2, 2, 4, 1], 1.5, 0.25, 0.3)
  • Test 4: only additiveapply_penalties([0.3, 0.1, -0.2], [0, 0, 2], 1.0, 0.5, 1.0)