-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtests.py
223 lines (167 loc) · 8.88 KB
/
tests.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
"""
Unittest for training.py
"""
import copy
import pyro
import torch
import warnings
import unittest
from pyro import poutine
from redbnn.nn.base import baseNN
from redbnn.nn.reduced import redBNN
from redbnn.utils.data import load_data
from redbnn.utils.pickling import load_from_pickle
dataloaders, num_classes = load_data(dataset_name='imagenette', data_dir='data/imagenette2-320',
subset_size=10)
filename = 'unittest'
architecture = 'resnet18'
savedir = 'data/trained_models/unittest/'
device = 'cuda'
class TestredBNN(unittest.TestCase):
def test_base_training(self):
model = baseNN(architecture='resnet18', num_classes=num_classes)
params_to_update = model._initialize_model(feature_extract=True, use_pretrained=True)
old_state_dict = model.network.to(device).state_dict()
model.train(dataloaders=dataloaders, num_iters=2, device=device)
assert torch.all(torch.eq(list(old_state_dict.values())[0], list(model.network.state_dict().values())[0]))
assert torch.all(~torch.eq(list(old_state_dict.values())[-1], list(model.network.state_dict().values())[-1]))
def test_save_load_baseNN(self):
model = baseNN(architecture=architecture, num_classes=num_classes)
model._initialize_model(feature_extract=True, use_pretrained=True)
model.evaluate(dataloaders['test'], device=device)
model.save(filename=filename, savedir=savedir)
model._initialize_model(feature_extract=True, use_pretrained=True)
model.load(filename=filename, savedir=savedir)
model.evaluate(dataloaders['test'], device=device)
def test_save_load_redBNN(self):
for inference in ['svi', 'hmc']:
model = redBNN(architecture=architecture, num_classes=num_classes,
inference=inference, reduction='layers', bayesian_idx=4)
model._initialize_model()
model.train(dataloaders=dataloaders, num_iters=2, device=device,
eval_samples=1, svi_iters=2, hmc_samples=2, hmc_warmup=5)
model.evaluate(dataloaders['test'], device=device, n_samples=2)
model.save(filename='redBNN_'+str(inference), savedir=savedir, hmc_samples=2)
model = redBNN(architecture=architecture, num_classes=num_classes,
inference=inference, reduction='layers', bayesian_idx=4)
model._initialize_model()
model.load(filename='redBNN_'+str(inference), savedir=savedir, hmc_samples=2)
model.evaluate(dataloaders['test'], device=device, n_samples=2)
def test_posterior_samples_svi_blocks(self):
warnings.filterwarnings('ignore')
from pyro.distributions import Normal
import torch.nn as nn
import torch.nn.functional as nnf
softplus = torch.nn.Softplus()
network = redBNN(architecture=architecture, num_classes=num_classes,
inference='svi', reduction='blocks', bayesian_idx=4)
network.train(dataloaders=dataloaders, num_iters=2, device=device, eval_samples=3, svi_iters=2)
old_state_dict = network.network.state_dict()
network.to(device)
network.network.eval()
with torch.no_grad():
inputs = next(iter(dataloaders['train']))[0]
inputs = inputs.to(device)
preds = []
for seed in [0,1,2]:
pyro.set_rng_seed(seed)
guide_trace = poutine.trace(network.guide).get_trace(inputs)
weights = {}
for key, value in network.network.state_dict().items():
weights.update({str(key):value})
for param_name, param in network.bayesian_weights.items():
dist = Normal(loc=guide_trace.nodes[param_name+"_loc"]["value"],
scale=softplus(guide_trace.nodes[param_name+"_scale"]["value"]))
w = pyro.sample(param_name, dist)
weights.update({param_name:w})
basenet_copy = copy.deepcopy(network.network)
basenet_copy.load_state_dict(weights)
preds.append(basenet_copy.forward(inputs))
assert torch.all(torch.eq(old_state_dict['conv1.weight'],
basenet_copy.state_dict()['conv1.weight']))
assert torch.all(~torch.eq(old_state_dict['layer1.0.conv1.weight'],
basenet_copy.state_dict()['layer1.0.conv1.weight']))
def test_posterior_samples_svi_layers(self):
warnings.filterwarnings('ignore')
from pyro.distributions import Normal
import torch.nn as nn
import torch.nn.functional as nnf
softplus = torch.nn.Softplus()
network = redBNN(architecture=architecture, num_classes=num_classes,
inference='svi', reduction='layers', bayesian_idx=4)
network.train(dataloaders=dataloaders, num_iters=2, device=device, eval_samples=3, svi_iters=2)
old_state_dict = network.network.state_dict()
network.to(device)
network.network.eval()
with torch.no_grad():
inputs = next(iter(dataloaders['train']))[0]
inputs = inputs.to(device)
preds = []
for seed in [0,1,2]:
pyro.set_rng_seed(seed)
guide_trace = poutine.trace(network.guide).get_trace(inputs)
weights = {}
for key, value in network.network.state_dict().items():
weights.update({str(key):value})
for param_name, param in network.bayesian_weights.items():
dist = Normal(loc=guide_trace.nodes[param_name+"_loc"]["value"],
scale=softplus(guide_trace.nodes[param_name+"_scale"]["value"]))
w = pyro.sample(param_name, dist)
weights.update({param_name:w})
basenet_copy = copy.deepcopy(network.network)
basenet_copy.load_state_dict(weights)
preds.append(basenet_copy.forward(inputs))
assert torch.all(torch.eq(old_state_dict['conv1.weight'],
basenet_copy.state_dict()['conv1.weight']))
assert torch.all(~torch.eq(old_state_dict['layer1.0.conv1.weight'],
basenet_copy.state_dict()['layer1.0.conv1.weight']))
def test_posterior_samples_hmc_blocks(self):
warnings.filterwarnings('ignore')
from pyro.distributions import Normal
import torch.nn as nn
import torch.nn.functional as nnf
softplus = torch.nn.Softplus()
network = redBNN(architecture=architecture, num_classes=num_classes,
inference='hmc', reduction='blocks', bayesian_idx=4)
network.train(dataloaders=dataloaders, num_iters=2, device=device, eval_samples=3,
hmc_samples=3, hmc_warmup=5)
old_state_dict = network.network.state_dict()
network.to(device)
network.network.eval()
with torch.no_grad():
inputs = next(iter(dataloaders['train']))[0]
inputs = inputs.to(device)
preds = []
for seed in [0,1,2]:
net = network.posterior_samples[seed]
preds.append(net.forward(inputs))
assert torch.all(torch.eq(old_state_dict['conv1.weight'],
net.state_dict()['conv1.weight']))
assert torch.all(~torch.eq(old_state_dict['layer1.0.conv1.weight'],
net.state_dict()['layer1.0.conv1.weight']))
def test_posterior_samples_hmc_layers(self):
warnings.filterwarnings('ignore')
from pyro.distributions import Normal
import torch.nn as nn
import torch.nn.functional as nnf
softplus = torch.nn.Softplus()
network = redBNN(architecture=architecture, num_classes=num_classes,
inference='hmc', reduction='layers', bayesian_idx=4)
network.train(dataloaders=dataloaders, num_iters=2, device=device, eval_samples=3,
hmc_samples=3, hmc_warmup=5)
old_state_dict = network.network.state_dict()
network.to(device)
network.network.eval()
with torch.no_grad():
inputs = next(iter(dataloaders['train']))[0]
inputs = inputs.to(device)
preds = []
for seed in [0,1,2]:
net = network.posterior_samples[seed]
preds.append(net.forward(inputs))
assert torch.all(torch.eq(old_state_dict['conv1.weight'],
net.state_dict()['conv1.weight']))
assert torch.all(~torch.eq(old_state_dict['layer1.0.conv1.weight'],
net.state_dict()['layer1.0.conv1.weight']))
if __name__ == '__main__':
unittest.main()