-
Notifications
You must be signed in to change notification settings - Fork 1
/
l0_dense.py
492 lines (414 loc) · 18.4 KB
/
l0_dense.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import math
import torch
import torch.nn.functional as F
from torch import nn
class L0Dense(torch.nn.Module):
def __init__(
self,
in_features: int,
out_features: int,
droprate=0.5,
lamba=1.0,
weight_decay=0.0,
bias: bool = True,
local_rep: bool = False,
):
super().__init__()
self.epsilon = 1e-6
self.limit_a = -0.1
self.limit_b = 1.1
self.in_features = in_features
self.out_features = out_features
self.prior_prec = weight_decay
self.local_rep = local_rep
self.weight = nn.Parameter(torch.empty(out_features, in_features))
if bias:
self.bias = nn.Parameter(torch.ones(out_features))
else:
self.register_parameter("bias", None)
self.qz_loga = nn.Parameter(torch.empty(out_features, in_features))
self.floatTensor = (
torch.FloatTensor
if not torch.cuda.is_available()
else torch.cuda.FloatTensor
)
self.droprate = droprate
self.lamba = lamba
self.temperature = 2.0 / 3.0
self.reset_parameters()
def reset_parameters(self):
"""Use pytorch linear for initialization (same member variable naming)"""
torch.nn.Linear.reset_parameters(self)
self.qz_loga.data.normal_(
math.log(1 - self.droprate) - math.log(self.droprate), 1e-2
)
def constrain_parameters(self, **kwargs):
self.qz_loga.data.clamp_(min=math.log(1e-2), max=math.log(1e2))
def cdf_qz(self, x):
"""Implements the CDF of the 'stretched' concrete distribution"""
xn = (x - self.limit_a) / (self.limit_b - self.limit_a)
logits = math.log(xn) - math.log(1 - xn)
return torch.sigmoid(logits * self.temperature - self.qz_loga).clamp(
min=self.epsilon, max=1 - self.epsilon
)
def quantile_concrete(self, x):
"""Implements the quantile, aka inverse CDF, of the 'stretched' concrete distribution"""
y = torch.sigmoid(
(torch.log(x) - torch.log(1 - x) + self.qz_loga) / self.temperature
)
return y * (self.limit_b - self.limit_a) + self.limit_a
def _reg_w(self):
"""Expected L0 norm under the stochastic gates, takes into account and re-weights also a potential L2 penalty"""
# logpw_col = torch.sum(- (.5 * self.prior_prec * self.weight.pow(2)) - self.lamba, 1)
# logpw = torch.sum((1 - self.cdf_qz(0)).t() * logpw_col)
# logpb = 0 if self.bias is None else - torch.sum(.5 * self.prior_prec * self.bias.pow(2))
# return logpw + logpb
return self.lamba * torch.sum(1 - self.cdf_qz(0))
def regularization(self):
return self._reg_w()
def regularization_constrained(self, idx):
"""Don't count L0 for every output but ignore reg for indices given by `idx`"""
# set given cdf for given indices to 1 which then cancels the sum
# could be implemented differently but this method doesn't require slicing/copying the cdf tensor
cdf = self.cdf_qz(0)
cdf[idx] = 1.0
return self.lamba * (torch.sum(1 - cdf))
def regularization_cheaper(self, idx, factor=0.5):
"""Make the L0 reg cheaper for indices given by `idx`"""
cdf = self.cdf_qz(0)
# cdf[idx] = torch.clamp_max(cdf[idx]*factor, 1.0)
# decrase penalty for div units by factor
reg_div = self.lamba * factor * torch.sum(1 - cdf[idx])
non_div = cdf
# div units won't result in penalty because 1-1 = 0
non_div[idx] = 1.0
reg_non_div = self.lamba * torch.sum(1 - non_div)
# return self.lamba * (torch.sum(1 - cdf))
return reg_div + reg_non_div
def get_eps(self, size):
"""Uniform random numbers for the concrete distribution"""
# eps = torch.zeros_like(size).uniform_(self.epsilon, 1-self.epsilon)
eps = self.floatTensor(size).uniform_(self.epsilon, 1 - self.epsilon)
eps.requires_grad_()
return eps
def sample_z(self, batch_size: int = 1, sample: bool = True):
"""Sample the hard-concrete gates for training and use a deterministic value for testing"""
if sample:
# eps = self.get_eps(torch.ones(batch_size, self.out_features, self.in_features))
eps = self.get_eps(
self.floatTensor(batch_size, self.out_features, self.in_features)
)
z = self.quantile_concrete(eps)
return F.hardtanh(z, min_val=0.0, max_val=1.0)
else:
# deterministic, hence batch_size=1 is enough, i.e. batch_size param can be None
# -> can't be none because of jit
pi = torch.sigmoid(self.qz_loga).expand(self.out_features, self.in_features)
return F.hardtanh(
pi * (self.limit_b - self.limit_a) + self.limit_a,
min_val=0.0,
max_val=1.0,
)
def sample_weight(self):
# z = self.quantile_concrete(self.get_eps(torch.ones(self.out_features, self.in_features)))
z = self.quantile_concrete(
self.get_eps(self.floatTensor(self.out_features, self.in_features))
)
mask = F.hardtanh(z, min_val=0.0, max_val=1.0)
return mask * self.weight
def deterministic_weight(self):
# get deterministic z
z = self.sample_z(sample=False)
return self.weight * z
def deterministic_bias(self):
return self.bias
def forward(self, input):
if self.local_rep or not self.training:
z = self.sample_z(sample=self.training)
output = F.linear(input, self.weight * z, self.bias)
else:
weight = self.sample_weight()
output = F.linear(input, weight, self.bias)
return output
def extra_repr(self) -> str:
return "in_features={}, out_features={}, bias={}".format(
self.in_features, self.out_features, self.bias is not None
)
class L0DenseBias(torch.nn.Module):
def __init__(
self,
in_features: int,
out_features: int,
droprate=0.5,
lamba=1.0,
weight_decay=0.0,
bias: bool = True,
local_rep: bool = False,
temperature=2.0 / 3.0,
):
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.epsilon = 1e-6
self.limit_a = -0.1
self.limit_b = 1.1
self.prior_prec = weight_decay
self.local_rep = local_rep
self.weight = nn.Parameter(torch.zeros(out_features, in_features))
if bias:
self.bias = nn.Parameter(torch.zeros(out_features))
else:
self.register_parameter("bias", None)
self.qz_loga = nn.Parameter(torch.zeros(out_features, in_features + 1))
self.floatTensor = (
torch.FloatTensor
if not torch.cuda.is_available()
else torch.cuda.FloatTensor
)
self.droprate = droprate
self.lamba = lamba
self.temperature = temperature
self.reset_parameters()
def reset_parameters(self):
"""Use pytorch linear for initialization (same member variable naming)"""
torch.nn.init.kaiming_uniform_(self.weight, mode="fan_out")
self.qz_loga.data.normal_(
math.log(1 - self.droprate) - math.log(self.droprate), 1e-2
)
def constrain_parameters(self, **kwargs):
self.qz_loga.data.clamp_(min=math.log(1e-2), max=math.log(1e2))
def cdf_qz(self, x):
"""Implements the CDF of the 'stretched' concrete distribution"""
xn = (x - self.limit_a) / (self.limit_b - self.limit_a)
logits = math.log(xn) - math.log(1 - xn)
return torch.sigmoid(logits * self.temperature - self.qz_loga).clamp(
min=self.epsilon, max=1 - self.epsilon
)
def quantile_concrete(self, x):
"""Implements the quantile, aka inverse CDF, of the 'stretched' concrete distribution"""
y = torch.sigmoid(
(torch.log(x) - torch.log(1 - x) + self.qz_loga) / self.temperature
)
return y * (self.limit_b - self.limit_a) + self.limit_a
def _reg_w(self):
"""Expected L0 norm under the stochastic gates, takes into account and re-weights also a potential L2 penalty"""
# logpw_col = torch.sum(- (.5 * self.prior_prec * self.weight.pow(2)) - self.lamba, 1)
# logpw = torch.sum((1 - self.cdf_qz(0)).t() * logpw_col)
# logpb = 0 if self.bias is None else - torch.sum(.5 * self.prior_prec * self.bias.pow(2))
# return logpw + logpb
return self.lamba * torch.sum(1 - self.cdf_qz(0))
def regularization(self):
return self._reg_w()
def regularization_constrained(self, idx):
"""Don't count L0 for every output but ignore reg for indices given by `idx`"""
# set given cdf for given indices to 1 which then cancels the sum
# could be implemented differently but this method doesn't require slicing/copying the cdf tensor
cdf = self.cdf_qz(0)
cdf[idx] = 1.0
return self.lamba * (torch.sum(1 - cdf))
def regularization_cheaper(self, idx, factor=0.5):
"""Make the L0 reg cheaper for indices given by `idx`"""
cdf = self.cdf_qz(0)
# cdf[idx] = torch.clamp_max(cdf[idx]*factor, 1.0)
# decrease penalty for div units by factor
reg_div = self.lamba * factor * torch.sum(1 - cdf[idx])
non_div = cdf
# div units won't result in penalty because 1-1 = 0
non_div[idx] = 1.0
reg_non_div = self.lamba * torch.sum(1 - non_div)
# return self.lamba * (torch.sum(1 - cdf))
return reg_div + reg_non_div
def get_eps(self, size):
"""Uniform random numbers for the concrete distribution"""
# eps = torch.zeros_like(size).uniform_(self.epsilon, 1-self.epsilon)
eps = self.floatTensor(size).uniform_(self.epsilon, 1 - self.epsilon)
eps.requires_grad_()
# eps = Variable(eps)
return eps
def sample_z(self, batch_size: int = 1, sample: bool = True):
"""Sample the hard-concrete gates for training and use a deterministic value for testing"""
if sample:
# eps = self.get_eps(torch.empty(batch_size, self.out_features, self.in_features+1))
eps = self.get_eps(
self.floatTensor(batch_size, self.out_features, self.in_features + 1)
)
z = self.quantile_concrete(eps)
return F.hardtanh(z, min_val=0.0, max_val=1.0)
else: # deterministic, hence batch_size=1 is enough, i.e. batch_size param can be None
pi = torch.sigmoid(self.qz_loga).expand(
self.out_features, self.in_features + 1
)
return F.hardtanh(
pi * (self.limit_b - self.limit_a) + self.limit_a,
min_val=0.0,
max_val=1.0,
)
def sample_weight(self):
# z = self.quantile_concrete(self.get_eps(torch.empty(self.out_features, self.in_features+1)))
z = self.quantile_concrete(
self.get_eps(self.floatTensor(self.out_features, self.in_features + 1))
)
mask = F.hardtanh(z, min_val=0.0, max_val=1.0)[..., :, :-1]
return mask * self.weight
def sample_weight_bias(self):
# z = self.quantile_concrete(self.get_eps(torch.empty(self.out_features, self.in_features+1)))
z = self.quantile_concrete(
self.get_eps(self.floatTensor(self.out_features, self.in_features + 1))
)
mask = F.hardtanh(z, min_val=0.0, max_val=1.0)
return (
mask[..., :, :-1] * self.weight,
self.bias * mask[..., :, -1] if self.bias is not None else None,
)
def deterministic_weight(self):
# get deterministic z
z = self.sample_z(sample=False)
return self.weight * z[:, :-1]
def deterministic_bias(self):
z = self.sample_z(sample=False)
return self.bias * z[:, -1]
def forward(self, input):
if self.local_rep or not self.training:
z = self.sample_z(sample=self.training)
output = F.linear(input, self.weight * z[:, :-1], self.bias * z[:, -1])
else:
weight, bias = self.sample_weight_bias()
output = F.linear(input, weight, bias)
return output
def extra_repr(self) -> str:
return "in_features={}, out_features={}, bias={}".format(
self.in_features, self.out_features, self.bias is not None
)
class L0DenseBiasCorr(torch.nn.Module):
def __init__(
self,
in_features: int,
out_features: int,
droprate=0.5,
lamba=1.0,
weight_decay=0.0,
bias: bool = True,
local_rep: bool = False,
):
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.epsilon = 1e-6
self.limit_a = -0.1
self.limit_b = 1.1
self.prior_prec = weight_decay
self.local_rep = local_rep
self.weight = nn.Parameter(torch.zeros(out_features, in_features))
if bias:
self.bias = nn.Parameter(torch.zeros(out_features))
else:
self.register_parameter("bias", None)
self.qz_loga = nn.Parameter(torch.zeros(out_features, in_features + 1))
##self.cov = nn.Parameter(torch.ones(torch.numel(self.qz_loga)))
self.floatTensor = (
torch.FloatTensor
if not torch.cuda.is_available()
else torch.cuda.FloatTensor
)
self.droprate = droprate
self.lamba = lamba
self.temperature = 2.0 / 3.0
self.reset_parameters()
def reset_parameters(self):
"""Use pytorch linear for initialization (same member variable naming)"""
torch.nn.init.kaiming_uniform_(self.weight, mode="fan_out")
self.qz_loga.data.normal_(
math.log(1 - self.droprate) - math.log(self.droprate), 1e-2
)
def constrain_parameters(self, **kwargs):
self.qz_loga.data.clamp_(min=math.log(1e-2), max=math.log(1e2))
def cdf_qz(self, x):
"""Implements the CDF of the 'stretched' concrete distribution"""
xn = (x - self.limit_a) / (self.limit_b - self.limit_a)
logits = math.log(xn) - math.log(1 - xn)
return torch.sigmoid(logits * self.temperature - self.qz_loga).clamp(
min=self.epsilon, max=1 - self.epsilon
)
def quantile_concrete(self, x):
"""Implements the quantile, aka inverse CDF, of the 'stretched' concrete distribution"""
y = torch.sigmoid(
(torch.log(x) - torch.log(1 - x) + self.qz_loga) / self.temperature
)
return y * (self.limit_b - self.limit_a) + self.limit_a
def _reg_w(self):
"""Expected L0 norm under the stochastic gates, takes into account and re-weights also a potential L2 penalty"""
# logpw_col = torch.sum(- (.5 * self.prior_prec * self.weight.pow(2)) - self.lamba, 1)
# logpw = torch.sum((1 - self.cdf_qz(0)).t() * logpw_col)
# logpb = 0 if self.bias is None else - torch.sum(.5 * self.prior_prec * self.bias.pow(2))
# return logpw + logpb
return self.lamba * torch.sum(1 - self.cdf_qz(0))
def regularization(self):
return self._reg_w()
def regularization_constrained(self, idx):
"""Don't count L0 for every output but ignore reg for indices given by `idx`"""
# set given cdf for given indices to 1 which then cancels the sum
# could be implemented differently but this method doesn't require slicing/copying the cdf tensor
cdf = self.cdf_qz(0)
cdf[idx] = 1.0
return self.lamba * (torch.sum(1 - cdf))
def get_eps(self, size):
"""Uniform random numbers for the concrete distribution"""
# eps = torch.zeros_like(size).uniform_(self.epsilon, 1-self.epsilon)
eps = self.floatTensor(size).uniform_(self.epsilon, 1 - self.epsilon)
eps.requires_grad_()
# eps = Variable(eps)
return eps
def sample_z(self, batch_size: int = 1, sample: bool = True):
"""Sample the hard-concrete gates for training and use a deterministic value for testing"""
if sample:
# eps = self.get_eps(torch.empty(batch_size, self.out_features, self.in_features+1))
eps = self.get_eps(
self.floatTensor(batch_size, self.out_features, self.in_features + 1)
)
z = self.quantile_concrete(eps)
return F.hardtanh(z, min_val=0.0, max_val=1.0)
else: # deterministic, hence batch_size=1 is enough, i.e. batch_size param can be None
pi = torch.sigmoid(self.qz_loga).expand(
self.out_features, self.in_features + 1
)
return F.hardtanh(
pi * (self.limit_b - self.limit_a) + self.limit_a,
min_val=0.0,
max_val=1.0,
)
def sample_weight(self):
# z = self.quantile_concrete(self.get_eps(torch.empty(self.out_features, self.in_features+1)))
z = self.quantile_concrete(
self.get_eps(self.floatTensor(self.out_features, self.in_features + 1))
)
mask = F.hardtanh(z, min_val=0.0, max_val=1.0)[..., :, :-1]
return mask * self.weight
def sample_weight_bias(self):
# z = self.quantile_concrete(self.get_eps(torch.empty(self.out_features, self.in_features+1)))
z = self.quantile_concrete(
self.get_eps(self.floatTensor(self.out_features, self.in_features + 1))
)
mask = F.hardtanh(z, min_val=0.0, max_val=1.0)
return (
mask[..., :, :-1] * self.weight,
self.bias * mask[..., :, -1] if self.bias is not None else None,
)
def deterministic_weight(self):
# get deterministic z
z = self.sample_z(sample=False)
return self.weight * z[:, :-1]
def deterministic_bias(self):
z = self.sample_z(sample=False)
return self.bias * z[:, -1]
def forward(self, input):
if self.local_rep or not self.training:
z = self.sample_z(sample=self.training)
output = F.linear(input, self.weight * z[:, :-1], self.bias * z[:, -1])
else:
weight, bias = self.sample_weight_bias()
output = F.linear(input, weight, bias)
return output
def extra_repr(self) -> str:
return "in_features={}, out_features={}, bias={}".format(
self.in_features, self.out_features, self.bias is not None
)