-
Notifications
You must be signed in to change notification settings - Fork 1
/
swag.py
132 lines (100 loc) · 4.87 KB
/
swag.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import torch
def flatten(lst):
tmp = [i.contiguous().view(-1,1) for i in lst]
return torch.cat(tmp).view(-1)
def set_weights(model, vector, device=None):
offset = 0
for param in model.parameters():
param.data.copy_(vector[offset:offset + param.numel()].view(param.size()).to(device))
offset += param.numel()
class CovarianceSpace(torch.nn.Module):
def __init__(self, num_parameters, max_rank=100):
super(CovarianceSpace, self).__init__()
self.num_parameters = num_parameters
self.register_buffer('rank', torch.zeros(1, dtype=torch.long))
self.register_buffer('cov_mat_sqrt',
torch.empty(0, self.num_parameters, dtype=torch.float32))
self.max_rank = max_rank
def collect_vector(self, vector):
if self.rank.item() + 1 > self.max_rank:
self.cov_mat_sqrt = self.cov_mat_sqrt[1:, :]
self.cov_mat_sqrt = torch.cat((self.cov_mat_sqrt, vector.view(1, -1)), dim=0)
self.rank = torch.min(self.rank + 1, torch.as_tensor(self.max_rank)).view(-1)
def get_space(self):
return self.cov_mat_sqrt.clone() / (self.cov_mat_sqrt.size(0) - 1) ** 0.5
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs):
rank = state_dict[prefix + 'rank'].item()
self.cov_mat_sqrt = self.cov_mat_sqrt.new_empty((rank, self.cov_mat_sqrt.size()[1]))
super(CovarianceSpace, self)._load_from_state_dict(state_dict, prefix, local_metadata,
strict, missing_keys, unexpected_keys,
error_msgs)
class SWAG(torch.nn.Module):
def __init__(self, base_model,
subspace_kwargs=None, var_clamp=1e-6):
super(SWAG, self).__init__()
self.base_model = base_model
self.num_parameters = sum(param.numel() for param in self.base_model.parameters())
self.register_buffer('mean', torch.zeros(self.num_parameters))
self.register_buffer('sq_mean', torch.zeros(self.num_parameters))
self.register_buffer('n_models', torch.zeros(1, dtype=torch.long))
# Initialize subspace
if subspace_kwargs is None:
subspace_kwargs = dict()
self.subspace = CovarianceSpace(num_parameters=self.num_parameters,
**subspace_kwargs)
self.var_clamp = var_clamp
self.cov_factor = None
self.model_device = 'cpu'
# dont put subspace on cuda?
def cuda(self, device=None):
self.model_device = 'cuda'
self.base_model.cuda(device=device)
def to(self, *args, **kwargs):
self.base_model.to(*args, **kwargs)
device, dtype, non_blocking = torch._C._nn._parse_to(*args, **kwargs)
self.model_device = device.type
self.subspace.to(device=torch.device('cpu'), dtype=dtype, non_blocking=non_blocking)
def forward(self, *args, **kwargs):
return self.base_model(*args, **kwargs)
def collect_model(self, base_model, *args, **kwargs):
# need to refit the space after collecting a new model
self.cov_factor = None
w = flatten([param.detach().cpu() for param in base_model.parameters()])
# first moment
self.mean.mul_(self.n_models.item() / (self.n_models.item() + 1.0))
self.mean.add_(w / (self.n_models.item() + 1.0))
# second moment
self.sq_mean.mul_(self.n_models.item() / (self.n_models.item() + 1.0))
self.sq_mean.add_(w ** 2 / (self.n_models.item() + 1.0))
dev_vector = w - self.mean
self.subspace.collect_vector(dev_vector, *args, **kwargs)
self.n_models.add_(1)
def _get_mean_and_variance(self):
variance = torch.clamp(self.sq_mean - self.mean ** 2, self.var_clamp)
return self.mean, variance
def fit(self):
if self.cov_factor is not None:
return
self.cov_factor = self.subspace.get_space()
def set_swa(self):
set_weights(self.base_model, self.mean, self.model_device)
def sample(self, scale=0.5, diag_noise=True):
self.fit()
mean, variance = self._get_mean_and_variance()
eps_low_rank = torch.randn(self.cov_factor.size()[0])
z = self.cov_factor.t() @ eps_low_rank
if diag_noise:
z += variance * torch.randn_like(variance)
z *= scale ** 0.5
sample = mean + z
# apply to parameters
set_weights(self.base_model, sample, self.model_device)
return sample
def get_space(self, export_cov_factor=True):
mean, variance = self._get_mean_and_variance()
if not export_cov_factor:
return mean.clone(), variance.clone()
else:
self.fit()
return mean.clone(), variance.clone(), self.cov_factor.clone()