Backpropagate a scalar loss
Training a neural network
PyTorch · Module
Computes gradients of a tensor through its autograd graph and accumulates them in leaf tensors. Non-scalar outputs require a matching gradient tensor.
Calling backward differentiates the tensor through its autograd graph using the chain rule. Gradients are accumulated in leaf tensors’ .grad fields; a non-scalar output requires a same-shaped gradient tensor, while create_graph can retain derivative tracking for higher-order derivatives.
Tensor.backward(*gradient=None*, *retain_graph=None*, *create_graph=False*, *inputs=None*)| Name | Type | Description |
|---|---|---|
gradient | Tensor, optional | Gradient of the differentiated function with respect to self; omit for a scalar tensor. |
retain_graph | bool, optional | Whether to preserve the graph used for gradient computation. If omitted, it is inferred from create_graph. |
create_graph | bool, optional | Whether to construct a graph for the derivative, enabling higher-order derivative products. |
inputs | Sequence[Tensor] or dict[str, Tensor], optional | Sequence of inputs whose .grad fields receive accumulated gradients; other tensors are ignored. |
None
import torch
x = torch.tensor(2.0, requires_grad=True)
y = x**3
y.backward()
print(x.grad) # tensor(12.)A scalar output can start backpropagation without an explicit gradient; the derivative is accumulated in x.grad.
Training a neural network
Vector-valued objectives
Meta-learning or curvature calculations
It applies the chain rule to the autograd graph and accumulates derivatives in graph leaves. For scalar outputs, no gradient argument is needed.
Follow-up: What changes for a vector output? Supply a gradient tensor matching the output’s type and shape; this represents the gradient with respect to the output.
The gradient argument supplies the output-side derivative used to propagate gradients. It may be omitted when the differentiated tensor is scalar.
Follow-up: Why must its shape match? Each output element needs a corresponding weighting for the vector-Jacobian product.
create_graph=True constructs a graph for the derivative calculation, enabling higher-order derivative products. retain_graph controls whether the original graph remains available after differentiation.
Follow-up: What is the default retain_graph behavior? When omitted, the value is inferred from create_graph.
torch.autograd.gradtorch.Tensor.requires_gradtorch.Tensor.grad