Run reverse mode over an op tape where values are reused
Autograd engines record each operation on a tape, then walk it backwards. When one value feeds several later operations, its gradient is the SUM of what flows back along each use. Overwriting instead of adding is the most common autograd bug.
Write tape_grads(inputs, tape). inputs is a dict name -> float. tape is a list of (out, op, args) in execution order, where op is "add", "sub", "mul" or "square", and args is a list of names (two for add/sub/mul, one for square). The output of the last entry is the final result f.
Return a dict with df/dname for every name in inputs (0.0 for unused inputs).
def tape_grads(inputs, tape)Example
inputs {"x": 3.0}, tape [("y", "mul", ["x", "x"])] gives {"x": 6.0}.
Understand the idea
Reverse mode autodiff replays the tape from the last operation to the first, passing each output's gradient back to its inputs. When a value is used in several places, each use sends back its own share, and the shares must be added, never overwritten. Worked example: inputs x = 2, y = 3. Tape: a = mul(x, y) = 6, then f = add(a, x) = 8. Start with df/df = 1. The add sends 1 to a and 1 to x. The mul sends a's gradient times y = 3 to x and times x = 2 to y. So df/dx = 1 + 3 = 4 and df/dy = 2. Rules for local derivatives: add passes the gradient unchanged to both args, sub passes +g and -g, mul passes g times the other arg, square passes g * 2 * arg. Inputs that never appear get 0. For mul(x, x) both args are x, so x receives two contributions and the result is 2x. Every framework, from PyTorch to JAX, accumulates gradients this way.