makemore Lecture 1: Bigrams
Overview
This lecture builds the simplest possible language model: a character-level bigram model that predicts the next letter of a name from the current letter alone. Karpathy builds it twice, once by counting and once as a one-layer neural net trained by gradient descent. Both land on the same loss, about 2.45 to 2.48 nats per character.
What makemore is. makemore “makes more” of whatever you give it. Feed it a text file with one item per line, and it generates new items that look like they belong. The example dataset is names.txt: 32,033 of the most common US baby names from 2018. After training, makemore produces name-like inventions that aren’t real names.
Character-level language model. Each name is treated as a sequence of characters. The model’s one job is: given what came before, assign a probability to every possible next character. Generation is then just repeated sampling: pick a character, feed it back in, pick the next.
The bigram model looks back only one character. It knows that “q” is usually followed by “u”, but it has no idea what came two letters ago. That makes it weak, but it is the perfect place to set up the machinery the whole series reuses:
- turning text into integers, and integers into tensors
- probabilities, sampling and the negative log likelihood loss
- broadcasting and vectorised tensor code
- one-hot inputs, logits, softmax,
backward()and gradient descent in PyTorch
Where the series goes. makemore climbs from this bigram model through an MLP (Bengio et al. 2003), RNNs, LSTMs and GRUs, and a WaveNet-style CNN, up to a Transformer like GPT-2. Only the model in the middle changes; the data, loss and training loop set up here stay.
The two halves of the lecture
| Part A: counting | Part B: neural net | |
|---|---|---|
| Parameters | 27 × 27 table of bigram counts N | 27 × 27 weight matrix W |
| How it is “trained” | Count every bigram, then normalise each row | Gradient descent on the average negative log likelihood |
| Probabilities | P = N / row sums | softmax(one_hot(x) @ W) |
| Smoothing | Add fake counts (N + 1) | Regularisation: penalise large W |
| Final loss | ≈ 2.45 to 2.48 | ≈ 2.45 to 2.48 |
The two models end up essentially identical, and that’s the point. The neural-net framing reaches the same answer, but unlike a count table it scales to models that look back much further.
Chapter map
| Time | Chapter in the video | Notes section |
|---|---|---|
| 0:00 | Intro | Overview |
| 3:03 | Reading and exploring the dataset | Part 1 |
| 6:24 | Exploring the bigrams in the dataset | Part 2 |
| 9:24 | Counting bigrams in a Python dictionary | Part 2 |
| 12:45 | Counting bigrams in a 2D torch tensor (“training the model”) | Part 2 |
| 18:19 | Visualising the bigram tensor | Part 2 |
| 20:54 | Replacing the start and end tokens with a single . token | Part 2 |
| 24:02 | Sampling from the model | Part 3 |
| 36:17 | Vectorised normalisation of the rows, tensor broadcasting | Part 4 |
| 50:14 | Loss function: negative log likelihood of the data | Part 5 |
| 1:00:50 | Model smoothing with fake counts | Part 5 |
| 1:02:57 | Part 2 of the lecture: the neural-network approach | Part 6 |
| 1:05:26 | Creating the bigram dataset for the neural net | Part 6 |
| 1:10:01 | Feeding integers into neural nets: one-hot encodings | Part 6 |
| 1:13:53 | One linear layer of neurons as a matrix multiply | Part 7 |
| 1:18:46 | Turning outputs into probabilities: the softmax | Part 7 |
| 1:26:17 | Summary, preview of next steps, link to micrograd | Part 7 |
| 1:35:49 | Vectorised loss | Part 8 |
| 1:38:36 | Backward and update, in PyTorch | Part 8 |
| 1:42:55 | Putting everything together | Part 8 |
| 1:47:49 | Note 1: one-hot encoding just selects a row of W | Part 9 |
| 1:50:18 | Note 2: model smoothing as a regularisation loss | Part 9 |
| 1:54:31 | Sampling from the neural net | Part 10 |
| 1:56:16 | Conclusion | Part 10 |
Code follows Karpathy’s lecture notebook (makemore_part1_bigrams.ipynb). Dataset statistics and losses were re-computed from names.txt to check them.
Part 1 — The dataset
The training data is 32,033 lowercase names, one per line. They use 26 distinct characters (a–z) and run from 2 to 15 letters long.
words = open('names.txt', 'r').read().splitlines()
words[:10]
# ['emma', 'olivia', 'ava', 'isabella', 'sophia',
# 'charlotte', 'mia', 'amelia', 'harper', 'evelyn']
len(words) # 32033
min(len(w) for w in words) # 2
max(len(w) for w in words) # 15
The names are the most common US baby names from 2018, taken from the Social Security Administration’s list.
One word, many examples
Karpathy’s key observation: a single name is not one training example but a bundle of them. Take isabella. It says that:
- i is a plausible first letter;
- s is likely to follow i, a to follow is, b to follow isa, and so on;
- after isabella, the name is likely to end.
The ending is information too, which is why the model needs a way to say “start” and “end” (Part 2).
A full language model would use all of that context. The bigram model throws most of it away and keeps only pairs of neighbouring characters. That is the simplification this whole lecture lives with.
Part 2 — Bigrams: counting them
“Training” the counting model means one thing: tally how often each character follows each other character. The result is a 27 × 27 table N, which is the entire model.
Extracting bigrams
A bigram is a pair of neighbouring characters. Python’s zip makes them neatly, because it stops as soon as the shorter input runs out:
for w in words[:1]:
for ch1, ch2 in zip(w, w[1:]):
print(ch1, ch2)
# e m / m m / m a
That misses two facts: that e starts “emma”, and that a ends it. So wrap each word in special start and end tokens first:
chs = ['<S>'] + list(w) + ['<E>']
# <S> e / e m / m m / m a / a <E>
First attempt: a Python dict
b = {}
for w in words:
chs = ['<S>'] + list(w) + ['<E>']
for ch1, ch2 in zip(chs, chs[1:]):
bigram = (ch1, ch2)
b[bigram] = b.get(bigram, 0) + 1 # .get returns 0 if not seen yet
sorted(b.items(), key=lambda kv: -kv[1]) # most common first
| Rank | Bigram | Count | Reading |
|---|---|---|---|
| 1 | n → end | 6,763 | Lots of names end in n |
| 2 | a → end | 6,640 | …and in a |
| 3 | a → n | 5,438 | “an” is everywhere |
| 4 | start → a | 4,410 | a is the most common first letter |
| 5 | e → end | 3,983 | |
| 6 | a → r | 3,264 | |
| 7 | e → l | 3,248 | |
| 8 | r → i | 3,033 | |
| 9 | n → a | 2,977 | |
| 10 | start → k | 2,963 | k is the second most common first letter |
Better: a 2D torch tensor
A dict works, but a 2D array is far more convenient. Row = first character, column = second character, cell = count. Characters need integer indices, so build lookup tables in both directions:
import torch
chars = sorted(list(set(''.join(words)))) # 'a'..'z'
stoi = {s: i+1 for i, s in enumerate(chars)} # string -> int: a=1 ... z=26
stoi['.'] = 0 # the special token gets 0
itos = {i: s for s, i in stoi.items()} # int -> string
N = torch.zeros((27, 27), dtype=torch.int32)
for w in words:
chs = ['.'] + list(w) + ['.']
for ch1, ch2 in zip(chs, chs[1:]):
N[stoi[ch1], stoi[ch2]] += 1
In total that is 228,146 bigrams. Of the 729 cells, 102 are zero: those pairs never occur in any name.
Why one . token instead of <S> and <E>
Karpathy first builds a 28 × 28 table with separate <S> and <E> tokens. Visualising it shows the waste:
- The
<E>row is all zeros, because nothing ever follows the end. - The
<S>column is all zeros, because nothing ever comes before the start.
So he replaces both with a single token, ., at index 0, and shifts the letters to 1–26. That gives a 27 × 27 table with no dead rows or columns:
- Row 0 (
.→ x) is the distribution of first letters. - Column 0 (x →
.) counts how often each letter ends a name.
Reading the table
plt.imshow(N, cmap='Blues'), with each cell labelled by its bigram and count, gives the big heat map from the video. A few things stand out:
- First letters (row 0): a 13.8%, k 9.3%, m 7.9%, j 7.6%, s 6.4%.
- Endings (column 0): 36.9% of all n’s end a name, and so do 19.6% of all a’s.
- q appears only 272 times, and 75.7% of those are followed by u.
plt.figure(figsize=(16, 16))
plt.imshow(N, cmap='Blues')
for i in range(27):
for j in range(27):
chstr = itos[i] + itos[j]
plt.text(j, i, chstr, ha='center', va='bottom', color='gray')
plt.text(j, i, N[i, j].item(), ha='center', va='top', color='gray') # .item(): tensor -> int
plt.axis('off')
Indexing a tensor returns a tensor, not a Python number, hence .item() when printing a count.
Part 3 — Sampling names from the count model
To generate a name, start at ., turn that row of counts into probabilities, draw the next character, and repeat until . comes up again. The results are recognisably name-ish but bad, because one character of context is very little.
Counts to probabilities
p = N[0].float() # row 0: counts of each first letter (as floats!)
p = p / p.sum() # normalise so the row sums to 1
# tensor([0.0000, 0.1377, 0.0408, 0.0481, ...]) p[1] = P(first letter is 'a') = 13.8%
Convert to float first: counts are integers, and you want real-valued probabilities.
Drawing samples: torch.multinomial
torch.multinomial(p, num_samples, replacement, generator) returns integer indices drawn according to the probabilities in p. Hand it probabilities and it hands back indices.
g = torch.Generator().manual_seed(2147483647)
ix = torch.multinomial(p, num_samples=1, replacement=True, generator=g).item()
itos[ix] # 'm'
generator=gwith a fixed seed makes the randomness reproducible. Karpathy uses the same seed throughout, so you get the same numbers he does.replacement=Truematters. The default isFalse, which would never draw the same index twice. That’s wrong for sampling characters.
A quick sanity check on a 3-element distribution: p = [0.6064, 0.3033, 0.0903]. Draw 100 samples, and roughly 60 are 0s, 30 are 1s and 9 are 2s.
The sampling loop
g = torch.Generator().manual_seed(2147483647)
for i in range(5):
out = []
ix = 0 # start at '.'
while True:
p = P[ix] # row of next-character probabilities
ix = torch.multinomial(p, num_samples=1, replacement=True, generator=g).item()
out.append(itos[ix])
if ix == 0: # drew '.', so the name has ended
break
print(''.join(out))
With the seed above and the smoothed P from Part 5, the output is:
mor.
axx.
minaymoryles.
kondlaisah.
anchshizarie.
Is it learning anything?
These look terrible. To check that the model is doing something, swap P for a uniform distribution: every character with probability 1/27. The output becomes completely random strings of any length. The bigram samples are clearly more name-like: sensible starts, plausible letter pairs, and endings in common places. The trouble is that each choice sees only the previous character. A name like “axx.” is fine pair by pair, but nonsense as a whole.
Part 4 — Vectorised normalisation and broadcasting
Normalise all 27 rows in one line, P = N.float(); P /= P.sum(1, keepdim=True). But drop keepdim=True and broadcasting silently normalises the columns instead, with no error. Karpathy spends a long stretch here because this kind of shape bug haunts all later tensor code.
Why vectorise
The sampling loop renormalised a row of N every time it drew a character. Doing it once for the whole matrix is cleaner and faster:
P = N.float()
P /= P.sum(1, keepdim=True) # each row now sums to 1
The in-place /= also avoids allocating a new tensor.
sum along a dimension
P.sum(dim, keepdim) adds up along one axis:
| Call | Result shape | What it is |
|---|---|---|
P.sum(0, keepdim=True) | 1 × 27 | Column totals (summed down the rows) |
P.sum(1, keepdim=True) | 27 × 1 | Row totals, kept as a column vector |
P.sum(1) | 27 | Row totals, with that dimension squeezed out |
The broadcasting rules
Two tensors can be combined element-wise when, aligning their shapes from the right, each pair of dimensions is either equal, or one of them is 1, or one of them is missing. A size-1 or missing dimension is then copied (“stretched”) to match the other.
Same numbers, opposite stretch: a 4 × 4 grid stands in for the 27 × 27 table.
Correct: (27, 27) / (27, 1)
27 27
27 1 <- the 1 is stretched across the 27 columns
The column of row totals is copied sideways, so each row is divided by its own total. Every row sums to 1. ✔
The bug: (27, 27) / (27)
27 27
27 <- missing dim on the left becomes 1, i.e. shape (1, 27)
The 27 row totals become a row vector, which is stretched down the rows. Now element [i, j] is divided by the total of row j, not row i. You have quietly normalised the columns: column 0 sums to exactly 1, but row 0 sums to 6.92 (Karpathy’s “seven”). No error, no warning, and sampling from it gives subtly wrong names.
Lessons
- Respect broadcasting. Read the docs, and line shapes up from the right in your head.
- Prefer
keepdim=Truewhen you reduce and then combine with the original tensor. - Check your work.
P[0].sum()should be 1. A cheap assertion would have caught the bug instantly. - Mind the dimension you sum over.
dim=1means “collapse the columns”, leaving one number per row.
Part 5 — The loss: negative log likelihood
The model’s quality is summed up in one number: the average negative log likelihood of the training bigrams. The count model scores 2.454, against 3.296 for a model that guesses uniformly. Lower is better, and 0 would be perfect.
From probabilities to one number
Start by printing the probability the model gives each bigram it actually sees in the data. A uniform guess would give 1/27 ≈ 3.7% to everything. The trained model gives many real bigrams far more, some as high as 35–40%, so it has learned something.
To combine them, use the likelihood: the product of the probabilities the model assigns to all the training bigrams. A good model makes the observed data likely, so we want this product to be high. This is maximum likelihood estimation, and the model’s parameters are the entries of the table.
The product of 228,146 numbers below 1 is astronomically small, so work with logs instead:
- log is monotonic, so maximising the log of the likelihood is the same as maximising the likelihood;
- log(1) = 0, and log of a tiny probability is a large negative number;
- the log of a product is the sum of the logs: log(a·b·c) = log a + log b + log c.
The chain of equivalences
Karpathy writes these in the notebook. They are all the same optimisation problem:
- maximise the likelihood of the data with respect to the model’s parameters;
- maximise the log likelihood (log is monotonic);
- minimise the negative log likelihood (so that “lower is better”, like a loss);
- minimise the average negative log likelihood (so the number doesn’t grow with dataset size).
Computing it
log_likelihood = 0.0
n = 0
for w in words:
chs = ['.'] + list(w) + ['.']
for ch1, ch2 in zip(chs, chs[1:]):
prob = P[stoi[ch1], stoi[ch2]]
log_likelihood += torch.log(prob)
n += 1
nll = -log_likelihood
print(nll / n) # about 2.45
| Model | Average NLL (nats per character) |
|---|---|
| Uniform guess, −log(1/27) | 3.296 |
| Bigram counts, no smoothing | 2.454 |
| Bigram counts, +1 smoothing | 2.455 |
The saved notebook prints 2.4765 for this cell. Its grad_fn shows the cell was re-run after P had been overwritten by the neural net’s probabilities, so don’t be surprised by the mismatch.
The “andrejq” problem
You can score any single name the same way. “andrej” averages about 3.04, worse than typical, because the bigram “ej” is rare. But “andrejq” scores infinity. The bigram “jq” never occurs in the data, so P = 0, and log(0) = −∞. One impossible pair makes the whole loss infinite.
Model smoothing with fake counts
The fix is to pretend every bigram was seen a few extra times before normalising:
P = (N + 1).float()
P /= P.sum(1, keepdim=True)
Now no probability is zero, and “andrejq” scores a finite 3.48. The number of fake counts controls how smooth the model is:
| Fake counts added | Average NLL on training data | Effect |
|---|---|---|
| 0 | 2.454 | Sharpest fit; unseen pairs are impossible |
| 1 | 2.455 | Karpathy’s choice: no zeros, barely any cost |
| 5 | 2.458 | Smoother |
| 100 | 2.538 | Heavily smoothed, drifting towards uniform |
The more you add, the closer every row gets to uniform. Remember this dial: Part 9 shows the neural net has exactly the same one, called regularisation.
Part 6 — The neural-net approach: data and one-hot inputs
The second half rebuilds the same bigram model as a neural net. It takes one character in and puts a probability for each of the 27 possible next characters out. The weights are tuned by gradient descent to minimise the same average negative log likelihood. First, the data has to be put into a form a net can eat.
The plan
- Input: one character (as an integer index).
- Output: 27 probabilities for the next character.
- Loss: average negative log likelihood of the correct next characters, exactly as in Part 5.
- Training: compute the loss, backprop to get the gradient for every weight, nudge the weights, repeat. This is the micrograd loop.
The training set of bigrams (x, y)
xs, ys = [], []
for w in words[:1]: # just 'emma' to start
chs = ['.'] + list(w) + ['.']
for ch1, ch2 in zip(chs, chs[1:]):
xs.append(stoi[ch1]) # input: current character
ys.append(stoi[ch2]) # label: the character that follows
xs = torch.tensor(xs)
ys = torch.tensor(ys)
| Example | Bigram | x (input) | y (label) |
|---|---|---|---|
| 1 | . → e | 0 | 5 |
| 2 | e → m | 5 | 13 |
| 3 | m → m | 13 | 13 |
| 4 | m → a | 13 | 1 |
| 5 | a → . | 1 | 0 |
So xs = tensor([0, 5, 13, 13, 1]) and ys = tensor([5, 13, 13, 1, 0]). Over all the names there are 228,146 of these pairs.
torch.tensor vs torch.Tensor. Lowercase torch.tensor infers the dtype from the data, giving integers here. Capital torch.Tensor always gives float32. Karpathy recommends the lowercase one and notes the docs are confusing on the difference.
One-hot encoding
You can’t sensibly feed the integer 13 into a neuron. Multiplying it by a weight would imply that “m” is somehow 13 times “a”. Instead, encode each index as a vector of 27 zeros with a single 1 at that index:
import torch.nn.functional as F
xenc = F.one_hot(xs, num_classes=27).float()
xenc.shape # torch.Size([5, 27])
# row 0 has its 1 at position 0 ('.'), row 1 at position 5 ('e'), ...
- Pass
num_classes=27explicitly. Otherwiseone_hotguesses the size from the largest index it sees. one_hotreturns int64, so call.float(): the net needs real numbers that can be multiplied by weights and receive gradients.plt.imshow(xenc)shows five rows, each with one bright pixel. It’s a quick way to sanity-check the encoding.
Part 7 — One linear layer, then softmax
The whole “neural net” is one matrix multiply: logits = xenc @ W with W of shape 27 × 27. Its outputs are read as log-counts. Exponentiate them to get counts, then normalise each row to get probabilities. Those last two steps together are the softmax.
W is the only thing training changes; everything after the matrix multiply is a fixed recipe for turning numbers into probabilities and a loss.
A layer of neurons is a matrix multiply
Start with one neuron with 27 weights:
W = torch.randn((27, 1)) # 27 inputs -> 1 neuron, weights drawn from a standard normal
xenc @ W # (5, 27) @ (27, 1) -> (5, 1)
@ is matrix multiplication in PyTorch. One call evaluates that neuron on all 5 inputs in parallel: each entry is the dot product of one input row with the weight column.
Now use 27 neurons, one per possible next character:
W = torch.randn((27, 27))
xenc @ W # (5, 27) @ (27, 27) -> (5, 27)
Entry [i, j] is neuron j’s output on example i, which is the dot product of xenc[i] with column W[:, j]. There is no bias and no nonlinearity. It’s the simplest network there is.
Turning outputs into probabilities
The outputs are arbitrary real numbers, positive and negative. They aren’t probabilities, and they aren’t counts either (counts are positive). The trick is to interpret them:
- logits = the raw outputs, read as log-counts;
- counts =
logits.exp(): exponentiating makes everything positive, like the entries of N; - probs = counts normalised per row, so each row sums to 1, like P.
logits = xenc @ W # log-counts
counts = logits.exp() # equivalent to N
probs = counts / counts.sum(1, keepdim=True) # equivalent to P
# the last two lines together are a 'softmax'
probs.shape # torch.Size([5, 27])
probs[0].sum() # tensor(1.)
Softmax takes any vector of real numbers and turns it into a probability distribution. Big logits become big probabilities, and every probability is positive. Every operation here (matmul, exp, sum, divide) is differentiable, so gradients can flow back to W.
Scoring the random network
With random W, look at what probability the net gives the correct next character for each of the five “emma” bigrams, then take −log of each and average. A random init gives the right answers only a percent or two, so the loss starts around 3.7. That’s worse than the uniform guess’s 3.30.
You could re-seed W and keep whichever random draw scores best. Karpathy calls that “amateur hour”. The real method is gradient descent.
The link back to micrograd
This is the same loop as in the micrograd lecture: forward pass, loss, backward(), update. Three things differ:
| micrograd | makemore bigram net | |
|---|---|---|
| Inputs | A few real numbers | One-hot vectors of length 27 |
| Network | MLP of tanh neurons, built from scalar Values | One linear layer (27 neurons), then softmax |
| Loss | Squared error (regression-style) | Negative log likelihood (classification) |
| Engine | Our own Value autograd | PyTorch tensors and autograd |
Part 8 — Training it: vectorised loss, backward, update
With a one-line loss, W.grad = None, loss.backward() and W.data += -lr * W.grad, the net trains on all 228,146 bigrams. With a learning rate of 50 it reaches a loss of about 2.46–2.48, the same as counting.
Vectorised loss with torch.arange
For each example i, you need probs[i, ys[i]], the probability given to the correct next character. Indexing with two tensors plucks out exactly those entries in one go:
probs[torch.arange(5), ys] # [probs[0, 5], probs[1, 13], probs[2, 13], probs[3, 1], probs[4, 0]]
loss = -probs[torch.arange(5), ys].log().mean()
Pluck the correct-class probabilities, take the log, average, and negate. That is the average negative log likelihood from Part 5, now over a batch.
Backward and update in PyTorch
g = torch.Generator().manual_seed(2147483647)
W = torch.randn((27, 27), generator=g, requires_grad=True) # tell PyTorch to track W
# forward pass
xenc = F.one_hot(xs, num_classes=27).float()
logits = xenc @ W
counts = logits.exp()
probs = counts / counts.sum(1, keepdim=True)
loss = -probs[torch.arange(5), ys].log().mean()
# backward pass
W.grad = None # reset the gradient (None is treated as zero, and is cheaper)
loss.backward() # fills W.grad, same shape as W: 27 x 27
# update
W.data += -0.1 * W.grad
requires_grad=Trueis needed on leaf tensors you want gradients for. PyTorch then records every operation in the forward pass, just like micrograd’s_prevand_op.W.gradhas one entry per weight. Each says how much nudging that weight would change the loss.W.grad = Noneis PyTorch’s version of zero_grad. Forgetting it makes gradients pile up across steps, exactly the micrograd bug.
On the five “emma” examples, each step lowers the loss a little: about 3.76, then 3.74, then 3.72.
Putting it all together on the full dataset
# dataset: all 228,146 bigrams
xs, ys = [], []
for w in words:
chs = ['.'] + list(w) + ['.']
for ch1, ch2 in zip(chs, chs[1:]):
xs.append(stoi[ch1])
ys.append(stoi[ch2])
xs = torch.tensor(xs)
ys = torch.tensor(ys)
num = xs.nelement()
# the 'network'
g = torch.Generator().manual_seed(2147483647)
W = torch.randn((27, 27), generator=g, requires_grad=True)
# gradient descent
for k in range(100):
# forward
xenc = F.one_hot(xs, num_classes=27).float()
logits = xenc @ W
counts = logits.exp()
probs = counts / counts.sum(1, keepdim=True)
loss = -probs[torch.arange(num), ys].log().mean()
print(loss.item())
# backward
W.grad = None
loss.backward()
# update
W.data += -50 * W.grad
- The code is identical to the five-example version. Only the data got bigger.
- Learning rate 50 sounds huge, but this problem is very simple: a single linear layer under softmax with NLL is a convex optimisation, so big steps don’t blow it up. A rate of 0.1 barely moves the loss on the full data.
- After 100 steps Karpathy is at about 2.47, and after another 100 at about 2.46. The count model scored about 2.45.
Why it can’t do better than counting
Both models see exactly the same information: the previous character and nothing else. Counting gives the best possible table directly. Gradient descent can only rediscover it. The neural net’s advantage shows up only when the input grows, for example to several previous characters. A count table for that explodes in size, but a neural net handles it gracefully. Every later model in the series changes only the forward pass. The logits, softmax, NLL loss and gradient-descent loop all stay.
Part 9 — Two notes that tie the halves together
The net and the count table are the same model in different clothes. A one-hot input times W simply picks out one row of W, and that row holds log-counts. Adding fake counts is the same thing as a penalty that pulls W towards zero.
Note 1: one-hot × W selects a row
Multiply a one-hot vector by a matrix and every term vanishes except one. What’s left is the matching row of the matrix:
So for input character x, the logits are just row x of W. Compare the two models side by side:
| Step | Count model | Neural net |
|---|---|---|
| Look up by current character x | Row N[x] | Row W[x] (via one-hot @ W) |
| Make positive “counts” | Already counts | W[x].exp() |
| Normalise | N[x] / N[x].sum() | exp(W[x]) / exp(W[x]).sum() |
So W.exp() plays the role of N, which means W is the log of the counts, up to a constant per row. Counting fills that table in directly. Gradient descent arrives at essentially the same table, one small step at a time, guided only by the loss.
This also explains why later models replace the one-hot matmul with a direct lookup (C[x], an embedding table). It’s the same operation without multiplying by a pile of zeros.
Note 2: smoothing is regularisation
What would make the net output a uniform distribution? If W is all zeros, every logit is 0. Every count is e⁰ = 1, and every probability is 1/27. So pulling W towards zero pulls the model towards uniform. That’s exactly what fake counts did.
Add that pull to the loss as a regularisation term:
loss = -probs[torch.arange(num), ys].log().mean() + 0.01 * (W**2).mean()
- Squaring makes the penalty ignore sign and hit large weights hardest. The mean keeps it on a sensible scale.
- The two terms pull against each other. The data term wants W to match the bigram statistics. The penalty acts like a spring or gravity pulling every weight back to 0.
- λ is the fake-count dial. λ = 0 means no smoothing. Larger λ gives smoother, more uniform predictions. Too large, and the weights can’t grow at all, so the model just predicts uniform.
In an independent re-run (λ = 0.01, learning rate 50, 200 steps), the trained net’s probabilities came within 0.05 of the +1-smoothed count table in every cell.
Part 10 — Sampling from the net, and what comes next
Sampling from the trained net uses the same loop as before. Only the line that produces the probability row changes, and with the same seed it produces the same names as the count model. Two very differently built models turn out to be one model.
Sampling from the neural net
g = torch.Generator().manual_seed(2147483647)
for i in range(5):
out = []
ix = 0
while True:
# BEFORE: p = P[ix]
# NOW:
xenc = F.one_hot(torch.tensor([ix]), num_classes=27).float()
logits = xenc @ W
counts = logits.exp()
p = counts / counts.sum(1, keepdim=True)
ix = torch.multinomial(p, num_samples=1, replacement=True, generator=g).item()
out.append(itos[ix])
if ix == 0:
break
print(''.join(out))
The output is mor., axx., minaymoryles., kondlaisah., anch…izarie.: the same names as the count model. (In the saved notebook, one letter of the last name differs, because the two probability tables aren’t bit-for-bit identical.)
The real makemore repo
makemore.py is one hackable file. Pick a model with --type bigram|mlp|rnn|gru|bow|transformer; the default is a small Transformer. Its Bigram class is exactly this lecture, distilled:
class Bigram(nn.Module):
def __init__(self, config):
super().__init__()
n = config.vocab_size
self.logits = nn.Parameter(torch.zeros((n, n))) # the 27 x 27 table, starting at zero (uniform)
def forward(self, idx, targets=None):
logits = self.logits[idx] # Note 1: just a row lookup
loss = None
if targets is not None:
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
return logits, loss
- Row lookup, not one-hot @ W.
self.logits[idx]is the efficient form of the same operation (Part 9, Note 1). - Zero init starts the model at the uniform distribution.
F.cross_entropyfuses the softmax and the negative log likelihood into one call. It is more efficient and numerically safer than doing exp, normalise and log by hand.
To train any model on any one-item-per-line file: python makemore.py -i names.txt -o names.
Conclusion
The lecture introduced the character-level bigram language model and did four things with it:
- trained it, two ways: by counting and normalising, and by gradient descent on a one-layer net;
- sampled new names from it;
- evaluated it with the average negative log likelihood;
- smoothed it, with fake counts or the equivalent weight penalty.
Both training routes give the same model, about 2.45 nats per character. The gradient-based route is the one that scales.
Where the series goes next
The next lectures feed more previous characters into bigger networks: an MLP next (following Bengio et al. 2003), and later RNNs and finally a Transformer. A count table can’t keep up, because the number of possible contexts explodes with every extra character of context. Through all of it, the net still outputs logits, softmax still turns them into probabilities, the loss is still negative log likelihood, and training is still forward, backward, update. Only the network in the middle grows.
Cheat sheet
The whole lecture on one screen: shapes, the PyTorch calls it introduces, broadcasting, the bugs to avoid, and the vocabulary.
Tensor shapes (n = number of examples)
| Name | Shape | What it holds |
|---|---|---|
N | 27 × 27 | Bigram counts: row = current char, column = next char |
P | 27 × 27 | Row-normalised probabilities, each row summing to 1 |
xs, ys | n | Integer indices of input and next character (n = 228,146 for all names) |
xenc | n × 27 | One-hot encoded inputs (float) |
W | 27 × 27 | Weights of 27 neurons, each taking 27 inputs |
logits | n × 27 | xenc @ W, read as log-counts |
counts | n × 27 | logits.exp(), the counterpart of N |
probs | n × 27 | Row-normalised counts (the softmax output) |
probs[torch.arange(n), ys] | n | Probability given to the correct next character |
loss | scalar | Average negative log likelihood (+ regularisation) |
PyTorch calls introduced
| Call | Does |
|---|---|
torch.zeros((27, 27), dtype=torch.int32) | Make an all-zero tensor of a given shape and type |
t[i, j] += 1 / t[i] / t[:, j] | Index a cell / a row / a column |
t.item() | Convert a one-element tensor to a Python number |
t.float() | Cast to float32 |
t.sum(dim, keepdim=True) | Sum along one axis, keeping it as size 1 |
torch.Generator().manual_seed(s) | A reproducible random number source |
torch.multinomial(p, n, replacement=True, generator=g) | Draw indices according to probabilities p |
torch.tensor(list) vs torch.Tensor(list) | Infer the dtype vs always float32 |
F.one_hot(xs, num_classes=27) | One-hot encode integer indices (returns int64) |
A @ B | Matrix multiply |
t.exp(), t.log(), t.mean() | Element-wise exp and log; average |
torch.randn((27, 27), generator=g, requires_grad=True) | Random normal weights that PyTorch tracks for gradients |
W.grad = None / loss.backward() | Reset the gradient / backprop |
W.data += -lr * W.grad | Gradient descent step |
F.cross_entropy(logits, targets) | Softmax + NLL in one efficient call (used in makemore.py) |
Broadcasting in one rule
Align shapes from the right. Each pair of dimensions must be equal, or one of them must be 1, or one must be missing; size-1 and missing dimensions are stretched.
- (27, 27) / (27, 1) → each row divided by its own total. ✔
- (27, 27) / (27) → treated as (1, 27), so each column is divided instead. ✘ Silent bug.
Common bugs
| Bug | Symptom | Fix |
|---|---|---|
Dropping keepdim=True when normalising | Rows don’t sum to 1 (row 0 sums to 6.92); no error | P.sum(1, keepdim=True), then assert the row sums |
multinomial without replacement=True | Can’t draw the same character twice | Pass replacement=True |
| No smoothing | Infinite loss on any unseen bigram (“andrejq”) | Fake counts, or a W² penalty |
| Feeding raw integers to the net | Meaningless arithmetic on character IDs | One-hot (or an embedding lookup) |
Forgetting .float() after one_hot | dtype errors in the matmul | F.one_hot(...).float() |
one_hot without num_classes | Wrong width if the largest index is missing | num_classes=27 |
| Not resetting the gradient | Gradients accumulate across steps | W.grad = None before backward() |
| Learning rate too small for the problem | Loss barely moves | Try much larger rates; here 50 works |
Glossary
| Term | Meaning |
|---|---|
| Language model | A model that assigns probabilities to the next token, given the previous ones |
| Character-level | Tokens are single characters |
| Bigram | A pair of consecutive tokens; a bigram model conditions on just one previous token |
Special token . | Marks both the start and the end of a name |
| stoi / itos | Lookup tables from string to integer and integer to string |
| Likelihood | Product of the probabilities the model gives the observed data |
| Negative log likelihood (NLL) | −Σ log p; averaged over examples, it is the loss here (lower is better, 0 is perfect) |
| Maximum likelihood estimation | Choosing parameters that make the observed data most probable |
| Smoothing | Adding fake counts so no probability is exactly zero |
| One-hot encoding | A vector of zeros with a single 1 at the item’s index |
| Logits | Raw network outputs, read as log-counts |
| Softmax | exp, then normalise: turns logits into probabilities |
| Regularisation | An extra loss term (here λ·mean(W²)) that pulls the weights towards simpler solutions |
| Broadcasting | PyTorch’s rule for combining tensors of different shapes |
Self-check and exercises
If you can answer these without scrolling up, you’ve got the lecture. Answers are below the questions.
Questions
- How many training examples does the name “emma” give a bigram model, and what are they?
- Why replace
<S>and<E>with a single.token? - What goes wrong if you call
torch.multinomialwithoutreplacement=True? - What are the shapes of
P.sum(1)andP.sum(1, keepdim=True)? Which one gives a correctP / ..., and what does the other one silently do? - Why maximise the log likelihood instead of the likelihood itself?
- A model that predicts every character with probability 1/27 has what loss, and why?
- Why does “andrejq” get an infinite loss under the raw count model? Name two fixes.
- Why one-hot encode a character instead of feeding its index straight into the net?
- What is
F.one_hot(x, 27).float() @ Wequal to, in one phrase? - After training, what do the entries of W represent?
- How is the penalty λ·mean(W²) like adding fake counts? What happens as λ grows very large?
- Why can’t the gradient-trained net beat the count model’s loss of about 2.45?
Answers
- Five:
.e,em,mm,ma,a.. - With separate tokens, the
<E>row and the<S>column are all zeros (nothing follows the end, nothing precedes the start). One token at index 0 removes the waste: 27 × 27, where row 0 holds the first letters and column 0 the endings. - Its default is
replacement=False, which never returns the same index twice. Sampling characters needs repeats. - (27,) and (27, 1). The (27, 1) version divides each row by its own sum. The (27,) version is broadcast as (1, 27), so each column gets divided by a row’s sum. Rows stop summing to 1 (row 0 sums to 6.92), and there’s no error.
- The likelihood is a product of 228,146 numbers below 1, far too tiny to work with. The log turns the product into a sum, and because log is monotonic, the best parameters stay the same.
- −ln(1/27) = ln 27 ≈ 3.296, because every correct character gets probability 1/27.
- “jq” never appears in the data, so P = 0 and log 0 = −∞. Fixes: add fake counts (N + 1), or, for the net, regularise W towards 0.
- A raw index has no meaningful size: “m” (13) isn’t 13 times “a” (1). One-hot gives every character its own independent input.
- Row x of W.
- Log-counts.
W.exp()is (up to a scale per row) the bigram count table. - W = 0 gives a uniform distribution, so pulling W towards 0 pulls the model towards uniform, just as fake counts do. As λ → ∞, W is forced to 0 and the model predicts uniform.
- It sees the same information, one previous character, and the count table is already the optimal answer for that. Gradient descent can only find the same table.
Exercises
- Trigram model (Karpathy’s E01): use two previous characters to predict the third, by counting or with a net. Does the loss beat 2.45?
- Split the names 80/10/10 into train/dev/test, and report the loss on each for the bigram and trigram models.
- Tune the smoothing strength (fake counts or λ) on the dev set, and see how the dev loss changes.
- Delete
F.one_hotand index rows of W directly (W[xs]). Check that the loss is identical. - Replace the hand-written softmax and NLL with
F.cross_entropy(logits, ys), and explain why it’s preferable. - Re-introduce the keepdim bug on purpose and sample from the broken P. Can you spot the damage by eye?
- Visualise
W.exp()after training, normalised by row, next toPfrom counting.
Sources
- The spelled-out intro to language modeling: building makemore (Andrej Karpathy, YouTube)
- karpathy/makemore: README,
makemore.py(theBigramclass) andnames.txt - Lecture notebook: makemore_part1_bigrams.ipynb
- Video transcript with chapter timestamps
- Exercise E01 wording (trigram model)