makemore Lecture 2: MLP
Overview
This lecture replaces the bigram model with a small multi-layer perceptron (MLP), following Bengio et al. 2003. It looks at the previous three characters, embeds each as a learned vector, and predicts the next one. On held-out names the loss drops from the bigram’s 2.45 to 2.17. Along the way Karpathy introduces the everyday basics of training: minibatches, learning-rate search, train/dev/test splits, and under- versus overfitting.
Why the bigram model can’t just be extended. To condition on more context with a count table, you need a row for every possible context. There are 27 contexts of one character, 729 of two and 19,683 of three, and the table explodes. Most contexts then have few or no counts, so the estimates become useless. A neural net sidesteps this by learning a compact function of the context instead of memorising a table.
The model in one line. Look up a learned vector (an embedding) for each of the 3 context characters, concatenate them, pass them through a tanh hidden layer, then a linear output layer giving 27 logits. Softmax and negative log likelihood turn those into a loss, exactly as in Lecture 1.
What carries over from Lecture 1: characters ↔ integers, the . token, (input → next character) training pairs, logits → softmax → NLL loss, and the forward / backward / update loop.
What’s new
- Embeddings: a learned lookup table C that places every character as a point in a small vector space.
- A real hidden layer with a tanh nonlinearity, and tensor plumbing (
view, indexing with tensors). F.cross_entropy: the fused, numerically safe softmax + NLL.- Minibatch stochastic gradient descent.
- Finding a learning rate, and decaying it late in training.
- Train / dev / test splits to measure generalisation and detect overfitting.
- Hyperparameter experiments: hidden layer size and embedding size.
Where the lecture ends up
| Bigram (Lecture 1) | MLP (this lecture, final) | |
|---|---|---|
| Context | 1 character | 3 characters |
| Parameters | 729 | 11,897 |
| Loss | ≈ 2.45 (training set) | 2.13 train / 2.17 dev |
Chapter map
| Time | Chapter in the video | Notes section |
|---|---|---|
| 0:00 | Intro | Overview |
| 1:48 | Bengio et al. 2003 (MLP language model) paper walkthrough | Part 1 |
| 9:03 | (Re-)building the training dataset | Part 2 |
| 12:19 | Implementing the embedding lookup table | Part 3 |
| 18:35 | The hidden layer + internals of torch.Tensor: storage, views | Part 4 |
| 29:15 | Implementing the output layer | Part 5 |
| 29:53 | Implementing the negative log likelihood loss | Part 5 |
| 32:17 | Summary of the full network | Part 5 |
| 32:49 | Introducing F.cross_entropy, and why | Part 5 |
| 37:56 | The training loop; overfitting one batch | Part 6 |
| 41:25 | Training on the full dataset; minibatches | Part 6 |
| 45:40 | Finding a good initial learning rate | Part 7 |
| 53:20 | Splitting the dataset into train/val/test, and why | Part 8 |
| 1:00:49 | Experiment: larger hidden layer | Part 9 |
| 1:05:27 | Visualising the character embeddings | Part 9 |
| 1:07:16 | Experiment: larger embedding size | Part 9 |
| 1:11:46 | Summary of the final code; conclusion | Part 10 |
| 1:13:24 | Sampling from the model | Part 10 |
| 1:14:55 | Google Colab notebook | Part 10 |
Code follows Karpathy’s lecture notebook (makemore_part2_mlp.ipynb). Dataset sizes and parameter counts were re-computed to check them.
Part 1 — The Bengio et al. 2003 paper
The model comes from A Neural Probabilistic Language Model (Bengio, Ducharme, Vincent and Jauvin, 2003). Its key move: give every token a small learned vector, an embedding. Then predict the next token with a neural net over the embeddings of the previous few tokens. Similar tokens end up with similar vectors, so knowledge transfers between them.
The setting in the paper
- Word-level, with a vocabulary of about 17,000 words. Karpathy applies the same recipe to characters (27 tokens).
- Each word gets a 30-dimensional embedding, initialised randomly.
- During training, backprop moves the embeddings around. Words that behave alike drift close together, and unrelated words drift apart.
Why embeddings generalise
Suppose the exact phrase “a dog was running in a ___” never appears in the training data. A count table has nothing to say about it. But the training data might contain “the dog was running in a” and “a cat was running in a”. If the net has learned that “a” and “the” are interchangeable, and that “dog” and “cat” behave alike, those words sit near each other in embedding space. The prediction then transfers to the unseen phrase. Embeddings let the model fill in sentences it has never seen.
The architecture
- Take the indices of the 3 previous words.
- Look each one up in a shared embedding table C (17,000 × 30). The same table serves every position, so 3 lookups give 3 × 30 = 90 numbers, concatenated.
- Feed them to a fully connected hidden layer with a tanh nonlinearity. Its size is a hyperparameter, for example 100 neurons.
- Feed that to the output layer, with one neuron per vocabulary word: 17,000 logits. This is the most expensive part of the network.
- Softmax turns the logits into a probability distribution over the next word.
The same table C embeds every context position; the new idea versus Lecture 1 is that characters become learned vectors before any layer sees them.
Training maximises the log likelihood of the actual next word, the same objective as Lecture 1. Every parameter is learned jointly by backprop: the embedding table C, the hidden weights and biases, and the output weights and biases.
The character-level version built here
| Bengio et al. 2003 | This lecture | |
|---|---|---|
| Tokens | ~17,000 words | 27 characters |
| Context | 3 previous words | 3 previous characters (block_size = 3) |
| Embedding size | 30 | 2 at first, 10 in the final model |
| Hidden layer | e.g. 100, tanh | 100 → 300 → 200 tanh neurons, across experiments |
| Output | 17,000-way softmax | 27-way softmax |
Part 2 — Building the dataset with a context window
Every training example is now (the previous block_size characters → the next character). A window slides along each name, padded on the left with . tokens. With block_size = 3, all the names together give 228,146 examples, the same count as the bigrams, but each input is now 3 integers instead of 1.
The code
# vocabulary, exactly as in Lecture 1
chars = sorted(list(set(''.join(words))))
stoi = {s: i+1 for i, s in enumerate(chars)}
stoi['.'] = 0
itos = {i: s for s, i in stoi.items()}
block_size = 3 # context length: how many characters predict the next one?
X, Y = [], []
for w in words:
context = [0] * block_size # start padded with '...'
for ch in w + '.':
ix = stoi[ch]
X.append(context) # input: the current window
Y.append(ix) # label: the character that follows
context = context[1:] + [ix] # crop the oldest, append the newest
X = torch.tensor(X)
Y = torch.tensor(Y)
What “emma” turns into
| Context (X) | → Next (Y) |
|---|---|
... | e |
..e | m |
.em | m |
emm | a |
mma | . |
- The first five names give 32 examples.
Xhas shape (32, 3) andYhas shape (32,), both integer tensors. - All 32,033 names give 228,146 examples.
block_sizeis a dial. Set it to 4, 5 or 10 and the same code builds longer contexts. The rest of the network adapts through the hyperparameters in Part 4.
An ambiguity you can’t learn away
The context ... (the start of a name) appears once per name, followed by a different letter each time. In the first five names it’s followed by e, o, a, i and s. No model can predict all of those with certainty, so the loss can never reach 0, even on data it has memorised. Part 6 comes back to this.
Part 3 — The embedding lookup table
The embedding table C is a 27 × d matrix with one row per character. Embedding a character means taking its row. C[X] embeds a whole batch of contexts at once, turning a (32, 3) tensor of indices into a (32, 3, 2) tensor of vectors.
Start small: 2 dimensions
C = torch.randn((27, 2)) # each of the 27 characters gets a random 2D vector
Two dimensions is tiny, but it keeps the numbers readable and lets you plot the embeddings later (Part 9).
Indexing and one-hot are the same thing
There are two ways to embed the integer 5:
C[5] # pluck out row 5
F.one_hot(torch.tensor(5), num_classes=27).float() @ C # one-hot times C
They give the identical vector. This is Lecture 1’s note again: a one-hot vector times a matrix selects a row. So you can think of the embedding as the first layer of the net, a linear layer with no bias and one-hot inputs. In practice, indexing is much faster, so the one-hot view is dropped.
Indexing with tensors
PyTorch indexing is very flexible. You can index with a list, a 1-D tensor, or a multi-dimensional integer tensor, and the output shape follows the index shape plus the row shape:
C[[5, 6, 7]] # shape (3, 2)
C[torch.tensor([5, 6, 7])] # same
C[torch.tensor([7, 7, 7])] # repeats are fine
emb = C[X] # X is (32, 3) -> emb is (32, 3, 2)
| Index | Shape | Meaning |
|---|---|---|
X | (32, 3) | 32 examples × 3 context characters (integers) |
C | (27, 2) | 27 characters × 2-D embedding |
C[X] | (32, 3, 2) | each of the 96 integers replaced by its 2-D vector |
A quick check: if X[13, 2] is 1, then C[X][13, 2] equals C[1]. The lookup is a single, fully vectorised operation over the batch.
Part 4 — The hidden layer, and how tensors really work
The hidden layer is h = torch.tanh(emb.view(-1, 6) @ W1 + b1). The interesting part is the reshape. view flattens each example’s three 2-D embeddings into one 6-number row without copying any memory, because a tensor is just a flat block of numbers plus metadata describing its shape.
The weights
W1 = torch.randn((6, 100)) # 6 inputs (3 characters x 2 dims) -> 100 neurons
b1 = torch.randn(100)
The number of neurons, 100, is a hyperparameter. The number of inputs, 6, is forced on us: block_size × embedding size.
The shape problem
emb is (32, 3, 2), but the matrix multiply needs (32, 6): one row per example, with the three embeddings side by side. There are three ways to get there.
1. Concatenate the slices by hand. It works, but it hard-codes block_size = 3:
torch.cat([emb[:, 0, :], emb[:, 1, :], emb[:, 2, :]], 1) # (32, 6)
2. unbind then cat. This works for any block size, but cat allocates a whole new tensor:
torch.cat(torch.unbind(emb, 1), 1) # (32, 6)
3. view. Best: free and general.
emb.view(32, 6) # (32, 6), no copy
All three give the same numbers, and (emb.view(32, 6) == torch.cat(torch.unbind(emb, 1), 1)).all() is True.
Why view is free: storage vs view
a = torch.arange(18)
a.view(2, 9) # fine
a.view(9, 2) # fine
a.view(3, 3, 2) # fine: any shape whose sizes multiply to 18
In memory, every tensor is a one-dimensional run of numbers, its storage. The shape you see is metadata on top: sizes, strides (how far to jump in storage to move one step along each dimension) and an offset. view only rewrites that metadata, so no data moves. Operations like cat must build a new storage. For more, Karpathy points to Edward Yang’s blog post PyTorch internals.
Don’t hard-code the batch size
h = torch.tanh(emb.view(-1, 6) @ W1 + b1) # (32, 100)
-1 tells view to infer that dimension from the others, so the code works for any batch size. emb.shape[0] would also work. tanh squashes every hidden activation into (−1, 1).
Check the broadcast
emb.view(-1, 6) @ W1 is (32, 100), and b1 is (100,). Aligning from the right, the 100s match, and the missing dimension becomes 1 and is stretched over the 32 rows. So the same bias vector is added to every example, which is exactly what we want. It’s worth checking every time you add a bias.
Part 5 — Output layer, loss, and F.cross_entropy
A second linear layer maps the 100 hidden activations to 27 logits. The loss is the same average negative log likelihood as Lecture 1, but it’s computed with F.cross_entropy(logits, Y). That call gives the same number while being faster, giving a simpler backward pass, and not blowing up on large logits.
The output layer
W2 = torch.randn((100, 27)) # 100 hidden -> 27 possible next characters
b2 = torch.randn(27)
logits = h @ W2 + b2 # (32, 27)
The loss, written out by hand
counts = logits.exp()
prob = counts / counts.sum(1, keepdim=True) # (32, 27), rows sum to 1
loss = -prob[torch.arange(32), Y].log().mean() # about 17 at random init
This is Lecture 1’s softmax and NLL, unchanged. The starting loss of about 17 is far worse than uniform guessing (3.30). Random weights make the logits large, so the net is confidently wrong. The next lecture deals with that.
The whole network, tidied up
g = torch.Generator().manual_seed(2147483647) # reproducible
C = torch.randn((27, 2), generator=g)
W1 = torch.randn((6, 100), generator=g)
b1 = torch.randn(100, generator=g)
W2 = torch.randn((100, 27), generator=g)
b2 = torch.randn(27, generator=g)
parameters = [C, W1, b1, W2, b2]
sum(p.nelement() for p in parameters) # 3481
| Tensor | Shape | Parameters |
|---|---|---|
| C (embeddings) | 27 × 2 | 54 |
| W1 | 6 × 100 | 600 |
| b1 | 100 | 100 |
| W2 | 100 × 27 | 2,700 |
| b2 | 27 | 27 |
| Total | 3,481 |
Why F.cross_entropy instead of doing it by hand
loss = F.cross_entropy(logits, Y) # same value as the three lines above
- Efficient forward pass. The manual version creates intermediate tensors (
counts,prob) in memory. PyTorch’s cross-entropy uses fused kernels and skips them. - Simpler, faster backward pass. The gradient of softmax followed by NLL simplifies analytically to (probabilities − one-hot of the label). It’s like micrograd’s tanh: one op with a known, simple derivative beats backpropagating through many small ones.
- Numerical stability. With hand-written softmax, a logit of 100 makes
exp(100)overflow toinf, and the probabilities becomenan. Very negative logits are fine (they just go to 0); very positive ones break.
The fix PyTorch applies: softmax doesn’t change if you add the same constant to every logit, so subtract the largest one first.
The biggest logit becomes 0, every exp is at most 1, and nothing overflows. F.cross_entropy does this internally, which is the practical reason never to hand-roll softmax in real code.
Part 6 — The training loop and minibatches
The training loop is the micrograd loop on tensors. First Karpathy overfits 32 examples as a sanity check. Then he trains on all 228,146 examples using random minibatches of 32: each step only estimates the gradient, but it is so much cheaper that many noisy steps beat a few exact ones.
The loop
for p in parameters:
p.requires_grad = True
for _ in range(1000):
# forward pass
emb = C[X] # (32, 3, 2)
h = torch.tanh(emb.view(-1, 6) @ W1 + b1) # (32, 100)
logits = h @ W2 + b2 # (32, 27)
loss = F.cross_entropy(logits, Y)
# backward pass
for p in parameters:
p.grad = None
loss.backward()
# update
for p in parameters:
p.data += -0.1 * p.grad
Sanity check: overfit one batch
On just the first 32 examples, the loss drops quickly from about 17 to near 0. That’s expected: 3,481 parameters can easily memorise 32 examples. Overfitting a tiny batch is a good first check that the forward pass, loss and backward pass are wired correctly.
The loss doesn’t reach exactly 0, though. The context ... appears five times with five different next letters (e, o, a, i, s). The best the model can do for ... is spread probability across them, so those examples always cost something. Where the context is unique, the net predicts the label with near certainty.
To inspect it: logits.max(1) returns the largest logit and its index for each example. Compare the indices with Y: they match almost everywhere except the ambiguous rows.
The full dataset is slow, so use minibatches
Run the same loop on all 228,146 examples and every step does a forward and backward pass over the whole dataset. That’s slow. The standard fix is to pick a random minibatch each step:
ix = torch.randint(0, X.shape[0], (32,)) # 32 random example indices
emb = C[X[ix]] # (32, 3, 2)
h = torch.tanh(emb.view(-1, 6) @ W1 + b1)
logits = h @ W2 + b2
loss = F.cross_entropy(logits, Y[ix]) # labels for the same 32 examples
- The gradient from 32 examples is only an approximation of the full gradient. It points roughly the right way, but it’s noisy.
- Karpathy’s rule of thumb: it’s much better to take many steps with an approximate gradient than a few with the exact one.
- The minibatch loss jumps around, so to judge progress, evaluate the loss on the whole training set now and then. In the video that went from about 2.7 to 2.53 over a few rounds of training.
Part 7 — Finding a good learning rate
To find a learning rate, sweep it exponentially from 0.001 to 1 over one short run, and plot the loss against the exponent. Pick the bottom of the valley, here 0.1. Then train at that rate and decay it by 10× near the end. With this recipe the 3,481-parameter MLP reaches about 2.3, beating the bigram’s 2.45.
Step 1: bracket the range by hand
Try a few rates for a handful of steps each:
- 0.001: the loss barely moves, so it’s too small.
- 1: the loss is unstable and jumps around.
- 10: it doesn’t optimise at all.
So the good rate lies somewhere between about 0.001 and 1.
Step 2: sweep exponentially across that range
lre = torch.linspace(-3, 0, 1000) # exponents from -3 to 0, evenly spaced
lrs = 10**lre # rates from 0.001 to 1, spaced exponentially
lri, lossi = [], []
for i in range(1000):
# ... minibatch forward + backward as before ...
lr = lrs[i] # a slightly bigger rate every step
for p in parameters:
p.data += -lr * p.grad
lri.append(lre[i])
lossi.append(loss.item())
plt.plot(lri, lossi)
Spacing the rates exponentially (via the exponent) gives equal attention to 0.001–0.01, 0.01–0.1 and 0.1–1. The plot has a typical shape: flat at first (too small to make progress), a valley, then a rise into instability. The valley sits around an exponent of −1, so lr = 0.1, which happens to be the value Karpathy guessed at first.
The sweep isn’t a clean experiment, since the loss also falls because training is happening. But it’s a fast, practical way to find the right order of magnitude.
Step 3: train, then decay
| Phase | Learning rate | Result in the video |
|---|---|---|
| Train 10,000 steps | 0.1 | ≈ 2.48 |
| Another 10,000 steps | 0.1 | ≈ 2.46 |
| A few thousand more, decayed | 0.01 | ≈ 2.3 (beats the bigram’s 2.45) |
The recipe used for the rest of the lecture: find a good rate, train with it until progress slows, then drop it by 10× for a final stretch. Late in training, smaller steps let the parameters settle into the bottom of the valley instead of bouncing around it.
A lower training loss is not yet proof of a better model, though. That needs held-out data, which is the next section.
Part 8 — Train / dev / test splits
Training loss alone can’t tell a good model from one that has memorised the data. So split the names 80/10/10. Fit the parameters on train, tune hyperparameters on dev, and touch test only rarely, at the very end. Comparing train and dev loss then tells you whether you’re underfitting or overfitting.
Why a lower training loss can lie
A big enough network can memorise its training set. Its training loss then gets very low, but on new names it does badly. Sampling from it would just reproduce training names. The only honest measure is the loss on data the model never trained on.
The three splits
| Split | Share | Used for | How often |
|---|---|---|---|
| Train | 80% | Fitting the parameters by gradient descent | Every step |
| Dev / validation | 10% | Choosing hyperparameters: hidden size, embedding size, context length, regularisation, learning rate | Often |
| Test | 10% | The final, honest estimate of performance | Very sparingly, ideally once |
Use the test set sparingly. Every time you check it and adjust something, a little information about the test set leaks into your choices, and you start overfitting to it too.
In code
def build_dataset(words):
X, Y = [], []
for w in words:
context = [0] * block_size
for ch in w + '.':
ix = stoi[ch]
X.append(context)
Y.append(ix)
context = context[1:] + [ix]
X = torch.tensor(X)
Y = torch.tensor(Y)
print(X.shape, Y.shape)
return X, Y
import random
random.seed(42)
random.shuffle(words) # shuffle names before splitting
n1 = int(0.8 * len(words))
n2 = int(0.9 * len(words))
Xtr, Ytr = build_dataset(words[:n1]) # ~25.6k names -> 182,441 examples
Xdev, Ydev = build_dataset(words[n1:n2]) # ~3.2k names -> 22,902 examples
Xte, Yte = build_dataset(words[n2:]) # ~3.2k names -> 22,803 examples
The split is by name, not by example, so all the windows from one name land in the same split. Train with minibatches from Xtr / Ytr only, and evaluate on Xdev / Ydev:
emb = C[Xdev]
h = torch.tanh(emb.view(-1, 6) @ W1 + b1)
logits = h @ W2 + b2
loss = F.cross_entropy(logits, Ydev)
Reading train vs dev loss
| What you see | Diagnosis | What to try |
|---|---|---|
| Train ≈ dev, both mediocre | Underfitting: the model is too small or too constrained to fit the data | Make it bigger: more neurons, larger embeddings, longer context |
| Train much lower than dev | Overfitting: it is memorising the training set | More data, regularisation, a smaller model, stopping earlier |
With the 3,481-parameter model, train and dev loss come out roughly equal, at about 2.3. That means the network is underfitting: there’s room to make it bigger.
Part 9 — Scaling up: hidden layer, embeddings, and what they learned
Making the hidden layer bigger helped only a little. The real bottleneck was the 2-dimensional embeddings. Plotting them shows the net had already grouped the vowels together. Switching to 10-dimensional embeddings (and 200 hidden neurons) brought the dev loss to 2.17.
Experiment 1: a bigger hidden layer
Going from 100 to 300 hidden neurons takes the model from 3,481 to 10,281 parameters.
- The loss curve is now visibly noisy: each point is a 32-example minibatch, and the batch is small. A bigger batch would smooth it out.
- A bigger network can also take longer to converge, so it needs more steps.
- After a few rounds of training and decaying the learning rate, the dev loss got to about 2.32, then 2.23. That’s better, but not by much. Karpathy suspected something else was holding the model back.
Visualising the 2-D embeddings
With only 2 dimensions, you can plot every character’s embedding directly:
plt.figure(figsize=(8, 8))
plt.scatter(C[:, 0].data, C[:, 1].data, s=200)
for i in range(C.shape[0]):
plt.text(C[i, 0].item(), C[i, 1].item(), itos[i], ha='center', va='center', color='white')
plt.grid('minor')
The network has organised the characters by role:
- the vowels a, e, i, o and u sit together in one cluster, so the net treats them as roughly interchangeable;
- q and the
.token sit far from everything else, which fits their unusual behaviour (q is rare and almost always followed by u;.marks the start and end of names); - the remaining consonants spread out between.
Nobody told the model what a vowel is. This structure emerged purely from predicting the next character, which is exactly the Bengio et al. argument.
Experiment 2: bigger embeddings
Two numbers per character is probably too few to hold everything the model wants to know. So use 10-dimensional embeddings, and trim the hidden layer back to 200:
C = torch.randn((27, 10), generator=g)
W1 = torch.randn((30, 200), generator=g) # 3 characters x 10 dims = 30 inputs
b1 = torch.randn(200, generator=g)
W2 = torch.randn((200, 27), generator=g)
b2 = torch.randn(27, generator=g)
# and in the forward pass: emb.view(-1, 30) (no longer 6!)
That’s 11,897 parameters. Karpathy also switches to plotting log10 of the loss, which squashes the steep drop at the start (the “hockey stick”) so the slow progress later is visible.
The experiments side by side
| Model | Embedding | Hidden | Parameters | Result (from the video) |
|---|---|---|---|---|
| Bigram (Lecture 1) | – | – | 729 | ≈ 2.45 |
| MLP, first version | 2 | 100 | 3,481 | ≈ 2.3 train and dev (underfitting) |
| Bigger hidden layer | 2 | 300 | 10,281 | ≈ 2.23 dev |
| Bigger embeddings, 50k steps + 50k decayed | 10 | 200 | 11,897 | ≈ 2.17 train / 2.2 dev |
| Final: 200k steps (100k at 0.1, 100k at 0.01) | 10 | 200 | 11,897 | 2.126 train / 2.170 dev |
In the final runs, train and dev loss start to separate slightly. That’s the first hint of overfitting, and it means the model now has enough capacity to use the data.
Part 10 — Final code, sampling, and conclusion
The final model is about 20 lines: an embedding lookup, one tanh layer, one output layer and F.cross_entropy, trained for 200,000 minibatch steps. Its samples are noticeably more name-like than the bigram’s. Karpathy leaves beating his 2.17 dev loss as an open exercise.
The final training code
g = torch.Generator().manual_seed(2147483647)
C = torch.randn((27, 10), generator=g)
W1 = torch.randn((30, 200), generator=g)
b1 = torch.randn(200, generator=g)
W2 = torch.randn((200, 27), generator=g)
b2 = torch.randn(27, generator=g)
parameters = [C, W1, b1, W2, b2] # 11,897 parameters
for p in parameters:
p.requires_grad = True
for i in range(200000):
# minibatch
ix = torch.randint(0, Xtr.shape[0], (32,))
# forward pass
emb = C[Xtr[ix]] # (32, 3, 10)
h = torch.tanh(emb.view(-1, 30) @ W1 + b1) # (32, 200)
logits = h @ W2 + b2 # (32, 27)
loss = F.cross_entropy(logits, Ytr[ix])
# backward pass
for p in parameters:
p.grad = None
loss.backward()
# update, with a step decay halfway through
lr = 0.1 if i < 100000 else 0.01
for p in parameters:
p.data += -lr * p.grad
Then evaluate on the full train and dev splits: 2.1260 train, 2.1701 dev.
Sampling
g = torch.Generator().manual_seed(2147483647 + 10)
for _ in range(20):
out = []
context = [0] * block_size # start with '...'
while True:
emb = C[torch.tensor([context])] # (1, block_size, 10)
h = torch.tanh(emb.view(1, -1) @ W1 + b1)
logits = h @ W2 + b2
probs = F.softmax(logits, dim=1) # the stable, built-in softmax
ix = torch.multinomial(probs, num_samples=1, generator=g).item()
context = context[1:] + [ix] # slide the window
out.append(ix)
if ix == 0:
break
print(''.join(itos[i] for i in out))
Some of the 20 samples: carmahela, jhovi, kimrin, halanna, nellara, kaleigh, quinton, lilea, jamilio, jace. A few are real names, and most sound plausible. There’s still clear room to improve (chaiiv, chrudeley).
How the makemore repo writes the same model
makemore.py’s MLP class is this lecture in idiomatic PyTorch:
| Lecture code | makemore.py | Note |
|---|---|---|
C[X] | nn.Embedding(vocab_size + 1, n_embd) | One extra row for a special <BLANK> token used to pad before the start |
emb.view(-1, 30) | torch.cat(embs, -1) | Concatenate the block_size embeddings |
tanh(... @ W1 + b1) | nn.Linear(block_size * n_embd, n_embd2), then nn.Tanh() | Hidden layer |
h @ W2 + b2 | nn.Linear(n_embd2, vocab_size) | Output logits |
F.cross_entropy(logits, Y) | F.cross_entropy(..., ignore_index=-1) | Same loss |
Ideas for beating 2.17
Karpathy’s suggestions:
- Model size: the number of hidden neurons, and the embedding dimension.
- Context length: use more than 3 previous characters.
- Optimisation: how long to train, the learning rate and its decay schedule, and the batch size (bigger batches give less noisy gradients and may converge faster).
- Read the paper: Bengio et al. is 19 pages full of further ideas.
Tune all of these on the dev set, and only look at the test set at the very end.
Conclusion
The lecture took the bigram model’s machinery and swapped in a real neural net. It also introduced the working habits that the rest of the series assumes: minibatch SGD, learning-rate search and decay, train/dev/test splits, reading under- versus overfitting, and checking tensor shapes. Karpathy also shared a Google Colab version of the notebook (linked in the video description) so you can run everything in the browser with no setup.
Cheat sheet
Shapes, dials, calls and pitfalls of the final model (block_size 3, embedding 10, hidden 200, batch 32).
Shapes through the forward pass
| Tensor | Shape | Notes |
|---|---|---|
Xtr[ix] | (32, 3) | Integer context windows for one minibatch |
C | (27, 10) | Embedding table: one row per character |
emb = C[Xtr[ix]] | (32, 3, 10) | Every index replaced by its 10-D vector |
emb.view(-1, 30) | (32, 30) | The 3 embeddings side by side, with no copy |
W1, b1 | (30, 200), (200) | Hidden layer |
h | (32, 200) | tanh activations in (−1, 1) |
W2, b2 | (200, 27), (27) | Output layer |
logits | (32, 27) | Unnormalised scores for the next character |
loss | scalar | F.cross_entropy(logits, Ytr[ix]) |
Hyperparameters introduced
| Dial | Final value | Effect |
|---|---|---|
block_size | 3 | How many previous characters the model sees |
| Embedding size | 10 | Room per character for learned features (2 was a bottleneck) |
| Hidden size | 200 | Model capacity |
| Batch size | 32 | Bigger means less noisy gradients, but slower steps |
| Learning rate | 0.1, then 0.01 | Found with an exponential sweep; decayed 10× halfway |
| Steps | 200,000 | Longer training, until dev loss stops improving |
Parameter count: 27·d + (block_size·d)·H + H + H·27 + 27. With d = 10 and H = 200 that’s 11,897.
PyTorch calls introduced
| Call | Does |
|---|---|
C[X] (X an integer tensor) | Gather rows; output shape = X’s shape + row shape |
t.view(a, b) / t.view(-1, k) | Reshape without copying; −1 infers that dimension |
torch.cat(tensors, dim) | Concatenate along a dimension (allocates new memory) |
torch.unbind(t, dim) | Split a dimension into a tuple of slices |
t.storage() | The underlying 1-D buffer of numbers |
F.cross_entropy(logits, targets) | Fused, numerically stable softmax + NLL |
F.softmax(logits, dim=1) | Stable softmax (used when sampling) |
torch.randint(0, N, (32,)) | 32 random indices, for a minibatch |
torch.linspace(-3, 0, 1000) | Evenly spaced exponents for a learning-rate sweep |
logits.max(1) | Largest value and its index per row |
Common bugs and pitfalls
| Pitfall | Symptom | Fix |
|---|---|---|
Hard-coding view(32, 6) | Breaks with any other batch size | view(-1, block_size * d) |
Forgetting to update view(-1, 6) after changing the embedding size | Shape error, or the wrong reshape | Derive it from block_size * C.shape[1] |
| Hand-written softmax with large logits | inf / nan loss | F.cross_entropy / F.softmax |
| Judging progress on one minibatch’s loss | A noisy, misleading curve | Evaluate on the full train and dev splits |
| Tuning against the test set | Optimistic, leaky final number | Tune on dev; look at test once |
| Learning rate too low or too high | Stalls, or blows up | Exponential sweep, then decay |
| Expecting 0 loss when overfitting a batch | Puzzling floor above 0 | Ambiguous contexts like ... can’t be predicted |
Glossary
| Term | Meaning |
|---|---|
| MLP | Multi-layer perceptron: stacked fully connected layers with nonlinearities |
| Embedding | A learned vector for each token, stored as a row of a lookup table |
| Context / block size | The number of previous tokens the model conditions on |
| Logits | Raw output scores; softmax turns them into probabilities |
| Cross-entropy | Softmax + negative log likelihood of the correct class |
| Minibatch | A small random subset of examples used for one gradient step |
| Learning-rate decay | Lowering the step size later in training to settle into a minimum |
| Train / dev / test | Data for fitting / for tuning hyperparameters / for the final evaluation |
| Hyperparameter | A design choice not learned by gradient descent (sizes, learning rate, batch size) |
| Underfitting | The model is too weak: train ≈ dev, both high |
| Overfitting | The model memorises training data: train loss well below dev loss |
| View / storage | Shape metadata over a flat 1-D memory buffer |
Self-check and exercises
If you can answer these without scrolling up, you’ve got the lecture. Answers are below the questions.
Questions
- Why can’t you extend the bigram count table to 3 characters of context?
- In Bengio et al., what is shared across the 3 context positions, and why does that help generalisation?
- With
block_size = 3, what (context → label) pairs does “emma” produce? - Why is
C[5]the same asF.one_hot(torch.tensor(5), 27).float() @ C, and which one do we use? Xis (32, 3) and C is (27, 2). What is the shape ofC[X], and what reshaping does the hidden layer need?- Why is
emb.view(-1, 6)better thantorch.cat(torch.unbind(emb, 1), 1)? - Give three reasons to prefer
F.cross_entropyover hand-written softmax + NLL. - Why can’t the loss reach 0 even when overfitting a single batch of 32?
- Why sweep learning rates on an exponential scale, and what did the sweep pick?
- What do the train, dev and test splits each do, and why touch test so rarely?
- Train and dev loss are both about 2.3 and nearly equal. What does that mean, and what should you try?
- What did the 2-D embedding plot reveal?
- How many parameters does the final model have? Show the arithmetic.
Answers
- The number of contexts explodes: 27 → 729 → 19,683. Most contexts would have few or no counts, so the probability estimates become unreliable.
- The embedding table C is shared by every position. Similar tokens learn similar vectors, so what’s learned about one transfers to the others (“a/the”, “dog/cat”).
...→e,..e→m,.em→m,emm→a,mma→.- A one-hot vector times a matrix selects one row. Indexing does the same thing much faster, so we index.
- (32, 3, 2). It has to become (32, 6), with the 3 embeddings side by side, before multiplying by W1 (6 × 100).
viewonly changes shape metadata over the same storage, so no memory is copied.catallocates a new tensor.- Fused, memory-efficient kernels in the forward pass; a simpler analytic gradient in the backward pass; and numerical stability (subtracting the max logit stops
expfrom overflowing). - Some contexts are ambiguous.
...is followed by e, o, a, i and s in the same batch, so the model must spread probability across them. - Plausible rates span orders of magnitude (0.001 to 1), and exponential spacing gives each decade equal attention. The loss valley sat at an exponent of −1, so lr = 0.1.
- Train fits the parameters, dev chooses hyperparameters, and test is the final honest score. Each look at test leaks information into your choices.
- Underfitting: the model is too small to fit even the training data. Make it bigger (hidden size, embedding size, context), and train longer.
- The vowels clustered together, while q and
.sat far away. The net learned character roles without being told. - 27·10 + 30·200 + 200 + 200·27 + 27 = 270 + 6,000 + 200 + 5,400 + 27 = 11,897.
Exercises
- Beat 2.17 on dev (Karpathy’s open challenge). Tune the hidden size, embedding size,
block_size, batch size, steps and decay schedule, then report the test loss once. - What loss would a perfectly uniform prediction give? (Hint: −ln(1/27) ≈ 3.30.) Why does the random init start near 17 instead? Try scaling the initial weights down and watch the starting loss.
- Plot train and dev loss against model size, and find where overfitting starts.
- Train with 2-D embeddings and reproduce the vowel cluster plot.
- Rewrite the model with
nn.Embedding,nn.Linearandnn.Tanh(as inmakemore.py), and check that you get the same loss. - Read Bengio et al. 2003 and try one idea from it, such as direct connections from the embeddings to the output layer.
Sources
- Building makemore Part 2: MLP (Andrej Karpathy, YouTube)
- Lecture notebook: makemore_part2_mlp.ipynb
- karpathy/makemore:
makemore.py(theMLPclass),names.txt - Bengio et al. 2003, A Neural Probabilistic Language Model (linked from the makemore README)
- Video transcript with chapter timestamps