2 from .optimizer
import Optimizer
6 """Implements Adamax algorithm (a variant of Adam based on infinity norm). 8 It has been proposed in `Adam: A Method for Stochastic Optimization`__. 11 params (iterable): iterable of parameters to optimize or dicts defining 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) 20 __ https://arxiv.org/abs/1412.6980 23 def __init__(self, params, lr=2e-3, betas=(0.9, 0.999), eps=1e-8,
26 raise ValueError(
"Invalid learning rate: {}".format(lr))
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))
36 defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
37 super(Adamax, self).__init__(params, defaults)
39 def step(self, closure=None):
40 """Performs a single optimization step. 43 closure (callable, optional): A closure that reevaluates the model 47 if closure
is not None:
50 for group
in self.param_groups:
51 for p
in group[
'params']:
56 raise RuntimeError(
'Adamax does not support sparse gradients')
62 state[
'exp_avg'] = torch.zeros_like(p.data)
63 state[
'exp_inf'] = torch.zeros_like(p.data)
65 exp_avg, exp_inf = state[
'exp_avg'], state[
'exp_inf']
66 beta1, beta2 = group[
'betas']
71 if group[
'weight_decay'] != 0:
72 grad = grad.add(group[
'weight_decay'], p.data)
75 exp_avg.mul_(beta1).add_(1 - beta1, grad)
77 norm_buf = torch.cat([
78 exp_inf.mul_(beta2).unsqueeze(0),
79 grad.abs().add_(eps).unsqueeze_(0)
81 torch.max(norm_buf, 0, keepdim=
False, out=(exp_inf, exp_inf.new().long()))
83 bias_correction = 1 - beta1 ** state[
'step']
84 clr = group[
'lr'] / bias_correction
86 p.data.addcdiv_(-clr, exp_avg, exp_inf)
def step(self, closure=None)