sidd.

makemore Lecture 2: MLP

· 32 min read · Work

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

Where the lecture ends up

Bigram (Lecture 1)MLP (this lecture, final)
Context1 character3 characters
Parameters72911,897
Loss≈ 2.45 (training set)2.13 train / 2.17 dev

Chapter map

TimeChapter in the videoNotes section
0:00IntroOverview
1:48Bengio et al. 2003 (MLP language model) paper walkthroughPart 1
9:03(Re-)building the training datasetPart 2
12:19Implementing the embedding lookup tablePart 3
18:35The hidden layer + internals of torch.Tensor: storage, viewsPart 4
29:15Implementing the output layerPart 5
29:53Implementing the negative log likelihood lossPart 5
32:17Summary of the full networkPart 5
32:49Introducing F.cross_entropy, and whyPart 5
37:56The training loop; overfitting one batchPart 6
41:25Training on the full dataset; minibatchesPart 6
45:40Finding a good initial learning ratePart 7
53:20Splitting the dataset into train/val/test, and whyPart 8
1:00:49Experiment: larger hidden layerPart 9
1:05:27Visualising the character embeddingsPart 9
1:07:16Experiment: larger embedding sizePart 9
1:11:46Summary of the final code; conclusionPart 10
1:13:24Sampling from the modelPart 10
1:14:55Google Colab notebookPart 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

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

  1. Take the indices of the 3 previous words.
  2. 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.
  3. Feed them to a fully connected hidden layer with a tanh nonlinearity. Its size is a hyperparameter, for example 100 neurons.
  4. Feed that to the output layer, with one neuron per vocabulary word: 17,000 logits. This is the most expensive part of the network.
  5. Softmax turns the logits into a probability distribution over the next word.
Look up 3 embeddings, concatenate, one tanh layer, 27 logits Final model: block_size 3, embedding size 10, hidden size 200, 11,897 parameters context lookup embeddings concat (30) → hidden output . → 0 e → 5 m → 13 C 27 × 10 one table, shared by all 3 positions 10 numbers 10 numbers 10 numbers Hidden layer 30 → 200 tanh Output layer 200 → 27 logits softmax → P(next) Loss: F.cross_entropy(logits, label). For the context “.em” the label is m; all of C, W1, b1, W2, b2 learn by backprop.
character-level MLP · the final model from this lecture

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. 2003This lecture
Tokens~17,000 words27 characters
Context3 previous words3 previous characters (block_size = 3)
Embedding size302 at first, 10 in the final model
Hidden layere.g. 100, tanh100 → 300 → 200 tanh neurons, across experiments
Output17,000-way softmax27-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
..em
.emm
emma
mma.

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)
IndexShapeMeaning
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
TensorShapeParameters
C (embeddings)27 × 254
W16 × 100600
b1100100
W2100 × 272,700
b22727
Total3,481

Why F.cross_entropy instead of doing it by hand

loss = F.cross_entropy(logits, Y)   # same value as the three lines above
  1. Efficient forward pass. The manual version creates intermediate tensors (counts, prob) in memory. PyTorch’s cross-entropy uses fused kernels and skips them.
  2. 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.
  3. Numerical stability. With hand-written softmax, a logit of 100 makes exp(100) overflow to inf, and the probabilities become nan. 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.

softmax(z)j=ezj∑kezk=ezj−c∑kezk−c,c=max⁡kzk\text{softmax}(z)_j = \frac{e^{z_j}}{\sum_k e^{z_k}} = \frac{e^{z_j - c}}{\sum_k e^{z_k - c}}, \qquad c = \max_k z_k

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

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:

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

PhaseLearning rateResult in the video
Train 10,000 steps0.1≈ 2.48
Another 10,000 steps0.1≈ 2.46
A few thousand more, decayed0.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

SplitShareUsed forHow often
Train80%Fitting the parameters by gradient descentEvery step
Dev / validation10%Choosing hyperparameters: hidden size, embedding size, context length, regularisation, learning rateOften
Test10%The final, honest estimate of performanceVery 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 seeDiagnosisWhat to try
Train ≈ dev, both mediocreUnderfitting: the model is too small or too constrained to fit the dataMake it bigger: more neurons, larger embeddings, longer context
Train much lower than devOverfitting: it is memorising the training setMore 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.

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:

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

ModelEmbeddingHiddenParametersResult (from the video)
Bigram (Lecture 1)––729≈ 2.45
MLP, first version21003,481≈ 2.3 train and dev (underfitting)
Bigger hidden layer230010,281≈ 2.23 dev
Bigger embeddings, 50k steps + 50k decayed1020011,897≈ 2.17 train / 2.2 dev
Final: 200k steps (100k at 0.1, 100k at 0.01)1020011,8972.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 codemakemore.pyNote
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 + b2nn.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:

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

TensorShapeNotes
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
lossscalarF.cross_entropy(logits, Ytr[ix])

Hyperparameters introduced

DialFinal valueEffect
block_size3How many previous characters the model sees
Embedding size10Room per character for learned features (2 was a bottleneck)
Hidden size200Model capacity
Batch size32Bigger means less noisy gradients, but slower steps
Learning rate0.1, then 0.01Found with an exponential sweep; decayed 10× halfway
Steps200,000Longer 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

CallDoes
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

PitfallSymptomFix
Hard-coding view(32, 6)Breaks with any other batch sizeview(-1, block_size * d)
Forgetting to update view(-1, 6) after changing the embedding sizeShape error, or the wrong reshapeDerive it from block_size * C.shape[1]
Hand-written softmax with large logitsinf / nan lossF.cross_entropy / F.softmax
Judging progress on one minibatch’s lossA noisy, misleading curveEvaluate on the full train and dev splits
Tuning against the test setOptimistic, leaky final numberTune on dev; look at test once
Learning rate too low or too highStalls, or blows upExponential sweep, then decay
Expecting 0 loss when overfitting a batchPuzzling floor above 0Ambiguous contexts like ... can’t be predicted

Glossary

TermMeaning
MLPMulti-layer perceptron: stacked fully connected layers with nonlinearities
EmbeddingA learned vector for each token, stored as a row of a lookup table
Context / block sizeThe number of previous tokens the model conditions on
LogitsRaw output scores; softmax turns them into probabilities
Cross-entropySoftmax + negative log likelihood of the correct class
MinibatchA small random subset of examples used for one gradient step
Learning-rate decayLowering the step size later in training to settle into a minimum
Train / dev / testData for fitting / for tuning hyperparameters / for the final evaluation
HyperparameterA design choice not learned by gradient descent (sizes, learning rate, batch size)
UnderfittingThe model is too weak: train ≈ dev, both high
OverfittingThe model memorises training data: train loss well below dev loss
View / storageShape 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

  1. Why can’t you extend the bigram count table to 3 characters of context?
  2. In Bengio et al., what is shared across the 3 context positions, and why does that help generalisation?
  3. With block_size = 3, what (context → label) pairs does “emma” produce?
  4. Why is C[5] the same as F.one_hot(torch.tensor(5), 27).float() @ C, and which one do we use?
  5. X is (32, 3) and C is (27, 2). What is the shape of C[X], and what reshaping does the hidden layer need?
  6. Why is emb.view(-1, 6) better than torch.cat(torch.unbind(emb, 1), 1)?
  7. Give three reasons to prefer F.cross_entropy over hand-written softmax + NLL.
  8. Why can’t the loss reach 0 even when overfitting a single batch of 32?
  9. Why sweep learning rates on an exponential scale, and what did the sweep pick?
  10. What do the train, dev and test splits each do, and why touch test so rarely?
  11. Train and dev loss are both about 2.3 and nearly equal. What does that mean, and what should you try?
  12. What did the 2-D embedding plot reveal?
  13. How many parameters does the final model have? Show the arithmetic.

Answers

  1. The number of contexts explodes: 27 → 729 → 19,683. Most contexts would have few or no counts, so the probability estimates become unreliable.
  2. 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”).
  3. ...→e, ..e→m, .em→m, emm→a, mma→.
  4. A one-hot vector times a matrix selects one row. Indexing does the same thing much faster, so we index.
  5. (32, 3, 2). It has to become (32, 6), with the 3 embeddings side by side, before multiplying by W1 (6 × 100).
  6. view only changes shape metadata over the same storage, so no memory is copied. cat allocates a new tensor.
  7. Fused, memory-efficient kernels in the forward pass; a simpler analytic gradient in the backward pass; and numerical stability (subtracting the max logit stops exp from overflowing).
  8. 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.
  9. 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.
  10. Train fits the parameters, dev chooses hyperparameters, and test is the final honest score. Each look at test leaks information into your choices.
  11. Underfitting: the model is too small to fit even the training data. Make it bigger (hidden size, embedding size, context), and train longer.
  12. The vowels clustered together, while q and . sat far away. The net learned character roles without being told.
  13. 27·10 + 30·200 + 200 + 200·27 + 27 = 270 + 6,000 + 200 + 5,400 + 27 = 11,897.

Exercises

Sources