Functional autograd, batched transforms
torch.func (the in-tree replacement for the old standalone functorch) gives you JAX-style function transformations: grad, vmap, jacrev, hessian. They let you write code that operates on a single example and then automatically vectorize it over a batch.
Two practical use cases that come up surprisingly often:
- Per-sample gradients. Standard
.backward()gives you the gradient of the summed loss across the batch — every parameter has one gradient. Some research (differential privacy, influence functions, GradSAM) needs the gradient of every individual sample's loss.torch.func.vmap(grad(...))gives you that without writing a Python loop. - Higher-order gradients. Hessian-vector products, second-order optimizers, meta-learning — all need gradients of gradients.
torch.func.grad(grad(f))composes cleanly.
The mental shift
Standard PyTorch: tensors carry implicit graph state, you call .backward(). torch.func: pure functions of inputs and parameters, transforms produce new pure functions. It's a small but real mindset change — closer to JAX, slightly less ergonomic for normal training, much more powerful for the cases above.