Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Reading guide — matrix gradients

Reading guide: matrix gradients

Supplementary explanation · AI-assisted. Read alongside the original matrix multiplication notes and the two handwritten derivation pages that follow them. The original comments are unchanged.

What each dimension represents

Your output layer computes

Z=HW+b.Z = HW + b.

Here, HH has shape 32×6432\times64, WW has shape 64×2764\times27, and ZZ has shape 32×2732\times27. Each row is one example; each output column corresponds to a vocabulary entry. The bias vector is shared across all 32 rows.

Let G=∂L/∂ZG = \partial L / \partial Z. The backward pass starts with GG, which tells us how the scalar loss changes with each logit.

Follow one entry before using matrices

For one output entry,

Zij=∑kHikWkj+bj.Z_{ij} = \sum_k H_{ik}W_{kj} + b_j.

An entry HikH_{ik} contributes to every output column in row ii. Those contributions must be added:

∂L∂Hik=∑jGijWkj.\frac{\partial L}{\partial H_{ik}} = \sum_j G_{ij}W_{kj}.

Writing those sums as a matrix product gives

∂L∂H=GWT.\frac{\partial L}{\partial H}=GW^T.

A weight WkjW_{kj} is reused across the batch, so its gradient adds contributions over examples:

∂L∂Wkj=∑iHikGij,∂L∂W=HTG.\frac{\partial L}{\partial W_{kj}}=\sum_i H_{ik}G_{ij},\qquad \frac{\partial L}{\partial W}=H^TG.

The same bias bjb_j contributes to every example’s jjth logit:

∂L∂bj=∑iGij.\frac{\partial L}{\partial b_j}=\sum_i G_{ij}.

This explains the sum over the batch dimension in your bias-gradient code.

Shapes check the result; dependencies explain it

Your shape reasoning is a useful way to catch errors. A matching shape alone does not prove a derivative is correct: different expressions can share a shape. The index-wise chain rule above establishes the expression; dimensions provide a second check.

You do not need another division by batch size here if the incoming GG already contains the factor from a mean loss. The normalization travels backward with the gradient.

Check your understanding

Before looking back at the formulas, explain why the weight gradient sums across examples while the hidden-state gradient sums across output channels. Then compare your explanation with the arrows and sums in the original handwritten pages.

Try the recall questions.