-
Notifications
You must be signed in to change notification settings - Fork 7
/
binary.py
393 lines (302 loc) · 10.7 KB
/
binary.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
"""
@Author: Mehdi Bahri
@Contact: [email protected]
@File: binary.py
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class _STEQuantizer(torch.autograd.Function):
@staticmethod
def forward(ctx, in_):
ctx.save_for_backward(in_)
x = torch.sign(in_)
return x
@staticmethod
def backward(ctx, grad_out_):
(in_,) = ctx.saved_tensors
cond = in_.abs() <= 1
zeros = torch.zeros_like(grad_out_)
x = torch.where(cond, grad_out_, zeros)
return x
class STEQuantizer(torch.nn.Module):
def forward(self, x):
return _STEQuantizer.apply(x)
quantize = _STEQuantizer.apply
class PReLU(nn.PReLU):
def __init__(self, num_parameters: int = 1, init: float = 0.25):
super().__init__(num_parameters=num_parameters, init=init)
self.init = init
def reset_parameters(self):
nn.init.constant_(self.weight, self.init)
class ReLU(nn.ReLU):
def __init__():
super().__init__()
def reset_parameters(self):
pass
class LearnedRescaleLayer2d(nn.Module):
def __init__(self, input_shapes):
super(LearnedRescaleLayer2d, self).__init__()
"""Implements the learned activation rescaling XNOR-Net++ style.
This is used to scale the outputs of the binary convolutions in the Strong
Baseline networks. [(Bulat & Tzimiropoulos,
2019)](https://arxiv.org/abs/1909.13863)
"""
self.shapes = input_shapes
self.scale_a = nn.Parameter(torch.Tensor(self.shapes[1], 1, 1).fill_(1))
self.scale_b = nn.Parameter(torch.Tensor(1, self.shapes[2], 1).fill_(1))
self.scale_c = nn.Parameter(torch.Tensor(1, 1, self.shapes[3]).fill_(1))
def reset_parameters(self):
nn.init.ones_(self.scale_a)
nn.init.ones_(self.scale_b)
nn.init.ones_(self.scale_c)
def forward(self, x):
out = x * self.scale_a * self.scale_b * self.scale_c
return out
class LearnedRescaleLayer1d(nn.Module):
def __init__(self, input_shapes):
super(LearnedRescaleLayer1d, self).__init__()
"""Implements the learned activation rescaling XNOR-Net++ style.
This is used to scale the outputs of the binary convolutions in the Strong
Baseline networks. [(Bulat & Tzimiropoulos,
2019)](https://arxiv.org/abs/1909.13863)
"""
self.shapes = input_shapes
self.scale_a = nn.Parameter(torch.Tensor(self.shapes[1], 1).fill_(1))
self.scale_b = nn.Parameter(torch.Tensor(1, self.shapes[2]).fill_(1))
def reset_parameters(self):
nn.init.ones_(self.scale_a)
nn.init.ones_(self.scale_b)
def forward(self, x):
out = x * self.scale_a * self.scale_b
return out
class LearnedRescaleLayer0d(nn.Module):
def __init__(self, input_shapes):
super(LearnedRescaleLayer0d, self).__init__()
"""Implements the learned activation rescaling XNOR-Net++ style.
This is used to scale the outputs of the binary convolutions in the Strong
Baseline networks. [(Bulat & Tzimiropoulos,
2019)](https://arxiv.org/abs/1909.13863)
"""
self.shapes = input_shapes
self.scale_a = nn.Parameter(
torch.Tensor(
self.shapes[1],
).fill_(1)
)
def reset_parameters(self):
nn.init.ones_(self.scale_a)
def forward(self, x):
out = x * self.scale_a
return out
class LearnedRescaleLayer1db(nn.Module):
def __init__(self, input_shapes):
super().__init__()
"""Implements the learned activation rescaling XNOR-Net++ style.
This is used to scale the outputs of the binary convolutions in the Strong
Baseline networks. [(Bulat & Tzimiropoulos,
2019)](https://arxiv.org/abs/1909.13863)
"""
self.shapes = input_shapes
self.scale_a = nn.Parameter(
torch.Tensor(self.shapes[0], self.shapes[1]).fill_(1)
)
def forward(self, x):
out = x * self.scale_a
return out
class Transpose(nn.Module):
def __init__(self, a, b):
super().__init__()
self.a = a
self.b = b
def forward(self, X):
return X.transpose(self.a, self.b)
class BinLinear(nn.Module):
def __init__(self, in_channels, out_channels, binary_weights=True, bias=False):
super(BinLinear, self).__init__()
"""
An implementation of a Linear layer.
Parameters:
- weight: the learnable weights of the module of shape (in_channels, out_channels).
- bias: the learnable bias of the module of shape (out_channels).
"""
self.in_channel = in_channels
self.out_channels = out_channels
self.binary_weights = binary_weights
self.weights_real = nn.Parameter(torch.Tensor(out_channels, in_channels))
self.reset_parameters()
def reset_parameters(self):
nn.init.kaiming_uniform_(self.weights_real)
def forward(self, x):
"""
Input:
- x: Input data of shape (N, *, H) where * means any number of additional
dimensions and H = in_channels
Output:
- out: Output data of shape (N, *, H') where * means any number of additional
dimensions and H' = out_channels
"""
if self.binary_weights:
# self.weights_real.data = torch.clamp(self.weights_real.data - self.weights_real.data.mean(1, keepdim=True), -1, 1)
self.weights_real.data = torch.clamp(self.weights_real.data, -1, 1)
weights = quantize(self.weights_real)
else:
weights = self.weights_real
out = F.linear(x, weights)
return out
class RescaledDotProduct(nn.Module):
def __init__(self, dot_product, dot_product_args, rescaler, rescaler_args):
super().__init__()
self.inner = dot_product(**dot_product_args)
self.rescaler = rescaler(**rescaler_args)
def reset_parameters():
self.inner.reset_parameters()
self.rescaler.reset_parameters()
def forward(self, x):
x = self.inner(x)
return self.rescaler(x)
class NoOp(nn.Module):
def __init__(self, **kwargs):
super().__init__()
def forward(self, x):
return x
class Identity(nn.Identity):
def __init__(self):
super().__init__()
def reset_parameters(self):
pass
class BinConv1d(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
bias=False,
binary_weights=True,
):
super(BinConv1d, self).__init__()
"""
An implementation of a Linear layer.
Parameters:
- weight: the learnable weights of the module of shape (in_channels, out_channels).
- bias: the learnable bias of the module of shape (out_channels).
"""
self.in_channel = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.dilation = dilation
self.groups = groups
self.binary_weights = binary_weights
self.weights_real = nn.Parameter(
torch.Tensor(out_channels, in_channels, kernel_size)
)
nn.init.kaiming_normal_(self.weights_real)
def forward(self, x):
"""
Input:
- x: Input data of shape (N, *, H) where * means any number of additional
dimensions and H = in_channels
Output:
- out: Output data of shape (N, *, H') where * means any number of additional
dimensions and H' = out_channels
"""
if self.binary_weights:
self.weights_real.data = torch.clamp(self.weights_real.data, -1, 1)
weights = quantize(self.weights_real)
else:
weights = self.weights_real
out = F.conv1d(
x,
weights,
stride=self.stride,
padding=self.padding,
dilation=self.dilation,
groups=self.groups,
)
return out
class BinConv2d(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
bias=False,
binary_weights=True,
):
super(BinConv2d, self).__init__()
"""
An implementation of a Linear layer.
Parameters:
- weight: the learnable weights of the module of shape (in_channels, out_channels).
- bias: the learnable bias of the module of shape (out_channels).
"""
self.in_channel = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.dilation = dilation
self.groups = groups
self.binary_weights = binary_weights
if isinstance(kernel_size, int):
k1, k2 = kernel_size, kernel_size
else:
k1, k2 = kernel_size
self.weights_real = nn.Parameter(
torch.Tensor(out_channels, in_channels, k1, k2)
)
nn.init.kaiming_normal_(self.weights_real)
def forward(self, x):
"""
Input:
- x: Input data of shape (N, *, H) where * means any number of additional
dimensions and H = in_channels
Output:
- out: Output data of shape (N, *, H') where * means any number of additional
dimensions and H' = out_channels
"""
if self.binary_weights:
self.weights_real.data = torch.clamp(self.weights_real.data, -1, 1)
weights = quantize(self.weights_real)
else:
weights = self.weights_real
out = F.conv2d(
x,
weights,
stride=self.stride,
padding=self.padding,
dilation=self.dilation,
groups=self.groups,
)
return out
class MedianCenter(nn.Module):
def __init__(self, axis):
super().__init__()
self.axis = axis
def forward(self, x):
return x - x.median(self.axis, keepdim=True)[0]
def reset_parameters(self):
pass
class MeanCenter(nn.Module):
def __init__(self, axis):
super().__init__()
self.axis = axis
def forward(self, x):
return x - x.mean(self.axis, keepdim=True)[0]
def reset_parameters(self):
pass
def count_trainable_parameters(model):
model_parameters = filter(lambda p: p.requires_grad, model.parameters())
params = sum([np.prod(p.size()) for p in model_parameters])
return params