Caffe2 - Python API
A deep learning, cross platform ML framework
asgd.py
1 import math
2 import torch
3 from .optimizer import Optimizer
4 
5 
6 class ASGD(Optimizer):
7  """Implements Averaged Stochastic Gradient Descent.
8 
9  It has been proposed in `Acceleration of stochastic approximation by
10  averaging`_.
11 
12  Arguments:
13  params (iterable): iterable of parameters to optimize or dicts defining
14  parameter groups
15  lr (float, optional): learning rate (default: 1e-2)
16  lambd (float, optional): decay term (default: 1e-4)
17  alpha (float, optional): power for eta update (default: 0.75)
18  t0 (float, optional): point at which to start averaging (default: 1e6)
19  weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
20 
21  .. _Acceleration of stochastic approximation by averaging:
22  http://dl.acm.org/citation.cfm?id=131098
23  """
24 
25  def __init__(self, params, lr=1e-2, lambd=1e-4, alpha=0.75, t0=1e6, weight_decay=0):
26  if not 0.0 <= lr:
27  raise ValueError("Invalid learning rate: {}".format(lr))
28  if not 0.0 <= weight_decay:
29  raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
30 
31  defaults = dict(lr=lr, lambd=lambd, alpha=alpha, t0=t0,
32  weight_decay=weight_decay)
33  super(ASGD, self).__init__(params, defaults)
34 
35  def step(self, closure=None):
36  """Performs a single optimization step.
37 
38  Arguments:
39  closure (callable, optional): A closure that reevaluates the model
40  and returns the loss.
41  """
42  loss = None
43  if closure is not None:
44  loss = closure()
45 
46  for group in self.param_groups:
47  for p in group['params']:
48  if p.grad is None:
49  continue
50  grad = p.grad.data
51  if grad.is_sparse:
52  raise RuntimeError('ASGD does not support sparse gradients')
53  state = self.state[p]
54 
55  # State initialization
56  if len(state) == 0:
57  state['step'] = 0
58  state['eta'] = group['lr']
59  state['mu'] = 1
60  state['ax'] = torch.zeros_like(p.data)
61 
62  state['step'] += 1
63 
64  if group['weight_decay'] != 0:
65  grad = grad.add(group['weight_decay'], p.data)
66 
67  # decay term
68  p.data.mul_(1 - group['lambd'] * state['eta'])
69 
70  # update parameter
71  p.data.add_(-state['eta'], grad)
72 
73  # averaging
74  if state['mu'] != 1:
75  state['ax'].add_(p.data.sub(state['ax']).mul(state['mu']))
76  else:
77  state['ax'].copy_(p.data)
78 
79  # update eta and mu
80  state['eta'] = (group['lr'] /
81  math.pow((1 + group['lambd'] * group['lr'] * state['step']), group['alpha']))
82  state['mu'] = 1 / max(1, state['step'] - group['t0'])
83 
84  return loss
def step(self, closure=None)
Definition: asgd.py:35