823. Apply a logit bias to ban or boost tokens
Why it matters OpenAI-style logit_bias is used to block unwanted tokens, force yes/no answers and stop the model from emitting certain words.
LLM APIs accept a logit_bias map from token id to a number added to that token's logit before sampling. Large negative values effectively ban a token; positive values make it more likely.
Write apply_logit_bias(logits, bias, ban=-100) for a 1D logits array and a dict token_id -> bias. Add each bias to a copy of the logits. Any bias <= ban means the token is banned: set its logit to -inf. Ignore token ids outside the vocabulary. Return (new_logits, probs) where probs is the softmax of new_logits (banned tokens get probability 0).
Inputs can be Python lists or NumPy arrays, so convert them with np.asarray first.
def apply_logit_bias(logits, bias, ban=-100)Example 1
Input: apply_logit_bias([1.0, 1.0, 1.0], {0: -100, 2: 1.0})
Output: ([-inf, 1.0, 2.0], [0.0, 0.2689, 0.7311])
Example 2
Input: apply_logit_bias([0.0, 0.0], {})[1]
Output: [0.5, 0.5]
Example 3
Input: apply_logit_bias([2.0, 0.0, -1.0], {5: 3.0, 1: 2.0})[1]
Output: [0.487856, 0.487856, 0.024289]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Copy the logits before changing them.
Hint 2
Banned tokens become -inf; softmax then gives them exactly 0.
Hint 3
Subtract the max logit before exponentiating.
Common mistakes
- Adding -100 and leaving a tiny non-zero probability when the model expected a hard ban.
- Overflowing exp on large logits.
Understand the idea
Adding b to a logit multiplies that token's unnormalised probability by e^b. A ban sets the logit to -inf so exp gives exactly 0. Subtract the max before exp to stay stable.
equal logits [1, 1, 1], ban token 0 and add 1 to token 2: probabilities are 0, 1 / (1 + e), e / (1 + e) = 0, 0.269, 0.731.
z[t] += b, or -inf when b <= ban; softmax