Caffe2 - Python API
A deep learning, cross platform ML framework
adam.py
1 import math
2 import torch
3 from .optimizer import Optimizer
4 
5 
6 class Adam(Optimizer):
7  r"""Implements Adam algorithm.
8 
9  It has been proposed in `Adam: A Method for Stochastic Optimization`_.
10 
11  Arguments:
12  params (iterable): iterable of parameters to optimize or dicts defining
13  parameter groups
14  lr (float, optional): learning rate (default: 1e-3)
15  betas (Tuple[float, float], optional): coefficients used for computing
16  running averages of gradient and its square (default: (0.9, 0.999))
17  eps (float, optional): term added to the denominator to improve
18  numerical stability (default: 1e-8)
19  weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
20  amsgrad (boolean, optional): whether to use the AMSGrad variant of this
21  algorithm from the paper `On the Convergence of Adam and Beyond`_
22  (default: False)
23 
24  .. _Adam\: A Method for Stochastic Optimization:
25  https://arxiv.org/abs/1412.6980
26  .. _On the Convergence of Adam and Beyond:
27  https://openreview.net/forum?id=ryQu7f-RZ
28  """
29 
30  def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,
31  weight_decay=0, amsgrad=False):
32  if not 0.0 <= lr:
33  raise ValueError("Invalid learning rate: {}".format(lr))
34  if not 0.0 <= eps:
35  raise ValueError("Invalid epsilon value: {}".format(eps))
36  if not 0.0 <= betas[0] < 1.0:
37  raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0]))
38  if not 0.0 <= betas[1] < 1.0:
39  raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1]))
40  defaults = dict(lr=lr, betas=betas, eps=eps,
41  weight_decay=weight_decay, amsgrad=amsgrad)
42  super(Adam, self).__init__(params, defaults)
43 
44  def __setstate__(self, state):
45  super(Adam, self).__setstate__(state)
46  for group in self.param_groups:
47  group.setdefault('amsgrad', 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('Adam does not support sparse gradients, please consider SparseAdam instead')
67  amsgrad = group['amsgrad']
68 
69  state = self.state[p]
70 
71  # State initialization
72  if len(state) == 0:
73  state['step'] = 0
74  # Exponential moving average of gradient values
75  state['exp_avg'] = torch.zeros_like(p.data)
76  # Exponential moving average of squared gradient values
77  state['exp_avg_sq'] = torch.zeros_like(p.data)
78  if amsgrad:
79  # Maintains max of all exp. moving avg. of sq. grad. values
80  state['max_exp_avg_sq'] = torch.zeros_like(p.data)
81 
82  exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
83  if amsgrad:
84  max_exp_avg_sq = state['max_exp_avg_sq']
85  beta1, beta2 = group['betas']
86 
87  state['step'] += 1
88 
89  if group['weight_decay'] != 0:
90  grad.add_(group['weight_decay'], p.data)
91 
92  # Decay the first and second moment running average coefficient
93  exp_avg.mul_(beta1).add_(1 - beta1, grad)
94  exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)
95  if amsgrad:
96  # Maintains the maximum of all 2nd moment running avg. till now
97  torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)
98  # Use the max. for normalizing running avg. of gradient
99  denom = max_exp_avg_sq.sqrt().add_(group['eps'])
100  else:
101  denom = exp_avg_sq.sqrt().add_(group['eps'])
102 
103  bias_correction1 = 1 - beta1 ** state['step']
104  bias_correction2 = 1 - beta2 ** state['step']
105  step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1
106 
107  p.data.addcdiv_(-step_size, exp_avg, denom)
108 
109  return loss
def step(self, closure=None)
Definition: adam.py:49