-
Notifications
You must be signed in to change notification settings - Fork 18
/
prune_funcs.py
358 lines (286 loc) · 12.6 KB
/
prune_funcs.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
import numpy as np
import torch
import torch.nn as nn
from segment_anything_kd.modeling.image_encoder import Attention
from segment_anything_kd.modeling.common import LayerNorm2d
import torch_pruning as tp
seed = 0
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def calculate_iou(mask1, mask2):
"""
Calculate Intersection over Union (IoU) for two binary masks.
Parameters:
mask1 (numpy.ndarray): The first binary mask.
mask2 (numpy.ndarray): The second binary mask.
Returns:
float: The IoU score.
"""
# Make sure the input masks have the same shape
assert mask1.shape == mask2.shape, "Both masks must have the same shape."
# Calculate the intersection and union of the masks
intersection = np.logical_and(mask1, mask2)
union = np.logical_or(mask1, mask2)
# Compute the IoU score
iou_score = np.sum(intersection) / np.sum(union)
return iou_score
def get_pos_init(model):
depth = model.image_encoder.depth
for i in range(depth):
head_dim = model.image_encoder.blocks[i].attn.q.out_features // model.image_encoder.blocks[i].attn.num_heads
input_size = model.image_encoder.blocks[i].attn.input_size
model.image_encoder.blocks[i].attn.scale = head_dim**-0.5
model.image_encoder.blocks[i].attn.use_rel_pos = True
model.image_encoder.blocks[i].attn.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
model.image_encoder.blocks[i].attn.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
return model
def del_pos_init(model):
depth = model.image_encoder.depth
for i in range(depth):
model.image_encoder.blocks[i].attn.use_rel_pos = False
del(model.image_encoder.blocks[i].attn.rel_pos_h)
del(model.image_encoder.blocks[i].attn.rel_pos_w)
return model
def prune_sam_step1(model, example_inputs, model_name, round_to, ratio,imptype,norm_type,global_way):
ignored_layers = []
#########################################
# Ignore unprunable modules
#########################################
for m in model.modules():
if isinstance(m, torch.nn.Conv2d) and m.out_channels == 256:
ignored_layers.append(m)
if isinstance(m, LayerNorm2d):
ignored_layers.append(m)
for n in range(12):
ignored_layers.append(model.blocks[n].attn.q)
ignored_layers.append(model.blocks[n].attn.k)
ignored_layers.append(model.blocks[n].attn.v)
ignored_layers.append(model.blocks[n].mlp.lin1)
# print(ignored_layers)
# For ViT: Rounding the number of channels to the nearest multiple of num_heads
round_to = round_to
#########################################
# (Optional) Register unwrapped nn.Parameters
# TP will automatically detect unwrapped parameters and prune the last dim for you by default.
# If you want to prune other dims, you can register them here.
#########################################
unwrapped_parameters = None
#########################################
# Build network pruners
#########################################
if imptype == "Disturb":
importance = tp.importance.DisturbImportance(normalizer=norm_type ,group_reduction="mean")
elif imptype == "mag":
importance = tp.importance.MagnitudeImportance(p=2, normalizer=norm_type, group_reduction="mean")
elif imptype == "taylor":
importance = tp.importance.TaylorImportance(normalizer=norm_type, group_reduction="mean")
elif imptype == "random":
importance = tp.importance.RandomImportance()
channel_groups = {}
# All heads should be pruned simultaneously, so we group channels by head.
for m in model.modules():
if isinstance(m, Attention):
channel_groups[m.q] = m.num_heads
channel_groups[m.k] = m.num_heads
channel_groups[m.v] = m.num_heads
iterative_steps = 1
pruner = tp.pruner.MagnitudePruner(
model,
example_inputs=example_inputs,
importance=importance,
iterative_steps=iterative_steps,
ch_sparsity=ratio,
round_to=round_to,
unwrapped_parameters=unwrapped_parameters,
ignored_layers=ignored_layers,
global_pruning=global_way,
channel_groups=channel_groups,
)
#########################################
# Pruning
#########################################
for i in range(iterative_steps):
ori_macs, ori_size = tp.utils.count_ops_and_params(model, example_inputs)
pruner.step()
#########################################
# Testing
#########################################
with torch.no_grad():
if isinstance(example_inputs, dict):
out = model(**example_inputs)
else:
out = model(example_inputs)
print("{} Pruning: ".format(model_name))
macs_after_prune, params_after_prune = tp.utils.count_ops_and_params(model, example_inputs)
print(" Params: %s => %s" % (ori_size, params_after_prune))
print(" Macs: %s => %s" % (ori_macs, macs_after_prune))
if isinstance(out, (dict,list,tuple)):
print(" Output:")
for o in tp.utils.flatten_as_list(out):
print(o.shape)
else:
print(" Output:", out.shape)
print("------------------------------------------------------\n")
return model
def prune_sam_step2_local(model, example_inputs, model_name, round_to, ratio,imptype,norm_type,global_way):
ignored_layers = []
#########################################
# Ignore unprunable modules
#########################################
for m in model.modules():
if isinstance(m, torch.nn.Conv2d):
ignored_layers.append(m)
if isinstance(m, LayerNorm2d):
ignored_layers.append(m)
# print(ignored_layers)
# For ViT: Rounding the number of channels to the nearest multiple of num_heads
round_to = round_to
#########################################
# (Optional) Register unwrapped nn.Parameters
# TP will automatically detect unwrapped parameters and prune the last dim for you by default.
# If you want to prune other dims, you can register them here.
#########################################
unwrapped_parameters = None
#########################################
# Build network pruners
#########################################
if imptype == "Disturb":
importance = tp.importance.DisturbImportance(normalizer=norm_type ,group_reduction="mean")
elif imptype == "mag":
importance = tp.importance.MagnitudeImportance(p=2, normalizer=norm_type, group_reduction="mean")
elif imptype == "taylor":
importance = tp.importance.TaylorImportance(normalizer=norm_type, group_reduction="mean")
elif imptype == "random":
importance = tp.importance.RandomImportance()
channel_groups = {}
# All heads should be pruned simultaneously, so we group channels by head.
for m in model.modules():
if isinstance(m, Attention):
channel_groups[m.q] = m.num_heads
channel_groups[m.k] = m.num_heads
channel_groups[m.v] = m.num_heads
iterative_steps = 1
pruner = tp.pruner.MagnitudePruner(
model,
example_inputs=example_inputs,
importance=importance,
iterative_steps=iterative_steps,
ch_sparsity=ratio,
round_to=round_to,
unwrapped_parameters=unwrapped_parameters,
ignored_layers=ignored_layers,
global_pruning=global_way,
channel_groups=channel_groups,
)
#########################################
# Pruning
#########################################
for i in range(iterative_steps):
ori_macs, ori_size = tp.utils.count_ops_and_params(model, example_inputs)
pruner.step()
#########################################
# Testing
#########################################
with torch.no_grad():
if isinstance(example_inputs, dict):
out = model(**example_inputs)
else:
out = model(example_inputs)
print("{} Pruning: ".format(model_name))
macs_after_prune, params_after_prune = tp.utils.count_ops_and_params(model, example_inputs)
print(" Params: %s => %s" % (ori_size, params_after_prune))
print(" Macs: %s => %s" % (ori_macs, macs_after_prune))
if isinstance(out, (dict,list,tuple)):
print(" Output:")
for o in tp.utils.flatten_as_list(out):
print(o.shape)
else:
print(" Output:", out.shape)
print("------------------------------------------------------\n")
return model
def prune_sam_step2_global(model, example_inputs, model_name, round_to, ratio,imptype,norm_type,global_way,gs):
ignored_layers = []
#########################################
# Ignore unprunable modules
#########################################
for m in model.modules():
if isinstance(m, torch.nn.Conv2d):
ignored_layers.append(m)
if isinstance(m, LayerNorm2d):
ignored_layers.append(m)
if gs == 1:
for n in range(12):
ignored_layers.append(model.blocks[n].mlp.lin1)
if gs == 2:
for n in range(12):
ignored_layers.append(model.blocks[n].attn.q)
ignored_layers.append(model.blocks[n].attn.k)
ignored_layers.append(model.blocks[n].attn.v)
# print(ignored_layers)
# For ViT: Rounding the number of channels to the nearest multiple of num_heads
round_to = round_to
#########################################
# (Optional) Register unwrapped nn.Parameters
# TP will automatically detect unwrapped parameters and prune the last dim for you by default.
# If you want to prune other dims, you can register them here.
#########################################
unwrapped_parameters = None
#########################################
# Build network pruners
#########################################
if imptype == "Disturb":
importance = tp.importance.DisturbImportance(normalizer=norm_type ,group_reduction="mean")
elif imptype == "mag":
importance = tp.importance.MagnitudeImportance(p=2, normalizer=norm_type, group_reduction="mean")
elif imptype == "taylor":
importance = tp.importance.TaylorImportance(normalizer=norm_type, group_reduction="mean")
elif imptype == "random":
importance = tp.importance.RandomImportance()
channel_groups = {}
# All heads should be pruned simultaneously, so we group channels by head.
for m in model.modules():
if isinstance(m, Attention):
channel_groups[m.q] = m.num_heads
channel_groups[m.k] = m.num_heads
channel_groups[m.v] = m.num_heads
iterative_steps = 1
pruner = tp.pruner.MagnitudePruner(
model,
example_inputs=example_inputs,
importance=importance,
iterative_steps=iterative_steps,
ch_sparsity=ratio,
round_to=round_to,
unwrapped_parameters=unwrapped_parameters,
ignored_layers=ignored_layers,
global_pruning=global_way,
channel_groups=channel_groups,
)
#########################################
# Pruning
#########################################
for i in range(iterative_steps):
ori_macs, ori_size = tp.utils.count_ops_and_params(model, example_inputs)
pruner.step()
#########################################
# Testing
#########################################
with torch.no_grad():
if isinstance(example_inputs, dict):
out = model(**example_inputs)
else:
out = model(example_inputs)
print("{} Pruning: ".format(model_name))
macs_after_prune, params_after_prune = tp.utils.count_ops_and_params(model, example_inputs)
print(" Params: %s => %s" % (ori_size, params_after_prune))
print(" Macs: %s => %s" % (ori_macs, macs_after_prune))
if isinstance(out, (dict,list,tuple)):
print(" Output:")
for o in tp.utils.flatten_as_list(out):
print(o.shape)
else:
print(" Output:", out.shape)
print("------------------------------------------------------\n")
return model