This one took me a minute to get fully right.
Start by explaining the purpose of top-p sampling: to sample from the smallest set of tokens whose cumulative probability exceeds p, after applying temperature scaling. Then, walk through the implementation steps: temperature scaling, softmax, sorting, cumulative sum, truncation, renormalization, and sampling. Finally, discuss trade-offs and edge cases.
Pro tip: Mention that top-p sampling is often preferred over top-k because it adapts to the model's confidence, and highlight the importance of numerical stability (e.g., subtracting max logit before softmax).
Divide the logits by the temperature parameter to control the randomness of the distribution. Higher temperature increases randomness, lower temperature makes it more deterministic.
Apply softmax to the scaled logits to obtain a probability distribution over the vocabulary. Ensure numerical stability by subtracting the maximum logit before exponentiation.
Sort the probabilities in descending order and compute their cumulative sum. This allows identifying the smallest set of tokens whose cumulative probability exceeds p.
Remove tokens beyond the cumulative threshold p, then renormalize the remaining probabilities so they sum to 1. This forms the nucleus distribution.
Draw a random sample from the renormalized nucleus distribution using np.random.choice or inverse transform sampling, and return the index of the sampled token.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.