-
Notifications
You must be signed in to change notification settings - Fork 2
/
sparse_utils.py
178 lines (140 loc) · 5 KB
/
sparse_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
'''
created on Dec 28, 2019
@author: georgeretsi
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class SparseSTE(torch.autograd.Function):
@staticmethod
def forward(ctx, w):
w = F.hardshrink(w, 1)
return w
@staticmethod
def backward(ctx, g):
return g
class SparseConv(nn.Module):
def __init__(self, conv, r=.5, trainable=False):
super(SparseConv, self).__init__()
self.conv = conv
self.trainable = trainable
self.r = nn.Parameter(torch.Tensor([r]))
def forward(self, x):
w = self.conv.weight
b = self.conv.bias
stride = self.conv.stride
padding = self.conv.padding
groups = self.conv.groups
# impose zero mean
self.conv.weight.data = self.conv.weight.data - self.conv.weight.data.mean()
m = 0.0 # w.mean().detach()
rr = torch.clamp(self.r, 0, 5)
if self.trainable:
a = rr
else:
a = rr.detach()
l = a * (w-m).std().detach()
nw = (w - m) / (l + 1e-6)
sw = SparseSTE.apply(nw)
w = m + (l + 1e-6) * sw
out = F.conv2d(x, w, bias=b, padding=padding, stride=stride, groups=groups)
return out
class SparseFc(nn.Module):
def __init__(self, fc, r=.5, trainable=False):
super(SparseFc, self).__init__()
self.fc = fc
self.trainable = trainable
self.r = nn.Parameter(torch.Tensor([r]))
def forward(self, x):
w = self.fc.weight
b = self.fc.bias
# impose zero mean
self.fc.weight.data = self.fc.weight.data - self.fc.weight.data.mean()
m = 0.0 # w.mean().detach()
rr = torch.clamp(self.r, 0, 5)
if self.trainable:
a = rr
else:
a = rr.detach()
l = a * (w - m).std().detach()
nw = (w - m) / (l + 1e-6)
sw = SparseSTE.apply(nw)
w = m + (l + 1e-6) * sw
out = F.linear(x, w, bias=b)
return out
def iter_sparsify(m, r, trainable=True, pthres=1000):
for name, child in m.named_children():
iter_sparsify(child, r, trainable, pthres)
if type(child) == nn.Conv2d:
if (child.in_channels * child.out_channels * child.kernel_size[0] * child.kernel_size[1]) >= pthres:
slayer = SparseConv(child, r, trainable)
m.__setattr__(name, slayer)
if type(child) == nn.Linear:
if (child.in_features * child.out_features) >= pthres:
slayer = SparseFc(child, r, trainable)
m.__setattr__(name, slayer)
def iter_desparsify(m):
for name, child in m.named_children():
#print(name)
iter_desparsify(child)
if type(child) == SparseConv:
conv = child.conv
w = conv.weight.data
mean = 0.0 #w.mean()
s = (w-mean).std()
r = (s * torch.clamp(child.r, 0, 5)).item()
w = F.hardshrink(w-mean, r + 1e-6)
conv.weight.data = w
m.__setattr__(name, conv)
if type(child) == SparseFc:
fc= child.fc
w = fc.weight.data
mean = 0.0 # w.mean()
s = (w - mean).std()
r = (s * torch.clamp(child.r, 0, 5)).item()
w = F.hardshrink(w - mean, r + 1e-6)
fc.weight.data = w
m.__setattr__(name, fc)
def sparsity(model, print_per_layer=False):
zeros_cnt = 0
cnt = 0
for name, layer in model.named_modules():
if ('Sparse' in layer.__class__.__name__):
if 'Conv' in layer.__class__.__name__ :
w = layer.conv.weight
elif 'Fc' in layer.__class__.__name__:
w = layer.fc.weight
else:
print(" Not Recognized Sparse Module ")
m = 0.0 #w.mean()
a = torch.clamp(layer.r, 0, 5)
l = a * (w-m).std()
nw = F.hardshrink((w - m) / (l+1e-6), 1)
tsparsity = (nw == 0).float().sum().item()
tnum = nw.numel()
zeros_cnt += tsparsity
cnt += tnum
if print_per_layer:
print("{} sparsity: {}%".format(name, round(100.0 * tsparsity / tnum, 2)))
return 100 * float(zeros_cnt) / float(cnt), zeros_cnt
def change_sparsity(model, r):
for name, layer in model.named_modules():
if ('Sparse' in layer.__class__.__name__):
layer.r = r
def adaptive_loss(model, reduce=True):
eloss = []
nweights = []
for name, layer in model.named_modules():
if ('Sparse' in layer.__class__.__name__):
if 'Conv' in layer.__class__.__name__ :
nw = layer.conv.weight.numel()
if 'Fc' in layer.__class__.__name__:
nw = layer.fc.weight.numel()
eloss += [1 - torch.erf(layer.r / math.sqrt(2))]
nweights += [nw]
if reduce:
eloss = sum([e * n for e, n in zip(eloss, nweights)]) / sum(nweights)
else:
eloss = torch.cat(eloss)
return eloss