Lesson 3 of 116 min
Random variables and distributions
A distribution gives every outcome its chance, all adding up to 1; drawing from it gives a different outcome each time, and for a number that can land anywhere, a chance is an area.
After this lesson you can read a distribution, draw samples from it, and read a probability as an area under a curve.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Load the model, then draw
The video started with the model already loaded. Here is the whole thing. The first run downloads the model, about 1.6 GB, and later runs read it from your computer. It runs fine without a GPU. The ten draws are the same ten as in the video.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
name = "Qwen/Qwen3.5-0.8B-Base"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)
torch.manual_seed(0)
ids = tok("Penguins live in the", return_tensors="pt")
probs = model(**ids).logits[0, -1].softmax(-1)
draws = probs.multinomial(10, True)
print([tok.decode(d) for d in draws])[' Antarctic', ' Antarctic', ' Arctic', ' Antarctic', ' Antarctic', ' Antarctic', ' ice', ' northern', ' colder', ' Southern']
The top ten chances
probs holds a chance for each of the model's 248,077 words and pieces of words. topk gives the largest ones. Even the top ten add up to only about three quarters: the rest is spread thin over every other word.
top = probs.topk(10)
for p, i in zip(top.values, top.indices):
print(f"{tok.decode(i):>12} {p.item():.3f}")
print(f"{'the top ten':>12} {top.values.sum().item():.3f}") Antarctic 0.408
Arctic 0.103
Southern 0.081
…
the top ten 0.758Always the likeliest word
do_sample=False turns the draw off. The model then writes the likeliest word every time, so the same question gets the same answer. This is called greedy decoding. It is steady, but it can repeat itself, which is one reason chatbots draw.
for _ in range(3):
out = model.generate(**ids, do_sample=False, max_new_tokens=4)
print(tok.decode(out[0, ids.input_ids.shape[1]:]))Antarctic, where the Antarctic, where the Antarctic, where the
Word after word
generate with do_sample=True draws one word, adds it to the text, and draws again. top_k=0 lets it draw from every word, the way the video does. Without it, generate keeps only the likeliest 50 words. Each ending is a new run of draws.
torch.manual_seed(0)
out = model.generate(**ids, do_sample=True, top_k=0, max_new_tokens=4,
num_return_sequences=5)
for row in out:
print(tok.decode(row[ids.input_ids.shape[1]:]))Northern Hemisphere only; Antarctic region of the Arctic Ocean at Mc King Crayfish same region and want
How the curve is made
The curve in the video puts a small bell, a quarter of a kilo wide, on each penguin, and adds them up. SciPy's gaussian_kde makes the same curve. integrate_box_1d gives the area over a range, and calling the curve gives its height.
import pandas as pd
from scipy.stats import gaussian_kde
df = pd.read_csv("penguins.csv")
mass = df.body_mass_g.dropna() / 1000
curve = gaussian_kde(mass, bw_method=0.25 / mass.std())
print(round(curve.integrate_box_1d(4, 5), 2))
print(round(curve(4.0)[0], 2))0.33 0.44
Run on Python 3.13, PyTorch 2.15.0, transformers 5.24.0, pandas 3.1.1 and SciPy 1.18.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Probability
A penguin picked at random is a Chinstrap with a chance of 0.20. It lives on Dream island with a chance of 0.36. Every Chinstrap lives on Dream. What is the chance it's a Chinstrap and lives on Dream?
2 of 3
You ask a chatbot the same thing twice, and some words of its two answers differ. Nothing in the model changed. Where does the difference come from?
3 of 3
The penguins' masses are drawn as bars of share per kilo. The bar from 3.5 to 4 kilos is half a kilo wide, and 0.55 high. What share of the penguins weigh 3.5 to 4 kilos?
The ideas in this lesson
- Distribution
- Every outcome with its chance, all adding up to 1, like a model's chance for every next word.
- Sample
- One outcome drawn at random: each outcome comes up about as often as its chance.
- Probability as an area
- For a number that can land anywhere, the chance of a range is the area under its curve.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Why the words change
Here's a mystery. A chatbot writes its answer one word at a time. Ask it the same thing twice, and the words can change. Nothing in the model changed. So where does the difference come from?
Finish the sentence
Here's a clue. Finish this sentence in your head. Penguins live in the...
A chance for every word
A small open language model, the kind chatbots are built on, read that same sentence.
Before it writes the next word, it has a chance for every word it knows.
Antarctic gets zero point four one. Arctic gets zero point one. Southern gets a bit less, and the next words even less.
Then there are about a quarter of a million more words. All of those together get a bit more than a third.
Adding up to one
How do all these chances fit together?
Exactly one word comes next. Two words never come next together, so their chances add, the way "or" adds. And all of them together make one.
Every outcome with its chance, all adding up to one... is called a distribution.
A draw
So which word does the model write? It draws one at random, and each word comes up as often as its chance says.
Antarctic, about four times in ten.
One draw is called a sample.
Here are the model's own ten draws.
Will they all say Antarctic?
A wrong word, by chance
Antarctic came up five times. Southern once. Three other words. That's nine draws.
Now look at the third draw.
Arctic. No penguin lives in the Arctic in the wild, and the model still wrote it. A small chance still comes up, now and then. That's where the difference comes from: the same chances, and a different draw.
Many draws
Antarctic came up five times in ten, not four. Ten draws are too few to land on the chances. A thousand draws come out close to the bars: Antarctic, three hundred and ninety-six times. That's close to zero point four one.
A number that lands anywhere
Now a number. Here are the masses of three hundred and forty-two penguins. How heavy is a penguin picked at random? Its mass is a number that comes out of a draw. A number like that is called a random variable. A mass has no list of outcomes. It can be four point two kilos, four point two one, anything. So make bars for ranges, like the histogram in Python for AI. Each bar is half a kilo wide. What's the chance a penguin weighs four to five kilos?
The bar from four to four and a half holds zero point one seven of the penguins.
The bar from four and a half to five holds zero point one five.
No penguin's mass is in both bars, so they add: zero point three two.
Share per kilo
Now make the bars thinner. A thinner bar holds fewer penguins, so it shrinks, and the picture changes with the width.
We want a picture that stays the same. So make each bar as tall as its share, divided by its width.
The bar from four and a half to five holds zero point one five, and it's half a kilo wide. That's zero point three per kilo.
Its height times its width gives the share back. So a bar's area... is its share.
Narrow them to a quarter of a kilo, then a tenth. The area from four to five kilos stays zero point three two.
The area under a curve
Make the bars thin enough, and their tops become a smooth curve.
Now the chance of a range is the area under the curve. From four to five kilos, it's about a third. The curve smooths the bars a little, so it's close to the zero point three two, not the same.
An area is thin bars, added up.
Exactly four kilos
So what's the chance a penguin weighs exactly four kilos?
The curve is zero point four four high there. Is that the chance?
No. A height is a share per kilo. Exactly four kilos is a range with no width, so it has no area. The chance is zero.
But wait. Five penguins were weighed at exactly four thousand grams. How?
The scale weighs to the nearest twenty-five grams. So each one is somewhere in a thin range around four kilos. Their chance is the small area of that thin range.
In code
Now in real code.
Here's the model, loaded. Give it the sentence.
It gives a score for every word, and one line turns the scores into chances. Then draw ten. What will it print?
The model's own ten. Antarctic five times, and Arctic once. For the masses, one line gives the share from four to five kilos: zero point three two.
A chatbot writes this way, one draw for every word.
Every outcome, its chance
So a distribution gives every outcome its chance, all adding up to one. A draw from it is a sample. And for a number, a chance is an area under the curve.
The lab
That's the end of this unit. In its lab, you use these three lessons to check an AI detector by drawing. You'll see how often its flag is right.
Every word is a draw
A chatbot draws every word from its chances. Now try it on this lesson's page, and take the quiz. Draw until the model writes Arctic.
You use this lesson in Lab 1: Check an AI detector by drawing, which comes next.
Facts last checked on .
