Build a nucleus from sorted probabilities

Watch the spaces around tokens and probability values. · 168 words

A language model predicts a probability for each possible next token. To build a nucleus, also called the top-p set, first sort those probabilities from largest to smallest. Here is a tiny vocabulary after the prompt "A good pet is": cat 0.50, dog 0.30, fish 0.15, bird 0.05. Set p to 0.80. Keep cat and dog because their cumulative probability is 0.50 + 0.30 = 0.80. The next token, fish, would raise the total to 0.95, so it is excluded. The nucleus is therefore {cat, dog}.

During decoding, the model samples or chooses only from this nucleus. The kept probabilities are renormalized so they add to one: cat gets 0.50 / 0.80 = 0.625, and dog gets 0.30 / 0.80 = 0.375. If the sampler picks cat, the context changes and the model computes a fresh distribution for the next position. This makes nucleus sampling different from top-k sampling: top-k always keeps exactly k tokens, while top-p keeps the smallest sorted prefix whose probability reaches the chosen threshold.

Check your recall

With nucleus threshold p = 0.80, which tokens form the nucleus, and what probability does cat receive after renormalization?

Check your answer

The nucleus contains cat and dog. After renormalization, cat has probability 0.625 and dog has probability 0.375.

Sources and credits

Original KeyTouch lesson. Background reading · Hugging Face · LLM Course.