Lesson 3 of 96 min
Language modeling
A language model gives every token a chance of coming next. It practices on plain text, where each next token is the answer. Perplexity expresses its average uncertainty as a count of equally likely choices.
After this lesson you can explain "predict the next token" and score a model with perplexity.
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.
Let the model shift the answers
Install torch and transformers in your notebook's Python environment. The first run downloads the tokenizer and weights. Run these blocks in order. With labels=ids, the model lines up each position's guess with the following token. The first token gives context, so a seven-token sentence yields six scores.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
name = "Qwen/Qwen3.5-0.8B-Base"
revision = "dc7cdfe2ee4154fa7e30f5b51ca41bfa40174e68"
tok = AutoTokenizer.from_pretrained(name, revision=revision)
model = AutoModelForCausalLM.from_pretrained(name, revision=revision).eval()
sentence = "Penguins live in the Antarctic."
ids = tok(sentence, return_tensors="pt")["input_ids"]
print(ids.size(1), ids.size(1) - 1)7 6
Convert bits or nats to perplexity
The loss from this model counts nats. Divide by math.log(2) for bits. Raise two to the average bits or take exp() of the average nats. Both give the same perplexity.
import math
@torch.inference_mode()
def score(text):
inputs = tok(text, return_tensors="pt")
return model(**inputs, labels=inputs["input_ids"]).loss.item()
nats = score(sentence)
bits = nats / math.log(2)
print(f"{nats:.4f} nats | {bits:.4f} bits")
print(f"{math.exp(nats):.2f} | {2 ** bits:.2f}")3.0081 nats | 4.3397 bits 20.25 | 20.25
Compare scores on the same pieces
A tokenizer changes what counts as one guess. GPT-2 and Qwen can cut the same text into different numbers of tokens. In this output, Ġ marks a space. To compare a model before and after training, score the same held-out text with the same tokenizer and context setup in both runs.
gpt2_tok = AutoTokenizer.from_pretrained("openai-community/gpt2")
print(tok.tokenize(sentence))
print(gpt2_tok.tokenize(sentence))['P', 'enguins', 'Ġlive', 'Ġin', 'Ġthe', 'ĠAntarctic', '.'] ['P', 'engu', 'ins', 'Ġlive', 'Ġin', 'Ġthe', 'ĠAntarctic', '.']
Look at the hardest token
The sentence's toughest guess comes right after the first token. From just P, the model had to guess enguins. With only six scores, one big surprise can pull up the average. Look at more held-out text before drawing a conclusion from a score this short.
@torch.inference_mode()
def surprises(model, ids):
log_p = model(input_ids=ids).logits[0, :-1].float().log_softmax(dim=-1)
return -log_p.gather(1, ids[0, 1:, None]).squeeze(1) / math.log(2)
word_bits = surprises(model, ids)
hardest = word_bits.argmax().item()
print(f"{tok.decode(ids[0, hardest + 1].item())} | {word_bits[hardest]:.2f} bits")enguins | 11.33 bits
Check the effect of rounding
The text before Antarctic is identical in the sentence and paragraph. With bfloat16 weights and operations, rounding can change the score a little when input length changes. Here the same model in float32 gives matching scores to the digits shown. Reloading in float32 takes more memory.
paragraph = (sentence + " They cannot fly, but they swim very well. "
"Most of their food is fish, krill and squid, which they catch in the cold sea.")
paragraph_ids = tok(paragraph, return_tensors="pt")["input_ids"]
print(*(f"{surprises(model, x)[4]:.4f}" for x in (ids, paragraph_ids)))
fp32 = AutoModelForCausalLM.from_pretrained(
name, revision=revision, dtype=torch.float32
).eval()
print(*(f"{surprises(fp32, x)[4]:.4f}" for x in (ids, paragraph_ids)))1.2930 1.3840 1.3237 1.3237
Run on CPU on macOS, Python 3.13.3, PyTorch 2.15.0, Transformers 5.24.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Random variables and distributions
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?
2 of 3
A language model learns from plain text, and nobody writes answers in. So what does it practice on?
3 of 3
On a text, a model's average surprise is 5 bits a token. What is its perplexity: like choosing evenly among how many tokens?
The ideas in this lesson
- Language model
- A model that gives every token a chance of coming next, given the tokens before it.
- Next-token training
- Every next token of a text is a question with its answer; the model is scored by its surprise and trained to make the average smaller.
- Perplexity
- 2 to the average surprise in bits: how many tokens the model is as unsure as choosing evenly among.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Language modeling
Here's a puzzle. A model learns from plain text. Nobody writes the answers in. So what does it practice on?
Keep your guess
Do people check its answers? Or is it something in the text itself? Hold on to your guess.
A question at every token
Finish this one: "Penguins live in the..." You just did it.
Every place in a text is that question.
Given the tokens so far, which one comes next?
And the text holds the answer: the token that really came next.
This sentence is seven tokens, so it holds six questions. The first token has nothing before it.
Any text holds its own questions. So a model can practice on all the text there is.
A chance for every token
So what does the model answer?
Not one token. It gives a chance to every token it knows, and the chances add up to one.
After "Penguins live in the", Antarctic gets about four in ten.
Arctic gets one in ten. And so on, for every token.
A model that does this is called a language model.
A score for each answer
So how is each answer scored? By the model's surprise at the token that really came next, in bits. The smaller the chance it gave that token, the bigger the surprise. Antarctic got about four in ten. That's a surprise of a little over one bit.
"In", after "live", is a little under one bit. Which token do you think surprised it most?... The piece after the capital P. Over eleven bits. A P alone could start almost anything.
The loss
Now average the surprise over the whole text. That average is the model's loss. In the Probability course, it's called cross-entropy. Training makes the loss smaller, on a huge amount of text, by moving every number in the model a little.
Perplexity
Bits are hard to picture. So let's turn the average into a count you can picture. Each bit doubles the choices. One bit is like choosing between two. Three bits, like choosing among eight.
So any average surprise can be turned into a count of choices. That number is called perplexity.
It says the model is as unsure as if it were choosing evenly among that many tokens.
Seven
Here's a short paragraph about penguins: the sentence, and two more. The average is just under three bits. So the perplexity is seven. Like choosing among seven tokens, out of the whole vocabulary.
Lower is more expected
Is seven good? Take the same words, in a random order. How much more unsure will the model be?
Six hundred and seventy-three. Almost a hundred times more. Shuffled, the words don't follow each other the way text does, so every next token is harder to guess. A lower perplexity means the text was more what the model expected.
Expected is not true
So does a lower perplexity always mean the text is true? "Penguins cannot fly." Seventy-seven.
"Penguins can fly." Seventy-one.
The false one is lower. "Penguins can" is a far more common start than "Penguins cannot". The tokens after it don't change that. Perplexity says how expected the words are. It says nothing about whether they're true.
One token at a time
So how does a model write? The same step, again and again. Pick a next token at random, each as often as its chance says. Add it to the text, and ask again. A chatbot writes every answer this way, one token at a time.
In code
Now in real code. Give the model the paragraph, and set its labels to the text itself: every next token is an answer. The loss is the average surprise at every next token. PyTorch measures surprise in its own unit, nats, not bits.
One more line turns that loss into the perplexity. What will it print?
Seven. The same perplexity. And on the shuffled words, six hundred and seventy-three.
Use it to check a model of your own, on text it never trained on, before and after training.
Three ideas
So a language model gives every token a chance of coming next. It practices on text, scored by its surprise. And perplexity says how unsure it is, as a count of tokens to choose from.
The lab
That's the end of this unit. In the lab, you use these three lessons to score any text, token by token. You'll cut it into pieces, and see how surprised the model is by each one.
A chance for every next token
A language model gives a chance to every next token. Now try it on this lesson's page, and take the quiz. Find a token it was almost sure of.
You use this lesson in Lab 1: Score any text, token by token, which comes next.
Facts last checked on .
