CodeRigor

LESSON

An embedding MLP with hand-written gradients

Look characters up in an embedding table, add a tanh layer, and derive every gradient by hand, including the scatter-add that repeated characters need.

A bigram model looks at one character. To predict from several, you need a way to feed characters into a network, and a way to train every part of it, including the table that turns characters into vectors. This lesson pairs with Building makemore Part 2: MLP by Andrej Karpathy, linked under Watch & read. You build that network in NumPy: a lookup table, one tanh layer and a softmax output, with the loss and every gradient written by hand and graded against PyTorch.

The network reads a window of context characters. Each character is an integer index. A table C of shape (vocab, emb) holds one row per character, and the window's rows are looked up and laid side by side into one long vector of length context · emb. A tanh layer and a linear layer turn that vector into one logit per character. The model has five parameters: C, W1, b1, W2, b2, with W stored as (out, in) as in torch.nn.Linear.

Forward: from indices to a loss
start / 3
One batch of N windows. The accented boxes are kept for the backward pass: flat is the input of layer 1 and h is both the input of layer 2 and the source of the tanh slope.
Forward: from indices to a loss
One batch of N windows. The accented boxes are kept for the backward pass: flat is the input of layer 1 and h is both the input of layer 2 and the source of the tanh slope.

Start with the first loss. A model that knows nothing should give every character the same probability 1/V, and a loss of log V, which is 3.30 for 27 characters. If the output weights are large, the first logits are large and confidently wrong, and the first loss is far above that. Scale W2 by 0.01 and set the biases to zero and the logits start near zero. Scale W1 by 1/√(context · emb) so that the pre-activations of the hidden layer stay of order one and tanh is not saturated.

Python
import numpy as np

rng = np.random.default_rng(0)
h = np.tanh(rng.normal(size=(200, 30)))
y = rng.integers(0, 27, size=200)
W = rng.normal(size=(30, 27))
for scale in (1.0, 0.01):
    z = scale * (h @ W)
    z = z - z.max(axis=1, keepdims=True)
    log_p = z - np.log(np.exp(z).sum(axis=1, keepdims=True))
    print(scale, round(float(-log_p[np.arange(200), y].mean()), 2))
print(round(float(np.log(27)), 2))

The backward pass for the two dense layers is ordinary backpropagation. The error at the logits is delta = (p - y) / N, where y is one-hot and the 1/N comes from the mean loss. Then dW₂ = deltaᵀh, db₂ is the column sums of delta, and the error crosses the tanh with dz = (delta W₂) ⊙ (1 - h²). Likewise dW₁ = dzᵀ flat and db₁ is the column sums of dz.

One step is new. The error at the input of layer 1 is dflat = dz W₁, one row per example and one value per looked-up slot. Reshape it to (N, context, emb) and each slice lines up with the row of C it came from. But C has only vocab rows, and a character that appears in several slots, or in several windows, owns one row. The derivative of a shared value is the sum of its uses, so that row's gradient is the sum of every slice that read it.

Backward: from delta to the table
start / 4
The last step goes back through the lookup. Slices of dflat are added into the row of C they were read from, so repeated indices accumulate.
Backward: from delta to the table
The last step goes back through the lookup. Slices of dflat are added into the row of C they were read from, so repeated indices accumulate.

A worked example makes the scatter concrete. Take a vocabulary of 2, context 2, emb 1 and hidden 1. C is zero, so h = tanh(0) = 0 and the slope is 1. One example has the label 0 and the window [1, 1], so both slots read row 1. The logits are 0, p = [0.5, 0.5] and delta = [-0.5, 0.5]. With W₂ = [[1], [-1]], dz = -0.5 · 1 + 0.5 · (-1) = -1. With W₁ = [[2, 3]], dflat = [-2, -3]. Row 1 of C was used twice, so its gradient is -2 + -3 = -5.

Python
import numpy as np

delta = np.array([[-0.5, 0.5]])
W2, W1 = np.array([[1.0], [-1.0]]), np.array([[2.0, 3.0]])
dflat = (delta @ W2) @ W1               # the tanh slope is 1 here
X = np.array([[1, 1]])
dC = np.zeros((2, 1))
np.add.at(dC, X, dflat.reshape(1, 2, 1))
print(dflat.tolist(), dC.ravel().tolist())

Now the mistakes that look fine. The first is writing dC[X] = demb. Fancy assignment writes once per listed index, so for a repeated index only one of the values survives, and dC[X] += demb has the same flaw because it reads the old value once per index. In the example it would return -3, not -5. Training still moves, because the unique rows are right, which is why only a comparison with an independent derivative finds it. The second mistake is leaving out the 1/N, which makes every gradient N times too large and acts like a learning rate N times too high. A third is a scale for W2 that makes the first loss 8 instead of 3.3: nothing is wrong with the gradients, but the first steps are spent shrinking logits.

The tests verify the code three ways: a case small enough to do by hand, the loss at initialization, and PyTorch's autograd on batches that deliberately repeat tokens. Together they show that your gradients match the function you wrote. They do not show that a window of this size is a good model of language. Part 3 of the same series, also linked, picks up the initial loss and the saturated tanh from the viewpoint of the whole training run.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Builds a character-level MLP language model with an embedding lookup table, a hidden layer and cross-entropy, then trains it with minibatches and splits the data. This lesson is the same network with the gradients written by hand.