Decoding and sampling · Easy

Sign-Aware Repetition Penalty

Problem 23 of 50 · Python and NumPy

Problem

Apply a repetition penalty once to each distinct token ID appearing in history. For a repeated token, divide a positive logit by penalty and multiply a zero or negative logit by penalty. Leave unseen tokens unchanged. Return the adjusted logits in vocabulary order.

def repetition_penalty(logits, history, penalty):

Constraints

  • logits contains 1..32 finite values; history contains 0..64 valid token IDs.
  • penalty is finite and ≥ 1. Repetition count does not compound the penalty.
  • Inputs satisfy these constraints; invalid-input handling is not graded. Use only Python standard library and NumPy.

Examples

Example 1

Arguments: [
  [
    2,
    4
  ],
  [
    1
  ],
  2
]
Expected result: [
  2,
  2
]

Only token 1 is repeated: its positive logit 4 becomes 2.

Example 2

Arguments: [
  [
    -2,
    0,
    2
  ],
  [
    0,
    1,
    2
  ],
  2
]
Expected result: [
  -4,
  0,
  1
]

The negative value becomes -4, zero stays zero, and the positive value becomes 1.

Sign in to solve this problem

Browse all coding problems · Learn the foundations