Library/Transformers from scratch/Gradients and fine-tuning

Backprop by hand

100 min6 partsFoundationFundamentalsChecked Nov 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • The chain rule as one move: each step multiplies the gradient from above by its own slope
  • Place every transpose and every sum by matching shapes, with no indices
  • Why softmax and cross-entropy together give softmax minus one-hot, divided by N
  • Take the ReLU mask from the input, and sum each bias gradient over the batch
  • Keep the loss finite with logits in the tens of thousands
  • Prove it all with a central-difference check, then answer the follow-ups on vanishing gradients, the max shift and layer norm
Part 1 of 6about 15 min
The chain rule

Backprop by hand, for a two-layer network

One OpenAI ML engineer candidate reports an ML coding round on a matrix multiplication's forward pass and backprop, written in PyTorch from a code skeleton (1 report). The same candidate says NumPy fluency was essential (1 report). Backprop by hand prepares you for both, and the practice problem asks for it on the smallest network that has every part. Our version reads like this:

Here's a two-layer network in NumPy: a linear layer, a ReLU, a second linear layer, and the mean softmax cross-entropy over the batch. Write forward_backward(params, x, y). Return the loss and a gradient for each of W1, b1, W2 and b2, with no autograd. Then show me it's right.

ArrayShape
x(N, D): N examples of D numbers
W1 and b1(D, H) and (H,)
W2 and b2(H, K) and (K,)
y(N,): one label per example, from 0 to K - 1

The practice comes in four levels. Level 1 checks only the loss. Level 2 checks every gradient against nudging each weight, then trains the network on three blobs of points. Level 3 multiplies W2 by 10,000, so the logits reach the tens of thousands and the loss must stay finite. Level 4 writes one training step that clips all the gradients together by their total length.

You don't write it yet. The lesson starts with what backprop computes and the one rule behind every step, then builds each gradient in the order the backward pass needs them. At the end you solve the whole problem, level by level, in an interview simulation with a 45-minute timer.

This lesson builds on the NumPy lesson's shapes and broadcasting, and on the softmax from the attention lessons. The matmul backward lesson comes next and writes a backward pass of your own in PyTorch, the round the report describes.

What backprop computes

Start from the forward pass, because the backward pass reads it in reverse.

import numpy as np

rng = np.random.default_rng(0)
N, D, H, K = 6, 4, 5, 3
x = rng.normal(size=(N, D))
y = rng.integers(0, K, size=N)
W1, b1 = rng.normal(size=(D, H)), np.zeros(H)
W2, b2 = rng.normal(size=(H, K)), np.zeros(K)

# hidden layer, before the ReLU
pre = x @ W1 + b1
# after the ReLU
h = np.maximum(pre, 0)
# one score per class
logits = h @ W2 + b2
print(pre.shape, h.shape, logits.shape)
Predict

x is (6, 4), W1 is (4, 5) and W2 is (5, 3). What shapes are pre, h and logits?

Pick one to see what it prints.
Pick an answer above to see the rest

The chain rule, one step at a time

Each step multiplies the gradient from above by its own slope

Start smaller: three numbers and two steps.

a, b, c = 2.0, -3.0, 10.0
e = a * b
L = e + c

dL = 1.0       # start at the loss
# an add passes the gradient through
de = dL
dc = dL
# a multiply sends each input the other input
da = de * b
db = de * a
print(L, da, db, dc)
Predict

a = 2, b = -3, c = 10, then e = a * b and L = e + c. What are da, db and dc?

Pick one to see what it prints.
Pick an answer above to see the rest

Six rules cover every step in this network

Write dX for the gradient of the loss with respect to X. It's an array with the same shape as X.

ForwardBackward, given dout
out = a + bda = dout, db = dout
out = a * b (elementwise)da = dout * b, db = dout * a
out = np.maximum(a, 0)da = dout * (a > 0)
out = a @ Wda = dout @ W.T, dW = a.T @ dout
out = a + b, with b broadcast over rowsdb = dout.sum(axis=0)
a feeds two operationsda is the sum of what each one sends back
  • An add passes the gradient through, unchanged.
  • A multiply swaps: each input gets the other input times the gradient.
  • ReLU is a gate. The gradient passes where the input was positive and stops everywhere else.
  • A matmul is a multiply for whole arrays, so it swaps too. The shapes tell you where the transposes go.

The last row of the table needs a picture. A value that feeds two steps gets a gradient back from each:

One value, two stepsInteractive
a = 3× 4+ 1y = 12z = 4+L = 16
forward, values backward, gradients
a feeds two steps: y = a × 4 = 12 and z = a + 1 = 4. Then L = y + z = 16.

That's why an autograd engine, the code that runs the backward pass for you in PyTorch, adds into each gradient instead of overwriting it.

In the editor, write grads(a, b) for L = a * b + a, where a is used twice.

Part 1 done
Part 2 of 6about 12 min
Shapes place the transposes

The shape rule

A gradient has the shape of its weight, and that places every transpose

Back to the network. Say you have the gradient at the logits, dlogits. It has the shape of logits, (N, K). A random stand-in will do for now.

dlogits = rng.normal(size=(N, K))
dW2 = h.T @ dlogits
dh = dlogits @ W2.T
print(dW2.shape, W2.shape)
print(dh.shape, h.shape)
Predict

dW2 = h.T @ dlogits and dh = dlogits @ W2.T. How do their shapes compare with W2's and h's?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

Add up one outer product per example, row n of h times row n of dlogits. Does the sum equal h.T @ dlogits?

Pick one to see what it prints.
Pick an answer above to see the rest

A bias was added to every row, so its gradient sums the rows

A bias needs one more rule.

db2 = dlogits.sum(axis=0)
print(db2.shape, b2.shape)
Predict

b2 is (3,), added to all 6 rows. What shape is dlogits.sum(axis=0)?

Pick one to see what it prints.
Pick an answer above to see the rest

The backward pass is the forward pass read bottom to top

Here is every gradient in the practice problem, from the loss down, with the rule that makes it. Step through it:

The backward passInteractive
dlogits (N, K) = softmax minus one-hot, over N. The next part derives it. Here it's given.

Every gradient comes from a rule you already have: the shape rule places a matmul's transpose, the bias rule sums over the batch, and the ReLU gate multiplies by the mask from the table of six rules. Only dlogits is new, and it gets the next part.

In the editor, write backward(params, x, pre, h, dlogits): every gradient in the flow, from dlogits down to dW1 and db1.

Part 2 done
Part 3 of 6about 20 min
The loss and its gradient

Softmax plus cross-entropy

Together they give softmax minus one-hot

Two examples with two classes. Example 1's label is class 0, and example 2's label is class 1.

logits = np.array([[1.0, 1.0], [1.0, -1.0]])
y = np.array([0, 1])
n = len(y)

p = np.exp(logits) / np.exp(logits).sum(axis=1, keepdims=True)
dlogits = p.copy()
dlogits[np.arange(n), y] -= 1
dlogits /= n
print(p.round(2))
print(dlogits.round(2))
Predict

Example 2 has logits [1, -1], label 1 and softmax [0.88, 0.12]. What is its row of dlogits, with the batch of 2?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

Which example sends back the biggest gradient?

Pick an answer above to see the rest

Subtract 1 at each row's label, and nowhere else

In code, the one-hot is one line of indexing, and it's easy to get wrong.

grid = np.zeros((3, 3))
labels = np.array([2, 0, 2])
grid[np.arange(3), labels] -= 1
print(grid)
Predict

grid[np.arange(3), labels] -= 1 with labels = [2, 0, 2]. Where do the -1s land?

Pick one to see what it prints.
Pick an answer above to see the rest

A loss that survives huge logits

Subtract each row's max, and np.exp can't overflow

The practice tests push the logits into the tens of thousands, and np.exp has a limit.

print(np.exp(709.0), np.exp(710.0))
row = np.array([30000.0, 30002.0, 29999.0])
print(np.exp(row - row.max()))
Predict

What do np.exp(709.0) and np.exp(710.0) print in float64?

Pick one to see what it prints.
Pick an answer above to see the rest

Do the softmax and the log as one step, and nothing divides by zero

You could run the log's backward and then the softmax's backward, one at a time. The math is the same. But the log's backward divides by pcp_c, the label's probability, and that can be 0:

p_c = np.exp(-800.0)
print(p_c, -1 / p_c, -1 / p_c * p_c)
Predict

p_c = np.exp(-800.0). What do p_c, -1 / p_c and -1 / p_c * p_c print?

Pick one to see what it prints.
Pick an answer above to see the rest

Take the log of a sum, never the log of a probability

Subtracting each row's max keeps np.exp finite. The log has a trap of its own.

z = np.array([0.0, -40000.0, 3.0])
z = z - z.max()
probs = np.exp(z) / np.exp(z).sum()
print(probs)
print(-np.log(probs[1]))
log_probs = z - np.log(np.exp(z).sum())
print(-log_probs[1])
Predict

The label is class 1, whose logit sits 40,003 below the top. Its probability rounds to 0.0. What do -np.log(probs[1]) and the log-space line give?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 3 done
Part 4 of 6about 19 min
The ReLU mask, and a worked example

The ReLU mask

The mask comes from pre, never from h

You've used the ReLU gate once already. One detail of it decides whether your gradients come out right.

pre = np.array([1.5, -0.5, 2.0, -3.0])
h = np.maximum(pre, 0)
dh = np.array([0.1, 0.2, 0.3, 0.4])
print(h)
print(dh * (pre > 0))
print(dh * (h >= 0))
Predict

pre is [1.5, -0.5, 2.0, -3.0] and dh is [0.1, 0.2, 0.3, 0.4]. What is dh * (pre > 0)?

Pick one to see what it prints.
Pick an answer above to see the rest

A unit that's off for the whole batch gets no gradient

The mask has a side effect worth naming in an interview.

Unit 1 was off for every example
dpre (3, 3)
unit 0unit 1unit 2example 00.30-0.1example 1-0.200.4example 20.500.2

Unit 1's column is all 0. So its column of W1, from x.T @ dpre, gets 0. Its entry of b1, from dpre.sum(axis=0), gets 0. Its row of W2, from h.T @ dlogits, gets 0 too, since its h is 0.

A unit that's off for every example in the batch gets an all-zero column in dpre. So its column of W1 and its entry of b1 get no gradient. Its row of W2 gets none either, because its column of h is 0.

If no input ever turns it back on, it never learns again. That's a dead ReLU.

In the editor, write hidden_backward(dh, pre, x, W1): the gate, then the linear layer below it. linear_backward from earlier is written for you.

CheckpointBack through the ReLU

The hidden layer is pre = x @ W1 + b1, then h = np.maximum(pre, 0). Write hidden_backward(dh, pre, x, W1): given dh, the (N, H) gradient at h, return (dx, dW1, db1). Your linear_backward from earlier is in the stub.

A worked example

These numbers are small enough to check by hand: two examples, two inputs, two hidden units, two classes, and biases at zero.

The forward pass: example 2 is confidently wrong

x = np.array([[1.0, -1.0], [1.0, 2.0]])
y = np.array([0, 1])
W1 = np.array([[1.0, 1.0], [0.0, -1.0]])
W2 = np.array([[1.0, -1.0], [0.0, 1.0]])

pre = x @ W1
h = np.maximum(pre, 0)
logits = h @ W2
z = logits - logits.max(axis=1, keepdims=True)
log_probs = z - np.log(np.exp(z).sum(axis=1, keepdims=True))
loss = -log_probs[np.arange(2), y].mean()
print(np.exp(log_probs).round(2))
print(round(loss, 2))
Predict

The probabilities come out [0.5, 0.5] and [0.88, 0.12], with labels 0 and 1. About what is the mean loss?

Pick one to see what it prints.
Pick an answer above to see the rest

The backward pass: the mask stops the blame

Now run the backward pass on the same numbers.

dlogits = np.exp(log_probs)
dlogits[np.arange(2), y] -= 1
dlogits /= 2
dh = dlogits @ W2.T
dpre = dh * (pre > 0)
print(dpre.round(2))
print((x.T @ dpre).round(2))
Predict

Example 2's second hidden unit had pre = -1. What does dpre hold there?

Pick one to see what it prints.
Pick an answer above to see the rest

Measure one entry, and it agrees

Nudge W1[1, 0] down and up by 10−610^{-6}:

def loss_at(W1: np.ndarray) -> float:
    """W1: (2, 2). The worked example's mean loss with this W1."""
    logits = np.maximum(x @ W1, 0) @ W2
    z = logits - logits.max(axis=1, keepdims=True)
    return np.mean(np.log(np.exp(z).sum(axis=1)) - z[np.arange(2), y])

down, up = W1.copy(), W1.copy()
down[1, 0] -= 1e-6
up[1, 0] += 1e-6
print(f"{loss_at(down):.9f} {loss_at(up):.9f}")
print(f"{(loss_at(up) - loss_at(down)) / 2e-6:.10f}")
print(f"{(x.T @ dpre)[1, 0]:.10f}")
Predict

Nudge W1[1, 0] by ±1e-6 and divide the change in the loss by 2e-6. How close does it come to backprop's 2.2615941560?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 4 done
Part 5 of 6about 15 min
Prove it with a gradient check

Prove it with a gradient check

Nudge a weight both ways, and the loss gives its gradient

You can't eyeball a gradient, but you can measure one. Try it on v3v^3 at v=2v = 2, whose true slope is 12:

def cube(v: float) -> float:
    """Returns v cubed. Its slope at v is 3 v²."""
    return v ** 3

for eps in [1e-2, 1e-4, 1e-6]:
    central = (cube(2 + eps) - cube(2 - eps)) / (2 * eps)
    one_sided = (cube(2 + eps) - cube(2)) / eps
    print(f"{eps:.0e}   {abs(central - 12):.0e}   {abs(one_sided - 12):.0e}")
Predict

The slope of v³ at 2 is 12. With a nudge of 1e-4, how far off are the central estimate, which nudges both ways, and the one-sided one, which nudges only up?

Pick one to see what it prints.
Pick an answer above to see the rest

Use ε near 1e-6, and run the check in float64

Too small an ϵ\epsilon fails the other way. Each loss is only accurate to about float64's rounding, and you divide that rounding error by 2ϵ2\epsilon.

Predict

Run the check in float32 at ε = 1e-6, on a network whose largest gradient entry is 0.64. How far off is the worst entry?

Pick an answer above to see the rest

Check every entry of every parameter

Here is the check on every parameter of the practice network. numeric_grad is the part you write next:

_, grads = forward_backward(params, x, y)
for name, p in params.items():
    num = numeric_grad(lambda w: forward_backward({**params, name: w}, x, y)[0], p.copy())
    assert grads[name].shape == p.shape, name
    assert np.allclose(grads[name], num, rtol=1e-5, atol=1e-7), name

How it works:

  • numeric_grad(f, w) measures the slope of f along every entry of w, one entry at a time: a central difference for each.
  • np.ndindex(w.shape) gives every index of an array of any shape, so one loop visits every entry.
  • The lambda takes an array w, runs forward_backward with w in place of that one parameter, and keeps item [0], the loss.
  • np.allclose passes when every entry is within atol + rtol * abs(num) of the numerical value.
  • Callable[[np.ndarray], float], in the stub, is the type of a function that takes an array and returns a float.

Three things to watch:

  • Kinks. A nudge that carries pre across 0 crosses ReLU's corner, and the check can fail on correct code. PyTorch's gradcheck docs warn about the same thing at points with no derivative. In the test network the pre value nearest zero is 0.16 away, far beyond any 10−610^{-6} nudge.
  • Cost. Two loss evaluations per entry: 86 for the test network, two billion for a billion-parameter model. On a real model, check a random sample of entries.
  • Coverage. Check every parameter, and check its shape before its values.

In the editor, write numeric_grad(f, x, eps): the central difference of f along every entry of x, for any function and any array.

CheckpointA central-difference check

Write numeric_grad(f, x, eps=1e-6): the central-difference gradient of a scalar function f at the float64 array x, any shape. Nudge one entry at a time, and leave x as you found it.

Each test catches bugs the others miss

The practice tests pair the gradient check with a test at huge logits and a training run on three blobs of points. You've met five bugs in this lesson:

  • no division by N
  • b2 averaged twice
  • no ReLU mask
  • the mask from h >= 0
  • no max subtraction
Predict

Each of the five bugs goes through the training run. How many still reach 98.3% accuracy, the same as correct code?

Pick an answer above to see the rest

What each test sees

Here is what each test sees, from running every bug through the practice tests:

BugGradient checkHuge logitsTraining run
No division by Nfails, all 6xpassesfails, NaN
b2 averaged twicefails on b2passespasses, 98.3%
No ReLU maskfails on W1, b1passespasses, 98.3%
Mask from h >= 0fails on W1, b1passespasses, 98.3%
No max subtractionpassesfails, infpasses, 98.3%

The gradient check can't see overflow, so it needs the huge-logit test beside it.

Part 5 done
Part 6 of 6about 19 min
What interviewers ask next

What interviewers ask next

Deep stacks multiply many factors, so gradients vanish or explode

Once your gradients pass the check, the questions turn to deeper networks.

print(round(0.9 ** 50, 3), round(1.1 ** 50))
Predict

Fifty layers each scale the gradient by 0.9, or each by 1.1. What reaches the bottom?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

50 ReLU layers of width 256, with c = 1, so each layer halves the gradient's variance. How big is the gradient at the bottom, against the top?

Pick an answer above to see the rest

Four fixes for a gradient that vanishes or explodes

Deep networks still train, because four fixes keep that product of factors in check. One of them is a new path for the gradient.

Predict

A residual block outputs x + f(x). What is its slope?

Pick an answer above to see the rest

Clipping shrinks every gradient by the same factor

Clipping is the fix you apply after the fact, when a step explodes anyway.

grads = {"W": np.array([[3.0, 0.0], [0.0, 4.0]]), "b": np.array([12.0])}
max_norm = 6.5

norm = np.sqrt(sum((g ** 2).sum() for g in grads.values()))
clipped = clip(grads, max_norm)
print(norm)
print(clipped["W"].tolist(), clipped["b"].tolist())
Predict

The gradients' total length is 13, and max_norm is 6.5. What does clipping do to W's 3 and 4 and b's 12?

Pick one to see what it prints.
Pick an answer above to see the rest

Shifting a row's logits changes nothing in the gradient

A common follow-up: why doesn't subtracting the max change the gradient?

row = np.array([2.0, 1.0, -1.0])
for shift in [0.0, -2.0, 5.0]:
    e = np.exp(row + shift)
    print((e / e.sum()).round(3))
Predict

Add 0, then -2, then 5 to every logit in [2, 1, -1]. What does the softmax give?

Pick one to see what it prints.
Pick an answer above to see the rest

Layer norm's backward mixes every feature in a row

Layer norm and batch norm both subtract a mean and divide by a spread. They differ only in the axis. Layer norm takes the mean across each row, axis 1. Batch norm takes it down each column, axis 0:

Layer norm reads across a row, batch norm down a columnInteractive
x.mean(axis=1, keepdims=True)
feature 0feature 1feature 2feature 3meanexample 0→example 1→example 2→
shape(3, 4)→(3, 1)the 4 features squash to 1, and the axis stays
example 0: (1 + 3 + 2 + 6) / 4 = 3. It stands beside example 0's row.
Predict

Layer norm rescales one example across its features. Which inputs does one of its outputs depend on?

Pick an answer above to see the rest
Predict

Why does each row of layer norm's dx sum to zero?

Pick an answer above to see the rest

Batch norm mixes every example in the batch

Batch norm is axis 0 in the layer norm step's figure. It uses the same formula, with the means taken over the batch axis instead of the features. Ioffe and Szegedy (2015) built the normalization over each training mini-batch into the model itself.

Predict

Batch norm: give one example a zero gradient from above. Is its dx zero?

Pick an answer above to see the rest

The practice problem, start to finish

That's every piece the practice problem needs. It asks for the four levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
5 questions
  1. 1.Your gradient check fails, and every analytic gradient is exactly 6 times its finite-difference value. The batch has 6 examples. What's the bug?

  2. 2.dlogits is (N, K) and already divided by N. Which line gives db2?

  3. 3.You write the ReLU backward as dh * (h >= 0), where h = np.maximum(pre, 0). What does it compute?

  4. 4.You forgot the ReLU mask entirely. Which of the practice tests fail?

  5. 5.You skip the max subtraction, and the test pushes the logits up to about 100,000. What comes back?

Where this shows up

The reports behind this lesson, each with its source.

Same report, ML coding round: matrix multiplication forward pass and backprop in PyTorch, from a given code skeleton.

Candidate report·PracHub (first-person report, curated and edited by the site)·2026-08-24Source

Same MLE report, onsite ML coding: NumPy fluency was essential.

Candidate report·PracHub (first-person report, curated and edited by the site)·2026-08-25Source

Practice

Sources (8)
  1. Learning representations by back-propagating errors · Nature 323 · Oct 9, 1986
    “The procedure repeatedly adjusts the weights of the connections in the network so as to minimize a measure of the difference between the actual output vector of the net and the desired output vector.”
  2. torch.nn.CrossEntropyLoss · PyTorch 2.15 documentation · Oct 28, 2026
    “The input is expected to contain the unnormalized logits for each class (which do not need to be positive or sum to 1, in general).”
  3. torch.autograd.gradcheck.gradcheck · PyTorch 2.15 documentation · Oct 28, 2026
    “The default values are designed for input of double precision. This check will likely fail if input is of less precision, e.g., FloatTensor.”
  4. Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification · arXiv 1502.01852 · Feb 6, 2015
    “we derive a robust initialization method that particularly considers the rectifier nonlinearities. This method enables us to train extremely deep rectified models directly from scratch”
  5. Identity Mappings in Deep Residual Networks · arXiv 1603.05027 · Mar 16, 2016
    “the forward and backward signals can be directly propagated from one block to any other block, when using identity mappings as the skip connections and after-addition activation”
  6. On the difficulty of training Recurrent Neural Networks · arXiv 1211.5063 · Nov 21, 2012
    “We propose a gradient norm clipping strategy to deal with exploding gradients and a soft constraint for the vanishing gradients problem.”
  7. Layer Normalization · arXiv 1607.06450 · Jul 21, 2016
    “we transpose batch normalization into layer normalization by computing the mean and variance used for normalization from all of the summed inputs to the neurons in a layer on a single training case.”
  8. Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift · arXiv 1502.03167 · Feb 11, 2015
    “Our method draws its strength from making normalization a part of the model architecture and performing the normalization for each training mini-batch.”