Nucleus (Top-P) Sampling
Implement nucleus (top-P) sampling.
Top-P sampling selects the smallest set of tokens whose cumulative probability exceeds P:
- Convert logits to probabilities (softmax)
- Sort by probability descending
- Find the smallest set where cumulative probability >= P
- Zero out all other positions and renormalize
Input:
- Line 1: P (nucleus threshold)
- Line 2: space-separated logits
Output: The filtered probability distribution, rounded to 4 decimal places.
Example
0.9 3.0 1.0 4.0 0.5
0.2583 0.0000 0.7417 0.0000
- First, we convert the logits to probabilities using the softmax function: , resulting in probabilities for the given logits: , , , .
- Then, we sort these probabilities in descending order and calculate their cumulative sum until it exceeds the given threshold .
- Next, we select the smallest set of tokens whose cumulative probability exceeds , which in this case are the first and third tokens ( and ), and zero out the other positions ( and ).
- Finally, we renormalize the selected probabilities to ensure they sum up to 1, resulting in the filtered probability distribution: , , , .
Constraints
- 0 < P <= 1
- Include the token that causes cumulative probability to exceed P
- Renormalize selected probabilities to sum to 1
- Round to 4 decimal places