torch.autograd.Function.forward — PyTorch 2.7 documentation (original) (raw)

static Function.forward(*args, **kwargs)[source]

Define the forward of the custom autograd Function.

This function is to be overridden by all subclasses. There are two ways to define forward:

Usage 1 (Combined forward and ctx):

@staticmethod def forward(ctx: Any, *args: Any, **kwargs: Any) -> Any: pass

Usage 2 (Separate forward and ctx):

@staticmethod def forward(*args: Any, **kwargs: Any) -> Any: pass

@staticmethod def setup_context(ctx: Any, inputs: Tuple[Any, ...], output: Any) -> None: pass

The context can be used to store arbitrary data that can be then retrieved during the backward pass. Tensors should not be stored directly on ctx (though this is not currently enforced for backward compatibility). Instead, tensors should be saved either withctx.save_for_backward() if they are intended to be used inbackward (equivalently, vjp) or ctx.save_for_forward()if they are intended to be used for in jvp.

Return type

Any