-
Notifications
You must be signed in to change notification settings - Fork 14
/
asam.py
69 lines (64 loc) · 2.16 KB
/
asam.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
import torch
from collections import defaultdict
class ASAM:
def __init__(self, optimizer, model, rho=0.5, eta=0.01):
self.optimizer = optimizer
self.model = model
self.rho = rho
self.eta = eta
self.state = defaultdict(dict)
@torch.no_grad()
def ascent_step(self):
wgrads = []
for n, p in self.model.named_parameters():
if p.grad is None:
continue
t_w = self.state[p].get("eps")
if t_w is None:
t_w = torch.clone(p).detach()
self.state[p]["eps"] = t_w
if 'weight' in n:
t_w[...] = p[...]
t_w.abs_().add_(self.eta)
p.grad.mul_(t_w)
wgrads.append(torch.norm(p.grad, p=2))
wgrad_norm = torch.norm(torch.stack(wgrads), p=2) + 1.e-16
for n, p in self.model.named_parameters():
if p.grad is None:
continue
t_w = self.state[p].get("eps")
if 'weight' in n:
p.grad.mul_(t_w)
eps = t_w
eps[...] = p.grad[...]
eps.mul_(self.rho / wgrad_norm)
p.add_(eps)
self.optimizer.zero_grad()
@torch.no_grad()
def descent_step(self):
for n, p in self.model.named_parameters():
if p.grad is None:
continue
p.sub_(self.state[p]["eps"])
self.optimizer.step()
self.optimizer.zero_grad()
class SAM(ASAM):
@torch.no_grad()
def ascent_step(self):
grads = []
for n, p in self.model.named_parameters():
if p.grad is None:
continue
grads.append(torch.norm(p.grad, p=2))
grad_norm = torch.norm(torch.stack(grads), p=2) + 1.e-16
for n, p in self.model.named_parameters():
if p.grad is None:
continue
eps = self.state[p].get("eps")
if eps is None:
eps = torch.clone(p).detach()
self.state[p]["eps"] = eps
eps[...] = p.grad[...]
eps.mul_(self.rho / grad_norm)
p.add_(eps)
self.optimizer.zero_grad()