Optimizers
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
An optimizer in PyTorch is an object that holds references to the parameters it updates, keeps per-parameter state (momentum buffers, Adam moments), and applies one update rule when you call step(). The ideas behind SGD, momentum, Adam and decoupled weight decay are in Gradient Descent & Optimization and Optimizers & Learning-Rate Schedules. This page covers torch.optim: how to construct an optimizer correctly, what the defaults are, which implementation runs, and how it interacts with autograd, clipping, checkpointing and mixed precision. Learning-rate schedules are in Learning-Rate Schedulers & SWA/EMA.
Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31. Optimizer defaults have changed between releases (for example the default learning rate of SGD), so pass lr explicitly in your own code.
The algorithms in torch.optim
The 2.15 reference lists: Adadelta, Adafactor, Adagrad, Adam, AdamW, SparseAdam, Adamax, ASGD, LBFGS, Muon, NAdam, RAdam, RMSprop, Rprop and SGD.
| Optimizer | Notes | Typical use |
|---|---|---|
|
Momentum buffer starts as the first gradient; PyTorch applies the learning rate after the momentum accumulation, which differs from the formulation in some papers and other frameworks. Nesterov needs non-zero momentum. |
CNNs on images with a tuned schedule; strong baseline |
|
|
Default for quick experiments |
|
Decoupled weight decay: the decay does not flow into the moment estimates. |
Transformers and most modern training |
|
Factored second moments for lower memory. Uses |
Memory-constrained large models |
|
For 2-D hidden-layer weight matrices only; use AdamW for embeddings, biases, norms and the output head. |
Large-scale pretraining experiments |
|
Quasi-Newton; |
Small problems, full batch |
|
Accept the sparse gradients produced by |
Huge embedding tables |
|
Variants with specific behaviours; consult the algorithm page for the formulas. |
Specialized or legacy setups |
For a first run use AdamW(lr=1e-3 to 3e-4) for transformers and SGD(lr=0.1, momentum=0.9, nesterov=True) with a schedule for CNNs; confirm by following the guidance in Deep Learning Tuning Playbook rather than copying these numbers.
The Adafactor page shows a weight_decay signature default of 0.0 while its parameter description mentions 1e-2; the two disagree in the documentation, so set the value explicitly. Muon, per its reference page, supports only 2-D parameters and offers adjust_lr_fn values "original", "match_rms_adamw" (so the learning rate and weight decay tuned for AdamW can be reused) and "spectral_unclamped".
The basic loop and call order
import torch
from torch import nn
model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 1))
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)
loss_fn = nn.MSELoss()
x, y = torch.randn(256, 20), torch.randn(256, 1)
for step in range(100):
optimizer.zero_grad() # set_to_none=True is the default
loss = loss_fn(model(x), y)
loss.backward() # fills .grad
optimizer.step() # reads .grad, updates parameters
# scheduler.step() goes here, after optimizer.step()
Rules of the loop:
-
optimizer.step()comes afterloss.backward(), andscheduler.step()afteroptimizer.step(). Calling the scheduler first skips the first value of the schedule. -
Gradients accumulate across backward calls. Without
zero_grad()each step uses the sum of all earlier gradients, a classic bug. -
Optimizer.zero_grad(set_to_none=True)is the default in 2.15. ANonegradient saves memory and makes the optimizer skip the parameter; a zero gradient still performs the update, which matters for momentum and weight decay on unused parameters. Passset_to_none=Falseif you rely on the old behaviour. -
Create the optimizer after moving the model to its final device (
model.to(device)), or the optimizer’s state refers to different tensors. Parameters registered after construction are not updated unless you calloptimizer.add_param_group. -
LBFGSand other closure-based optimizers take a closure that clears gradients, computes the loss, callsbackward()and returns the loss.
import torch
model = torch.nn.Linear(2, 1)
opt = torch.optim.LBFGS(model.parameters(), lr=1.0, max_iter=20)
x, y = torch.randn(64, 2), torch.randn(64, 1)
def closure():
opt.zero_grad()
loss = torch.nn.functional.mse_loss(model(x), y)
loss.backward()
return loss
for _ in range(5):
opt.step(closure)
Parameter groups and weight decay
An optimizer takes either an iterable of parameters or a list of dicts, each with a params key; any other key overrides the default for that group, and keyword arguments passed to the constructor are the defaults for groups that do not set them. This is how you give biases and normalization weights no weight decay, use a smaller learning rate for a pretrained backbone, or train only part of a model.
import torch
from torch import nn
model = nn.Sequential(
nn.Embedding(1000, 64),
nn.Flatten(),
nn.Linear(64 * 8, 128),
nn.LayerNorm(128),
nn.Linear(128, 10),
)
decay, no_decay = [], []
for name, p in model.named_parameters():
if not p.requires_grad:
continue
(no_decay if p.ndim < 2 or name.endswith("bias") else decay).append(p)
optimizer = torch.optim.AdamW(
[
{"params": decay, "weight_decay": 0.1},
{"params": no_decay, "weight_decay": 0.0},
],
lr=3e-4,
betas=(0.9, 0.95),
)
for group in optimizer.param_groups:
print(len(group["params"]), group["lr"], group["weight_decay"])
Pass parameters as a list (or another ordered collection), never as a set. The order of the parameters ties each one to its optimizer state in state_dict(), and a set iterates in a different order from run to run. In 2.15 a set emits a FutureWarning ("optimizer parameters need to be organized in ordered collections, but the ordering of tensors in sets will change between runs. Please use a list instead. This will be an error in a future release."). Deduplicating with set(...) is the usual way to fall into it; deduplicate with list(dict.fromkeys(params)) instead, which keeps the order.
Weight decay pitfalls: with plain Adam the argument is an L2 penalty folded into the gradient, which interacts with the adaptive scaling; AdamW decouples it and is the usual choice. Weight decay on embeddings, biases and normalization parameters is commonly turned off, as in the example (a convention, not a rule).
scheduler.get_last_lr() and optimizer.param_groups[i]["lr"] expose the current learning rate for logging. The values in param_groups are plain Python numbers (or tensors for tensor learning rates) and may be edited directly, which is what warmup hacks and some schedulers do.
Implementations: for-loop, foreach and fused
The reference describes three implementations per optimizer: a for-loop over parameters, a multi-tensor foreach implementation, and a fused kernel. Speed generally goes fused, then foreach, then for-loop, at the cost of peak memory for foreach.
-
foreach=Nonemeans PyTorch chooses foreach when it is available, all tensors are native CUDA tensors and no implementation-specific keyword was passed. Adadelta, Adagrad, Adam, AdamW, Adamax, ASGD, NAdam, RAdam, RMSprop, Rprop and SGD have foreach versions; Adafactor, SparseAdam, LBFGS and Muon use the for-loop. -
fused=Truemust be requested explicitly; it is never the default. The documentation rates Adam and AdamW fused as stable on CUDA and beta on CPU and MPS, SGD as beta on those devices and Adagrad’s fused path as beta and CPU only. Fused Adam and AdamW support float64, float32, float16 and bfloat16 parameters. -
capturable=Truemakes Adam and AdamW safe inside CUDA graphs andtorch.compile; it may slow ungraphed runs, so leave it off otherwise. A Tensor learning rate is not supported by every implementation: use a float unless you also setfused=Trueorcapturable=True. -
differentiable=Truelets autograd flow throughstep()(meta-learning); by defaultstep()runs underno_grad.
import torch
device = torch.accelerator.current_accelerator() or torch.device("cpu")
model = torch.nn.Linear(1024, 1024).to(device)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, fused=True) # fused kernel: CUDA, CPU or MPS
Gradient clipping and accumulation
Clip after backward() and before step(). clip_grad_norm_(parameters, max_norm, norm_type=2.0, error_if_nonfinite=False, foreach=None) rescales all gradients so that their global norm is at most max_norm and returns the norm before clipping, which is also a useful monitoring signal.
import torch
from torch import nn
model = nn.Linear(32, 4)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
accum_steps = 4
loader = [(torch.randn(8, 32), torch.randint(0, 4, (8,))) for _ in range(16)]
optimizer.zero_grad()
for i, (x, y) in enumerate(loader):
loss = nn.functional.cross_entropy(model(x), y) / accum_steps # scale to keep the mean
loss.backward()
if (i + 1) % accum_steps == 0:
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
optimizer.zero_grad()
When using torch.amp.GradScaler, call scaler.unscale_(optimizer) before clipping so the threshold applies to the true gradients (see Mixed Precision with torch.amp). With DDP, accumulate under no_sync() to avoid communicating on every micro-batch (see DistributedDataParallel).
Saving and restoring optimizer state
optimizer.state_dict() returns the state and the parameter-group settings; load_state_dict() restores them. By default state is matched to parameters by position in the groups with no verification, so the optimizer must be constructed with the same parameters in the same order. If param_names is present it is stored but not used for matching; to match by name or to remap after an architecture change register a load_state_dict pre-hook (the documentation gives examples). Call load_state_dict after creating any LRScheduler; loading before overwrites the loaded learning rates with the scheduler’s initial values.
import torch
model = torch.nn.Linear(4, 2)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=100)
checkpoint = {
"model": model.state_dict(),
"optimizer": optimizer.state_dict(),
"scheduler": scheduler.state_dict(),
"step": 1234,
}
torch.save(checkpoint, "ckpt.pt")
state = torch.load("ckpt.pt", weights_only=True)
model.load_state_dict(state["model"])
optimizer.load_state_dict(state["optimizer"])
scheduler.load_state_dict(state["scheduler"])
Safe loading, weights_only and checkpoint conventions are explained in Saving & Loading Models; sharded checkpoints for large distributed runs in Distributed Checkpoint & Flight Recorder.
Optimizer step in the backward pass
For memory-bound training, one pattern from the PyTorch tutorials updates each parameter as soon as its gradient has been computed, so gradients never all sit in memory at once. It registers a post-accumulate-grad hook per parameter and keeps one optimizer per parameter.
import torch
from torch import nn
model = nn.Sequential(nn.Linear(512, 512), nn.ReLU(), nn.Linear(512, 10))
optimizer_dict = {p: torch.optim.AdamW([p], lr=1e-3, foreach=False) for p in model.parameters()}
def step_in_hook(param):
optimizer_dict[param].step()
optimizer_dict[param].zero_grad()
for p in model.parameters():
p.register_post_accumulate_grad_hook(step_in_hook)
x, y = torch.randn(32, 512), torch.randint(0, 10, (32,))
loss = nn.functional.cross_entropy(model(x), y)
loss.backward() # parameters are updated during backward
The trade-offs: no gradient clipping across the whole model, no gradient accumulation, and it is awkward with schedulers, DDP and torch.compile. Treat it as a specialized technique and read the tutorial’s caveats before adopting it.
Choosing and troubleshooting
-
Start with
AdamW; useSGDwith momentum and a schedule when you have a recipe known to work for the architecture. -
Epsilon in Adam matters in half precision:
1e-8underflows in float16 statistics, which is one reason mixed-precision recipes keep optimizer state and master weights in float32. -
Loss does not move: check
requires_grad, that the parameters were passed to the optimizer, thatzero_gradis not called betweenbackwardandstep, and that the learning rate is not scheduled to zero. -
Loss explodes: lower the learning rate, add warmup (see Learning-Rate Schedulers & SWA/EMA) and clip gradients.
-
Memory: Adam stores two extra tensors per parameter; Adafactor, 8-bit optimizers from other libraries, FSDP2 sharding (FSDP2) and optimizer-in-backward reduce it.