Custom autograd Functions
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Autograd differentiates any combination of built-in tensor operations automatically. Sometimes that is not enough: an operation may be non-differentiable but you want a surrogate gradient (a quantizer), a numerically better backward formula exists (a fused kernel, a stable log-sum-exp), the forward calls NumPy or a C++ library that autograd cannot see, or you need to control which tensors are kept in memory. For these cases PyTorch lets you define the forward and the backward of an operation yourself by subclassing torch.autograd.Function. This page shows the recommended form of the API, every ctx helper, double backward, forward-mode and vmap support, and how to verify a backward with gradcheck.
Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31. The general graph machinery is in Autograd Fundamentals; the concept of backpropagation is in Backpropagation & Automatic Differentiation.
When to write a Function
The official note lists the situations in which a custom Function is the right tool: the operation is not differentiable or is not expressed in PyTorch operations (for example it relies on NumPy), or you wrap a C++ extension with its own forward and backward. If the operation can be written with built-in tensor operations, you do not need a Function. If the operation has trainable parameters, put them in a custom nn.Module (see nn.Module) and, only if necessary, call a Function from its forward. For registering new operators that also work with torch.compile and torch.export, see Custom Operators & Extensions.
Anatomy of a Function
A Function is a class with static methods. The recommended layout separates the computation from the saving of context:
-
forward(*inputs): computes the output from tensors and other Python values. It takes noctxargument in this form. It runs with autograd disabled, so operations inside it are not recorded. -
setup_context(ctx, inputs, output): stores whatbackwardwill need onctx. It receives the inputs tuple and the output. -
backward(ctx, *grad_outputs): receives one gradient per output offorwardand returns one gradient per input offorward.
You call the operation through MyFunction.apply(...), never by instantiating the class or calling forward directly. The official note recommends this separate forward and setup_context style because it mirrors how native PyTorch operators work and composes better with torch.func transforms. An older style that puts ctx as the first argument of forward and saves everything inside it is still supported.
import torch
from torch.autograd import Function
class LinearFunction(Function):
@staticmethod
def forward(input, weight, bias=None):
output = input.mm(weight.t())
if bias is not None:
output = output + bias.unsqueeze(0).expand_as(output)
return output
@staticmethod
def setup_context(ctx, inputs, output):
input, weight, bias = inputs
ctx.save_for_backward(input, weight, bias)
@staticmethod
def backward(ctx, grad_output):
input, weight, bias = ctx.saved_tensors
grad_input = grad_weight = grad_bias = None
if ctx.needs_input_grad[0]:
grad_input = grad_output.mm(weight)
if ctx.needs_input_grad[1]:
grad_weight = grad_output.t().mm(input)
if bias is not None and ctx.needs_input_grad[2]:
grad_bias = grad_output.sum(0)
return grad_input, grad_weight, grad_bias
def linear(input, weight, bias=None):
# Wrapper so that callers can use keyword and default arguments
return LinearFunction.apply(input, weight, bias)
This is the official linear layer example, with the forward written out-of-place so that it also works under double backward. Function.apply itself accepts positional arguments only, which is why the note suggests wrapping it in an ordinary function to support keywords and defaults. The gradient for an input that is not a tensor, or that does not need a gradient, can be None.
The diagram shows what happens when a Function is applied and later differentiated.
The ctx helpers
ctx is an object that lives as long as the graph node. The methods you will use:
| Helper | Purpose |
|---|---|
|
Stores tensors needed by |
|
A tuple of Booleans, one per input of |
|
Declare every input that |
|
Declare outputs, such as indices, that do not require gradients. |
|
By default, an output that did not take part in the loss gets a zero tensor as its gradient in |
|
Stores tensors for a |
Non-tensor values such as a scale factor are stored as plain attributes on ctx, and their gradient returned from backward is None:
class Scale(Function):
@staticmethod
def forward(x, k):
return x * k
@staticmethod
def setup_context(ctx, inputs, output):
ctx.k = inputs[1] # a Python float, not a tensor
@staticmethod
def backward(ctx, grad_output):
return grad_output * ctx.k, None # None for the non-tensor input
s = torch.ones(2, requires_grad=True)
Scale.apply(s, 5.0).sum().backward()
print(s.grad) # tensor([5., 5.])
Rules for backward
-
One return value per input of
forward, in order. More return values than inputs are allowed only if the extra ones are allNone. -
Never modify the incoming gradients in place; the engine may reuse them.
-
Make
backwarditself out of differentiable operations if you want to support higher-order derivatives (see below). -
Intermediate tensors computed inside
forwardcan only be saved forbackwardif they are returned as outputs of the Function, unless you use the combinedforward(ctx, ...)style that saves them directly; remember that gradients flowing into such extra outputs also need a formula.
Example: a straight-through estimator
Rounding has a zero gradient almost everywhere, so a network that contains a rounding step (quantization-aware training) cannot learn through it. The straight-through estimator keeps the forward as it is but pretends the operation was the identity in the backward:
class RoundSTE(Function):
@staticmethod
def forward(x):
return torch.round(x)
@staticmethod
def setup_context(ctx, inputs, output):
pass # nothing to save
@staticmethod
def backward(ctx, grad_output):
return grad_output # pretend the identity
v = torch.tensor([0.2, 1.7, -0.6], requires_grad=True)
RoundSTE.apply(v).sum().backward()
print(v.grad) # tensor([1., 1., 1.])
This is a surrogate gradient, not the true derivative of the operation. It is a modelling decision and should be documented as such; the same pattern is used for binarized networks and spiking neurons (see Model Compression for the quantization context).
Non-differentiable outputs and unused outputs
An operation that returns a differentiable value together with an index tensor should tell autograd that the index has no gradient:
class SortWithIdx(Function):
@staticmethod
def forward(ctx, x):
values, idx = torch.sort(x)
ctx.mark_non_differentiable(idx)
ctx.save_for_backward(idx)
return values, idx
@staticmethod
def backward(ctx, g_values, g_idx):
(idx,) = ctx.saved_tensors
grad = torch.zeros_like(g_values)
grad.scatter_(0, idx, g_values) # route gradients back to the original positions
return grad
xx = torch.tensor([3.0, 1.0, 2.0], requires_grad=True)
vals, idx = SortWithIdx.apply(xx)
print(idx.requires_grad) # False
(vals * torch.tensor([1.0, 10.0, 100.0])).sum().backward()
print(xx.grad) # tensor([100., 1., 10.])
This example uses the older style in which forward receives ctx; both styles are valid, and a Function must use one or the other.
When a Function has several outputs and only some of them reach the loss, the unused ones get zero gradients by default. Calling ctx.set_materialize_grads(False) in forward hands you None instead, which lets you skip work:
class Two(Function):
@staticmethod
def forward(ctx, x):
ctx.set_materialize_grads(False)
return x * 2, x * 3
@staticmethod
def backward(ctx, ga, gb):
out = 0
if ga is not None:
out = out + 2 * ga
if gb is not None:
out = out + 3 * gb
return out
a = torch.tensor([1.0, 2.0], requires_grad=True)
p, q = Two.apply(a)
p.sum().backward() # q is unused: gb is None inside backward
print(a.grad) # tensor([2., 2.])
In-place operations
If forward modifies an input in place and returns it, call ctx.mark_dirty(input) so that autograd knows the tensor’s history changed. Without it, results are wrong or the engine raises an error. The returned object is then the same Python object as the input:
class AddOneInplace(Function):
@staticmethod
def forward(ctx, x):
x.add_(1)
ctx.mark_dirty(x)
return x
@staticmethod
def backward(ctx, grad_output):
return grad_output
base = torch.zeros(2, requires_grad=True)
h = base.clone() # a non-leaf copy: in-place on a leaf requiring grad is not allowed
out = AddOneInplace.apply(h)
out.sum().backward()
print(out is h, base.grad) # True tensor([1., 1.])
In-place Functions are rarely worth the trouble; prefer returning a new tensor unless memory is the binding constraint.
Double backward and once_differentiable
Whether a Function supports second derivatives depends on how backward is written. When backward is built from differentiable PyTorch operations (as in the examples above), autograd records a graph during the first backward when you pass create_graph=True, and a second differentiation works. The official note adds a caveat: tensors stored as plain attributes on ctx do not receive gradients in double backward. A tensor whose gradient matters there has to be an input or an output of the Function and be stored with save_for_backward.
If backward calls non-differentiable code (NumPy, a custom CUDA kernel), decorate it with torch.autograd.function.once_differentiable: it runs backward without recording, and trying to differentiate through it raises a clear error instead of silently returning a wrong result.
from torch.autograd.function import once_differentiable
class Sq(Function):
@staticmethod
def forward(x):
return x * x
@staticmethod
def setup_context(ctx, inputs, output):
ctx.save_for_backward(inputs[0])
@staticmethod
@once_differentiable
def backward(ctx, g):
(x,) = ctx.saved_tensors
return 2 * x * g
t = torch.tensor(3.0, requires_grad=True)
(g,) = torch.autograd.grad(Sq.apply(t), t, create_graph=True)
print(g, g.requires_grad) # tensor(6.) False: the backward is not recorded
try:
torch.autograd.grad(g, t)
except RuntimeError as e:
print("RuntimeError:", e) # element 0 of tensors does not require grad ...
Without the decorator, the same Function (a backward made of ordinary tensor operations) returns the second derivative: for \(f(x) = x^2\) at \(x = 3\) the first derivative is \(6\) and the second \(2\), which the executed snippet confirmed with create_graph=True. The official tutorial walks through a full example, including why saving an output (rather than an input) matters for the second derivative: https://docs.pytorch.org/tutorials/intermediate/custom_function_double_backward_tutorial.html
Higher-order derivatives in general are the subject of Higher-Order Gradients & torch.func.
Forward-mode AD with jvp
Forward-mode automatic differentiation propagates tangents together with values. To support it, add a static jvp(ctx, *grad_inputs) method that returns the output tangents. It runs right after forward. Tensors it needs must be registered with ctx.save_for_forward in setup_context; ctx.saved_tensors is empty inside jvp unless you also saved them for backward. The executed snippet raised ValueError: not enough values to unpack when jvp read ctx.saved_tensors without save_for_forward.
import torch.autograd.forward_ad as fwAD
class Exp(Function):
@staticmethod
def forward(x):
return x.exp()
@staticmethod
def setup_context(ctx, inputs, output):
ctx.save_for_backward(output)
ctx.save_for_forward(output)
@staticmethod
def backward(ctx, grad_output):
(out,) = ctx.saved_tensors
return grad_output * out
@staticmethod
def jvp(ctx, tangent):
(out,) = ctx.saved_tensors
return tangent * out
with fwAD.dual_level():
dual = fwAD.make_dual(torch.tensor([0.0, 1.0]), torch.tensor([1.0, 1.0]))
result = Exp.apply(dual)
print(fwAD.unpack_dual(result).tangent) # tensor([1.0000, 2.7183])
Source: https://docs.pytorch.org/docs/stable/notes/extending.html and https://docs.pytorch.org/docs/stable/autograd.html (forward-mode automatic differentiation)
The in-place and view behaviour of jvp must match that of forward.
Using a Function inside torch.func transforms
The torch.func transforms (grad, vmap, jacrev and others) can differentiate and vectorize a Function only if it is written in the separate forward and setup_context style. For vmap, either define a vmap static method that says how the operation batches, or set the class attribute generate_vmap_rule = True when forward, backward and jvp are written with PyTorch operations only; PyTorch then generates the rule. The official guide for these cases is "Extending torch.func with autograd.Function": https://docs.pytorch.org/docs/stable/notes/extending.func.html
from torch.func import vmap, grad
class Cube(Function):
generate_vmap_rule = True
@staticmethod
def forward(x):
return x ** 3
@staticmethod
def setup_context(ctx, inputs, output):
ctx.save_for_backward(inputs[0])
@staticmethod
def backward(ctx, grad_output):
(x,) = ctx.saved_tensors
return 3 * x ** 2 * grad_output
print(vmap(grad(Cube.apply))(torch.tensor([1.0, 2.0, 3.0]))) # tensor([ 3., 12., 27.])
Read the guide’s rules about what generate_vmap_rule supports before relying on it for a Function that calls non-PyTorch code.
Verifying with gradcheck
Hand-written backward formulas are a classic source of silent errors. torch.autograd.gradcheck compares the analytical Jacobian from backward with a numerical one computed by finite differences; gradgradcheck does the same for second derivatives. Use double-precision inputs with requires_grad=True, because single precision is too coarse for the finite differences:
from torch.autograd import gradcheck, gradgradcheck
x = torch.randn(4, 3, dtype=torch.double, requires_grad=True)
w = torch.randn(2, 3, dtype=torch.double, requires_grad=True)
b = torch.randn(2, dtype=torch.double, requires_grad=True)
print(gradcheck(linear, (x, w, b), eps=1e-6, atol=1e-4)) # True
print(gradgradcheck(linear, (x, w, b), eps=1e-6, atol=1e-4)) # True
Source: https://docs.pytorch.org/docs/stable/autograd.html (gradcheck, gradgradcheck) and https://docs.pytorch.org/docs/stable/notes/extending.html
A straight-through estimator such as RoundSTE will fail gradcheck by construction, because its backward is deliberately not the true derivative; test those separately with a hand-computed expectation.
Other techniques worth knowing
-
Backward hooks and tensor hooks (
tensor.register_hook) modify gradients without a new Function; use them for clipping or logging a gradient at one point. -
torch.utils.checkpointtrades computation for memory without a custom Function (see GPU Memory & Activation Checkpointing). -
A fused convolution and batch-norm Function can reduce memory; the official tutorial shows the technique: https://docs.pytorch.org/tutorials/intermediate/custom_function_conv_bn_tutorial.html
-
torch.library.custom_opis the modern route for operators that must work withtorch.compileandtorch.export.
Common pitfalls
-
Calling
forwardor instantiating the class instead ofapply. -
Returning the wrong number of gradients from
backward, or a gradient with the wrong shape or dtype for an input. -
Keeping tensors as plain
ctxattributes, which keeps them alive for the whole lifetime of the graph and defeats early freeing. -
Forgetting
mark_dirtyfor in-place operations, ormark_non_differentiablefor index outputs. -
Modifying
grad_outputin place. -
Reading
ctx.saved_tensorsinsidejvpwithoutsave_for_forward. -
Writing a
backwardwith NumPy or a non-differentiable kernel and not applyingonce_differentiable, so double backward silently returns wrong or missing gradients. -
Using the combined
forward(ctx, ...)style and expectingtorch.functransforms to work; switch tosetup_context.