Week 02 · Backpropagation and autodiff
Derive one gradient, then check it with both autodiff and finite differences.
← Week 1 · Subject contents · Week 3 →
Derive one gradient, then check it with both autodiff and finite differences.
Work through the problem
Use a network with h = wx, ŷ = vh, and L = (ŷ−y)²/2. The chain rule gives ∂L/∂w = (ŷ−y)vx and ∂L/∂v = (ŷ−y)h. With x=2, y=5, w=1, and v=3, ŷ=6, so the two gradients are 6 and 2.
Reverse-mode autodiff sends the upstream derivative through each operation in reverse order. Compare its result with the hand derivation and the centered finite difference [L(w+ε)−L(w−ε)]/(2ε). Double precision helps avoid cancellation when ε is small.
Run the Python lab
import torch
w = torch.tensor(1.,dtype=torch.float64,requires_grad=True)
v = torch.tensor(3.,dtype=torch.float64,requires_grad=True)
def loss(weight, scale):
return (scale*weight*2-5)**2/2
loss(w,v).backward()
eps = 1e-5
with torch.no_grad():
finite = (loss(w+eps,v)-loss(w-eps,v))/(2*eps)
print("Autodiff:", w.grad.item(), v.grad.item())
print("Finite difference for w:", round(finite.item(),6))
assert abs(finite.item()-w.grad.item())<1e-8
Output from the lab
Autodiff: 6.0 2.0
Finite difference for w: 6.0
Practice
- What gradient reaches w when v is zero?
Check your reasoning
- Zero in this network, because changing w cannot change the output when v=0.
← Week 1 · Subject contents · Week 3 →
Further reading · Goodfellow, Bengio, and Courville · Deep Learning