Foundations to Frontier
Tests
C. Programming, Tools and HPC › C3 Deep Learning Frameworks

Writing Custom Autograd Functions

Sometimes the gradient autograd would compute is slow, numerically unstable, undefined, or not the one you want. A custom torch.autograd.Function lets you write forward and backward yourself: to make a function numerically stable (softplus, logsumexp), to define a gradient where the true one is nan or zero (safe norms, the straight-through estimator for rounding), to wrap code autograd can't see (NumPy, C++, a simulator), or to differentiate an iterative solver with the implicit function theorem instead of replaying its loop. This topic covers the Function API (ctx, save_for_backward, needs_input_grad, once_differentiable), verifying a backward with gradcheck, and JAX's custom_vjp. In the exercises you implement the Function pattern and gradcheck in NumPy, then differentiate through a Kepler's-equation solver and compare unrolled and implicit gradients.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Telling the computer the shortcut

Autograd works out slopes by retracing every small step of a calculation. Usually that’s fine. But imagine a calculation that takes a hundred guesses to find an answer (like a solver hunting for where a satellite is on its orbit). Retracing all hundred guesses is slow, and early guesses were wrong anyway. If you know a math shortcut for the slope of the final answer, you can hand the computer that shortcut directly. A custom autograd function is exactly that: “here’s how to compute the value, and here’s how to compute its slope.”

Gradients through a solver: unroll the loop, or use the implicit function theorem?
1e01e-41e-81e-121e-1612345678910error in Eerror in unrolled dE/dM● converged · ○ after k iterations
implicit (custom backward): dE/dM = 1.681838
unrolled after 3: dE/dM = 1.686278 (error 4.4e-3)
memory for backward: implicit stores 1 value; unrolled reverse mode stores 3 iterates
E = 1.103518 rad; E after 3: 1.157264 (error 5.4e-2)
Raise e toward 1 with small M: Newton needs more iterations, and the unrolled gradient is wrong until the solver has converged. The custom backward costs one division whatever the iteration count, as long as the forward pass converged. The same idea (a torch.autograd.Function whose backward solves a linear system instead of replaying the loop) is used for optimization layers, equilibrium models and differentiable physics.
Why engineers care

Physics inside learning systems often comes from solvers: Kepler’s equation, inverse kinematics, contact models, optimal-control problems, implicit integrators. Custom backward passes let gradients flow through them cheaply and stably, which is what makes differentiable simulators and “physics layers” practical.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A custom autograd function supplies…
  2. 2. Why not just retrace every guess of a solver?
  3. 3. In the demo, when is the unrolled gradient right?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The Function API

import torch

class Softplus(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x):
        ctx.save_for_backward(x)                       # tensors needed in backward
        return torch.clamp(x, min=0) + torch.log1p(torch.exp(-x.abs()))

    @staticmethod
    def backward(ctx, grad_out):                       # one grad_out per output
        (x,) = ctx.saved_tensors
        return grad_out * torch.sigmoid(x)             # one gradient per input (None if not needed)

y = Softplus.apply(x)                                  # use .apply, never call forward directly

Rules: forward runs without recording a graph; backward receives the gradient of the loss with respect to each output and returns the gradient with respect to each input (a vector-Jacobian product, never the full Jacobian). Return None for inputs that don’t need gradients (ctx.needs_input_grad says which do). Save tensors with save_for_backward; store non-tensors as attributes on ctx.

📝 Quick check (Level 1)
0/3 answered
  1. 1. How do you call a custom Function?
  2. 2. backward returns…
  3. 3. Where do you keep tensors needed for backward?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

When to write one

  1. Numerical stability. log(1 + exp(x)) overflows for x ≈ 710 and autograd would differentiate the unstable formula; the stable form and an explicit sigmoid backward fix both. LogSumExp is shifted by its maximum; its gradient is the softmax.
  2. Defined gradients at singular points. The gradient of ‖x‖ at 0 is 0/0 = nan, which poisons every parameter. A safe norm defines it as 0.
  3. Surrogate gradients. Rounding, sampling or thresholding have zero gradient almost everywhere. The straight-through estimator (STE) uses the identity in backward so quantized networks can train. It is deliberately not the true derivative.
  4. Opaque code. Wrapping a NumPy, C++ or CUDA routine with a known derivative.
  5. Iterative solvers. Use the implicit function theorem instead of unrolling (Level 3).
  6. Memory. Recompute instead of saving activations (gradient checkpointing is the general version).

Checking a backward: gradcheck

torch.autograd.gradcheck(fn, inputs) compares your backward with central finite differences in float64. It checks each column of the Jacobian: for a random direction u, the vector-Jacobian product must match the derivative of ⟨u, f(x)⟩. Always run it, with inputs away from kinks and in double precision. gradgradcheck does the same for second derivatives.

🐍 Exercise 1: the Function pattern and gradcheck
Implement a ctx object with save_for_backward, a Function base with apply, and gradcheck (vector-Jacobian product versus central differences of the inner product with a random output direction). Write Softplus (stable), LogSumExp (shifted, gradient = softmax), SafeNorm (zero gradient at the origin), RoundSTE (straight-through), and Mul. gradcheck must pass for the true derivatives and flag a backward with swapped gradients and the STE.
📝 Quick check (Level 2)
0/3 answered
  1. 1. The gradient of logsumexp(x) with respect to x is…
  2. 2. Why run gradcheck in float64?
  3. 3. The straight-through estimator for rounding uses in backward…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Implicit differentiation

If the output y of a solver satisfies F(y, θ) = 0, then differentiating the identity gives

∂F/∂y · dy/dθ + ∂F/∂θ = 0, so dy/dθ = −(∂F/∂y)⁻¹ ∂F/∂θ,

wherever ∂F/∂y is invertible (implicit function theorem). The backward pass then needs only the converged y, one linear solve, and no record of the iterations. For Kepler’s equation F = E − e sin E − M:

dE/dM = 1/(1 − e cos E), dE/de = sin E/(1 − e cos E).

Unrolling instead differentiates the k iterations that actually ran. Its result is the derivative of an approximation, it is right only once the iterates have converged, and reverse mode stores every iterate (memory grows with k). Implicit gradients are exact for the exact solution, cost O(1) memory, and are only as accurate as the forward solve.

In JAX

jax.custom_vjp (forward returns the output and residuals; backward maps residuals and output gradient to input gradients) and jax.custom_jvp play the same roles; jax.lax.custom_root and the JAXopt/Optimistix libraries implement implicit differentiation of solvers. PyTorch’s torch.func offers the same for functional code.

📝 Quick check (Level 3)
0/3 answered
  1. 1. The implicit gradient needs…
  2. 2. The implicit function theorem requires that…
  3. 3. Memory of reverse-mode through k solver iterations grows like…

Level 4: Expert

★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.

Custom gradients, measured

Exercise 1. gradcheck passes for Softplus, LogSumExp, SafeNorm and Mul on random 3×4 inputs and fails for the swapped-gradient multiplication (error 22) and the STE. The naive softplus returns inf at x = 800 while the stable version returns 800 with gradient 1; at x = −30 both the value and the gradient equal 9.36e−14 to full relative precision.

Exercise 2: differentiating Kepler’s equation. At M = 0.3 rad and e = 0.9, E = 1.103518 rad, dE/dM = 1.681838 and dE/de = 1.501541. The implicit gradients match finite differences to 7e−11. Differentiating through k Newton iterations started at E₀ = M gives:

k error in E error in unrolled dE/dM
1 1.09 1.85
3 0.054 4.4e−3
5 2.3e−6 9.0e−6
6 3.6e−12 3.3e−11
8 0 4e−16

Chaining the custom backward into the true anomaly gives dν/dM = 1.232949, equal to the orbital-mechanics formula (1 + e cos ν)²/(1 − e²)^1.5 to 1e−16. The unrolled gradient is a gradient of the wrong function until the solver converges, and the near-parabolic orbit (1 − e cos E small near periapsis) is exactly where convergence is slowest.

🐍 Exercise 2 (research): differentiate through a Kepler solver
Solve Kepler's equation with Newton's method. Write a custom backward with the implicit function theorem for dE/dM and dE/de, check it against finite differences, compare it with forward-mode dual numbers propagated through k Newton iterations, and chain it into the true anomaly to reproduce the analytic dν/dM.

Custom gradients in AI, robotics and aerospace

  • Differentiable orbit determination: gradients of predicted observations through Kepler solvers and propagators for gradient-based fitting.
  • Optimization layers: a QP or MPC solve inside a network (OptNet, differentiable MPC) differentiated through its KKT conditions.
  • Deep equilibrium models: a fixed point z = f(z, x) with implicit backward.
  • Quantization-aware training for embedded inference, using straight-through estimators.
  • Contact and collision in differentiable physics, where true gradients are zero or undefined and surrogates are designed.

References

  1. PyTorch documentation (pytorch.org/docs): Extending PyTorch, torch.autograd.Function, gradcheck.
  2. Y. Bengio, N. Léonard, A. Courville (2013). “Estimating or propagating gradients through stochastic neurons for conditional computation.” arXiv:1308.3432.
  3. B. Amos, J. Z. Kolter (2017). “OptNet: differentiable optimization as a layer in neural networks.” ICML.
  4. S. Bai, J. Z. Kolter, V. Koltun (2019). “Deep equilibrium models.” NeurIPS 32.
  5. M. Blondel et al. (2022). “Efficient and modular implicit differentiation.” NeurIPS 35.
  6. H. D. Curtis (2020). Orbital Mechanics for Engineering Students, 4th ed. Butterworth-Heinemann (Kepler’s equation).