Below is how tinygrad (and frameworks like PyTorch) set up and execute the backward pass when you write
python
x = Tensor([1.0, 2.0, 3.0], requires_grad=True)
y = x.relu() * x.sum()
1. Building the forward graph
Relu node
Input: x
Operation: relu(x)
Creates a new tensor a = x.relu(), with
• a.children = [x]
• a.grad_fn = relu_backward_closure
• also stores a mask (or the original x) in the closure for use in backward.
Sum node
Input: x
Operation: sum(x)
Creates a new tensor b = x.sum(), with
• b.children = [x]
• b.grad_fn = sum_backward_closure
• no mask needed, but may store the shape of x.
Mul node
Inputs: a and b
Operation: a * b
Creates the final y = a * b, with
• y.children = [a, b]
• y.grad_fn = mul_backward_closure
Visually:
code
x ───► relu ──► a ──┐
│ │
└──► sum ─────► b ──┴► mul ─► y
Each arrow holds a reference (.children) plus a tiny backward function stored in .grad_fn.
2. Saving context for backward
Each .grad_fn is really a small closure that “remembers” whatever it needs from forward:
ReLU
python
def relu_forward(x):
mask = (x.data > 0)
out = Tensor(x.data * mask, requires_grad=True)
def relu_backward(grad_out):
# gradient only flows where x > 0
return grad_out * mask
out.grad_fn = relu_backward
return out
Sum
python
def sum_forward(x):
out = Tensor(x.data.sum(), requires_grad=True)
def sum_backward(grad_out):
# grad_out is a scalar, broadcast to x.shape
return grad_out * np.ones_like(x.data)
out.grad_fn = sum_backward
return out
Mul
python
def mul_forward(a, b):
out = Tensor(a.data * b.data, requires_grad=True)
def mul_backward(grad_out):
# ∂(a*b)/∂a = b, ∂(a*b)/∂b = a
return grad_out * b.data, grad_out * a.data
out.grad_fn = mul_backward
return out
3. Executing y.backward()
Initialize.
Set y.grad = 1.0 (∂y/∂y).
Traverse the graph in reverse topological order.
Commonly done with a queue or recursive calls.
At each node:
Call its stored grad_fn, passing in the gradient flowing from above.
The grad_fn returns gradients w.r.t. its inputs.
Accumulate those into each input’s .grad field.
Enqueue each input tensor if it itself has a grad_fn.
grad_x_from_sum = sum_backward(b.grad)
# sum_backward broadcasts b.grad to shape of x
x.grad += grad_x_from_sum
End: x.grad now holds the total ∂y/∂x.
4. Why “context for backward” matters
Efficiency: you only store what you need (e.g. the ReLU mask, tensor shapes) so that backward is as cheap as possible.
Flexibility: every new op simply defines its own small grad_fn closure—no global dispatcher needed.
Clarity: the graph anatomy (.children, .grad_fn) plus saved context gives you a full recipe to compute ∂(output)/∂(each input).
That’s the essence of “backward context” in tinygrad (and PyTorch): each forward op saves just enough into a closure so that its paired backward can compute local gradients and pass them backward through the graph.