-
Notifications
You must be signed in to change notification settings - Fork 1
/
train.py
365 lines (305 loc) · 12.8 KB
/
train.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
357
358
359
360
361
362
363
364
365
import time
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
import torch.utils.data
import torchvision.transforms as transforms
from torchvision.datasets import CIFAR10, CIFAR100, ImageNet, ImageFolder
from utils import AverageMeter, ProgressMeter, accuracy, save_ckpt, load_ckpt
import utils
import numpy as np
from rexnet import Model
import argparse
import os
parser = argparse.ArgumentParser(description='ReXNet')
parser.add_argument('--dataset', default='cifar10',
help='dataset: ')
parser.add_argument('--datapath', default='../data', type=str,
help='where you want to load/save your dataset? (default: ../data)')
parser.add_argument('--savepath', default='./checkpoint/', type=str,
help='where you want to load/save checkpoint?')
parser.add_argument('--num_workers', default=8, type=int,
help='number of data loading workers (default: 8)')
parser.add_argument('--epochs', default=200, type=int,
help='number of total epochs to run (default: 200)')
parser.add_argument('--batch_size', default=128, type=int,
help='mini-batch size (default: 128)')
parser.add_argument('--learning_rate', default=0.1, type=float,
help='initial learning rate (default: 0.1)')
parser.add_argument('--momentum', default=0.9, type=float,
help='momentum (default: 0.9)')
parser.add_argument('--weight_decay', default=5e-4, type=float,
help='weight decay (default: 5e-4)')
parser.add_argument('--nesterov', default=True, type=bool,
help='use nesterov momentum?')
parser.add_argument('--scheduler', default='multistep', type=str, help='scheduler: ')
parser.add_argument('--step_size', default=30,
type=int, metavar='STEP',
help='period of learning rate decay / '
'maximum number of iterations for '
'cosine annealing scheduler (default: 30)')
parser.add_argument('--milestones', default=[100,150], type=int, nargs='+',
help='list of epoch indices for multi step scheduler '
'(must be increasing) (default: 100 150)')
parser.add_argument('--gamma', default=0.1, type=float,
help='multiplicative factor of learning rate decay (default: 0.1)')
parser.add_argument('--print_freq', default=100, type=int)
parser.add_argument('--resume', action='store_true', help='resume?')
parser.add_argument('--beta', default=1.0, type=float, help='cutmix beta')
parser.add_argument('--cutmix_prob', default=0.0, type=float,help='cutmix probability')
args = parser.parse_args()
def main(args):
model = Model()
optimizer = torch.optim.SGD(model.parameters(), lr=args.learning_rate,
momentum=args.momentum, weight_decay=args.weight_decay,
nesterov=args.nesterov)
if args.scheduler=='multistep':
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, args.milestones,
gamma=args.gamma)
elif args.scheduler=='cosine':
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, args.step_ssize)
criterion = torch.nn.CrossEntropyLoss()
model = model.cuda()
criterion = criterion.cuda()
start_epoch = 0
# Check number of parameters your model
pytorch_total_params = sum(p.numel() for p in model.parameters())
print(f"Number of parameters: {pytorch_total_params}")
if not os.path.exists('{}'.format(args.savepath)):
os.makedirs('{}'.format(args.savepath))
# resume
if args.resume:
model, optimizer, start_epoch = load_ckpt(model, optimizer, args)
# Dataloader
if args.dataset=='cifar10':
normalize = transforms.Normalize(
mean=[0.4914, 0.4822, 0.4465],
std=[0.2023, 0.1994, 0.2010])
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
transform_val = transforms.Compose([
transforms.ToTensor(),
normalize,
])
trainset = CIFAR10(
root=args.datapath, train=True, download=True,
transform=transform_train)
valset = CIFAR10(
root=args.datapath, train=False, download=True,
transform=transform_val)
elif args.dataset=='cifar100':
normalize = transforms.Normalize(
mean=[0.4914, 0.4822, 0.4465],
std=[0.2023, 0.1994, 0.2010])
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
transform_val = transforms.Compose([
transforms.ToTensor(),
normalize,
])
trainset = CIFAR100(
root=args.datapath, train=True, download=True,
transform=transform_train)
valset = CIFAR100(
root=args.datapath, train=False, download=True,
transform=transform_val)
elif args.dataset=='ImageNet':
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
transform_train = transforms.Compose([
transforms.RandomResizedCrop(image_size),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
transform_val = transforms.Compose([
transforms.Resize(image_size + 32),
transforms.CenterCrop(image_size),
transforms.ToTensor(),
normalize,
])
trainset = ImageNet(
root=args.datapath, split='train', download=False,
transform=transform_train)
valset = ImageNet(
root=args.datapath, split='val', download=False,
transform=transform_val)
elif args.dataeset=='tiny-imagenet-200':
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
transform_train = transforms.Compose([
transforms.RandomResizedCrop(image_size),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
transform_val = transforms.Compose([
transforms.Resize(image_size + 32),
transforms.CenterCrop(image_size),
transforms.ToTensor(),
normalize,
])
trainset = ImageFolder(
root=args.datapath, split='train', download=False,
transform=transform_train)
valset = ImageFolder(
root=args.datapath, split='val', download=False,
transform=transform_val)
train_loader = torch.utils.data.DataLoader(
trainset,
batch_size=args.batch_size, shuffle=True,
num_workers=args.num_workers, pin_memory=False)
val_loader = torch.utils.data.DataLoader(
valset,
batch_size=args.batch_size, shuffle=False,
num_workers=args.num_workers, pin_memory=False)
# start training
last_top1_acc = 0
acc1_valid = 0
best_acc1 = 0
is_best = False
for epoch in range(start_epoch, args.epochs):
print("\n----- epoch: {}, lr: {} -----".format(
epoch, optimizer.param_groups[0]["lr"]))
# train for one epoch
start_time = time.time()
last_top1_acc = train(train_loader, epoch, model, optimizer, criterion)
elapsed_time = time.time() - start_time
print('==> {:.2f} seconds to train this epoch\n'.format(
elapsed_time))
# validate for one epoch
start_time = time.time()
acc1_valid = validate(val_loader, model, criterion)
elapsed_time = time.time() - start_time
print('==> {:.2f} seconds to validate this epoch\n'.format(
elapsed_time))
# learning rate scheduling
scheduler.step()
is_best = acc1_valid > best_acc1
best_acc1 = max(acc1_valid, best_acc1)
checkpoint = {
'epoch': epoch + 1,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict()
}
save_ckpt(checkpoint, is_best, args)
#if is_best:
# torch.save(model.state_dict(), args.savepath+'model_weight_best.pth')
# Save model each epoch
#torch.save(model.state_dict(), args.savepath+'model_weight_epoch{}.pth'.format(epoch))
print(f"Last Top-1 Accuracy: {last_top1_acc}")
print(f"Number of parameters: {pytorch_total_params}")
def train(train_loader, epoch, model, optimizer, criterion):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
progress = ProgressMeter(len(train_loader), batch_time, data_time, losses,
top1, top5, prefix="Epoch: [{}]".format(epoch))
# switch to train mode
model.train()
end = time.time()
for i, (input, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
input = input.cuda()
target = target.cuda()
r = np.random.rand(1)
if args.beta > 0 and r < args.cutmix_prob:
# generate mixed sample
lam = np.random.beta(args.beta, args.beta)
rand_index = torch.randperm(input.size()[0]).cuda()
target_a = target
target_b = target[rand_index]
bbx1, bby1, bbx2, bby2 = rand_bbox(input.size(), lam)
input[:, :, bbx1:bbx2, bby1:bby2] = input[rand_index, :, bbx1:bbx2, bby1:bby2]
# adjust lambda to exactly match pixel ratio
lam = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / (input.size()[-1] * input.size()[-2]))
# compute output
output = model(input)
loss = criterion(output, target_a) * lam + criterion(output, target_b) * (1. - lam)
else:
# compute output
output = model(input)
loss = criterion(output, target)
# measure accuracy and record loss, accuracy
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), input.size(0))
top1.update(acc1[0].item(), input.size(0))
top5.update(acc5[0].item(), input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.print(i)
print('=> Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg
def validate(val_loader, model, criterion):
batch_time = AverageMeter("Time", ":6.3f")
losses = AverageMeter("Loss", ":.4e")
top1 = AverageMeter("Acc@1", ":6.2f")
top5 = AverageMeter("Acc@5", ":6.2f")
progress = ProgressMeter(
len(val_loader), batch_time, losses, top1, top5, prefix="Test: "
)
# switch to evaluate mode
model.eval()
total_loss = 0.0
with torch.no_grad():
end = time.time()
for i, (input, target) in enumerate(val_loader):
input = input.cuda()
target = target.cuda()
# compute output
output = model(input)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), input.size(0))
top1.update(acc1[0], input.size(0))
top5.update(acc5[0], input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
total_loss += loss.item()
if i % args.print_freq == 0:
progress.print(i)
end = time.time()
print(
"====> Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}".format(
top1=top1, top5=top5
)
)
total_loss = total_loss / len(val_loader)
return top1.avg
def rand_bbox(size, lam):
W = size[2]
H = size[3]
cut_rat = np.sqrt(1. - lam)
cut_w = np.int(W * cut_rat)
cut_h = np.int(H * cut_rat)
# uniform
cx = np.random.randint(W)
cy = np.random.randint(H)
bbx1 = np.clip(cx - cut_w // 2, 0, W)
bby1 = np.clip(cy - cut_h // 2, 0, H)
bbx2 = np.clip(cx + cut_w // 2, 0, W)
bby2 = np.clip(cy + cut_h // 2, 0, H)
return bbx1, bby1, bbx2, bby2
if __name__ == "__main__":
main(args)