forked from Freder-chen/RepVGG-Pruning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_pruning.py
executable file
·243 lines (188 loc) · 8.07 KB
/
train_pruning.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
import os
import time
import argparse
import thop
import torch
from torch import nn
import torchvision
import torchvision.transforms as transforms
import models
from models.repvgg_pruning import RepVGG
from utils import AverageMeter, ProgressMeter, accuracy, adjust_learning_rate
def parse_args():
parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')
parser.add_argument('--epochs', default=200, type=int, help='total epochs')
parser.add_argument('--bs', default=128, type=int, help='batch size')
parser.add_argument('--lr', default=0.1, type=float, help='learning rate')
parser.add_argument('--min_lr', default=1e-6, type=float, help='min lr')
parser.add_argument('--warmup_epochs', default=5, type=float, help='warmup epochs')
parser.add_argument('--weight_decay', default=5e-4, type=float, help='weight decay')
# prune args
parser.add_argument('--sr', default=0, type=float, help='sr')
parser.add_argument('--threshold', default=0, type=float, help='thresh')
parser.add_argument('--finetune', type=str)
parser.add_argument('--eval', type=str)
return parser.parse_args()
def sgd_optimizer(model, lr, momentum, weight_decay, use_custwd):
params = []
for key, value in model.named_parameters():
if not value.requires_grad:
continue
apply_weight_decay = weight_decay
apply_lr = lr
is_custwd = use_custwd and ('rbr_dense' in key or 'rbr_1x1' in key)
is_mask = 'mask' in key
if is_custwd or is_mask or 'bias' in key or 'bn' in key:
apply_weight_decay = 0
print('set weight decay=0 for {}'.format(key))
if 'bias' in key:
apply_lr = 2 * lr # Just a Caffe-style common practice. Made no difference.
params += [{'params': [value], 'lr': apply_lr, 'weight_decay': apply_weight_decay}]
optimizer = torch.optim.SGD(params, lr, momentum=momentum)
return optimizer
def train(epoch, model, criterion, optimizer, trainloader, args):
device = 'cuda' if torch.cuda.is_available() else 'cpu'
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
losses = AverageMeter('Loss', ':6.3f')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
progress = ProgressMeter(
len(trainloader),
[batch_time, data_time, losses, top1, top5, ],
prefix="Epoch: [{}]".format(epoch)
)
# switch to train mode
model.train()
end = time.time()
for batch_idx, (inputs, targets) in enumerate(trainloader):
# measure data loading time
data_time.update(time.time() - end)
adjust_learning_rate(optimizer, batch_idx / len(trainloader) + epoch, args)
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
loss = criterion(outputs, targets)
if isinstance(model, RepVGG):
for module in model.modules():
if hasattr(module, 'get_custom_L2') and not module.deploy:
loss += args.weight_decay * 0.5 * module.get_custom_L2()
optimizer.zero_grad()
loss.backward()
if args.sr * args.threshold > 0 and not args.finetune:
model.update_mask(args.sr, args.threshold)
optimizer.step()
# measure accuracy and record loss
acc1, acc5 = accuracy(outputs, targets, topk=(1, 5))
losses.update(loss.item(), inputs.size(0))
top1.update(acc1[0], inputs.size(0))
top5.update(acc5[0], inputs.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if batch_idx % 100 == 0:
progress.display(batch_idx)
@torch.no_grad()
def test(epoch, model, criterion, testloader, args):
device = 'cuda' if torch.cuda.is_available() else 'cpu'
batch_time = AverageMeter('Time', ':6.3f')
losses = AverageMeter('Loss', ':6.3f')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
progress = ProgressMeter(
len(testloader),
[batch_time, losses, top1, top5],
prefix='Test: '
)
# switch to evaluate mode
model.eval()
end = time.time()
for batch_idx, (inputs, targets) in enumerate(testloader):
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
loss = criterion(outputs, targets)
# measure accuracy and record loss
acc1, acc5 = accuracy(outputs, targets, topk=(1, 5))
losses.update(loss.item(), inputs.size(0))
top1.update(acc1[0], inputs.size(0))
top5.update(acc5[0], inputs.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if batch_idx % 50 == 0:
progress.display(batch_idx)
# TODO: this should also be done with the ProgressMeter
print(' * Epoch {epoch}: Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}'.format(
epoch=epoch, top1=top1, top5=top5
))
return top1.avg
def main():
args = parse_args()
dataset_path = 'dataset'
best_acc = 0 # best test accuracy
start_epoch = 0 # start from epoch 0 or last checkpoint epoch
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Data
print('==> Preparing data..')
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
trainset = torchvision.datasets.CIFAR10(
root=dataset_path, train=True, download=True, transform=transform_train
)
trainloader = torch.utils.data.DataLoader(
trainset, batch_size=args.bs, shuffle=True, num_workers=2
)
testset = torchvision.datasets.CIFAR10(
root=dataset_path, train=False, download=True, transform=transform_test
)
testloader = torch.utils.data.DataLoader(
testset, batch_size=100, shuffle=False, num_workers=2
)
# Model
print('==> Building model..')
# model = models.repvgg_a1(10, pretrained=True).to(device)
model = models.rmnet_pruning_18(10).to(device)
if args.sr * args.threshold == 0:
model.fix_mask()
print('=> fixed mask, use origin training setting.')
if args.finetune or args.eval:
checkpoint_model = torch.load(args.finetune) if args.finetune else torch.load(args.eval)
# load pre-trained model
msg = model.load_state_dict(checkpoint_model, strict=True)
print(msg)
# prune model
model = model.cpu().prune().cuda()
print(model)
# Criterion and Optimizer
criterion = nn.CrossEntropyLoss()
optimizer = sgd_optimizer(model, args.lr, 0.9, args.weight_decay, isinstance(model, RepVGG))
# Train or eval model
if args.eval:
test(0, model, criterion, testloader, args)
flops, params = thop.profile(model, (torch.randn(1,3,224,224).to(device),))
print('flops:%.2fM, params:%.2fM' % (flops / 1e6, params / 1e6))
else:
for epoch in range(start_epoch, start_epoch + args.epochs):
train(epoch, model, criterion, optimizer, trainloader, args)
acc = test(epoch, model, criterion, testloader, args)
# Save checkpoint.
if acc > best_acc:
print('Saving..')
if args.finetune:
save_dir = args.finetune.replace('ckpt', 'finetune_lr%f' % args.lr)
else:
save_dir = './lr_%f_sr_%f_thres_%f'%( args.lr, args.sr, args.threshold)
if not os.path.isdir(save_dir):
os.mkdir(save_dir)
save_dir += '/ckpt.pth'
torch.save(model.state_dict(), save_dir)
best_acc = acc
if __name__ == '__main__':
main()