class
SGD
extends
OptimizerSGD(params: Iterable[Parameter] | Iterable[dict[str, object]], lr: float = 0.001, momentum: float = 0, dampening: float = 0, weight_decay: float = 0, nesterov: bool = False)Stochastic Gradient Descent optimizer with optional momentum and weight decay.
Implements the classic SGD update rule. Without momentum the update is:
With momentum (Polyak momentum), a velocity buffer is maintained and the update becomes:
where is the momentum factor and is the dampening coefficient. With Nesterov momentum the gradient is evaluated at the lookahead position:
L2 weight decay adds to the gradient before the momentum step:
Parameters
paramsiterable of Parameter or iterable of dictParameters to optimise, or a list of parameter-group dicts.
lrfloat= 0.001Learning rate (default:
1e-3).momentumfloat= 0Momentum factor (default:
0). Set to a value
such as 0.9 to enable momentum.dampeningfloat= 0Dampening factor for the momentum buffer
(default:
0). Has no effect when momentum=0.weight_decayfloat= 0L2 regularisation coefficient (default:
0).nesterovbool= FalseIf
True, use Nesterov momentum (default: False).
Requires momentum > 0 and dampening == 0.Attributes
param_groupslist of dictParameter groups, each containing
"params", "lr",
"momentum", "dampening", "weight_decay", and
"nesterov".defaultsdictDefault hyperparameter values.
Notes
SGD with momentum is the de-facto standard for training image classifiers. Nesterov momentum often converges faster than vanilla momentum because it incorporates a correction based on where the parameters will be after the momentum step.
Examples
>>> import lucid
>>> import lucid.nn as nn
>>> model = nn.Linear(4, 2)
>>> loss = model(lucid.randn(1, 4)).sum()
>>> import lucid.optim as optim
>>> optimizer = optim.SGD(
... model.parameters(), lr=0.01, momentum=0.9, weight_decay=1e-4
... )
>>> optimizer.zero_grad()
>>> loss.backward()
>>> optimizer.step()