KatInterview

Truncated Sampling from Logits with a Cumulative Probability Cutoff

Machine LearningModel answer
MediumModel answerMachine Learningnumpysamplingsoftmax

Last updated

Write a NumPy function that turns logits into probabilities, keeps the smallest top-ranked set whose mass reaches a threshold p, renormalizes, and draws one token index.

Cumulative-Probability Truncated Sampling

When a language model generates text, one common strategy is to avoid the unlikely tail of the vocabulary. Instead of sampling from all tokens, you keep only the most probable tokens whose combined probability reaches a threshold p, and sample from that reduced set.

Task

Write nucleus_sampling(logits, p) that returns one token index. It should:

  1. Convert the logits to probabilities with a softmax.
  2. Order the tokens by probability, highest first, while remembering each token's original index.
  3. Compute the running total of the ordered probabilities.
  4. Keep every token needed to reach the threshold. A token is kept if the running total up to and including it is at most p, and additionally the first token whose running total goes above p is kept too.
  5. Rescale the kept probabilities so they sum to 1, then draw one token and return its index in the original vocabulary.
import numpy as np

def nucleus_sampling(logits: np.ndarray, p: float) -> int:
    ...

Constraints

  • logits is a 1D array of shape (vocab_size,).
  • 0 < p <= 1.0.
  • Compute the softmax using np.exp(logits - np.max(logits)) so large logits do not overflow.

Example

logits = np.array([2.0, 1.0, 0.1])
p = 0.9
# probabilities       ~ [0.659, 0.242, 0.098]
# running totals      ~ [0.659, 0.901, 1.000]
# kept tokens         -> indices 0 and 1

The returned value is either 0 or 1 (about 73% / 27% after renormalizing), never 2.

What to discuss

  • What does the function do when p = 1.0?
  • What happens when a single logit is far larger than the others?
  • State the time and space complexity, and mention any way to speed it up for large vocabularies.

Hints

Hint 1

Subtract the maximum logit before exponentiating. It does not change the probabilities but removes any risk of overflow.

Hint 2

Use argsort on the negated probabilities so you keep the original token ids. Sampling from the sorted positions would return a rank, not a token.

Hint 3

A simple comparison `cumsum <= p` can drop the token that crosses the threshold and may even leave nothing. Think about it as: keep a token if the mass strictly before it is at most p.

Hint 4

After masking, divide by the sum of the kept probabilities, otherwise np.random.choice will complain that they do not sum to 1.