-
Notifications
You must be signed in to change notification settings - Fork 9
/
vitprune.py
176 lines (153 loc) · 5.17 KB
/
vitprune.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
import torch
from torch import nn
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import numpy as np
import torchvision
import torchvision.transforms as transforms
import os
import argparse
from models.vit import ViT, channel_selection
from models.vit_slim import ViT_slim
device = 'cuda' if torch.cuda.is_available() else 'cpu'
cudnn.benchmark = True
model = ViT(
image_size = 32,
patch_size = 4,
num_classes = 10,
dim = 512, # 512
depth = 6,
heads = 8,
mlp_dim = 512,
dropout = 0.1,
emb_dropout = 0.1
)
model = model.to(device)
model_path = "checkpoint/pruning-adamw-vit-4-79.84.t7"
print("=> loading checkpoint '{}'".format(model_path))
checkpoint = torch.load(model_path)
start_epoch = checkpoint['epoch']
best_prec1 = checkpoint['acc']
model.load_state_dict(checkpoint['net'])
print("=> loaded checkpoint '{}' (epoch {}) Prec1: {:f}".format(model_path, checkpoint['epoch'], best_prec1))
total = 0
for m in model.modules():
if isinstance(m, channel_selection):
total += m.indexes.data.shape[0]
bn = torch.zeros(total)
index = 0
for m in model.modules():
if isinstance(m, channel_selection):
size = m.indexes.data.shape[0]
bn[index:(index+size)] = m.indexes.data.abs().clone()
index += size
percent = 0.3
y, i = torch.sort(bn)
thre_index = int(total * percent)
thre = y[thre_index]
# print(thre)
pruned = 0
cfg = []
cfg_mask = []
for k, m in enumerate(model.modules()):
if isinstance(m, channel_selection):
# print(k)
# print(m)
if k in [16,40,64,88,112,136]:
weight_copy = m.indexes.data.abs().clone()
mask = weight_copy.gt(thre).float().cuda()
thre_ = thre.clone()
while (torch.sum(mask)%8 !=0): # heads
thre_ = thre_ - 0.0001
mask = weight_copy.gt(thre_).float().cuda()
else:
weight_copy = m.indexes.data.abs().clone()
mask = weight_copy.gt(thre).float().cuda()
pruned = pruned + mask.shape[0] - torch.sum(mask)
m.indexes.data.mul_(mask)
cfg.append(int(torch.sum(mask)))
cfg_mask.append(mask.clone())
print('layer index: {:d} \t total channel: {:d} \t remaining channel: {:d}'.
format(k, mask.shape[0], int(torch.sum(mask))))
pruned_ratio = pruned/total
print('Pre-processing Successful!')
print(cfg)
def test(model):
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
testset = torchvision.datasets.CIFAR10(root='/home/lxc/ABCPruner/data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=8)
model.eval()
test_loss = 0
correct = 0
total = 0
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(testloader):
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
print('Acc: %.3f%% (%d/%d)' % (100.*correct/total, correct, total))
test(model)
cfg_prune = []
for i in range(len(cfg)):
if i%2!=0:
cfg_prune.append([cfg[i-1],cfg[i]])
newmodel = ViT_slim(image_size = 32,
patch_size = 4,
num_classes = 10,
dim = 512,
depth = 6,
heads = 8,
mlp_dim = 512,
dropout = 0.1,
emb_dropout = 0.1,
cfg=cfg_prune)
newmodel.to(device)
# num_parameters = sum([param.nelement() for param in newmodel.parameters()])
newmodel_dict = newmodel.state_dict().copy()
i = 0
newdict = {}
for k,v in model.state_dict().items():
if 'net1.0.weight' in k:
# print(k)
# print(v.size())
# print('----------')
idx = np.squeeze(np.argwhere(np.asarray(cfg_mask[i].cpu().numpy())))
newdict[k] = v[idx.tolist()].clone()
elif 'net1.0.bias' in k:
# print(k)
# print(v.size())
# print('----------')
idx = np.squeeze(np.argwhere(np.asarray(cfg_mask[i].cpu().numpy())))
newdict[k] = v[idx.tolist()].clone()
elif 'to_q' in k or 'to_k' in k or 'to_v' in k:
# print(k)
# print(v.size())
# print('----------')
idx = np.squeeze(np.argwhere(np.asarray(cfg_mask[i].cpu().numpy())))
newdict[k] = v[idx.tolist()].clone()
elif 'net2.0.weight' in k:
# print(k)
# print(v.size())
# print('----------')
idx = np.squeeze(np.argwhere(np.asarray(cfg_mask[i].cpu().numpy())))
newdict[k] = v[:,idx.tolist()].clone()
i = i + 1
elif 'to_out.0.weight' in k:
# print(k)
# print(v.size())
# print('----------')
idx = np.squeeze(np.argwhere(np.asarray(cfg_mask[i].cpu().numpy())))
newdict[k] = v[:,idx.tolist()].clone()
i = i + 1
elif k in newmodel.state_dict():
newdict[k] = v
newmodel_dict.update(newdict)
newmodel.load_state_dict(newmodel_dict)
torch.save(newmodel.state_dict(), 'pruned.pth')
print('after pruning: ', end=' ')
test(newmodel)