Backpropagation Through a Dense Layer
Intuition
DL-10 differentiated one neuron for one example. A dense layer is many neurons applied to a batch at once: . The same chain rule gives compact matrix formulas, and there is a simple check: every gradient has exactly the same shape as the thing it is the gradient of.
Precise explanation
Shapes: is , is , is , and the upstream gradient is . Then
Each entry , so ; summing over examples gives . The bias is added to every row, so its gradient sums rows.
ReLU : (gradient passes where the input was positive).
MSE loss over all entries: with the number of entries, so .
Two-layer network , : start from , apply the dense rule for layer 2 (giving ), the ReLU rule, then the dense rule for layer 1.
Worked example
, , : , , .
Common mistakes
- — the transpose of the right answer (shape ).
- Averaging over the batch when the loss already divided by (dividing twice).
- ReLU backward using vs is fine, but using
dA > 0is wrong.
Why this matters
These four lines are the backward pass of every fully connected network; DL-13 verifies them numerically and DL-19 uses them to train.
Library implementation
In PyTorch the layer is torch.nn.Linear(d_in, d_out) (it stores the weight transposed, shape
(d_out, d_in)) and loss.backward() computes exactly these gradients. The comparison below
builds the same two-layer network in PyTorch and checks the gradients match; it runs only when
PyTorch is installed.
References
- CS231n: Backpropagation notes — Stanford University CS231n (
S016) - Dive into Deep Learning — Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola (
S013)