3 from .optimizer
import Optimizer
7 r"""Implements Adam algorithm. 9 It has been proposed in `Adam: A Method for Stochastic Optimization`_. 12 params (iterable): iterable of parameters to optimize or dicts defining 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`_ 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 30 def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,
31 weight_decay=0, amsgrad=
False):
33 raise ValueError(
"Invalid learning rate: {}".format(lr))
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)
44 def __setstate__(self, state):
45 super(Adam, self).__setstate__(state)
46 for group
in self.param_groups:
47 group.setdefault(
'amsgrad',
False)
49 def step(self, closure=None):
50 """Performs a single optimization step. 53 closure (callable, optional): A closure that reevaluates the model 57 if closure
is not None:
60 for group
in self.param_groups:
61 for p
in group[
'params']:
66 raise RuntimeError(
'Adam does not support sparse gradients, please consider SparseAdam instead')
67 amsgrad = group[
'amsgrad']
75 state[
'exp_avg'] = torch.zeros_like(p.data)
77 state[
'exp_avg_sq'] = torch.zeros_like(p.data)
80 state[
'max_exp_avg_sq'] = torch.zeros_like(p.data)
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']
89 if group[
'weight_decay'] != 0:
90 grad.add_(group[
'weight_decay'], p.data)
93 exp_avg.mul_(beta1).add_(1 - beta1, grad)
94 exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)
97 torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)
99 denom = max_exp_avg_sq.sqrt().add_(group[
'eps'])
101 denom = exp_avg_sq.sqrt().add_(group[
'eps'])
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
107 p.data.addcdiv_(-step_size, exp_avg, denom)
def step(self, closure=None)