Update parameters from gradients
After a standard backward pass in a minibatch training loop.
PyTorch · Module
optimizer.step() applies one optimizer update after gradients are computed. Most optimizers use it without arguments; closure-based optimizers can reevaluate the model and loss.
After gradients have been computed by backpropagation, calling step applies the optimizer's update rule to its managed parameters. Most optimizers use the no-argument form; algorithms that must reevaluate the objective can receive a closure that clears gradients, recomputes the loss, performs backpropagation, and returns that loss.
optimizer.step()
optimizer.step(closure)| Name | Type | Description |
|---|---|---|
closure | Callable[[], float] | A callable that reevaluates the model, computes the loss, and returns it; optional for most optimizers. |
None for the usual form; a loss value for the closure form, as specified by the optimizer API.
import torch
model = torch.nn.Linear(4, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
inputs = torch.randn(8, 4)
targets = torch.randn(8, 1)
optimizer.zero_grad()
loss = torch.nn.functional.mse_loss(model(inputs), targets)
loss.backward()
optimizer.step()Clears accumulated gradients, computes a loss, backpropagates its gradients, and updates the model parameters.
After a standard backward pass in a minibatch training loop.
When using an optimizer that needs multiple objective evaluations, such as LBFGS.
At each iteration after accumulating the gradients intended for the update.
step performs one optimization update on the parameters managed by the optimizer. In the usual training loop, gradients are computed first with backward(), then step applies the optimizer's rule.
Follow-up: Why is zero_grad typically called before backward()? Gradients accumulate by default, so clearing them prevents contributions from previous iterations from being reused unintentionally.
The no-argument form is the simplified interface supported by most optimizers. It is called after gradients have been computed and updates the parameters using those gradients.
Follow-up: What if an optimizer must reevaluate the model? Pass a closure that clears gradients, recomputes the output and loss, backpropagates, and returns the loss.
A closure is a callable that reevaluates the model and returns the loss. Optimizers such as LBFGS can invoke it multiple times during one optimization step.
Follow-up: Why must the closure clear gradients? Repeated reevaluation would otherwise accumulate gradients across closure calls instead of computing each trial update from a fresh gradient.
torch.optim.OptimizerOptimizer.zero_gradOptimizer.add_param_grouptorch.optim.LBFGStorch.optim.SGD