-
Notifications
You must be signed in to change notification settings - Fork 0
/
another_lars.py
executable file
·90 lines (80 loc) · 3.69 KB
/
another_lars.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import torch
from torch.optim.optimizer import Optimizer, required
class LARS(Optimizer):
r"""Implements LARS (Layer-wise Adaptive Rate Scaling).
https://github.com/4uiiurz1/pytorch-lars
Args:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float): learning rate
momentum (float, optional): momentum factor (default: 0)
eta (float, optional): LARS coefficient as used in the paper (default: 1e-3)
weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
dampening (float, optional): dampening for momentum (default: 0)
nesterov (bool, optional): enables Nesterov momentum (default: False)
epsilon (float, optional): epsilon to prevent zero division (default: 0)
Example:
>>> optimizer = torch.optim.LARS(model.parameters(), lr=0.1, momentum=0.9)
>>> optimizer.zero_grad()
>>> loss_fn(model(input), target).backward()
>>> optimizer.step()
"""
def __init__(self, params, lr=required, momentum=0, eta=1e-3, dampening=0,
weight_decay=0, nesterov=False, epsilon=0):
if lr is not required and lr < 0.0:
raise ValueError("Invalid learning rate: {}".format(lr))
if momentum < 0.0:
raise ValueError("Invalid momentum value: {}".format(momentum))
if weight_decay < 0.0:
raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
defaults = dict(lr=lr, momentum=momentum, eta=eta, dampening=dampening,
weight_decay=weight_decay, nesterov=nesterov, epsilon=epsilon)
if nesterov and (momentum <= 0 or dampening != 0):
raise ValueError("Nesterov momentum requires a momentum and zero dampening")
super(LARS, self).__init__(params, defaults)
def __setstate__(self, state):
super(LARS, self).__setstate__(state)
for group in self.param_groups:
group.setdefault('nesterov', False)
def step(self, closure=None):
"""Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
"""
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
weight_decay = group['weight_decay']
momentum = group['momentum']
eta = group['eta']
dampening = group['dampening']
nesterov = group['nesterov']
epsilon = group['epsilon']
for p in group['params']:
if p.grad is None:
continue
w_norm = torch.norm(p.data)
g_norm = torch.norm(p.grad.data)
if w_norm * g_norm > 0:
local_lr = eta * w_norm / (g_norm +
weight_decay * w_norm + epsilon)
else:
local_lr = 1
d_p = p.grad.data
if weight_decay != 0:
d_p.add_(weight_decay, p.data)
if momentum != 0:
param_state = self.state[p]
if 'momentum_buffer' not in param_state:
buf = param_state['momentum_buffer'] = torch.clone(d_p).detach()
else:
buf = param_state['momentum_buffer']
buf.mul_(momentum).add_(1 - dampening, d_p)
if nesterov:
d_p = d_p.add(momentum, buf)
else:
d_p = buf
p.data.add_(-local_lr * group['lr'], d_p)
return loss