Caffe2 - Python API A deep learning, cross platform ML framework
1 import math
2 import torch
3 from .optimizer import Optimizer
4
5
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,
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,
43
44  def __setstate__(self, state):
46  for group in self.param_groups:
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']:
63  continue
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)
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']
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:
91
92  # Decay the first and second moment running average coefficient
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