forked from CoinCheung/pytorch-loss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ema.py
84 lines (73 loc) · 2.9 KB
/
ema.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
import torch
class EMA(object):
'''
apply expontential moving average to a model. This should have same function as the `tf.train.ExponentialMovingAverage` of tensorflow.
usage:
model = resnet()
model.train()
ema = EMA(model, 0.9999)
....
for img, lb in dataloader:
loss = ...
loss.backward()
optim.step()
ema.update_params() # apply ema
evaluate(model) # evaluate with original model as usual
ema.apply_shadow() # copy ema status to the model
evaluate(model) # evaluate the model with ema paramters
ema.restore() # resume the model parameters
args:
- model: the model that ema is applied
- alpha: each parameter p should be computed as p_hat = alpha * p + (1. - alpha) * p_hat
- buffer_ema: whether the model buffers should be computed with ema method or just get kept
methods:
- update_params(): apply ema to the model, usually call after the optimizer.step() is called
- apply_shadow(): copy the ema processed parameters to the model
- restore(): restore the original model parameters, this would cancel the operation of apply_shadow()
'''
def __init__(self, model, alpha, buffer_ema=True):
self.step = 0
self.model = model
self.alpha = alpha
self.buffer_ema = buffer_ema
self.shadow = self.get_model_state()
self.backup = {}
self.param_keys = [k for k, _ in self.model.named_parameters()]
self.buffer_keys = [k for k, _ in self.model.named_buffers()]
def update_params(self):
decay = min(self.alpha, (self.step + 1) / (self.step + 10))
state = self.model.state_dict()
for name in self.param_keys:
self.shadow[name].copy_(
decay * self.shadow[name]
+ (1 - decay) * state[name]
)
for name in self.buffer_keys:
if self.buffer_ema:
self.shadow[name].copy_(
decay * self.shadow[name]
+ (1 - decay) * state[name]
)
else:
self.shadow[name].copy_(state[name])
self.step += 1
def apply_shadow(self):
self.backup = self.get_model_state()
self.model.load_state_dict(self.shadow)
def restore(self):
self.model.load_state_dict(self.backup)
def get_model_state(self):
return {
k: v.clone().detach()
for k, v in self.model.state_dict().items()
}
if __name__ == '__main__':
print('=====')
model = torch.nn.BatchNorm1d(5)
ema = EMA(model, 0.9, 0.02, 0.002)
inten = torch.randn(10, 5)
out = model(inten)
ema.update_params()
print(model.state_dict())
ema.update_buffer()
print(model.state_dict())