Skip to content

Bridges: DSA to LLMs

Prefix sums and binary search to top-p sampling

Cumulative mass and the nucleus

The "nucleus" in nucleus sampling is not a new idea - it is a running total and a binary search, two of the first tools you learned, pointed at a probability distribution.

A language model's final act is to hand you a probability for every token in its vocabulary. Top-p (nucleus) sampling keeps only the smallest set of the most likely tokens whose probabilities add up past a threshold , then draws from that set. Strip away the ML vocabulary and the recipe is pure data structures: sort the probabilities, take a running total, and binary-search for the cutoff. This lesson makes that equivalence something you can grab with the mouse.

From bars to a rising staircase

Start with the next-token probabilities and sort them descending - biggest first. Now walk left to right keeping a running total. That running total is a prefix sum, and the array of prefix sums over a probability list has a name in statistics: the cumulative distribution function, or CDF. Because probabilities are non-negative, the CDF only ever climbs - it is a monotonically increasing staircase from up to . Each step's height is exactly one token's probability, so the tallest bar is the tallest step. That single fact - the CDF is sorted - is what lets a binary search do the rest.

CDF, nucleus, and the search

Let the sorted probabilities be . The CDF is the prefix-sum array

The nucleus is the shortest prefix whose mass reaches the threshold - the smallest index with

Since is sorted ascending, this is a textbook lower_bound: a binary search costing instead of an scan. Sorting is , the prefix sums are , and the cutoff is .

Drag the threshold, watch the nucleus

Below are ten sorted next-token probabilities for the prompt "The weather today is ___". The teal bars are the probabilities; the amber staircase is their CDF - notice each riser is the same height as the bar beneath it, because a prefix sum just stacks the bars. Drag the dashed line up and down (grab anywhere on the plot, or use the slider). The cutoff marker jumps to the first bar where the staircase crosses your line - that is the binary search landing. Then trace the search step by step, or throw a dart to sample.

Nucleus finder. Teal bars are token probabilities; the amber staircase is their CDF (the prefix sum). Drag the dashed p line, trace the binary search, or throw a dart to sample.
0.000.250.500.751.00sunny28%cloudy19%warm14%clear11%rainy8%cold6%hot5%mild4%gray3%windy2%p = 0.90
token probability (in nucleus)CDF = prefix sumtop-p thresholdsampled token
7 of 10 tokens · 91% of the mass

Drag the dashed line to move p. The nucleus is every bar left of where the amber staircase first climbs above it.

The aha to trigger

Push down to about 0.30: the staircase clears it almost immediately, so the nucleus collapses to one or two confident tokens - sampling becomes nearly greedy. Now push up to 0.99: the line rides near the top, so the search must walk far right and the nucleus swells to include the long, unsure tail. That is the whole personality of top-p - the set breathes with the model's confidence, all controlled by where a horizontal line crosses a sorted array. Press Trace binary search and watch lo, mid, hi halve the search space to reach the same cutoff your eye already found.

One dart: inverse-CDF sampling

Finding the nucleus is only half the job - we still have to pick a token from it. The trick reuses the very same staircase. Draw a random height uniformly along the vertical axis (inside the nucleus's mass), then find the first token whose CDF rises above . That is inverse-transform sampling, and it is again a binary search into the CDF. Because a wider bar owns a taller slice of the staircase, it catches more darts - so tokens are drawn in exact proportion to their probability. Press Throw a dart to watch drop and slide into a token's band.

import numpy as np

def top_p_sample(probs, p):
    order = np.argsort(probs)[::-1]     # 1. sort tokens high -> low   O(V log V)
    probs = probs[order]
    cdf   = np.cumsum(probs)            # 2. prefix sums = the CDF      O(V)
    m     = np.searchsorted(cdf, p)      # 3. binary search the cutoff   O(log V)
    keep  = order[: m + 1]              #    the nucleus (smallest prefix)
    u     = np.random.random() * cdf[m]  # 4. inverse-CDF: a random height
    j     = np.searchsorted(cdf, u)      #    first token whose CDF >= u
    return order[j]                     #    the sampled token
Top-p, end to end - sort, prefix-sum, binary-search, sample

Top-p versus top-k. Top-k (last lesson) keeps a fixed count of tokens - a job for a heap or partial sort. Top-p keeps a fixed mass, so its count adapts: many tokens when the model is unsure, few when it is confident. Both cut the tail; top-p just lets the tail's own shape decide where the knife falls. In practice people stack them - a small top-k as a safety cap, then top-p inside it.

Check yourself

Binary search over the sorted CDF returns the nucleus, which is the…

Inverse-CDF sampling draws u at random and returns the token whose…

Recall: why is finding the top-p nucleus a binary search rather than a linear scan?

Try to state it, then check.

Lock it in

  • Top-p (nucleus) sampling keeps the smallest set of most-likely tokens whose probabilities sum past a threshold , then samples from it.
  • Sort the probabilities descending and take a running total: that prefix-sum array is the CDF, a monotonically increasing staircase from to .
  • Because the CDF is sorted, the nucleus edge is a lower_bound binary search - , not an scan.
  • Sampling from the nucleus reuses the same staircase: inverse-transform sampling draws a random height and binary-searches the CDF, so tokens are drawn in exact proportion to their probability.

Primary source

Prefix sums and binary search are foundational patterns on the NeetCode Roadmap - the same two tools reused here. For how a language model produces the distribution in the first place and how generation strategies like top-p consume it, see the Hugging Face LLM Course.

Ask your teacher

Here is the connection to hold onto: top-p decoding is prefix sums plus binary search - the "nucleus" is just the smallest prefix of the sorted CDF that crosses . Sorting the probabilities is the same descending sort that powered top-k; the cutoff is the binary search you already know; the dart is inverse-transform sampling on that same staircase. Ask me to derive why inverse-CDF sampling reproduces the exact distribution, to show how a repetition penalty reshapes the bars before the sort, or to compare top-p's cost against top-k's heap.