All courses
Courses › How LLMs really work · foundation

Sampling from a distribution

Draw an index from a probability vector, e.g. with cumulative sums or np.random.choice.

Builds on: Probability and distributions

▶ Watch this lesson Start the whole course

What the animation says

One number, a fair pick

A text generator, choosing its next word, holds a list of probabilities. Ours has three options: point five, point three, point two. We want one pick, so that over many picks option zero wins half the time, option one thirty percent, option two twenty. But the computer only gives us one uniform random number, anywhere from zero up to just below one. How do we turn that one number into a fair pick?

Throw a dart at a ruler

Lay the probabilities end to end on a ruler from zero to one. Option zero gets zero to point five. Option one gets point five to point eight. Option two gets point eight to one. The random number is a dart, equally likely to land anywhere. A stretch twice as long gets hit twice as often. Whichever stretch the dart lands in is the pick. Our dart is at point six two. Which option is it?

Running totals make the stretches

Option one. The dart landed past point five, but before point eight. Those boundaries are running totals. Point five. Point five plus point three, point eight. Plus point two, one. These are cumulative sums, and the last one is always one. The rule: check the running totals from left to right, and pick the first one bigger than the dart. Compare the dart with the running totals, never with the probabilities themselves. New dart: point nine three. Tap the option it picks.

Why the pick is fair

Option two: point nine three gets past point five and point eight, and stops at one. A dart at point one stops at the very first total, so option zero. Why is this fair? Each option's stretch runs from the previous total to its own total. That length is exactly its probability, so a uniform dart hits it exactly that often. Throw a hundred thousand darts, and the counts settle near half, thirty percent and twenty percent.

In code: by hand, then NumPy

In code, cumsum builds the running totals: point five, point eight, one. This line draws the dart. The loop walks the totals and stops at the first one bigger than the dart. NumPy's random choice does the same job in one call: give it the number of options and the probabilities. The last two lines draw a hundred thousand times and count how often each option comes up. So, to sample: stack the probabilities into running totals, then pick the first total above a uniform dart.

Turning probabilities into an actual choice

Say a program holds the probabilities $[0.5, 0.3, 0.2]$ for three options, numbered 0, 1 and 2. You want it to **pick one** so that, over many picks, option 0 comes out about 50% of the time, option 1 about 30% and option 2 about 20%. The computer only gives you a **uniform** random number in $[0,1)$. How do you turn that one number into a fair pick? A text generator does exactly this each time it picks its next word.

Throw a dart at a ruler

Lay the probabilities end to end on a ruler from 0 to 1. Each option gets a stretch as long as its probability: - option 0 gets 0 to 0.5, - option 1 gets 0.5 to 0.8, - option 2 gets 0.8 to 1. Now throw a dart that is equally likely to land anywhere. A stretch twice as long gets hit twice as often. Whichever stretch the dart lands in is your pick.

Cumulative sums make the stretches

Number the options $0,\dots,n-1$. Write $p_i$ (read "p sub i") for the probability of option $i$, so $p_0$ is option 0's probability. Build **cumulative sums**: $c_0=p_0$, $c_1=p_0+p_1$, $c_2=p_0+p_1+p_2$, and so on. Each $c_i$ is the running total up to option $i$, and the last one, $c_{n-1}$, is 1. Draw $u$ uniformly from $[0,1)$. Pick the **smallest** $i$ with $u < c_i$. Option 0 owns $[0, c_0)$. Every later option $i$ owns $[c_{i-1}, c_i)$, of length $c_i-c_{i-1}=p_i$. A uniform $u$ lands in a stretch with probability equal to its length, so option $i$ is picked with probability exactly $p_i$.

Three darts, by hand

$p=[0.5, 0.3, 0.2]$, so the cumulative sums are $c=[0.5, 0.8, 1.0]$. - $u=0.62$: is $0.62<0.5$? No. Is $0.62<0.8$? Yes → **index 1**. - $u=0.93$: not $<0.5$, not $<0.8$, is $<1.0$ → **index 2**. - $u=0.10$: $0.10<0.5$ → **index 0**. Over many draws, about 50%, 30% and 20% of the picks land on 0, 1 and 2.

By hand, then with np.random.choice

The loop does the dart method. `np.random.choice` from NumPy does the same job in one call. The last two lines draw 100,000 times and count how often each option came up. Those fractions come out close to $p$.
import numpy as np
p = [0.5, 0.3, 0.2]
c = np.cumsum(p)            # [0.5, 0.8, 1.0]
u = np.random.rand()        # uniform in [0, 1)
for i, ci in enumerate(c):  # first i with u < c[i]
    if u < ci:
        break
print(u, i)
j = np.random.choice(len(p), p=p)  # built-in version
print(j)
draws = np.random.choice(3, size=100000, p=p)
print(np.bincount(draws) / 100000)  # close to [0.5, 0.3, 0.2]

Remember this

To sample from a list of probabilities (a probability vector), stack the probabilities into cumulative sums. Draw a uniform $u$ in $[0,1)$ and pick the first index whose cumulative sum is above $u$. Each option is picked with exactly its probability, because its stretch of the ruler is exactly that long. `np.random.choice(n, p=p)` does this for you.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.