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 no ctx argument in this form. It runs with autograd disabled, so operations inside it are not recorded.

  • setup_context(ctx, inputs, output): stores what backward will need on ctx. It receives the inputs tuple and the output.

  • backward(ctx, *grad_outputs): receives one gradient per output of forward and returns one gradient per input of forward.

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.

sequenceDiagram participant U as User code participant A as "Function.apply" participant G as Autograd graph U->>A: apply(x, w) A->>A: forward(x, w) with autograd disabled A->>A: setup_context(ctx, inputs, output) A->>G: record node holding ctx A-->>U: output tensor with grad_fn U->>G: loss.backward() G->>A: backward(ctx, grad_output) A-->>G: one gradient per input of forward
Figure 1. Life of a custom Function across the forward and backward passes

The ctx helpers

ctx is an object that lives as long as the graph node. The methods you will use:

Helper Purpose

ctx.save_for_backward(*tensors)

Stores tensors needed by backward. Retrieve them with ctx.saved_tensors. Save tensors with this method rather than as plain attributes: the engine can then free them early, detect in-place modification through the version counter, and cooperate with activation checkpointing. Tensors stored directly as ctx attributes stay alive for the lifetime of the graph.

ctx.needs_input_grad

A tuple of Booleans, one per input of forward; compute only the gradients that are needed.

ctx.mark_dirty(*tensors)

Declare every input that forward modified in place and returned.

ctx.mark_non_differentiable(*tensors)

Declare outputs, such as indices, that do not require gradients.

ctx.set_materialize_grads(False)

By default, an output that did not take part in the loss gets a zero tensor as its gradient in backward. After this call backward receives None instead, saving memory and computation; the method must then handle None.

ctx.save_for_forward(*tensors)

Stores tensors for a jvp (forward-mode) formula; see below.

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 all None.

  • Never modify the incoming gradients in place; the engine may reuse them.

  • Make backward itself out of differentiable operations if you want to support higher-order derivatives (see below).

  • Intermediate tensors computed inside forward can only be saved for backward if they are returned as outputs of the Function, unless you use the combined forward(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])

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

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

Common pitfalls

  • Calling forward or instantiating the class instead of apply.

  • Returning the wrong number of gradients from backward, or a gradient with the wrong shape or dtype for an input.

  • Keeping tensors as plain ctx attributes, which keeps them alive for the whole lifetime of the graph and defeats early freeing.

  • Forgetting mark_dirty for in-place operations, or mark_non_differentiable for index outputs.

  • Modifying grad_output in place.

  • Reading ctx.saved_tensors inside jvp without save_for_forward.

  • Writing a backward with NumPy or a non-differentiable kernel and not applying once_differentiable, so double backward silently returns wrong or missing gradients.

  • Using the combined forward(ctx, ...) style and expecting torch.func transforms to work; switch to setup_context.