Lesson 1.7 — Automatic Differentiation
What does an automatic differentiation engine do?
Symbolic differentiation
Transform mathematical expressions into new derivative expressions. Correct, but expressions can grow rapidly.
Finite differences
Perturb an input and rerun the function. Simple, but suffers truncation and floating-point error and costs one forward pass per input.
Automatic differentiation
Apply the local derivative of each primitive actually executed, then combine them with the chain rule. Exact up to floating-point rounding, with no perturbation.
AD is a method; backpropagation is a use of it. Forward mode propagates input perturbations (JVP); reverse mode propagates output adjoints (VJP). For many parameters and a single scalar loss, one reverse sweep yields every input gradient without building the full Jacobian.
Course boundary. This lesson builds a scalar engine and studies the real PyTorch Autograd API. Full model training belongs to Lesson 1.8. Browser labs are deterministic JavaScript simulations; the Python code runs locally.
Record operations during forward execution
Dynamic Graph Recorder
x = torch.tensor(1.5, dtype=torch.float64)
w = torch.tensor(0.5, dtype=torch.float64, requires_grad=True)
b = torch.tensor(0.25, dtype=torch.float64, requires_grad=True)
p = x*w
z = p+b
a = z.tanh()
e = a - 0.5
L = e*e
for name, t in [('p',p), ('z',z), ('a',a), ('L',L)]:
print(name, t.item(), t.grad_fn)
What is stored? A differentiable operation creates an output with a
grad_fn pointing to its backward rule. Forward values needed by that rule are saved
for the reverse pass. The drawing shows value nodes; a real grad_fn is a function
object, not another value node.
Topological order and gradient propagation
Reverse-topological Graph Player
x = torch.tensor(2, dtype=torch.float64, requires_grad=True)
c = torch.tensor(-1, dtype=torch.float64)
u, v = x*x, c*x
L = u + v
L.backward()
print(x.grad, 2*x.detach() + c)
Identity is not multiplicity. Topological sorting visits each object once, but
local differentiation must still walk every operand position. In x*x both operand
edges contribute, so the derivative is x + x, not x.
Which tensors receive a .grad buffer?
requires_grad
Whether a tensor participates in gradient tracking. Trainable parameters are normally set to True.
Leaf tensor
A user-created tensor that requires gradients accumulates into .grad by default.
Non-leaf tensor
An intermediate produced by an operation still participates in propagation, but its .grad is not retained by default. Call retain_grad() to keep it.
Leaf & retain-grad Inspector
| Tensor | requires_grad | is_leaf | .grad buffer |
|---|---|---|---|
| x | True | True | None |
| w | True | True | None |
| z | True | False | None |
| L | True | False | None |
x = torch.tensor(2, dtype=torch.float64, requires_grad=True)
w = torch.tensor(2., requires_grad=True)
z = x*w
# non-leaf .grad is not retained
L = z*z
L.backward()
print('x:', x.requires_grad, x.is_leaf, x.grad)
print('w:', w.requires_grad, w.is_leaf, w.grad)
print('z:', z.is_leaf, 'grad not retained')
Three attributes, three questions
| Tensor | requires_grad | is_leaf | .grad by default |
|---|---|---|---|
x created by the user | user's choice | True | saved if tracking |
w = torch.tensor(2., requires_grad=True) | True | True | saved |
z = x * w | True if any input tracks | False | None |
L = z * z | True | False | None |
None is not zero. If no gradient was saved, .grad is
None. That is different from a stored numerical zero. Even when x
does not require gradients, it can still supply the numerical value needed to compute
w.grad.
What does backward(gradient=...) compute?
Vector-output Backward Seed
x = torch.tensor([1, 0.5], dtype=torch.float64, requires_grad=True)
a, b = x
y = torch.stack([a*a+b, a*b, b.sin()])
v = torch.tensor([1,-1,2], dtype=x.dtype)
g, = torch.autograd.grad(y, x, grad_outputs=v)
print(g) # returned VJP; x.grad is still None
grad versus backward. torch.autograd.grad returns the requested
gradient and normally does not accumulate into .grad.
backward() accumulates into the .grad buffers of the relevant leaf
tensors. Both compute a VJP, not the full Jacobian.
Gradient accumulation and zero_grad()
Suppose two batches use the same weight before the optimizer updates it. Batch A produces loss and gradient . Batch B produces and at the same value of . Each forward pass records its own operations. Both backward passes write to the same leaf tensor.
| Event | Computation used | Stored on the leaf as w.grad |
|---|---|---|
Clear with set_to_none=True | Start the accumulation window | None |
loss_A.backward() | Differentiate | |
Compute loss_B | Record the forward pass for B | Still |
loss_B.backward() | Differentiate |
The third row explains a common surprise. Running the model again creates a graph but does nothing to the gradient already stored on . Clearing just before the last row would discard A's contribution. An optimizer step changes the weight and starts a different comparison.
Each backward call here uses a fresh forward graph and the same parameter value. To reproduce the gradient of a mean over a larger batch, weight each micro-batch mean by its fraction of examples, then run the optimizer once. Clearing before each backward instead retains only the latest contribution.
This equivalence assumes each example's loss and forward computation are the same in the full and split batches. Training-mode BatchNorm can change the forward computation when batch composition changes.
Compare clearing once with clearing before every backward pass
Gradient Buffer Timeline
| Fresh graph | x | y | Local grad | Buffer before | Buffer after |
|---|---|---|---|---|---|
| 1 | 1 | 2 | — | — | — |
| 2 | 2 | 4 | — | — | — |
| 3 | 3 | 6 | — | — | — |
import torch
w = torch.tensor(1, dtype=torch.float64, requires_grad=True)
for x, y in [(1.,2.), (2.,4.), (3.,6.)]:
# keep the old buffer
L = (w*x - y)**2 # fresh graph
L.backward()
print(w.item(), w.grad.item())
Micro-batch accumulation. For equal-size micro-batches whose target is the mean
loss of the full batch, divide each micro-batch mean by the number of accumulation steps before
calling backward. For unequal sizes, weight by sample count. The optimizer updates parameters
only at step(). For accumulation, clear once, run the forward and backward
passes for every micro-batch, then take one optimizer step.
Fresh graph, old buffer. Each forward pass creates a new graph, but
.grad lives on the leaf tensor and persists until it is cleared. A second backward
without clearing adds to the first result.
Stop tracking without changing the forward result
requires_grad_(False)
Freezes a leaf parameter. Gradients may still flow through that operation to other inputs that require gradients.
detach()
Returns a tensor sharing the same storage but carrying no history from the original graph. It cuts that path.
torch.no_grad()
Records no reverse graph inside the scope. Common for inference and parameter updates. Factory functions with an explicit requires_grad argument are an exception.
Gradient Route Switch
x = torch.tensor(2, dtype=torch.float64, requires_grad=True)
q = x*x
r = 3*x
L = q + r
L.backward()
print(L.item(), q.requires_grad, x.grad)
eval() is not no_grad(). model.eval() changes the behaviour of
Dropout and BatchNorm; it does not disable Autograd. Do not wrap a training path in
detach() or no_grad() by accident. detach() is not a
copy; shared-storage in-place mutation is outside this lesson.
Build a scalar reverse-mode engine from scratch
Value object stores a forward number, an adjoint, its parents, and a local backward rule. Addition, multiplication and tanh are enough to differentiate the network below.Mini Autograd Engine — live trace
x,w,b,c = Value(1.5), Value(0.5), Value(0.25), Value(0.3)
z = x*w + b
a = z.tanh()
e = a + (-0.5)
L = e*e + c*w*w
L.backward()
print(L.data, w.grad, b.grad, x.grad, c.grad)
Full Python implementation
The closure saves the forward operands and tanh output, so later changes to data cannot corrupt the local derivative.
import math
class Value:
def __init__(self, data, parents=(), op="leaf"):
self.data = float(data)
self.grad = 0.0
self.parents = tuple(parents)
self.op = op
self._backward = lambda: None
def __add__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other), "+")
def backward():
self.grad += out.grad
other.grad += out.grad
out._backward = backward
return out
def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
a, b = self.data, other.data # save forward values
out = Value(a * b, (self, other), "*")
def backward():
self.grad += b * out.grad
other.grad += a * out.grad
out._backward = backward
return out
def tanh(self):
a = math.tanh(self.data)
out = Value(a, (self,), "tanh")
def backward():
self.grad += (1 - a*a) * out.grad
out._backward = backward
return out
def backward(self):
topo, visited = [], set()
def visit(v):
if v in visited:
return
visited.add(v)
for parent in v.parents:
visit(parent)
topo.append(v)
visit(self)
# teaching engine: clear ALL reachable nodes each call
for v in topo:
v.grad = 0.0
self.grad = 1.0
for v in reversed(topo):
v._backward()
# A tiny network with a shared parameter
x, w, b, c = Value(1.5), Value(0.5), Value(0.25), Value(0.3)
z = x*w + b
a = z.tanh()
e = a + (-0.5)
L = e*e + c*w*w
L.backward()
print('loss:', L.data)
print('dw, db, dx, dc:', w.grad, b.grad, x.grad, c.grad)
# Independent reference
import torch
xt, wt, bt, ct = [torch.tensor(v.data, dtype=torch.float64,
requires_grad=True) for v in (x,w,b,c)]
Lt = ((xt*wt+bt).tanh()-0.5)**2 + ct*wt*wt
Lt.backward()
for manual, ref in zip((x,w,b,c), (xt,wt,bt,ct)):
assert math.isclose(manual.grad, ref.grad.item(), abs_tol=1e-12)
print('Matches PyTorch Autograd')
w is shared by the neural path and the penalty c·w², so its adjoint receives two contributions.
Teaching simplifications. This scalar engine clears every reachable gradient on each backward call, so it differs from PyTorch's leaf-buffer accumulation. It has no tensor broadcasting, device handling, graph freeing, version counting, requires_grad filtering or higher-order derivatives. Its purpose is to expose reverse-topological traversal and local VJPs.
PyTorch training lifecycle (preview of 1.8)
import torch
w = torch.nn.Parameter(torch.tensor(0.0))
optimizer = torch.optim.SGD([w], lr=0.1)
x = torch.tensor([1., 2., 3.])
y = 2*x
optimizer.zero_grad(set_to_none=True)
loss = ((w*x - y)**2).mean()
loss.backward() # only compute gradients
print(w.item(), w.grad.item())
optimizer.step() # update parameters
print(w.item())
The gradient pushes w towards 2; one small step moves it only part of the way.
What changed from 1.6 to 1.7. We stopped writing the derivative of the entire model. Instead we defined a local derivative for each primitive and let one generic graph traversal combine those rules.