-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimagenet.py
203 lines (155 loc) · 6.12 KB
/
imagenet.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
import json
from torch import optim
import time
import argparse
from torch.utils.data import DataLoader
from datasets import *
from loss import *
batch_size = 128
batch_size_ft = 64
v_batch_size = 50
epoch = 1
ft_epoch = 2
max_train = 2000
max_train_ft = 24000
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
torch.backends.cudnn.benchmark = True
def eval(model):
model.eval()
val_loss = []
val_acc = []
i = 1
for imgs, lbls in val_ds:
imgs = imgs.to(device)
lbls = lbls.to(device)
outputs = model(imgs)
val_loss.append(criterion(outputs, lbls).detach().cpu())
val_acc.append(((outputs.argmax(dim=1) == lbls).sum() / lbls.shape[0]).detach().cpu())
print('{}/{} val loss {:5.02f} val acc {:5.02f}'.format(i, n_val, torch.stack(val_loss).mean(), 100. * torch.stack(val_acc).mean()), end='\r')
i += 1
print()
return torch.stack(val_loss).mean().item(), 100. * torch.stack(val_acc).mean().item()
#############
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir", help="path to imagenet")
parser.add_argument("--eval_pretrained", type=bool, default=False)
parser.add_argument("--output", default="results_imagenet.json")
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--nb_seeds", type=int, default=10)
args = parser.parse_args()
data = []
train, val = build_imagenet(args.data_dir)
val_ds = DataLoader(val, batch_size=v_batch_size, num_workers=10)
n_val = len(val_ds)
for s in range(args.seed, args.seed + args.nb_seeds):
print('doing seed {}'.format(s))
torch.manual_seed(s)
np.random.seed(s)
train_ds = DataLoader(train, batch_size=batch_size, num_workers=10, shuffle=True)
n_train = len(train_ds)
tr_loss = []
tr_acc = []
ft_loss = []
ft_acc = []
# build model
model = torchvision.models.resnet50(pretrained=True)
if not args.eval_pretrained:
torch.nn.init.kaiming_uniform_(model.fc.weight)
torch.nn.init.normal_(model.fc.bias)
for p in model.parameters():
p.requires_grad = False
if not args.eval_pretrained:
model.fc.weight.requires_grad = True
model.fc.bias.requires_grad = True
model.to(device)
# optimization hparams
criterion = nn.CrossEntropyLoss()
if not args.eval_pretrained:
criterion2 = CrossEntropyLabelSmooth(num_classes=1000, epsilon=0.1)
optimizer = optim.SGD(model.parameters(), lr=0.02, momentum=0.9, nesterov=True, weight_decay=0.0001)
sched = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epoch*n_train//1000, eta_min=0.001)
# training loop
print('Training last layer')
t_start = time.time()
i = 1
for e in range(epoch): # loop over the dataset multiple times
running_loss = []
running_acc = []
start = time.time()
for imgs, lbls in train_ds:
imgs = imgs.to(device)
lbls = lbls.to(device)
optimizer.zero_grad()
outputs = model(imgs)
loss = criterion(outputs, lbls)
loss2 = criterion2(outputs, lbls)
loss = loss + loss2
loss.backward()
optimizer.step()
# print statistics
running_loss.append(loss.detach().cpu())
running_acc.append(((outputs.argmax(dim=1) == lbls).sum() / lbls.shape[0]).detach().cpu())
print('{}/{} loss: {:5.02f} acc: {:5.02f} in {:6.01f}'.format(i, n_train, torch.stack(running_loss).mean(), 100*torch.stack(running_acc).mean(), time.time()-start), end='\r')
if i%1000 == 0:
print()
l, a = eval(model)
tr_loss.append(l)
tr_acc.append(a)
model.train()
sched.step()
if i >= max_train:
break
i += 1
print('Fine tuning all layers')
# new dataset batch_size
train_ds = DataLoader(train, batch_size=batch_size_ft, num_workers=10, shuffle=True)
n_train = len(train_ds)
# train all model
for p in model.parameters():
p.requires_grad = True
# new optim and sched
optimizer = optim.SGD(model.parameters(), lr=0.0005, momentum=0.9, nesterov=True, weight_decay=0.0001)
sched = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=max_train_ft//2000, eta_min=0.0001)
i = 1
for e in range(ft_epoch):
running_loss = []
running_acc = []
for imgs, lbls in train_ds:
imgs = imgs.to(device)
lbls = lbls.to(device)
optimizer.zero_grad()
outputs = model(imgs)
loss = criterion(outputs, lbls)
loss = loss
loss.backward()
optimizer.step()
# print statistics
running_loss.append(loss.detach().cpu())
running_acc.append(((outputs.argmax(dim=1) == lbls).sum() / lbls.shape[0]).detach().cpu())
print('{}/{} loss: {:5.02f} acc: {:5.02f} in {:6.01f}'.format(i, n_train, torch.stack(running_loss).mean(),
100 * torch.stack(running_acc).mean(),
time.time() - start), end='\r')
if i % 2000 == 0:
print()
l, a = eval(model)
ft_loss.append(l)
ft_acc.append(a)
model.train()
sched.step()
if i >= max_train_ft:
break
i += 1
# eval
if args.eval_pretrained:
eval(model)
d = { 'seed': s,
'tr_loss': tr_loss,
'tr_acc': tr_acc,
'ft_loss': ft_loss,
'ft_acc': ft_acc,
'time': time.time() - start
}
data.append(d)
print(d)
with open(args.output, 'w') as fp:
json.dump(data, fp)