Higher-Order Gradients & torch.func
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Plain backward() gives you first derivatives of a scalar loss with respect to leaf tensors. Many techniques need more: gradient penalties (WGAN-GP) differentiate a gradient, second-order optimizers and curvature analysis need Hessians and Hessian-vector products, meta-learning differentiates through an optimization step, and privacy-preserving training needs a gradient per example rather than per batch. PyTorch covers this with three layers: create_graph=True on the ordinary autograd engine, the torch.autograd.functional helpers, and torch.func, a library of composable function transforms in the style of JAX.
Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31. torch.func is labelled beta in the 2.15 documentation: "APIs may change based on user feedback and coverage of PyTorch operations is incomplete". For the foundations see Autograd Fundamentals and Backpropagation & Automatic Differentiation; mathematical background on Jacobians and Hessians is in Math for ML.
Higher-order derivatives with create_graph
torch.autograd.grad(outputs, inputs, create_graph=True) returns the gradient and records the computation of that gradient in the graph, so the result can be differentiated again. Without create_graph=True the returned gradient has no history and a second call fails.
import torch
x = torch.tensor(2.0, requires_grad=True)
y = x ** 3
(g1,) = torch.autograd.grad(y, x, create_graph=True) # 3x^2 = 12
(g2,) = torch.autograd.grad(g1, x, create_graph=True) # 6x = 12
(g3,) = torch.autograd.grad(g2, x) # 6
print(g1.item(), g2.item(), g3.item()) # 12.0 12.0 6.0
loss.backward(create_graph=True) does the same for .grad fields. The graph is retained until the result is freed, so double backward costs more memory than the first pass.
Gradient penalty
A gradient penalty adds a term that depends on the gradient of the output with respect to the input. Here the penalty drives the input-gradient norm of a linear critic towards 1, the pattern used in WGAN-GP:
import torch.nn as nn
xp = torch.randn(4, 3, requires_grad=True)
net = nn.Linear(3, 1)
(gp,) = torch.autograd.grad(net(xp).sum(), xp, create_graph=True)
penalty = ((gp.norm(dim=1) - 1) ** 2).mean()
penalty.backward() # differentiates through the gradient computation
print(net.weight.grad.shape) # torch.Size([1, 3])
For generative models that use this penalty see Generative Models.
Hessian-vector products without the Hessian
For a large model the full Hessian is far too big, but the product of the Hessian with a vector \(v\) costs about as much as one extra backward pass. Differentiate the dot product of the gradient and \(v\):
\[ H v = \nabla_{\theta} \left( \nabla_{\theta} L(\theta)^\top v \right) \]
w = torch.randn(3, requires_grad=True)
loss = (w ** 4).sum()
(gw,) = torch.autograd.grad(loss, w, create_graph=True)
v = torch.ones(3)
(hv,) = torch.autograd.grad(gw, w, grad_outputs=v) # grad_outputs plays the role of v
print(torch.allclose(hv, 12 * w.detach() ** 2)) # True: the Hessian is diag(12 w^2)
This is the basis of conjugate-gradient solvers, influence functions and the power-iteration estimates of the top Hessian eigenvalue used in sharpness studies.
torch.autograd.functional
torch.autograd.functional offers convenience functions that take a Python function and inputs and return a Jacobian, a Hessian or a product: jacobian, hessian, vjp, jvp, hvp and vhp. They are built on the ordinary engine, accept create_graph and strict arguments, and are easy to use for small problems.
from torch.autograd.functional import jacobian, hessian, hvp
def f(v):
return (v ** 2).sum() + v[0] * v[1]
v = torch.tensor([1.0, 2.0, 3.0])
print(jacobian(f, v)) # tensor([4., 5., 6.])
print(hessian(f, v)) # [[2, 1, 0], [1, 2, 0], [0, 0, 2]]
print(hvp(f, v, torch.ones(3))) # (tensor(16.), tensor([3., 3., 2.]))
Source: https://docs.pytorch.org/docs/stable/autograd.html (torch.autograd.functional)
The documentation labels this module beta and notes that major performance improvements are planned. In practice these helpers compute a Jacobian by differentiating one output element at a time, so for anything beyond small problems the torch.func equivalents, which batch that work with vmap, are usually the better choice (this performance statement is general experience and was not benchmarked here).
torch.func: composable function transforms
torch.func (previously called functorch) provides JAX-like transforms. A transform takes a function and returns a new function that computes something else, and transforms nest: vmap(grad(f)) is a vectorized gradient. The documentation’s "UX limitations" page lists what the transforms require of the function: it should be pure (no side effects through globals or mutable state), and some Python features such as data-dependent control flow on tensor values are restricted. A migration guide exists for code that still imports functorch.
-
grad(f, argnums=0, has_aux=False): gradient of a scalar-valued function with respect to selected inputs. -
grad_and_value(f): returns the gradient and the function value together. -
vjp(f, *primals): returns the output and a function that computes vector-Jacobian products (reverse mode). -
jvp(f, primals, tangents): Jacobian-vector product (forward mode). -
jacrev(f)andjacfwd(f): full Jacobian using reverse or forward mode. -
hessian(f): Hessian, computed with a forward-over-reverse strategy; the executed snippet below shows that it matchesjacfwd(jacrev(f)). -
vmap(f, in_dims=0, out_dims=0, randomness='error'): vectorizes a function written for one sample over a batch dimension. -
functional_call(module, params_and_buffers, args): calls a module with substituted parameters. -
stack_module_state(models): stacks the parameters and buffers of identically structured models, for ensembling.
Source: https://docs.pytorch.org/docs/stable/func.html and https://docs.pytorch.org/docs/stable/func.api.html
Gradients, Jacobians and Hessians
from torch.func import grad, grad_and_value, jacrev, jacfwd, hessian, jvp, vjp
print(grad(f)(v)) # tensor([4., 5., 6.])
print(grad_and_value(f)(v)) # (tensor([4., 5., 6.]), tensor(16.))
print(jacrev(f)(v), jacfwd(f)(v)) # identical for this scalar-valued f
print(hessian(f)(v)) # same matrix as above
print(jacfwd(jacrev(f))(v)) # the same Hessian, built explicitly
out, jvp_out = jvp(f, (v,), (torch.ones(3),))
print(out, jvp_out) # tensor(16.) tensor(15.): the directional derivative
out, vjp_fn = vjp(f, v)
print(vjp_fn(torch.tensor(1.0))) # (tensor([4., 5., 6.]),)
def g(a, b):
return (a * b).sum()
a, b = torch.ones(3), torch.arange(3.0)
print(grad(g, argnums=(0, 1))(a, b)) # gradients for both arguments
def h(a):
r = (a ** 2).sum()
return r, {"norm": r.sqrt()} # auxiliary output that is not differentiated
gr, aux = grad(h, has_aux=True)(torch.tensor([3.0, 4.0]))
print(gr, aux) # tensor([6., 8.]) {'norm': tensor(5.)}
Source: https://docs.pytorch.org/tutorials/intermediate/jacobians_hessians.html and https://docs.pytorch.org/docs/stable/func.api.html
Choosing between jacrev and jacfwd is a cost question. For a function from \(\mathbb{R}^n\) to \(\mathbb{R}^m\) the Jacobian has \(m\) rows. Reverse mode needs one backward pass per output (cheap when \(m\) is small, as for a scalar loss); forward mode needs one pass per input (cheap when \(n\) is small). The Hessian of a scalar function is square and uses both: forward-over-reverse is usually the cheapest composition, which is why hessian is defined that way.
vmap
vmap takes a function written for a single example and runs it over a batch dimension without a Python loop; the batching rules are implemented per operation, and the function is not traced into a graph.
from torch.func import vmap
batched = torch.randn(5, 3)
print(vmap(torch.dot)(batched, batched).shape) # torch.Size([5])
print(vmap(lambda r: r.sum(), in_dims=1)(batched).shape) # torch.Size([3])
print(vmap(lambda r: r * 2, out_dims=1)(batched).shape) # torch.Size([3, 5])
in_dims says which dimension of each input is the batch dimension (None means the argument is shared, not batched) and out_dims where to put it in the result. Restrictions observed when running the snippets (the official limitations page, linked below, documents the general rules):
-
Calling
.item()or otherwise pulling a value into Python inside a vmapped function raisesRuntimeError: vmap: It looks like you're calling .item() on a Tensor. Data-dependent control flow is unsupported for the same reason. -
Random operations raise an error by default (
randomness='error'). Passrandomness='different'to draw independent random numbers per sample, or'same'to share one draw. With'different'the examplevmap(lambda r: torch.rand(1) + r, randomness="different")(torch.zeros(3))returned a tensor of shape[3, 1]. -
In-place operations interact with batching in subtle ways; the UX limitations page documents which cases are supported.
Per-sample gradients
Ordinary autograd sums (or averages) the gradients of a batch. Differentially private SGD, influence analysis and gradient-norm-based sampling need one gradient per example. A Python loop with a backward per sample is slow; vmap over grad computes all of them in one vectorized pass. The model has to be called functionally, with functional_call, because grad differentiates with respect to explicit arguments and not hidden module state.
import torch
import torch.nn as nn
from torch.func import functional_call, vmap, grad
model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 3))
params = {k: v.detach() for k, v in model.named_parameters()}
buffers = {k: v.detach() for k, v in model.named_buffers()}
def loss_fn(params, buffers, x, y):
# The module expects a batch, so give it a batch of one
out = functional_call(model, (params, buffers), (x.unsqueeze(0),))
return nn.functional.cross_entropy(out, y.unsqueeze(0))
X = torch.randn(10, 4)
Y = torch.randint(0, 3, (10,))
# in_dims: params and buffers are shared, data and labels are batched over dim 0
per_sample = vmap(grad(loss_fn), in_dims=(None, None, 0, 0))(params, buffers, X, Y)
print({k: tuple(v.shape) for k, v in per_sample.items()})
# {'0.weight': (10, 8, 4), '0.bias': (10, 8), '2.weight': (10, 3, 8), '2.bias': (10, 3)}
# Check sample 0 against ordinary autograd
model.zero_grad()
nn.functional.cross_entropy(model(X[:1]), Y[:1]).backward()
print(torch.allclose(model[0].weight.grad, per_sample["0.weight"][0], atol=1e-6)) # True
Every leaf in the result gains a leading batch dimension. Layers whose behaviour couples examples, above all batch normalization in training mode, do not fit this scheme (the per-sample gradient is not well defined because each output depends on the whole batch); use layer, group or no normalization, or put the batch-norm layers in evaluation mode.
Model ensembling with stack_module_state
An ensemble of identically shaped models can be evaluated in one vectorized call instead of a loop. stack_module_state stacks every parameter and buffer along a new leading dimension, and vmap maps over that dimension. The base model used for the call is moved to the meta device so that no unused memory is kept for its weights.
import copy
from torch.func import stack_module_state
models = [nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 3)) for _ in range(3)]
stacked_params, stacked_buffers = stack_module_state(models)
base = copy.deepcopy(models[0]).to("meta") # a structural template only
def fmodel(params, buffers, x):
return functional_call(base, (params, buffers), (x,))
# in_dims: map over the model dimension of params and buffers; share the input
preds = vmap(fmodel, in_dims=(0, 0, None))(stacked_params, stacked_buffers, X)
print(preds.shape) # torch.Size([3, 10, 3]): model, sample, class
print(torch.allclose(preds[1], models[1](X), atol=1e-6)) # True
Averaging preds over dimension 0 gives the ensemble prediction. The same trick underlies model-agnostic meta-learning with functional_call, where inner-loop updated parameters are passed explicitly.
Forward-mode AD
Reverse mode computes vector-Jacobian products, which is efficient when there are few outputs (a scalar loss). Forward mode computes Jacobian-vector products and needs no stored graph, which is efficient for functions with few inputs and many outputs, and for directional derivatives. PyTorch exposes it in two ways. torch.func.jvp is the functional one shown above. torch.autograd.forward_ad is the lower-level interface with dual tensors:
import torch.autograd.forward_ad as fwAD
with fwAD.dual_level():
dx = fwAD.make_dual(torch.tensor([1.0, 2.0]), torch.tensor([1.0, 0.0]))
dy = dx.sin() * dx
print(fwAD.unpack_dual(dy).tangent) # tensor([1.3818, 0.0000])
Source: https://docs.pytorch.org/tutorials/intermediate/forward_ad_usage.html and https://docs.pytorch.org/docs/stable/autograd.html (forward-mode automatic differentiation)
The tangent is the derivative of \(\sin(x)\,x\) in the direction \((1, 0)\): at \(x = 1\) that is \(\cos(1) \cdot 1 + \sin(1) \approx 1.3818\), which matches. The 2.15 documentation says of the forward-mode API "This API is in beta", and operator coverage may be incomplete; custom Functions support it through jvp (see Custom autograd Functions).
Choosing the tool
| Need | Use | Notes |
|---|---|---|
Second derivative of a scalar loss |
|
Memory grows with the retained graph |
Hessian-vector product for a large model |
Double backward with |
Never materialize the full Hessian |
Full Jacobian or Hessian of a small function |
|
Pick reverse mode for few outputs and forward mode for few inputs |
One gradient per example |
|
Avoid batch norm in training mode |
Ensemble of models with the same architecture |
|
Base model on the |
Directional derivatives, few inputs |
|
Beta; check operator coverage |
Common pitfalls
-
Forgetting
create_graph=True, so the first gradient has no history and the secondgradcall raises "element 0 of tensors does not require grad". -
Calling
.backward()twice on the same graph withoutretain_graph=True;create_graph=Truekeeps the needed buffers. -
Using side effects (Python lists, global counters,
.item()) inside a function passed tovmaporgrad. -
Reusing a
torch.func.gradfunction on a module directly: call the module throughfunctional_callso the parameters are explicit. -
Using
randomness='error'(the default) with dropout insidevmap; setrandomnessdeliberately. -
Expecting per-sample gradients through batch norm in training mode.
-
Building the full Hessian of a model with millions of parameters, which needs memory quadratic in the parameter count; use Hessian-vector products.
-
Treating
torch.funcas final: it is beta, and operator coverage can be incomplete.