Where We Are
We already know how learning works for scalar parameters:
But a neural-network layer looks like
where
- is a batch of inputs,
- is a matrix of weights,
- is a bias vector,
- is a matrix of outputs.
So the real object we need is not one derivative. It is
— a whole matrix telling us how every weight affects the loss.
1. Start With One Neuron
Suppose
and the loss is .
By the chain rule,
Similarly,
Collect both derivatives into a vector:
Already we can see the pattern:
input × upstream gradient
That pattern becomes matrix multiplication when we process batches.
2. From One Example to a Batch
Let
and
Then
has shape
Now imagine the next part of the network has already told us
with the same shape as :
We want the gradient of the loss with respect to .
The answer is
Check the shapes:
Therefore
which matches the shape of exactly.
This is not coincidence. A gradient must match the shape of the object it updates.
3. Why ?
Take one weight .
The output entry for batch item and output unit is
So
The loss depends on through every example in the batch:
Substitute:
But that sum is exactly the entry of
So matrix calculus is not magic. It is many scalar chain-rule calculations compressed into one matrix operation.
4. Gradient With Respect to the Input
Training also needs to pass information backward into earlier layers.
For
we get
Shape check:
therefore
which matches .
This quantity is often called dX in neural-network derivations.
5. Gradient With Respect to Bias
Now include the bias:
The same bias is added to every example in the batch.
So each example contributes to the bias gradient.
Therefore
In code, this is usually a sum across the batch dimension:
db = dY.sum(axis=0)
If has shape [D_out], then db also has shape [D_out].
6. The Three Equations to Remember
For a linear layer
and upstream gradient
we get
Do not memorize them as unrelated formulas.
Read them as information flow:
- dW asks: which inputs were present when the output error arrived?
- dX asks: how should that output error be projected back through the weights?
- db asks: how much total output error accumulated across the batch?
7. Tiny Numerical Example
Let
and
Then
Suppose the next layer sends back
Then
with
Therefore
Every number in this matrix tells us how changing one weight would change the final loss.
8. NumPy From Scratch
import numpy as np
X = np.array([[1., 2.],
[3., 4.]])
W = np.array([[5., 6.],
[7., 8.]])
b = np.array([1., 1.])
Y = X @ W + b
dY = np.array([[1., 2.],
[3., 4.]])
dW = X.T @ dY
dX = dY @ W.T
db = dY.sum(axis=0)
print("Y =\n", Y)
print("dW =\n", dW)
print("dX =\n", dX)
print("db =", db)
Before running it, predict every shape.
9. Finite-Difference Gradient Check
How do we know the matrix formula is correct?
We can perturb one weight slightly.
For a small :
This is called a numerical gradient check.
It is slow, so we do not train this way.
But it is extremely useful for verifying a hand-derived backward pass.
eps = 1e-5
Change one entry of W, recompute the loss, and compare the numerical slope with the matching entry in dW.
This is how you turn calculus into testable software.
10. PyTorch Confirms the Derivation
import torch
X = torch.tensor([[1., 2.],
[3., 4.]])
W = torch.tensor([[5., 6.],
[7., 8.]], requires_grad=True)
b = torch.tensor([1., 1.], requires_grad=True)
Y = X @ W + b
loss = (Y ** 2).sum()
loss.backward()
print(W.grad)
print(b.grad)
PyTorch’s autograd does not replace the mathematics.
It automates exactly the chain-rule bookkeeping we just derived.
When debugging a neural network, understanding the underlying shapes and formulas is what lets you decide whether an autograd result makes sense.
11. Shape Check
Suppose
X : [32, 128]
W : [128, 64]
b : [64]
Then
Y : [32, 64]
dY : [32, 64]
Predict:
dW = X.T @ dY → [128, 64]
dX = dY @ W.T → [32, 128]
db = sum(dY, 0) → [64]
This habit catches a huge fraction of backpropagation mistakes before code runs.
12. Why Transposes Keep Appearing
A transpose is often needed because forward and backward information travel in opposite structural directions.
Forward:
Backward into :
Backward into :
The transpose is what makes the inner dimensions align while preserving the correct output shape.
A useful debugging question is:
What shape must the gradient have? What multiplication produces exactly that shape?
Shape reasoning does not prove the derivative, but it eliminates many impossible answers.
13. From Matrix Calculus to Backpropagation
A neural network is a composition:
Backpropagation repeatedly applies the same principle:
- receive an upstream gradient,
- compute local gradients,
- produce parameter gradients,
- pass a new upstream gradient to the previous operation.
Matrix calculus is the language that makes those steps compact.
Without it, backpropagation looks like mysterious symbol pushing.
With it, backpropagation becomes structured bookkeeping.
14. Break It
Deliberately create these bugs:
- use
X @ dYinstead ofX.T @ dY, - sum
dYacross the wrong axis fordb, - swap the order in
dY @ W.T, - create a batch of size 1 and accidentally squeeze a dimension,
- compare your manual gradient against PyTorch autograd.
For each failure, explain whether the problem is:
- mathematically wrong,
- shape-incompatible,
- accidentally broadcastable,
- numerically plausible but conceptually wrong.
The last category is the dangerous one.
15. What You Should Now Understand
You should be able to derive and explain:
You should also understand that:
- matrix gradients are collections of scalar partial derivatives,
- the chain rule is still doing the real work,
- transposes arise from the structure of matrix multiplication,
- gradient shapes must match the quantities they update,
- numerical gradient checks can verify a backward pass,
- autograd automates these exact operations.
Level 2 Milestone
We began this level with a simple question: how does a value change?
That forced us to discover:
functions
↓
slopes
↓
derivatives
↓
partial derivatives
↓
gradients
↓
chain rule
↓
computational graphs
↓
gradient descent
↓
learning-rate geometry
↓
matrix calculus
We now have the mathematical machinery required to train neural networks.
But learning from data also means reasoning when outcomes are uncertain.
Next → Level 3: Probability and Uncertainty.