Nucleus Sampling
Implement top-p (nucleus) sampling from a probability distribution.
Nucleus sampling selects the smallest set of tokens whose cumulative probability exceeds a threshold p, then renormalizes.
Algorithm:
- Sort tokens by probability (descending)
- Compute cumulative probabilities
- Find the smallest set of tokens where cumulative probability >= p
- Renormalize the selected probabilities to sum to 1
Since we need deterministic output, return the renormalized probability distribution (with non-selected tokens set to 0).
Input format:
- Line 1: p threshold (float, 0 < p <= 1)
- Line 2: Token names (space-separated)
- Line 3: Corresponding probabilities (space-separated floats, sum to 1)
Output: A dictionary of token: renormalized_probability for selected tokens (prob > 0), sorted by probability descending. Round to 4 decimal places.
Example
0.8 the a an this that 0.35 0.25 0.20 0.15 0.05
{'the': 0.4375, 'a': 0.3125, 'an': 0.25}Step 1: Sort by probability (already sorted) the: 0.35, a: 0.25, an: 0.20, this: 0.15, that: 0.05
Step 2: Cumulative probabilities the: 0.35 the + a: 0.60 the + a + an: 0.80 >= 0.8 => STOP
Step 3: Selected tokens: {the, a, an} with probs [0.35, 0.25, 0.20]
Step 4: Renormalize Sum = 0.80 the: 0.35/0.80 = 0.4375 a: 0.25/0.80 = 0.3125 an: 0.20/0.80 = 0.25
Constraints
- Include the minimum number of tokens to reach cumulative prob >= p
- Renormalize selected probabilities to sum to 1
- Round to 4 decimal places
- Output only tokens with non-zero probability