X = torch.tensor([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]]) # [1, input]
y = torch.tensor([1.0, 1.0, 0.0])
w = torch.tensor([1.0, 0.0])
def loss(w):
return ((X @ w - y) ** 2).sum()Dive into Deep Learning · §1.5
Automatic Differentiation: Computational Graphs, Reverse-Mode AD, and Dynamic Programs
forward & reverse mode · computational graphs · VJPs · detaching & memory control · dynamic control flow
Motivation
float32 precision to subtraction cancellation.Jacobians & Sweeps
For \mathbf{f}: \mathbb{R}^n \to \mathbb{R}^m with m \times n Jacobian \mathbf{J} (J_{ji} = \partial f_j / \partial x_i):
Forward Trace
loss(w) (matrix–vector product, subtraction, elementwise square, and sum) carries its own local backward VJP rule.Graph Construction
How Backpropagation Works
Backward Pass
Stateful Buffers
w.grad += g): Enables summing gradients across micro-batches when a full batch exceeds GPU memory.w.grad.zero_() before the next step adds onto stale gradients ((2, 4) + (2, 4) = (4, 8)).tensor([4., 8.])
Vector Outputs
tensor([2., 4.])
Graph Surgery
c = u.detach() (stop_gradient(u)) freezes u as constant x^2 \implies \frac{\partial z}{\partial x}\big|_c = c = x^2.Detaching in Practice
detach() / stop_gradient() (z = c * x): At \mathbf{x} = [0, 1, 2, 3]^\top, c = \mathbf{x}^2 = [0, 1, 4, 9]^\top acts as a constant, yielding \nabla_{\mathbf{x}} \sum_i z_i = \mathbf{x}^2 = [0, 1, 4, 9]^\top:tensor([0., 1., 4., 9.])
Memory & Inference
(tensor([ 0.8000, -0.4000], requires_grad=True), tensor(0.4000))
Differentiable Programs
f(a):
b inside a data-dependent while loop until \|\mathbf{b}\|_2 \ge 1000 (k doublings in total).b.sum() > 0 to return either b or 100 * b.Trace vs. Function
if branch) \implies k = 2^{12} = 4096.else branch) \implies k = 100 \cdot 2^{11} = 204{,}800.Check Your Understanding
Predict the behavior and gradient outcome in each scenario:
L.backward() on each without calling w.grad.zero_(). What does w.grad hold?u = x * x and c = u.detach() (or stop_gradient(u)). What is \nabla_{\mathbf{x}} \sum_i z_i for (a) z = u * u, (b) z = u * c, and (c) z = c * c?Answers:
z = u * u = x^4 \implies 4\mathbf{x}^3; (b) z = u * c = c * x^2 \implies 2c\mathbf{x} = 2\mathbf{x}^3 (half of 4\mathbf{x}^3, since one factor is frozen); (c) z = c * c has no active path to x \implies 0 (or no grad_fn).Key Takeaways
| Operation / Concept | API | Graph & Memory Behavior | Primary Deep Learning Role |
|---|---|---|---|
| Opt-in / Trace | w.requires_grad_(True) |
Caches forward activations in VRAM for backward VJPs | Standard neural network training (O(1) reverse sweep) |
| Reverse Sweep (VJP) | L.backward() or u.backward(v) |
Frees activation buffers after computing \mathbf{J}^\top \mathbf{v} | Backpropagation of scalar loss (m = 1) or upstream vector \mathbf{v} |
| Reset / Accumulate | w.grad.zero_() (adds += by default) |
Decides whether a new gradient adds to or replaces the last one | Micro-batch gradient accumulation vs. fresh optimizer step |
| Detach Subgraph | u.detach() |
Zero-copy constant view; cuts backward edge | RL target networks, BYOL/SimSiam teacher branch, GAN steps |
| Inference / No-Grad | with torch.no_grad(): |
Skips graph construction & activation caching (3\text{--}10\times less VRAM) | Validation loops, production inference, parameter updates |