Caffe2 - Python API
A deep learning, cross platform ML framework
adamax.py
1 import torch
2 from .optimizer import Optimizer
3 
4 
5 class Adamax(Optimizer):
6  """Implements Adamax algorithm (a variant of Adam based on infinity norm).
7 
8  It has been proposed in `Adam: A Method for Stochastic Optimization`__.
9 
10  Arguments:
11  params (iterable): iterable of parameters to optimize or dicts defining
12  parameter groups
13  lr (float, optional): learning rate (default: 2e-3)
14  betas (Tuple[float, float], optional): coefficients used for computing
15  running averages of gradient and its square
16  eps (float, optional): term added to the denominator to improve
17  numerical stability (default: 1e-8)
18  weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
19 
20  __ https://arxiv.org/abs/1412.6980
21  """
22 
23  def __init__(self, params, lr=2e-3, betas=(0.9, 0.999), eps=1e-8,
24  weight_decay=0):
25  if not 0.0 <= lr:
26  raise ValueError("Invalid learning rate: {}".format(lr))
27  if not 0.0 <= eps:
28  raise ValueError("Invalid epsilon value: {}".format(eps))
29  if not 0.0 <= betas[0] < 1.0:
30  raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0]))
31  if not 0.0 <= betas[1] < 1.0:
32  raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1]))
33  if not 0.0 <= weight_decay:
34  raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
35 
36  defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
37  super(Adamax, self).__init__(params, defaults)
38 
39  def step(self, closure=None):
40  """Performs a single optimization step.
41 
42  Arguments:
43  closure (callable, optional): A closure that reevaluates the model
44  and returns the loss.
45  """
46  loss = None
47  if closure is not None:
48  loss = closure()
49 
50  for group in self.param_groups:
51  for p in group['params']:
52  if p.grad is None:
53  continue
54  grad = p.grad.data
55  if grad.is_sparse:
56  raise RuntimeError('Adamax does not support sparse gradients')
57  state = self.state[p]
58 
59  # State initialization
60  if len(state) == 0:
61  state['step'] = 0
62  state['exp_avg'] = torch.zeros_like(p.data)
63  state['exp_inf'] = torch.zeros_like(p.data)
64 
65  exp_avg, exp_inf = state['exp_avg'], state['exp_inf']
66  beta1, beta2 = group['betas']
67  eps = group['eps']
68 
69  state['step'] += 1
70 
71  if group['weight_decay'] != 0:
72  grad = grad.add(group['weight_decay'], p.data)
73 
74  # Update biased first moment estimate.
75  exp_avg.mul_(beta1).add_(1 - beta1, grad)
76  # Update the exponentially weighted infinity norm.
77  norm_buf = torch.cat([
78  exp_inf.mul_(beta2).unsqueeze(0),
79  grad.abs().add_(eps).unsqueeze_(0)
80  ], 0)
81  torch.max(norm_buf, 0, keepdim=False, out=(exp_inf, exp_inf.new().long()))
82 
83  bias_correction = 1 - beta1 ** state['step']
84  clr = group['lr'] / bias_correction
85 
86  p.data.addcdiv_(-clr, exp_avg, exp_inf)
87 
88  return loss
def step(self, closure=None)
Definition: adamax.py:39