BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Sampling and decoding17 of 17 in topic

826. Apply presence and frequency penalties to logits

EasySampling and decoding

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.

Functiondef 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.

Worked example

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
Topics
Sampling and decoding
Similar questions
  • LLM sampling: turn logits into probabilities without overflowingEasy
  • Keep only the k most likely tokens before samplingEasy
  • Filter the next-token distribution with min-pEasy
  • Greedy decode until end of sequenceEasy
All Sampling and decoding problems
Report
826 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
from collections import Counter
import numpy as np
​
def penalize(logits, generated, presence, frequency):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS