Truncate and Renormalize a Next-Token Distribution
Heaps, Sorting & SearchAuto-graded · 20 test casesLast updated
Sort a probability list with deterministic tie-breaking, then build two truncated, renormalized versions: fixed-size top-k and cumulative-mass top-p.
Truncate and Renormalize a Next-Token Distribution
A language model assigns a probability to each token in a small vocabulary. Before drawing a token, a decoder often discards unlikely candidates and rescales the survivors so they sum to 1. You will compute two such truncated distributions from the same input.
Task
Given token_probs, where token_probs[i] is the probability of the token at index i, a positive integer k, and a threshold p, return a dictionary with two keys, each mapping to a list of floats with the same length and index order as token_probs:
"top_k": the fixed-size truncation."top_p": the cumulative-mass truncation.
Ranking order
Rank tokens by probability from highest to lowest. If two tokens have equal probability, the one with the smaller original index ranks first. Both truncations use this one ranking.
Top-k list
Keep the k highest-ranked tokens. If k is at least the number of tokens, keep all of them. Each kept token's value is its probability divided by the total probability of the kept tokens. Every other position is 0.0.
Top-p list
Walk through tokens in ranked order, adding each token's probability to a running total. The total is a plain floating-point sum, accumulated in ranked order. Add a token to the kept set first, then check whether the running total is >= p. As soon as it is, stop. The kept set is therefore the shortest ranked prefix whose cumulative probability reaches p.
- The comparison is non-strict (
>=), not>. - At least one token is always kept, even when
p <= 0. - If the running total never reaches
p, for example becausep >= 1or because of rounding, keep every token.
Each kept token's value is its probability divided by the total probability of the kept tokens. Every other position is 0.0.
Constraints
1 <= len(token_probs) <= 10^5- Each probability is non-negative, and they sum to 1 up to floating-point error.
1 <= kpis a real number. It may be at most 0 or at least 1, and both cases follow the rules above.- Positions are never reordered. Results are indexed exactly like the input.
- Results are compared as floating-point numbers, so follow the summation order described above.
Examples
Example 1
Input: truncate_distribution([0.4, 0.3, 0.15, 0.1, 0.05], 3, 0.7)
Output: {'top_k': [0.4705882352941177, 0.35294117647058826, 0.17647058823529413, 0, 0], 'top_p': [0.5714285714285715, 0.4285714285714286, 0, 0, 0]}
Example 2
Input: truncate_distribution([0.95, 0.02, 0.01, 0.01, 0.01], 2, 0.9)
Output: {'top_k': [0.979381443298969, 0.020618556701030927, 0, 0, 0], 'top_p': [1, 0, 0, 0, 0]}
Example 3
Input: truncate_distribution([0.2, 0.2, 0.2, 0.2, 0.2], 3, 0.6)
Output: {'top_k': [0.3333333333333333, 0.3333333333333333, 0.3333333333333333, 0, 0], 'top_p': [0.3333333333333333, 0.3333333333333333, 0.3333333333333333, 0, 0]}
Example 4
Input: truncate_distribution([0.7, 0.2, 0.1], 1, 1)
Output: {'top_k': [1, 0, 0], 'top_p': [0.7, 0.2, 0.1]}
Hints
Hint 1
Compute the ranking once as a list of original indices sorted by the key (-probability, index). Both outputs can reuse it.
Hint 2
For the top-k list, take the first k indices of the ranking, sum their probabilities, and divide each kept probability by that sum. Put 0.0 everywhere else.
Hint 3
For the top-p list, loop over the ranking, append the index, add its probability to a running total, and break as soon as the total is >= p. Renormalize by the sum over the kept set.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both outputs follow the same pattern: choose a subset of tokens, zero the rest, and divide each survivor by the subset's total mass. They differ only in how the subset is chosen. A single shared ranking handles both.
- Rank once. Sort the indices by the key
(-probability, index). This gives probability descending with ties going to the smaller index, so the result is deterministic. - Top-k. The kept set is the first
kindices of the ranking. Slicing handlesklarger than the vocabulary size automatically. Sum their probabilities and divide each kept probability by that sum. Other positions get0.0. - Top-p. Scan the ranking, appending each index and adding its probability to a running total. Stop right after the total becomes
>= p. Because the token is added before the check, at least one token is always kept, which coversp <= 0. If the loop finishes without reachingp, every token is kept. Renormalize by the kept set's sum.
Why it is correct
- The ranking puts the most likely tokens first, so any prefix is the highest-mass set of its size. The first
kentries are therefore exactly thekmost probable tokens. - Stopping at the first prefix that reaches
pgives the shortest such prefix, which matches the definition. Using>=means a prefix that hitspexactly is accepted, so no extra token is included. - Dividing by the kept mass makes each output list sum to 1 and preserves the relative odds among kept tokens.
- Writing results by original index keeps the output aligned with the input.
Complexity
- Time: O(n log n) for the sort. The scans and normalization are O(n).
- Space: O(n) for the ranking, the kept sets and the output.
Reference solution
from typing import Dict, List
def truncate_distribution(token_probs: List[float], k: int, p: float) -> Dict[str, List[float]]:
n = len(token_probs)
order = sorted(range(n), key=lambda i: (-token_probs[i], i))
k_indices = set(order[:k])
k_total = sum(token_probs[i] for i in k_indices)
top_k = [token_probs[i] / k_total if i in k_indices else 0.0 for i in range(n)]
p_indices = []
cumulative = 0.0
for i in order:
p_indices.append(i)
cumulative += token_probs[i]
if cumulative >= p:
break
p_set = set(p_indices)
p_total = sum(token_probs[i] for i in p_set)
top_p = [token_probs[i] / p_total if i in p_set else 0.0 for i in range(n)]
return {"top_k": top_k, "top_p": top_p}