Safemotion Lib
Loading...
Searching...
No Matches
Public Member Functions | List of all members
fastreid.solver.optim.sgd.SGD Class Reference
Inheritance diagram for fastreid.solver.optim.sgd.SGD:

Public Member Functions

 __init__ (self, params, lr=required, momentum=0, dampening=0, weight_decay=0, nesterov=False)
 
 __setstate__ (self, state)
 
 step (self, closure=None)
 

Detailed Description

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
        parameter groups
    lr (float): learning rate
    momentum (float, optional): momentum factor (default: 0)
    weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
    dampening (float, optional): dampening for momentum (default: 0)
    nesterov (bool, optional): enables Nesterov momentum (default: False)
Example:
    >>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
    >>> optimizer.zero_grad()
    >>> loss_fn(model(input), target).backward()
    >>> optimizer.step()
__ http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf
.. note::
    The implementation of SGD with Momentum/Nesterov subtly differs from
    Sutskever et. al. and implementations in some other frameworks.
    Considering the specific case of Momentum, the update can be written as
    .. math::
        \begin{aligned}
            v_{t+1} & = \mu * v_{t} + g_{t+1}, \\
            p_{t+1} & = p_{t} - \text{lr} * v_{t+1},
        \end{aligned}
    where :math:`p`, :math:`g`, :math:`v` and :math:`\mu` denote the 
    parameters, gradient, velocity, and momentum respectively.
    This is in contrast to Sutskever et. al. and
    other frameworks which employ an update of the form
    .. math::
        \begin{aligned}
            v_{t+1} & = \mu * v_{t} + \text{lr} * g_{t+1}, \\
            p_{t+1} & = p_{t} - v_{t+1}.
        \end{aligned}
    The Nesterov version is analogously modified.

Definition at line 5 of file sgd.py.

Constructor & Destructor Documentation

◆ __init__()

fastreid.solver.optim.sgd.SGD.__init__ ( self,
params,
lr = required,
momentum = 0,
dampening = 0,
weight_decay = 0,
nesterov = False )

Definition at line 44 of file sgd.py.

45 weight_decay=0, nesterov=False):
46 if lr is not required and lr < 0.0:
47 raise ValueError("Invalid learning rate: {}".format(lr))
48 if momentum < 0.0:
49 raise ValueError("Invalid momentum value: {}".format(momentum))
50 if weight_decay < 0.0:
51 raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
52
53 defaults = dict(lr=lr, momentum=momentum, dampening=dampening,
54 weight_decay=weight_decay, nesterov=nesterov)
55 if nesterov and (momentum <= 0 or dampening != 0):
56 raise ValueError("Nesterov momentum requires a momentum and zero dampening")
57 super(SGD, self).__init__(params, defaults)
58

Member Function Documentation

◆ __setstate__()

fastreid.solver.optim.sgd.SGD.__setstate__ ( self,
state )

Definition at line 59 of file sgd.py.

59 def __setstate__(self, state):
60 super(SGD, self).__setstate__(state)
61 for group in self.param_groups:
62 group.setdefault('nesterov', False)
63

◆ step()

fastreid.solver.optim.sgd.SGD.step ( self,
closure = None )
Performs a single optimization step.
Arguments:
    closure (callable, optional): A closure that reevaluates the model
        and returns the loss.

Definition at line 65 of file sgd.py.

65 def step(self, closure=None):
66 """Performs a single optimization step.
67 Arguments:
68 closure (callable, optional): A closure that reevaluates the model
69 and returns the loss.
70 """
71 loss = None
72 if closure is not None:
73 with torch.enable_grad():
74 loss = closure()
75
76 for group in self.param_groups:
77 if group['freeze']: continue
78
79 weight_decay = group['weight_decay']
80 momentum = group['momentum']
81 dampening = group['dampening']
82 nesterov = group['nesterov']
83
84 for p in group['params']:
85 if p.grad is None:
86 continue
87 d_p = p.grad
88 if weight_decay != 0:
89 d_p = d_p.add(p, alpha=weight_decay)
90 if momentum != 0:
91 param_state = self.state[p]
92 if 'momentum_buffer' not in param_state:
93 buf = param_state['momentum_buffer'] = torch.clone(d_p).detach()
94 else:
95 buf = param_state['momentum_buffer']
96 buf.mul_(momentum).add_(d_p, alpha=1 - dampening)
97 if nesterov:
98 d_p = d_p.add(buf, alpha=momentum)
99 else:
100 d_p = buf
101
102 p.add_(d_p, alpha=-group['lr'])
103
104 return loss

The documentation for this class was generated from the following file: