sidd.

makemore Lecture 1: Bigrams

· 37 min read · Work

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:

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: countingPart B: neural net
Parameters27 × 27 table of bigram counts N27 × 27 weight matrix W
How it is “trained”Count every bigram, then normalise each rowGradient descent on the average negative log likelihood
ProbabilitiesP = N / row sumssoftmax(one_hot(x) @ W)
SmoothingAdd 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

TimeChapter in the videoNotes section
0:00IntroOverview
3:03Reading and exploring the datasetPart 1
6:24Exploring the bigrams in the datasetPart 2
9:24Counting bigrams in a Python dictionaryPart 2
12:45Counting bigrams in a 2D torch tensor (“training the model”)Part 2
18:19Visualising the bigram tensorPart 2
20:54Replacing the start and end tokens with a single . tokenPart 2
24:02Sampling from the modelPart 3
36:17Vectorised normalisation of the rows, tensor broadcastingPart 4
50:14Loss function: negative log likelihood of the dataPart 5
1:00:50Model smoothing with fake countsPart 5
1:02:57Part 2 of the lecture: the neural-network approachPart 6
1:05:26Creating the bigram dataset for the neural netPart 6
1:10:01Feeding integers into neural nets: one-hot encodingsPart 6
1:13:53One linear layer of neurons as a matrix multiplyPart 7
1:18:46Turning outputs into probabilities: the softmaxPart 7
1:26:17Summary, preview of next steps, link to microgradPart 7
1:35:49Vectorised lossPart 8
1:38:36Backward and update, in PyTorchPart 8
1:42:55Putting everything togetherPart 8
1:47:49Note 1: one-hot encoding just selects a row of WPart 9
1:50:18Note 2: model smoothing as a regularisation lossPart 9
1:54:31Sampling from the neural netPart 10
1:56:16ConclusionPart 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:

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
RankBigramCountReading
1n → end6,763Lots of names end in n
2a → end6,640…and in a
3a → n5,438“an” is everywhere
4start → a4,410a is the most common first letter
5e → end3,983
6a → r3,264
7e → l3,248
8r → i3,033
9n → a2,977
10start → k2,963k 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:

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:

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:

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'

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:

CallResult shapeWhat it is
P.sum(0, keepdim=True)1 × 27Column totals (summed down the rows)
P.sum(1, keepdim=True)27 × 1Row totals, kept as a column vector
P.sum(1)27Row 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.

keepdim decides which way the row totals get stretched Broadcasting aligns shapes from the right; size-1 or missing dimensions are copied to fit keepdim=True: totals are (27, 1) P 27 row totals Copied across the columns: each row ÷ its own total Every row sums to 1 ✔ keepdim dropped: (27,) acts as (1, 27) P 27 row totals, laid flat Copied down the rows: column j ÷ row j’s total Row 0 sums to 6.92, no error ✘
broadcasting · P / P.sum(1, keepdim=True) vs P / P.sum(1)

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

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 likelihood=∑i=1nlog⁡P(ci+1∣ci),loss=−1n∑i=1nlog⁡P(ci+1∣ci)\text{log likelihood} = \sum_{i=1}^{n} \log P(c_{i+1} \mid c_i), \qquad \text{loss} = -\frac{1}{n}\sum_{i=1}^{n} \log P(c_{i+1} \mid c_i)

The chain of equivalences

Karpathy writes these in the notebook. They are all the same optimisation problem:

  1. maximise the likelihood of the data with respect to the model’s parameters;
  2. maximise the log likelihood (log is monotonic);
  3. minimise the negative log likelihood (so that “lower is better”, like a loss);
  4. 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
ModelAverage NLL (nats per character)
Uniform guess, −log(1/27)3.296
Bigram counts, no smoothing2.454
Bigram counts, +1 smoothing2.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 addedAverage NLL on training dataEffect
02.454Sharpest fit; unseen pairs are impossible
12.455Karpathy’s choice: no zeros, barely any cost
52.458Smoother
1002.538Heavily 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

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)
ExampleBigramx (input)y (label)
1. → e05
2e → m513
3m → m1313
4m → a131
5a → .10

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'), ...

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.

The bigram net: one-hot in, one matrix multiply, softmax out Shapes for one example; a batch of n examples just stacks n rows one_hot @ W exp ÷ row sum Input x = 5 (e) an integer One-hot 1 × 27 a single 1 Logits 1 × 27 log-counts Counts 1 × 27 all positive Probs 1 × 27 sums to 1 softmax W 27 × 27 weights the only parameters Loss −log p[y] averaged
bigram neural net · forward pass from character to loss

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:

  1. logits = the raw outputs, read as log-counts;
  2. counts = logits.exp(): exponentiating makes everything positive, like the entries of N;
  3. 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(z)j=ezj∑k=127ezk\text{softmax}(z)_j = \frac{e^{z_j}}{\sum_{k=1}^{27} e^{z_k}}

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.

This is the same loop as in the micrograd lecture: forward pass, loss, backward(), update. Three things differ:

microgradmakemore bigram net
InputsA few real numbersOne-hot vectors of length 27
NetworkMLP of tanh neurons, built from scalar ValuesOne linear layer (27 neurons), then softmax
LossSquared error (regression-style)Negative log likelihood (classification)
EngineOur own Value autogradPyTorch 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

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

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:

one_hot(x) W=W[x, :]\text{one\_hot}(x)\,W = W[x,\,:]

So for input character x, the logits are just row x of W. Compare the two models side by side:

StepCount modelNeural net
Look up by current character xRow N[x]Row W[x] (via one-hot @ W)
Make positive “counts”Already countsW[x].exp()
NormaliseN[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()
L=−1n∑ilog⁡pi⏟fit the data+λ⋅mean(W2)⏟keep W near 0,λ=0.01\mathcal{L} = \underbrace{-\frac{1}{n}\sum_i \log p_i}_{\text{fit the data}} + \underbrace{\lambda \cdot \text{mean}(W^2)}_{\text{keep } W \text{ near } 0}, \qquad \lambda = 0.01

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

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:

  1. trained it, two ways: by counting and normalising, and by gradient descent on a one-layer net;
  2. sampled new names from it;
  3. evaluated it with the average negative log likelihood;
  4. 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)

NameShapeWhat it holds
N27 × 27Bigram counts: row = current char, column = next char
P27 × 27Row-normalised probabilities, each row summing to 1
xs, ysnInteger indices of input and next character (n = 228,146 for all names)
xencn × 27One-hot encoded inputs (float)
W27 × 27Weights of 27 neurons, each taking 27 inputs
logitsn × 27xenc @ W, read as log-counts
countsn × 27logits.exp(), the counterpart of N
probsn × 27Row-normalised counts (the softmax output)
probs[torch.arange(n), ys]nProbability given to the correct next character
lossscalarAverage negative log likelihood (+ regularisation)

PyTorch calls introduced

CallDoes
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 @ BMatrix 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.gradGradient 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.

Common bugs

BugSymptomFix
Dropping keepdim=True when normalisingRows don’t sum to 1 (row 0 sums to 6.92); no errorP.sum(1, keepdim=True), then assert the row sums
multinomial without replacement=TrueCan’t draw the same character twicePass replacement=True
No smoothingInfinite loss on any unseen bigram (“andrejq”)Fake counts, or a W² penalty
Feeding raw integers to the netMeaningless arithmetic on character IDsOne-hot (or an embedding lookup)
Forgetting .float() after one_hotdtype errors in the matmulF.one_hot(...).float()
one_hot without num_classesWrong width if the largest index is missingnum_classes=27
Not resetting the gradientGradients accumulate across stepsW.grad = None before backward()
Learning rate too small for the problemLoss barely movesTry much larger rates; here 50 works

Glossary

TermMeaning
Language modelA model that assigns probabilities to the next token, given the previous ones
Character-levelTokens are single characters
BigramA 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 / itosLookup tables from string to integer and integer to string
LikelihoodProduct 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 estimationChoosing parameters that make the observed data most probable
SmoothingAdding fake counts so no probability is exactly zero
One-hot encodingA vector of zeros with a single 1 at the item’s index
LogitsRaw network outputs, read as log-counts
Softmaxexp, then normalise: turns logits into probabilities
RegularisationAn extra loss term (here λ·mean(W²)) that pulls the weights towards simpler solutions
BroadcastingPyTorch’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

  1. How many training examples does the name “emma” give a bigram model, and what are they?
  2. Why replace <S> and <E> with a single . token?
  3. What goes wrong if you call torch.multinomial without replacement=True?
  4. What are the shapes of P.sum(1) and P.sum(1, keepdim=True)? Which one gives a correct P / ..., and what does the other one silently do?
  5. Why maximise the log likelihood instead of the likelihood itself?
  6. A model that predicts every character with probability 1/27 has what loss, and why?
  7. Why does “andrejq” get an infinite loss under the raw count model? Name two fixes.
  8. Why one-hot encode a character instead of feeding its index straight into the net?
  9. What is F.one_hot(x, 27).float() @ W equal to, in one phrase?
  10. After training, what do the entries of W represent?
  11. How is the penalty λ·mean(W²) like adding fake counts? What happens as λ grows very large?
  12. Why can’t the gradient-trained net beat the count model’s loss of about 2.45?

Answers

  1. Five: .e, em, mm, ma, a..
  2. 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.
  3. Its default is replacement=False, which never returns the same index twice. Sampling characters needs repeats.
  4. (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.
  5. 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.
  6. −ln(1/27) = ln 27 ≈ 3.296, because every correct character gets probability 1/27.
  7. “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.
  8. A raw index has no meaningful size: “m” (13) isn’t 13 times “a” (1). One-hot gives every character its own independent input.
  9. Row x of W.
  10. Log-counts. W.exp() is (up to a scale per row) the bigram count table.
  11. 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.
  12. 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

Sources