-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.py
238 lines (175 loc) · 8.12 KB
/
utils.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
import numpy as np
import pickle
import torch
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.data.dataloader import default_collate
from torch.nn import functional as F
from torchvision import transforms
import copy
# import data
# from encoder import Classifier
# from vae_models import AutoEncoder
###################
## Loss function ##
###################
def loss_fn_kd(scores, target_scores, T=2.):
"""Compute knowledge-distillation (KD) loss given [scores] and [target_scores].
Both [scores] and [target_scores] should be tensors, although [target_scores] should be repackaged.
'Hyperparameter': temperature"""
device = scores.device
log_scores_norm = F.log_softmax(scores / T, dim=1)
targets_norm = F.softmax(target_scores / T, dim=1)
# if [scores] and [target_scores] do not have equal size, append 0's to [targets_norm]
n = scores.size(1)
if n>target_scores.size(1):
n_batch = scores.size(0)
zeros_to_add = torch.zeros(n_batch, n-target_scores.size(1))
zeros_to_add = zeros_to_add.to(device)
targets_norm = torch.cat([targets_norm.detach(), zeros_to_add], dim=1)
# Calculate distillation loss (see e.g., Li and Hoiem, 2017)
KD_loss_unnorm = -(targets_norm * log_scores_norm)
KD_loss_unnorm = KD_loss_unnorm.sum(dim=1) #--> sum over classes
KD_loss_unnorm = KD_loss_unnorm.mean() #--> average over batch
# normalize
KD_loss = KD_loss_unnorm * T**2
return KD_loss
def loss_fn_kd_binary(scores, target_scores, T=2.):
"""Compute binary knowledge-distillation (KD) loss given [scores] and [target_scores].
Both [scores] and [target_scores] should be tensors, although [target_scores] should be repackaged.
'Hyperparameter': temperature"""
device = scores.device
scores_norm = torch.sigmoid(scores / T)
targets_norm = torch.sigmoid(target_scores / T)
# if [scores] and [target_scores] do not have equal size, append 0's to [targets_norm]
n = scores.size(1)
if n>target_scores.size(1):
n_batch = scores.size(0)
zeros_to_add = torch.zeros(n_batch, n-target_scores.size(1))
zeros_to_add = zeros_to_add.to(device)
targets_norm = torch.cat([targets_norm, zeros_to_add], dim=1)
# Calculate distillation loss
KD_loss_unnorm = -( targets_norm * torch.log(scores_norm) + (1-targets_norm) * torch.log(1-scores_norm) )
KD_loss_unnorm = KD_loss_unnorm.sum(dim=1) #--> sum over classes
KD_loss_unnorm = KD_loss_unnorm.mean() #--> average over batch
# normalize
KD_loss = KD_loss_unnorm * T**2
return KD_loss
##-------------------------------------------------------------------------------------------------------------------##
#############################
## Data-handling functions ##
#############################
def get_data_loader(dataset, batch_size, cuda=False, collate_fn=None, drop_last=False, augment=False):
'''Return <DataLoader>-object for the provided <DataSet>-object [dataset].'''
# If requested, make copy of original dataset to add augmenting transform (without altering original dataset)
if augment:
dataset_ = copy.deepcopy(dataset)
dataset_.transform = transforms.Compose([dataset.transform, *data.AVAILABLE_TRANSFORMS['augment']])
else:
dataset_ = dataset
# Create and return the <DataLoader>-object
return DataLoader(
dataset_, batch_size=batch_size, shuffle=True,
collate_fn=(collate_fn or default_collate), drop_last=drop_last,
**({'num_workers': 0, 'pin_memory': True} if cuda else {})
)
def label_squeezing_collate_fn(batch):
x, y = default_collate(batch)
return x, y.long().squeeze()
def to_one_hot(y, classes):
'''Convert a nd-array with integers [y] to a 2D "one-hot" tensor.'''
c = np.zeros(shape=[len(y), classes], dtype='float32')
c[range(len(y)), y] = 1.
c = torch.from_numpy(c)
return c
##-------------------------------------------------------------------------------------------------------------------##
##########################################
## Object-saving and -loading functions ##
##########################################
def save_object(object, path):
with open(path + '.pkl', 'wb') as f:
pickle.dump(object, f, pickle.HIGHEST_PROTOCOL)
def load_object(path):
with open(path + '.pkl', 'rb') as f:
return pickle.load(f)
##-------------------------------------------------------------------------------------------------------------------##
################################
## Model-inspection functions ##
################################
def count_parameters(model, verbose=True):
'''Count number of parameters, print to screen.'''
total_params = learnable_params = fixed_params = 0
for param in model.parameters():
n_params = index_dims = 0
for dim in param.size():
n_params = dim if index_dims==0 else n_params*dim
index_dims += 1
total_params += n_params
if param.requires_grad:
learnable_params += n_params
else:
fixed_params += n_params
if verbose:
print("--> this network has {} parameters (~{} million)"
.format(total_params, round(total_params / 1000000, 1)))
print(" of which: - learnable: {} (~{} million)".format(learnable_params,
round(learnable_params / 1000000, 1)))
print(" - fixed: {} (~{} million)".format(fixed_params, round(fixed_params / 1000000, 1)))
return total_params, learnable_params, fixed_params
def print_model_info(model, title="MODEL"):
'''Print information on [model] onto the screen.'''
print("\n" + 40*"-" + title + 40*"-")
print(model)
print(90*"-")
_ = count_parameters(model)
print(90*"-")
##-------------------------------------------------------------------------------------------------------------------##
#################################
## Custom-written "nn-Modules" ##
#################################
class Identity(nn.Module):
'''A nn-module to simply pass on the input data.'''
def forward(self, x):
return x
def __repr__(self):
tmpstr = self.__class__.__name__ + '()'
return tmpstr
class Reshape(nn.Module):
'''A nn-module to reshape a tensor to a 4-dim "image"-tensor with [image_channels] channels.'''
def __init__(self, image_channels):
super().__init__()
self.image_channels = image_channels
def forward(self, x):
batch_size = x.size(0) # first dimenstion should be batch-dimension.
image_size = int(np.sqrt(x.nelement() / (batch_size*self.image_channels)))
return x.view(batch_size, self.image_channels, image_size, image_size)
def __repr__(self):
tmpstr = self.__class__.__name__ + '(channels = {})'.format(self.image_channels)
return tmpstr
class ToImage(nn.Module):
'''Reshape input units to image with pixel-values between 0 and 1.
Input: [batch_size] x [in_units] tensor
Output: [batch_size] x [image_channels] x [image_size] x [image_size] tensor'''
def __init__(self, image_channels=1):
super().__init__()
# reshape to 4D-tensor
self.reshape = Reshape(image_channels=image_channels)
# put through sigmoid-nonlinearity
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.reshape(x)
x = self.sigmoid(x)
return x
def image_size(self, in_units):
'''Given the number of units fed in, return the size of the target image.'''
image_size = np.sqrt(in_units/self.image_channels)
return image_size
class Flatten(nn.Module):
'''A nn-module to flatten a multi-dimensional tensor to 2-dim tensor.'''
def forward(self, x):
batch_size = x.size(0) # first dimenstion should be batch-dimension.
return x.view(batch_size, -1)
def __repr__(self):
tmpstr = self.__class__.__name__ + '()'
return tmpstr
##-------------------------------------------------------------------------------------------------------------------##