TensorTau PathToAGI Neural Networks from First Principles Level 06

Level 06 · Neural Networks from First Principles · Chapter 084

dW, db and dX by Hand

For the basic layer Z = XW + b, what gradients must flow backward—and why do their matrix shapes make perfect sense?

1. Forward pass

Use batch-first notation:

X [B,D]
W [D,H]
b [H]
Z [B,H]

Z=XW+b.Z=XW+b.

Suppose the next part of the network sends us

G=∂L∂Z,G:[B,H].G=\frac{\partial L}{\partial Z},\qquad G:[B,H].

We need gradients for WW, bb, and XX.

2. Weight gradient

Each weight WdhW_{dh} connects input feature dd to output feature hh. Its contribution accumulates over all examples:

∂L∂W=XTG.\frac{\partial L}{\partial W}=X^TG.

Shape Check:

[D,B] @ [B,H] → [D,H]

Exactly the shape of W.

3. Bias gradient

The same bias is added to every example, so its gradient sums across the batch:

db=∑i=1BGi.db=\sum_{i=1}^{B}G_i.

Shape:

[B,H] sum over B → [H]

4. Input gradient

Earlier layers need to know how the loss changes with XX:

dX=GWT.dX=GW^T.

[B,H] @ [H,D] → [B,D]

Again, exactly the shape of X.

5. Small scalar check

For one example with z=xw+bz=xw+b and upstream gradient g=dL/dzg=dL/dz:

dW=xg,db=g,dx=wg.dW=xg,\qquad db=g,\qquad dx=wg.

The matrix rules are just all scalar paths organized efficiently.

6. Activation joins the chain

If A=f(Z)A=f(Z) and upstream gradient is dAdA,

dZ=dA⊙f′(Z).dZ=dA\odot f'(Z).

Then feed dZ into the three equations above.

What to Remember

dW = Xᵀ dZ
db = sum_batch(dZ)
dX = dZ Wᵀ

Do not memorize blindly: derive them from dependency paths and verify every shape.

Next → Matrix Backpropagation: how do these local rules compose across an entire multilayer network?

Six ways to work the chapter, climbing from explaining it in your own words to investigating it like a researcher. Reading is not enough — this is where the chapter lands.

  1. Explain: Why does db sum over the batch?
  2. Calculate: For tiny 2×2 matrices, compute dW=X.T@dZ by hand.
  3. Predict: State shapes of dX,dW,db from X [32,5], W [5,7].
  4. Break: Intentionally transpose the wrong matrix and diagnose the shape error.
  5. Build: Implement dense-layer forward/backward in NumPy.
  6. Investigate: Compare manual gradients with finite differences and PyTorch autograd.