Caffe2 - Python API
A deep learning, cross platform ML framework
rmsprop.py
1 import torch
2 from .optimizer import Optimizer
3 
4 
5 class RMSprop(Optimizer):
6  """Implements RMSprop algorithm.
7 
8  Proposed by G. Hinton in his
9  `course <http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf>`_.
10 
11  The centered version first appears in `Generating Sequences
12  With Recurrent Neural Networks <https://arxiv.org/pdf/1308.0850v5.pdf>`_.
13 
14  Arguments:
15  params (iterable): iterable of parameters to optimize or dicts defining
16  parameter groups
17  lr (float, optional): learning rate (default: 1e-2)
18  momentum (float, optional): momentum factor (default: 0)
19  alpha (float, optional): smoothing constant (default: 0.99)
20  eps (float, optional): term added to the denominator to improve
21  numerical stability (default: 1e-8)
22  centered (bool, optional) : if ``True``, compute the centered RMSProp,
23  the gradient is normalized by an estimation of its variance
24  weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
25 
26  """
27 
28  def __init__(self, params, lr=1e-2, alpha=0.99, eps=1e-8, weight_decay=0, momentum=0, centered=False):
29  if not 0.0 <= lr:
30  raise ValueError("Invalid learning rate: {}".format(lr))
31  if not 0.0 <= eps:
32  raise ValueError("Invalid epsilon value: {}".format(eps))
33  if not 0.0 <= momentum:
34  raise ValueError("Invalid momentum value: {}".format(momentum))
35  if not 0.0 <= weight_decay:
36  raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
37  if not 0.0 <= alpha:
38  raise ValueError("Invalid alpha value: {}".format(alpha))
39 
40  defaults = dict(lr=lr, momentum=momentum, alpha=alpha, eps=eps, centered=centered, weight_decay=weight_decay)
41  super(RMSprop, self).__init__(params, defaults)
42 
43  def __setstate__(self, state):
44  super(RMSprop, self).__setstate__(state)
45  for group in self.param_groups:
46  group.setdefault('momentum', 0)
47  group.setdefault('centered', False)
48 
49  def step(self, closure=None):
50  """Performs a single optimization step.
51 
52  Arguments:
53  closure (callable, optional): A closure that reevaluates the model
54  and returns the loss.
55  """
56  loss = None
57  if closure is not None:
58  loss = closure()
59 
60  for group in self.param_groups:
61  for p in group['params']:
62  if p.grad is None:
63  continue
64  grad = p.grad.data
65  if grad.is_sparse:
66  raise RuntimeError('RMSprop does not support sparse gradients')
67  state = self.state[p]
68 
69  # State initialization
70  if len(state) == 0:
71  state['step'] = 0
72  state['square_avg'] = torch.zeros_like(p.data)
73  if group['momentum'] > 0:
74  state['momentum_buffer'] = torch.zeros_like(p.data)
75  if group['centered']:
76  state['grad_avg'] = torch.zeros_like(p.data)
77 
78  square_avg = state['square_avg']
79  alpha = group['alpha']
80 
81  state['step'] += 1
82 
83  if group['weight_decay'] != 0:
84  grad = grad.add(group['weight_decay'], p.data)
85 
86  square_avg.mul_(alpha).addcmul_(1 - alpha, grad, grad)
87 
88  if group['centered']:
89  grad_avg = state['grad_avg']
90  grad_avg.mul_(alpha).add_(1 - alpha, grad)
91  avg = square_avg.addcmul(-1, grad_avg, grad_avg).sqrt().add_(group['eps'])
92  else:
93  avg = square_avg.sqrt().add_(group['eps'])
94 
95  if group['momentum'] > 0:
96  buf = state['momentum_buffer']
97  buf.mul_(group['momentum']).addcdiv_(grad, avg)
98  p.data.add_(-group['lr'], buf)
99  else:
100  p.data.addcdiv_(-group['lr'], grad, avg)
101 
102  return loss
def step(self, closure=None)
Definition: rmsprop.py:49