Linear algebra for LLMsPart 8: Gradients through matrices

Gradients have shapes

5 min

One slope per parameter

∂L∂W=[∂L∂Wij]same shape as W\displaystyle \frac{\partial L}{\partial W} = \left[\frac{\partial L}{\partial W_{ij}}\right] \quad \text{same shape as } W

The loss LL is one number. Nudge one entry WijW_{ij} and LL changes at some rate: that rate is entry (i,j)(i, j) of the gradient. So the gradient of a 4096×40964096 \times 4096 weight is another 4096×40964096 \times 4096 matrix.

Write

∂L/∂W\partial L/\partial W has the shape of WW: one slope per entry.

The gradient of a dot product

L=w⋅x=w1x1+w2x2+w3x3\displaystyle L = w \cdot x = w_1 x_1 + w_2 x_2 + w_3 x_3
∂L∂w=[x1,x2,x3]=x\displaystyle \frac{\partial L}{\partial w} = [x_1, x_2, x_3] = x

Each wiw_i appears once, multiplied by xix_i, so its slope is xix_i. With x=[1,2,3]x = [1, 2, 3], the gradient is [1,2,3][1, 2, 3]: the weight paired with the biggest input matters most.

Write

∇w(w⋅x)=x\nabla_w (w \cdot x) = x.

And of a squared length

L=12∣w∣2=12∑iwi2  ⇒  ∇wL=w\displaystyle L = \tfrac12 |w|^2 = \tfrac12 \textstyle\sum_i w_i^2 \;\Rightarrow\; \nabla_w L = w

Each term 12wi2\tfrac12 w_i^2 has slope wiw_i. This is weight decay’s pull: it shrinks every weight in proportion to its size.

Gradient descent

w←w−η ∇wL\displaystyle w \leftarrow w - \eta\, \nabla_w L
− 0.10.1 =

The gradient points uphill, so step the other way, scaled by the learning rate η\eta. With L=w⋅xL = w \cdot x: before the step L=6L = 6, after it L=0.9+1.6+2.1=4.6L = 0.9 + 1.6 + 2.1 = 4.6.

Write

w←w−η∇Lw \leftarrow w - \eta\nabla L. Here LL: 6→4.66 \to 4.6.

✏️ Your turn

One step

L=w⋅x,x=[2,−1],w=[0,0],η=0.5\displaystyle L = w \cdot x, \quad x = [2, -1], \quad w = [0, 0], \quad \eta = 0.5

Write the gradient and ww after one step.

Work it out on paper, then go to the next card to check.

Answer

∇wL=[2,−1]\displaystyle \nabla_w L = [2, -1]
w=[0,0]−0.5 [2,−1]=[−1,0.5]\displaystyle w = [0, 0] - 0.5\,[2, -1] = [-1, 0.5]

LL goes from 0 to −2−0.5=−2.5-2 - 0.5 = -2.5: down, as it should.

In PyTorch

loss.backward()
w.grad.shape == w.shape      # True: one slope per parameter
with torch.no_grad():
    w -= lr * w.grad

📌 Recap

Gradients have shapes in one card

  • ∂L/∂W\partial L / \partial W has WW’s shape.
  • ∇w(w⋅x)=x\nabla_w(w \cdot x) = x; ∇w12∣w∣2=w\nabla_w \tfrac12|w|^2 = w.
  • Descent: w←w−η∇Lw \leftarrow w - \eta\nabla L.

Write

The three lines above.