How autograd works

The forward pass constructs a graph; the backward pass applies the chain rule in reverse.

Computation graph

Arrows run from each input to the value it produces. Blue nodes track gradients.

x = Tensor(2.0, requires_grad=True, label="x")
w = Tensor(-3.0, requires_grad=True, label="w")
b = Tensor(10.0, requires_grad=True, label="b")

prediction = (x * w + b).relu()
loss = prediction**2
loss.label = "loss"

loss.backward()
xdata = 2grad = -24leafwdata = -3grad = 16leafv2data = -6grad = 8*bdata = 10grad = 8leafv4data = 4grad = 8+v5data = 4grad = 8ReLUlossdata = 16grad = 1**2

Example walkthrough

Rows are in forward execution order. Gradients show the completed backward pass.

StepTensorCreated byForward valueBackward gradient
1xinput2-24
2winput-316
3v2x * w-68
4binput108
5v4v2 + b48
6v5ReLU(v4)48
7lossv5 **2161