Automatic Differentiation

Automatic differentiation computes exact derivatives of a program by applying the chain rule to elementary operations. It is different from symbolic differentiation, which manipulates expressions, and finite differences, which approximate derivatives by perturbing inputs.

For a composed function:

the derivative is a product of local derivatives:

where .

Forward and Reverse Mode

Forward-mode automatic differentiation propagates tangent information from inputs to outputs. It is efficient when the number of inputs is small and the number of outputs is large.

Reverse-mode automatic differentiation propagates adjoints from outputs back to inputs. It is efficient for scalar losses with many parameters, which is the common neural network case.

For a scalar loss and intermediate variable , reverse mode stores:

and propagates:

In practice, reverse-mode systems compute vector-Jacobian products rather than materializing full Jacobians:

This is why Backpropagation scales to models with many parameters.

Computation Graph

A training step builds a graph of operations:

Each operation records enough information to compute its local backward rule. During backward pass, gradients are accumulated at parameters:

This accumulation matters for shared parameters, recurrent computation, tied embeddings, and gradient accumulation.

Practical Notes

  • Stop-gradient or detach breaks a path in the computation graph.
  • In-place operations can invalidate saved tensors needed for backward.
  • Mixed precision may require gradient scaling before backward stability is reliable.
  • Non-differentiable operations require surrogate losses, straight-through estimators, relaxation, or policy gradients.
  • Memory use often comes from saved activations rather than parameter gradients.

Checks

  • Is the loss a scalar or reduced in the intended way before backward?
  • Are masked, padded, or invalid examples excluded before gradients are computed?
  • Are detached tensors intentional?
  • Are parameters shared, frozen, or excluded from optimizer groups correctly?
  • Does Gradient checking pass for custom operations?