AkashDataScience commited on
Commit
6b1f333
·
1 Parent(s): d0c450a
Files changed (1) hide show
  1. utils/lion.py +67 -0
utils/lion.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyTorch implementation of the Lion optimizer."""
2
+ import torch
3
+ from torch.optim.optimizer import Optimizer
4
+
5
+
6
+ class Lion(Optimizer):
7
+ r"""Implements Lion algorithm."""
8
+
9
+ def __init__(self, params, lr=1e-4, betas=(0.9, 0.99), weight_decay=0.0):
10
+ """Initialize the hyperparameters.
11
+ Args:
12
+ params (iterable): iterable of parameters to optimize or dicts defining
13
+ parameter groups
14
+ lr (float, optional): learning rate (default: 1e-4)
15
+ betas (Tuple[float, float], optional): coefficients used for computing
16
+ running averages of gradient and its square (default: (0.9, 0.99))
17
+ weight_decay (float, optional): weight decay coefficient (default: 0)
18
+ """
19
+
20
+ if not 0.0 <= lr:
21
+ raise ValueError('Invalid learning rate: {}'.format(lr))
22
+ if not 0.0 <= betas[0] < 1.0:
23
+ raise ValueError('Invalid beta parameter at index 0: {}'.format(betas[0]))
24
+ if not 0.0 <= betas[1] < 1.0:
25
+ raise ValueError('Invalid beta parameter at index 1: {}'.format(betas[1]))
26
+ defaults = dict(lr=lr, betas=betas, weight_decay=weight_decay)
27
+ super().__init__(params, defaults)
28
+
29
+ @torch.no_grad()
30
+ def step(self, closure=None):
31
+ """Performs a single optimization step.
32
+ Args:
33
+ closure (callable, optional): A closure that reevaluates the model
34
+ and returns the loss.
35
+ Returns:
36
+ the loss.
37
+ """
38
+ loss = None
39
+ if closure is not None:
40
+ with torch.enable_grad():
41
+ loss = closure()
42
+
43
+ for group in self.param_groups:
44
+ for p in group['params']:
45
+ if p.grad is None:
46
+ continue
47
+
48
+ # Perform stepweight decay
49
+ p.data.mul_(1 - group['lr'] * group['weight_decay'])
50
+
51
+ grad = p.grad
52
+ state = self.state[p]
53
+ # State initialization
54
+ if len(state) == 0:
55
+ # Exponential moving average of gradient values
56
+ state['exp_avg'] = torch.zeros_like(p)
57
+
58
+ exp_avg = state['exp_avg']
59
+ beta1, beta2 = group['betas']
60
+
61
+ # Weight update
62
+ update = exp_avg * beta1 + grad * (1 - beta1)
63
+ p.add_(torch.sign(update), alpha=-group['lr'])
64
+ # Decay the momentum running average coefficient
65
+ exp_avg.mul_(beta2).add_(grad, alpha=1 - beta2)
66
+
67
+ return loss