forked from IST-DASLab/sparsegpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsparse_op.py
349 lines (276 loc) · 12.2 KB
/
sparse_op.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
import torch
from torch import autograd, nn
import torch.nn.functional as F
from itertools import repeat
import collections.abc as container_abcs
class Sparse(autograd.Function):
"""" Prune the unimprotant weight for the forwards phase but pass the gradient to dense weight using SR-STE in the backwards phase"""
@staticmethod
def forward(ctx, weight, N, M, decay = 0.0002):
ctx.save_for_backward(weight)
output = weight.clone()
length = weight.numel()
group = int(length/M)
weight_temp = weight.detach().abs().reshape(group, M)
index = torch.argsort(weight_temp, dim=1)[:, :int(M-N)]
w_b = torch.ones(weight_temp.shape, device=weight_temp.device)
w_b = w_b.scatter_(dim=1, index=index, value=0).reshape(weight.shape)
ctx.mask = w_b
ctx.decay = decay
return output*w_b
@staticmethod
def backward(ctx, grad_output):
weight, = ctx.saved_tensors
return grad_output + ctx.decay * (1-ctx.mask) * weight, None, None
class Sparse_NHWC(autograd.Function):
"""" Prune the unimprotant edges for the forwards phase but pass the gradient to dense weight using SR-STE in the backwards phase"""
@staticmethod
def forward(ctx, weight, N, M, decay = 0.0002):
ctx.save_for_backward(weight)
output = weight.clone()
length = weight.numel()
group = int(length/M)
weight_temp = weight.detach().abs().permute(0,2,3,1).reshape(group, M)
index = torch.argsort(weight_temp, dim=1)[:, :int(M-N)]
w_b = torch.ones(weight_temp.shape, device=weight_temp.device)
w_b = w_b.scatter_(dim=1, index=index, value=0).reshape(weight.permute(0,2,3,1).shape)
w_b = w_b.permute(0,3,1,2)
ctx.mask = w_b
ctx.decay = decay
return output*w_b
@staticmethod
def backward(ctx, grad_output):
weight, = ctx.saved_tensors
return grad_output + ctx.decay * (1-ctx.mask) * weight, None, None
class SparseConv(nn.Conv2d):
"""" implement N:M sparse convolution layer """
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', N=2, M=4, **kwargs):
self.N = N
self.M = M
super(SparseConv, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode, **kwargs)
def get_sparse_weights(self):
return Sparse_NHWC.apply(self.weight, self.N, self.M)
def forward(self, x):
w = self.get_sparse_weights()
x = F.conv2d(
x, w, self.bias, self.stride, self.padding, self.dilation, self.groups
)
return x
class SparseLinear(nn.Linear):
def __init__(self, in_features: int, out_features: int, bias: bool = True, N=2, M=2, decay = 0.0002, **kwargs):
self.N = N
self.M = M
super(SparseLinear, self).__init__(in_features, out_features, bias = True)
def get_sparse_weights(self):
return Sparse.apply(self.weight, self.N, self.M)
def forward(self, x):
w = self.get_sparse_weights()
x = F.linear(x, w, self.bias)
return x
import numpy as np
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import math
class VRPGELinear(nn.Linear):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.scores = nn.Parameter(torch.Tensor(self.weight.size()[0], 1))
self.register_buffer('subnet', torch.zeros_like(self.scores))
self.train_weights = False
nn.init.kaiming_uniform_(self.scores, a=math.sqrt(5))
self.prune = True
self.subnet = torch.ones_like(self.scores)
self.register_buffer("stored_mask_0", torch.zeros_like(self.scores))
self.register_buffer("stored_mask_1", torch.zeros_like(self.scores))
@property
def clamped_scores(self):
return self.scores
def fix_subnet(self):
self.subnet = (torch.rand_like(self.scores) < self.clamped_scores).float()
def forward(self, x):
if self.prune:
if not self.train_weights:
self.subnet = StraightThroughBinomialSampleNoGrad.apply(self.scores)
self.stored_mask_0.data = (self.subnet-self.scores)/torch.sqrt((self.scores+1e-20)*(1-self.scores+1e-20))
w = self.weight * self.subnet.view(-1, 1)
x = F.linear(x, w, self.bias)
else:
w = self.weight * self.subnet.view(-1, 1)
x = F.linear(x, w, self.bias)
else:
x = F.linear(x, self.weight, self.bias)
return x
class VRPGE(nn.Conv2d):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.scores = nn.Parameter(torch.Tensor(self.weight.size()[0], 1, 1, 1))
self.register_buffer('subnet', torch.zeros_like(self.scores))
self.train_weights = False
score_init_constant = 0.5
# self.scores.data = (
# torch.ones_like(self.scores) * score_init_constant
# )
nn.init.kaiming_uniform_(self.scores, a=math.sqrt(5))
if self.out_channels == 10 or self.out_channels == 100:
self.prune = False
self.subnet = torch.ones_like(self.scores)
else:
self.prune = True
self.register_buffer("stored_mask_0", torch.zeros_like(self.scores))
self.register_buffer("stored_mask_1", torch.zeros_like(self.scores))
self.j = 0
@property
def clamped_scores(self):
return self.scores
def fix_subnet(self):
self.subnet = (torch.rand_like(self.scores) < self.clamped_scores).float()
def forward(self, x):
if self.prune:
if not self.train_weights:
self.subnet = StraightThroughBinomialSampleNoGrad.apply(self.scores)
if self.j == 0:
self.stored_mask_0.data = (self.subnet-self.scores)/torch.sqrt((self.scores+1e-20)*(1-self.scores+1e-20))
else:
self.stored_mask_1.data = (self.subnet-self.scores)/torch.sqrt((self.scores+1e-20)*(1-self.scores+1e-20))
w = self.weight * self.subnet
x = F.conv2d(x, w, self.bias, self.stride, self.padding, self.dilation, self.groups)
else:
w = self.weight * self.subnet
x = F.conv2d(x, w, self.bias, self.stride, self.padding, self.dilation, self.groups)
else:
x = F.conv2d(x, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups)
return x
class StraightThroughBinomialSampleNoGrad(autograd.Function):
@staticmethod
def forward(ctx, scores):
output = (torch.rand_like(scores) < scores).float()
return output
@staticmethod
def backward(ctx, grad_outputs):
return torch.zeros_like(grad_outputs)
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class ProbMaskLinear(nn.Linear):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# self.scores = nn.Parameter(torch.Tensor(self.weight.size())) # Probability
self.scores = nn.Parameter(torch.ones_like(self.weight)) # Probability
self.subnet = None # Mask
self.train_weights = False
# nn.init.kaiming_uniform_(self.scores, a=math.sqrt(5))
score_init_constant = 0.5
self.scores.data = (
torch.ones_like(self.scores) * score_init_constant
)
self.args = args
@property
def clamped_scores(self):
return self.scores
def fix_subnet(self):
self.subnet = (torch.rand_like(self.scores) < self.clamped_scores).float()
def forward(self, x):
if not self.train_weights: # training
eps = 1e-20
temp = self.args.T
uniform0 = torch.rand_like(self.scores)
uniform1 = torch.rand_like(self.scores)
noise = -torch.log(torch.log(uniform0 + eps) / torch.log(uniform1 + eps) + eps)
self.subnet = torch.sigmoid((torch.log(self.clamped_scores + eps) - torch.log(1.0 - self.clamped_scores + eps) + noise) * temp)
w = self.weight * self.subnet
# print(f'self.weight:{self.weight}')
# print(f'self.scores:{self.scores}')
# print(f'self.subnet:{self.subnet}')
x = F.linear(x, w, self.bias)
else: # testing
w = self.weight * self.subnet
x = F.linear(x, w, self.bias)
return x
import numpy as np
class VRPGE_Linear(nn.Linear):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.scores = nn.Parameter(torch.rand_like(self.weight[0]))
self.register_buffer('subnet', torch.zeros_like(self.scores))
self.train_weights = False
# nn.init.kaiming_uniform_(self.scores, a=math.sqrt(5))
score_init_constant = 0.5
self.scores.data = (
torch.ones_like(self.scores) * score_init_constant
)
self.prune = True
self.register_buffer("stored_mask_0", torch.zeros_like(self.scores))
self.register_buffer("stored_mask_1", torch.zeros_like(self.scores))
@property
def clamped_scores(self):
return self.scores
def fix_subnet(self):
self.subnet = (torch.rand_like(self.scores) < self.clamped_scores).float()
def forward(self, x):
# print(f'self.j: {self.j}')
if self.prune:
if not self.train_weights:
self.subnet = StraightThroughBinomialSampleNoGrad.apply(self.scores)
if self.args.j == 0:
self.stored_mask_0.data = (self.subnet-self.scores)/torch.sqrt((self.scores+1e-20)*(1-self.scores+1e-20))
else:
self.stored_mask_1.data = (self.subnet-self.scores)/torch.sqrt((self.scores+1e-20)*(1-self.scores+1e-20))
w = self.weight * self.subnet
x = F.linear(x, w, self.bias)
else:
w = self.weight * self.subnet
x = F.linear(x, w, self.bias)
else:
x = F.linear(x, self.weight, self.bias)
return x
class StraightThroughBinomialSampleNoGrad(autograd.Function):
@staticmethod
def forward(ctx, scores):
output = (torch.rand_like(scores) < scores).float()
return output
@staticmethod
def backward(ctx, grad_outputs):
return torch.zeros_like(grad_outputs)
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
DenseConv = nn.Conv2d
class ProbMaskConv(nn.Conv2d):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.scores = nn.Parameter(torch.Tensor(self.weight.size())) #Probability
self.subnet = None #Mask
self.train_weights = False
score_init_constant = 0.5
self.scores.data = (
torch.ones_like(self.scores) * score_init_constant
)
# nn.init.kaiming_uniform_(self.scores, a=math.sqrt(5))
self.discrete = False
self.T = 0
@property
def clamped_scores(self):
return self.scores
def fix_subnet(self):
self.subnet = (torch.rand_like(self.scores) < self.clamped_scores).float()
def forward(self, x):
if not self.train_weights: #training
if self.discrete:
eps = 1e-20
temp = self.T
uniform0 = torch.rand_like(self.scores)
uniform1 = torch.rand_like(self.scores)
noise = -torch.log(torch.log(uniform0 + eps) / torch.log(uniform1 + eps) + eps)
self.subnet = torch.sigmoid((torch.log(self.clamped_scores + eps) - torch.log(1.0 - self.clamped_scores + eps) + noise) * temp)
else:
self.subnet = (torch.rand_like(self.scores) < self.clamped_scores).float()
w = self.weight * self.subnet
x = F.conv2d(x, w, self.bias, self.stride, self.padding, self.dilation, self.groups)
else: #testing
w = self.weight * self.subnet
x = F.conv2d(x, w, self.bias, self.stride, self.padding, self.dilation, self.groups)
return x