Tu Bui
commited on
Commit
•
d6b613a
1
Parent(s):
6142a25
add ema
Browse files- ldm/modules/ema.py +80 -0
ldm/modules/ema.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn
|
3 |
+
|
4 |
+
|
5 |
+
class LitEma(nn.Module):
|
6 |
+
def __init__(self, model, decay=0.9999, use_num_upates=True):
|
7 |
+
super().__init__()
|
8 |
+
if decay < 0.0 or decay > 1.0:
|
9 |
+
raise ValueError('Decay must be between 0 and 1')
|
10 |
+
|
11 |
+
self.m_name2s_name = {}
|
12 |
+
self.register_buffer('decay', torch.tensor(decay, dtype=torch.float32))
|
13 |
+
self.register_buffer('num_updates', torch.tensor(0, dtype=torch.int) if use_num_upates
|
14 |
+
else torch.tensor(-1, dtype=torch.int))
|
15 |
+
|
16 |
+
for name, p in model.named_parameters():
|
17 |
+
if p.requires_grad:
|
18 |
+
# remove as '.'-character is not allowed in buffers
|
19 |
+
s_name = name.replace('.', '')
|
20 |
+
self.m_name2s_name.update({name: s_name})
|
21 |
+
self.register_buffer(s_name, p.clone().detach().data)
|
22 |
+
|
23 |
+
self.collected_params = []
|
24 |
+
|
25 |
+
def reset_num_updates(self):
|
26 |
+
del self.num_updates
|
27 |
+
self.register_buffer('num_updates', torch.tensor(0, dtype=torch.int))
|
28 |
+
|
29 |
+
def forward(self, model):
|
30 |
+
decay = self.decay
|
31 |
+
|
32 |
+
if self.num_updates >= 0:
|
33 |
+
self.num_updates += 1
|
34 |
+
decay = min(self.decay, (1 + self.num_updates) / (10 + self.num_updates))
|
35 |
+
|
36 |
+
one_minus_decay = 1.0 - decay
|
37 |
+
|
38 |
+
with torch.no_grad():
|
39 |
+
m_param = dict(model.named_parameters())
|
40 |
+
shadow_params = dict(self.named_buffers())
|
41 |
+
|
42 |
+
for key in m_param:
|
43 |
+
if m_param[key].requires_grad:
|
44 |
+
sname = self.m_name2s_name[key]
|
45 |
+
shadow_params[sname] = shadow_params[sname].type_as(m_param[key])
|
46 |
+
shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key]))
|
47 |
+
else:
|
48 |
+
assert not key in self.m_name2s_name
|
49 |
+
|
50 |
+
def copy_to(self, model):
|
51 |
+
m_param = dict(model.named_parameters())
|
52 |
+
shadow_params = dict(self.named_buffers())
|
53 |
+
for key in m_param:
|
54 |
+
if m_param[key].requires_grad:
|
55 |
+
m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data)
|
56 |
+
else:
|
57 |
+
assert not key in self.m_name2s_name
|
58 |
+
|
59 |
+
def store(self, parameters):
|
60 |
+
"""
|
61 |
+
Save the current parameters for restoring later.
|
62 |
+
Args:
|
63 |
+
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
64 |
+
temporarily stored.
|
65 |
+
"""
|
66 |
+
self.collected_params = [param.clone() for param in parameters]
|
67 |
+
|
68 |
+
def restore(self, parameters):
|
69 |
+
"""
|
70 |
+
Restore the parameters stored with the `store` method.
|
71 |
+
Useful to validate the model with EMA parameters without affecting the
|
72 |
+
original optimization process. Store the parameters before the
|
73 |
+
`copy_to` method. After validation (or model saving), use this to
|
74 |
+
restore the former parameters.
|
75 |
+
Args:
|
76 |
+
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
77 |
+
updated with the stored parameters.
|
78 |
+
"""
|
79 |
+
for c_param, param in zip(self.collected_params, parameters):
|
80 |
+
param.data.copy_(c_param.data)
|