r"""Implements stochastic gradient descent (optionally with momentum). Nesterov momentum is based on the formula from `On the importance of initialization and momentum in deep learning`__. Args: params (iterable): iterable of parameters to optimize or dicts defining
| 190 | |
| 191 | |
| 192 | class SGDVec(Optimizer): |
| 193 | r"""Implements stochastic gradient descent (optionally with momentum). |
| 194 | |
| 195 | Nesterov momentum is based on the formula from |
| 196 | `On the importance of initialization and momentum in deep learning`__. |
| 197 | |
| 198 | Args: |
| 199 | params (iterable): iterable of parameters to optimize or dicts defining |
| 200 | parameter groups |
| 201 | lr (float): learning rate |
| 202 | momentum (float, optional): momentum factor (default: 0) |
| 203 | weight_decay (float, optional): weight decay (L2 penalty) (default: 0) |
| 204 | dampening (float, optional): dampening for momentum (default: 0) |
| 205 | nesterov (bool, optional): enables Nesterov momentum (default: False) |
| 206 | |
| 207 | Example: |
| 208 | >>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, |
| 209 | momentum=0.9) |
| 210 | >>> optimizer.zero_grad() |
| 211 | >>> loss_fn(model(input), target).backward() |
| 212 | >>> optimizer.step() |
| 213 | |
| 214 | __ http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf |
| 215 | |
| 216 | .. note:: |
| 217 | The implementation of SGD with Momentum/Nesterov subtly differs from |
| 218 | Sutskever et. al. and implementations in some other frameworks. |
| 219 | |
| 220 | Considering the specific case of Momentum, the update can be written as |
| 221 | |
| 222 | .. math:: |
| 223 | v = \rho * v + g \\ |
| 224 | p = p - lr * v |
| 225 | |
| 226 | where p, g, v and :math:`\rho` denote the parameters, gradient, |
| 227 | velocity, and momentum respectively. |
| 228 | |
| 229 | This is in contrast to Sutskever et. al. and |
| 230 | other frameworks which employ an update of the form |
| 231 | |
| 232 | .. math:: |
| 233 | v = \rho * v + lr * g \\ |
| 234 | p = p - v |
| 235 | |
| 236 | The Nesterov version is analogously modified. |
| 237 | """ |
| 238 | |
| 239 | def __init__(self, params, lr=required, momentum=0, dampening=0, |
| 240 | weight_decay=0, nesterov=False): |
| 241 | if lr is not required and lr < 0.0: |
| 242 | raise ValueError("Invalid learning rate: {}".format(lr)) |
| 243 | if momentum < 0.0: |
| 244 | raise ValueError("Invalid momentum value: {}".format(momentum)) |
| 245 | if weight_decay < 0.0: |
| 246 | raise ValueError( |
| 247 | "Invalid weight_decay value: {}".format(weight_decay)) |
| 248 | |
| 249 | defaults = dict(lr=lr, momentum=momentum, dampening=dampening, |
nothing calls this directly
no outgoing calls
no test coverage detected