Truncated Sampling from Logits with a Cumulative Probability Cutoff
Machine LearningModel answerLast 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:
- Convert the logits to probabilities with a softmax.
- Order the tokens by probability, highest first, while remembering each token's original index.
- Compute the running total of the ordered probabilities.
- 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 abovepis kept too. - 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
logitsis 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The goal is to sample from the smallest set of top-ranked tokens whose total probability reaches p. The pipeline is: stable softmax, sort descending, cumulative sum, boundary mask, renormalize, sample, map back to the original id.
The boundary rule
The subtle part is which tokens to keep. Writing mask = cumsum <= p is a common bug, because it drops the token that pushes the total past p. If the top token alone has probability above p, that mask is empty and sampling fails.
A cleaner formulation: keep token i if the mass of all tokens ranked above it is at most p. In code, that is the cumulative sum shifted right by one position, with the first entry treated as 0. This:
- includes the crossing token automatically,
- always keeps the top token (mass before it is 0), so the set is never empty.
Check on the example: cumulative sums are [0.659, 0.901, 1.0], shifted they are [0, 0.659, 0.901]. With p = 0.9, the comparison <= 0.9 gives [True, True, False], so indices 0 and 1 are kept.
Code
import numpy as np
def nucleus_sampling(logits: np.ndarray, p: float) -> int:
logits = np.asarray(logits, dtype=np.float64)
# 1. Stable softmax
exps = np.exp(logits - np.max(logits))
probs = exps / exps.sum()
# 2. Sort descending, keep original indices (stable => ties favor lower index)
order = np.argsort(-probs, kind="stable")
sorted_probs = probs[order]
# 3. Running total
cumsum = np.cumsum(sorted_probs)
# 4. Keep a token if the mass strictly before it is <= p
mask = np.empty(cumsum.shape, dtype=bool)
mask[0] = True
mask[1:] = cumsum[:-1] <= p
# 5. Renormalize and sample, returning the original vocabulary id
kept_ids = order[mask]
kept_probs = sorted_probs[mask]
kept_probs = kept_probs / kept_probs.sum()
return int(np.random.choice(kept_ids, p=kept_probs))
Why it is correct
- Softmax stability: subtracting the max multiplies numerator and denominator by the same constant, so probabilities are unchanged, while the largest exponent becomes
e^0 = 1. - Smallest set: since probabilities are sorted descending, any prefix of length
khas the largest mass among all sets of sizek. The first prefix that reachespis thus the smallest such set. - Index bookkeeping: we sort indices, not just values, so the result is a real token id.
- Renormalization: the kept mass lies between
pand 1 (or is the top token alone), so dividing by its sum yields a valid distribution.
Complexity
- Time: O(V log V) for the sort; softmax, cumsum, masking and sampling are O(V).
- Space: O(V).
Speed-up: the nucleus is usually far smaller than V. Take a generous top-k candidate set with np.argpartition (O(V)), sort only those k items, and check their mass reaches p. If it does not, fall back to the full sort.
Edge cases
p = 1.0: every shifted cumulative sum is below 1 (up to floating-point noise), so all tokens survive and this becomes ordinary sampling from the softmax.- One dominant logit (e.g.
[100, 0, 0]): the top token has probability about 1, so only it is kept for anyp < 1; the output is effectively greedy. Max-subtraction prevents overflow ofexp(100). - Very small
p: the top token is always kept, so the set is never empty. - Ties: a stable sort on
-probsmakes tie-breaking deterministic (lower index first). Without it, which tied token survives the cutoff is arbitrary. - Cumulative sum exactly equal to
p: by the stated rule that token is kept, and the next token is also kept as the first to exceed. Floating-point makes exact equality rare, but state the convention. -inflogits (masked tokens): they get probability 0, sort last, and are never selected, provided at least one logit is finite.
Common mistakes
- Using only
cumsum <= p, which drops the crossing token or empties the set. - Returning a position in the sorted array instead of the original id.
- Forgetting to renormalize before
np.random.choice, which raises an error. - Skipping the max subtraction in the softmax.
Follow-ups worth preparing
Batched input (B, V): apply everything along the last axis, using keepdims=True for the max, np.take_along_axis for sorting per row, and a concatenated shifted mask. Since np.random.choice is not vectorized, sample by inverse CDF: draw u of shape (B, 1), compute the cumulative sum of filtered, renormalized probabilities, and take (cdf < u).sum(axis=-1) as the chosen rank, then map back through the sorted indices.
Top-p vs. top-k: top-k uses a fixed candidate count, so on confident steps it still admits many poor tokens and on uncertain steps it may cut too much. Top-p adapts the set size to the distribution's shape, at the cost of a sort. They are often combined: top-k as a cheap cap, then top-p.
Temperature: divide the shifted logits by T > 0 before the softmax, e.g. np.exp((logits - logits.max()) / T). Low T sharpens the distribution (smaller nucleus), high T flattens it. Treat T = 0 as argmax. Apply temperature before the top-p cut, since the nucleus is defined on the tempered distribution.