826. Apply presence and frequency penalties to logits
Why it matters OpenAI-compatible APIs expose presence_penalty and frequency_penalty, and vLLM implements both in its sampler.
Chat APIs reduce repetition with two knobs. The presence penalty subtracts a fixed amount from any token that already appeared; the frequency penalty subtracts an amount for every time it appeared.
Write penalize(logits, generated, presence, frequency). logits is a 1D array over the vocabulary and generated is the list of token ids produced so far. For each token t with count c > 0 in generated: new[t] = logits[t] - presence - frequency * c. Other logits are unchanged. Return a new float array; do not modify the input.
def penalize(logits, generated, presence, frequency)Example 1
Input: penalize([2.0, 1.0, 0.5], [0, 0, 2], 0.5, 0.25)
Output: [1.0, 1.0, -0.25]
Example 2
Input: logits = [1.0, 1.0], generated = [], presence = 2.0, frequency = 2.0
Output: [1.0, 1.0]
Example 3
Input: logits = [0.0, 0.0, 0.0, 0.0], generated = [3, 3, 3, 1], presence = 0.0, frequency = 1.0
Output: [0.0, -1.0, 0.0, -3.0]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
Count how often each token appears with collections.Counter.
Hint 2
Apply both penalties only to tokens with a count above zero.
Common mistakes
- Applying the presence penalty once per occurrence, which turns it into a frequency penalty.
- Changing the caller's logits array in place.
Understand the idea
Presence penalises a token once, however often it appeared, so it nudges toward new topics. Frequency grows with each repeat, so it fights loops of the same word. Negative values encourage repeats instead.
logits [2, 1, 0.5], token 0 seen twice, token 2 once, presence 0.5, frequency 0.25. Token 0: 2 - 0.5 - 0.5 = 1. Token 2: 0.5 - 0.5 - 0.25 = -0.25.
z[t] -= presence + frequency * count[t] for every seen t