-
Notifications
You must be signed in to change notification settings - Fork 299
/
model.py
415 lines (310 loc) · 15.2 KB
/
model.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
from src.priors import *
from src.base_net import *
import torch.nn.functional as F
import torch.nn as nn
import copy
def sample_weights(W_mu, b_mu, W_p, b_p):
"""Quick method for sampling weights and exporting weights"""
eps_W = W_mu.data.new(W_mu.size()).normal_()
# sample parameters
std_w = 1e-6 + F.softplus(W_p, beta=1, threshold=20)
W = W_mu + 1 * std_w * eps_W
if b_mu is not None:
std_b = 1e-6 + F.softplus(b_p, beta=1, threshold=20)
eps_b = b_mu.data.new(b_mu.size()).normal_()
b = b_mu + 1 * std_b * eps_b
else:
b = None
return W, b
class BayesLinear_Normalq(nn.Module):
"""Linear Layer where weights are sampled from a fully factorised Normal with learnable parameters. The likelihood
of the weight samples under the prior and the approximate posterior are returned with each forward pass in order
to estimate the KL term in the ELBO.
"""
def __init__(self, n_in, n_out, prior_class):
super(BayesLinear_Normalq, self).__init__()
self.n_in = n_in
self.n_out = n_out
self.prior = prior_class
# Learnable parameters -> Initialisation is set empirically.
self.W_mu = nn.Parameter(torch.Tensor(self.n_in, self.n_out).uniform_(-0.1, 0.1))
self.W_p = nn.Parameter(torch.Tensor(self.n_in, self.n_out).uniform_(-3, -2))
self.b_mu = nn.Parameter(torch.Tensor(self.n_out).uniform_(-0.1, 0.1))
self.b_p = nn.Parameter(torch.Tensor(self.n_out).uniform_(-3, -2))
self.lpw = 0
self.lqw = 0
def forward(self, X, sample=False):
# print(self.training)
if not self.training and not sample: # When training return MLE of w for quick validation
output = torch.mm(X, self.W_mu) + self.b_mu.expand(X.size()[0], self.n_out)
return output, 0, 0
else:
# Tensor.new() Constructs a new tensor of the same data type as self tensor.
# the same random sample is used for every element in the minibatch
eps_W = Variable(self.W_mu.data.new(self.W_mu.size()).normal_())
eps_b = Variable(self.b_mu.data.new(self.b_mu.size()).normal_())
# sample parameters
std_w = 1e-6 + F.softplus(self.W_p, beta=1, threshold=20)
std_b = 1e-6 + F.softplus(self.b_p, beta=1, threshold=20)
W = self.W_mu + 1 * std_w * eps_W
b = self.b_mu + 1 * std_b * eps_b
output = torch.mm(X, W) + b.unsqueeze(0).expand(X.shape[0], -1) # (batch_size, n_output)
lqw = isotropic_gauss_loglike(W, self.W_mu, std_w) + isotropic_gauss_loglike(b, self.b_mu, std_b)
lpw = self.prior.loglike(W) + self.prior.loglike(b)
return output, lqw, lpw
class bayes_linear_2L(nn.Module):
"""2 hidden layer Bayes By Backprop (VI) Network"""
def __init__(self, input_dim, output_dim, n_hid, prior_instance):
super(bayes_linear_2L, self).__init__()
# prior_instance = isotropic_gauss_prior(mu=0, sigma=0.1)
# prior_instance = spike_slab_2GMM(mu1=0, mu2=0, sigma1=0.135, sigma2=0.001, pi=0.5)
# prior_instance = isotropic_gauss_prior(mu=0, sigma=0.1)
self.prior_instance = prior_instance
self.input_dim = input_dim
self.output_dim = output_dim
self.bfc1 = BayesLinear_Normalq(input_dim, n_hid, self.prior_instance)
self.bfc2 = BayesLinear_Normalq(n_hid, n_hid, self.prior_instance)
self.bfc3 = BayesLinear_Normalq(n_hid, output_dim, self.prior_instance)
# choose your non linearity
# self.act = nn.Tanh()
# self.act = nn.Sigmoid()
self.act = nn.ReLU(inplace=True)
# self.act = nn.ELU(inplace=True)
# self.act = nn.SELU(inplace=True)
def forward(self, x, sample=False):
tlqw = 0
tlpw = 0
x = x.view(-1, self.input_dim) # view(batch_size, input_dim)
# -----------------
x, lqw, lpw = self.bfc1(x, sample)
tlqw = tlqw + lqw
tlpw = tlpw + lpw
# -----------------
x = self.act(x)
# -----------------
x, lqw, lpw = self.bfc2(x, sample)
tlqw = tlqw + lqw
tlpw = tlpw + lpw
# -----------------
x = self.act(x)
# -----------------
y, lqw, lpw = self.bfc3(x, sample)
tlqw = tlqw + lqw
tlpw = tlpw + lpw
return y, tlqw, tlpw
def sample_predict(self, x, Nsamples):
"""Used for estimating the data's likelihood by approximately marginalising the weights with MC"""
# Just copies type from x, initializes new vector
predictions = x.data.new(Nsamples, x.shape[0], self.output_dim)
tlqw_vec = np.zeros(Nsamples)
tlpw_vec = np.zeros(Nsamples)
for i in range(Nsamples):
y, tlqw, tlpw = self.forward(x, sample=True)
predictions[i] = y
tlqw_vec[i] = tlqw
tlpw_vec[i] = tlpw
return predictions, tlqw_vec, tlpw_vec
class BBP_Bayes_Net(BaseNet):
"""Full network wrapper for Bayes By Backprop nets with methods for training, prediction and weight prunning"""
eps = 1e-6
def __init__(self, lr=1e-3, channels_in=3, side_in=28, cuda=True, classes=10, batch_size=128, Nbatches=0,
nhid=1200, prior_instance=laplace_prior(mu=0, b=0.1)):
super(BBP_Bayes_Net, self).__init__()
cprint('y', ' Creating Net!! ')
self.lr = lr
self.schedule = None # [] #[50,200,400,600]
self.cuda = cuda
self.channels_in = channels_in
self.classes = classes
self.batch_size = batch_size
self.Nbatches = Nbatches
self.prior_instance = prior_instance
self.nhid = nhid
self.side_in = side_in
self.create_net()
self.create_opt()
self.epoch = 0
self.test = False
def create_net(self):
torch.manual_seed(42)
if self.cuda:
torch.cuda.manual_seed(42)
self.model = bayes_linear_2L(input_dim=self.channels_in * self.side_in * self.side_in,
output_dim=self.classes, n_hid=self.nhid, prior_instance=self.prior_instance)
if self.cuda:
self.model.cuda()
# cudnn.benchmark = True
print(' Total params: %.2fM' % (self.get_nb_parameters() / 1000000.0))
def create_opt(self):
# self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr, betas=(0.9, 0.999), eps=1e-08,
# weight_decay=0)
self.optimizer = torch.optim.SGD(self.model.parameters(), lr=self.lr, momentum=0)
# self.optimizer = torch.optim.SGD(self.model.parameters(), lr=self.lr, momentum=0.9)
# self.sched = torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=1, gamma=10, last_epoch=-1)
def fit(self, x, y, samples=1):
x, y = to_variable(var=(x, y.long()), cuda=self.cuda)
self.optimizer.zero_grad()
if samples == 1:
out, tlqw, tlpw = self.model(x)
mlpdw = F.cross_entropy(out, y, reduction='sum')
Edkl = (tlqw - tlpw) / self.Nbatches
elif samples > 1:
mlpdw_cum = 0
Edkl_cum = 0
for i in range(samples):
out, tlqw, tlpw = self.model(x, sample=True)
mlpdw_i = F.cross_entropy(out, y, reduction='sum')
Edkl_i = (tlqw - tlpw) / self.Nbatches
mlpdw_cum = mlpdw_cum + mlpdw_i
Edkl_cum = Edkl_cum + Edkl_i
mlpdw = mlpdw_cum / samples
Edkl = Edkl_cum / samples
loss = Edkl + mlpdw
loss.backward()
self.optimizer.step()
# out: (batch_size, out_channels, out_caps_dims)
pred = out.data.max(dim=1, keepdim=False)[1] # get the index of the max log-probability
err = pred.ne(y.data).sum()
return Edkl.data, mlpdw.data, err
def eval(self, x, y, train=False):
x, y = to_variable(var=(x, y.long()), cuda=self.cuda)
out, _, _ = self.model(x)
loss = F.cross_entropy(out, y, reduction='sum')
probs = F.softmax(out, dim=1).data.cpu()
pred = out.data.max(dim=1, keepdim=False)[1] # get the index of the max log-probability
err = pred.ne(y.data).sum()
return loss.data, err, probs
def sample_eval(self, x, y, Nsamples, logits=True, train=False):
"""Prediction, only returining result with weights marginalised"""
x, y = to_variable(var=(x, y.long()), cuda=self.cuda)
out, _, _ = self.model.sample_predict(x, Nsamples)
if logits:
mean_out = out.mean(dim=0, keepdim=False)
loss = F.cross_entropy(mean_out, y, reduction='sum')
probs = F.softmax(mean_out, dim=1).data.cpu()
else:
mean_out = F.softmax(out, dim=2).mean(dim=0, keepdim=False)
probs = mean_out.data.cpu()
log_mean_probs_out = torch.log(mean_out)
loss = F.nll_loss(log_mean_probs_out, y, reduction='sum')
pred = mean_out.data.max(dim=1, keepdim=False)[1] # get the index of the max log-probability
err = pred.ne(y.data).sum()
return loss.data, err, probs
def all_sample_eval(self, x, y, Nsamples):
"""Returns predictions for each MC sample"""
x, y = to_variable(var=(x, y.long()), cuda=self.cuda)
out, _, _ = self.model.sample_predict(x, Nsamples)
prob_out = F.softmax(out, dim=2)
prob_out = prob_out.data
return prob_out
def get_weight_samples(self, Nsamples=10):
state_dict = self.model.state_dict()
weight_vec = []
for i in range(Nsamples):
previous_layer_name = ''
for key in state_dict.keys():
layer_name = key.split('.')[0]
if layer_name != previous_layer_name:
previous_layer_name = layer_name
W_mu = state_dict[layer_name + '.W_mu'].data
W_p = state_dict[layer_name + '.W_p'].data
# b_mu = state_dict[layer_name+'.b_mu'].cpu().data
# b_p = state_dict[layer_name+'.b_p'].cpu().data
W, b = sample_weights(W_mu=W_mu, b_mu=None, W_p=W_p, b_p=None)
for weight in W.cpu().view(-1):
weight_vec.append(weight)
return np.array(weight_vec)
def get_weight_SNR(self, thresh=None):
state_dict = self.model.state_dict()
weight_SNR_vec = []
if thresh is not None:
mask_dict = {}
previous_layer_name = ''
for key in state_dict.keys():
layer_name = key.split('.')[0]
if layer_name != previous_layer_name:
previous_layer_name = layer_name
W_mu = state_dict[layer_name + '.W_mu'].data
W_p = state_dict[layer_name + '.W_p'].data
sig_W = 1e-6 + F.softplus(W_p, beta=1, threshold=20)
b_mu = state_dict[layer_name + '.b_mu'].data
b_p = state_dict[layer_name + '.b_p'].data
sig_b = 1e-6 + F.softplus(b_p, beta=1, threshold=20)
W_snr = (torch.abs(W_mu) / sig_W)
b_snr = (torch.abs(b_mu) / sig_b)
if thresh is not None:
mask_dict[layer_name + '.W'] = W_snr > thresh
mask_dict[layer_name + '.b'] = b_snr > thresh
else:
for weight_SNR in W_snr.cpu().view(-1):
weight_SNR_vec.append(weight_SNR)
for weight_SNR in b_snr.cpu().view(-1):
weight_SNR_vec.append(weight_SNR)
if thresh is not None:
return mask_dict
else:
return np.array(weight_SNR_vec)
def get_weight_KLD(self, Nsamples=20, thresh=None):
state_dict = self.model.state_dict()
weight_KLD_vec = []
if thresh is not None:
mask_dict = {}
previous_layer_name = ''
for key in state_dict.keys():
layer_name = key.split('.')[0]
if layer_name != previous_layer_name:
previous_layer_name = layer_name
W_mu = state_dict[layer_name + '.W_mu'].data
W_p = state_dict[layer_name + '.W_p'].data
b_mu = state_dict[layer_name + '.b_mu'].data
b_p = state_dict[layer_name + '.b_p'].data
std_w = 1e-6 + F.softplus(W_p, beta=1, threshold=20)
std_b = 1e-6 + F.softplus(b_p, beta=1, threshold=20)
KL_W = W_mu.new(W_mu.size()).zero_()
KL_b = b_mu.new(b_mu.size()).zero_()
for i in range(Nsamples):
W, b = sample_weights(W_mu=W_mu, b_mu=b_mu, W_p=W_p, b_p=b_p)
# Note that this will currently not work with slab and spike prior
KL_W += isotropic_gauss_loglike(W, W_mu, std_w,
do_sum=False) - self.model.prior_instance.loglike(W,
do_sum=False)
KL_b += isotropic_gauss_loglike(b, b_mu, std_b,
do_sum=False) - self.model.prior_instance.loglike(b,
do_sum=False)
KL_W /= Nsamples
KL_b /= Nsamples
if thresh is not None:
mask_dict[layer_name + '.W'] = KL_W > thresh
mask_dict[layer_name + '.b'] = KL_b > thresh
else:
for weight_KLD in KL_W.cpu().view(-1):
weight_KLD_vec.append(weight_KLD)
for weight_KLD in KL_b.cpu().view(-1):
weight_KLD_vec.append(weight_KLD)
if thresh is not None:
return mask_dict
else:
return np.array(weight_KLD_vec)
def mask_model(self, Nsamples=0, thresh=0):
'''
Nsamples is used to select SNR (0) or KLD (>0) based masking
'''
original_state_dict = copy.deepcopy(self.model.state_dict())
state_dict = self.model.state_dict()
if Nsamples == 0:
mask_dict = self.get_weight_SNR(thresh=thresh)
else:
mask_dict = self.get_weight_KLD(Nsamples=Nsamples, thresh=thresh)
n_unmasked = 0
previous_layer_name = ''
for key in state_dict.keys():
layer_name = key.split('.')[0]
if layer_name != previous_layer_name:
previous_layer_name = layer_name
state_dict[layer_name + '.W_mu'][1 - mask_dict[layer_name + '.W']] = 0
state_dict[layer_name + '.W_p'][1 - mask_dict[layer_name + '.W']] = -1000
state_dict[layer_name + '.b_mu'][1 - mask_dict[layer_name + '.b']] = 0
state_dict[layer_name + '.b_p'][1 - mask_dict[layer_name + '.b']] = -1000
n_unmasked += mask_dict[layer_name + '.W'].sum()
n_unmasked += mask_dict[layer_name + '.b'].sum()
return original_state_dict, n_unmasked