-
Notifications
You must be signed in to change notification settings - Fork 1
/
lsep_trainer.py
261 lines (204 loc) · 7.34 KB
/
lsep_trainer.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
import argparse
import os
import time
import warnings
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from loss import MultiThresholdLoss, strong_LSEP, weak_LSEP
from model import LSEPModel
from reader import ArchitectureReader, LandscapeReader, RankedMNISTReader
from utils import save_plot
warnings.filterwarnings("ignore")
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument("--config_path", type=str)
parser.add_argument("--experiment_name", type=str)
parser.add_argument("--main_path", type=str)
parser.add_argument("--num_epoch", type=int, default=20)
parser.add_argument("--backbone", type=str, default="simple")
parser.add_argument("--dataset", type=str)
parser.add_argument("--supervision", type=str)
parser.add_argument("--stage", type=str)
parser.add_argument("--domain", type=str, default="ARC")
parser.add_argument("--subset", type=bool, default=False)
args = parser.parse_args()
main_result_path = os.path.join("results", args.experiment_name)
loss_path = os.path.join(main_result_path, "losses")
save_path = os.path.join(main_result_path, "saves")
plot_freq = 1
save_freq = 10000
preprint_freq = 100
if not os.path.isdir(main_result_path):
os.makedirs(loss_path)
os.makedirs(save_path)
else:
print("DIRECTORY ALREADY EXISTS, continuing")
time.sleep(1)
device_name = "cuda:1"
n_epoch = args.num_epoch
bs = 64
stage = args.stage
# Load data
if args.dataset == "ranked_mnist":
train_loader = DataLoader(
RankedMNISTReader(
args.main_path, args.config_path, mode="train", subset=args.subset
),
batch_size=bs,
shuffle=True,
num_workers=8,
)
val_loader = DataLoader(
RankedMNISTReader(
args.main_path, args.config_path, mode="val", subset=args.subset
),
batch_size=bs,
shuffle=False,
num_workers=8,
)
n_classes = 10
elif args.dataset == "landscape":
train_loader = DataLoader(
LandscapeReader(args.main_path, "train"),
batch_size=bs,
shuffle=True,
num_workers=8,
)
val_loader = DataLoader(
LandscapeReader(args.main_path, "test"),
batch_size=bs,
shuffle=False,
num_workers=8,
)
n_classes = 9
elif args.dataset == "architecture":
train_loader = DataLoader(
ArchitectureReader(args.main_path, mode="train", domain=args.domain),
batch_size=bs,
shuffle=True,
num_workers=8,
)
val_loader = DataLoader(
ArchitectureReader(args.main_path, mode="val", domain=args.domain),
batch_size=bs,
shuffle=False,
num_workers=8,
)
n_classes = 9
# Model
threshold_criterion = MultiThresholdLoss
if args.supervision == "weak":
criterion = weak_LSEP
elif args.supervision == "strong":
criterion = strong_LSEP
best_val_loss = 999999999
stats = {"train": {}, "val": {}}
if args.dataset == "ranked_mnist":
model = LSEPModel(n_classes, args.backbone).to(device_name)
if stage == "threshold":
state_dict = torch.load(os.path.join(save_path, "ranking_best.pth"))[
"state_dict"
]
model.load_state_dict(state_dict)
parameters = list(model.fc.parameters())
model = model.to(device_name)
else:
parameters = list(model.fc.parameters()) + list(
model.feature_extractor.parameters()
)
optimizer = torch.optim.Adam(parameters, lr=1.0e-4, weight_decay=1.0e-5)
schedual = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.9)
elif args.dataset == "landscape" or args.dataset == "architecture":
model = LSEPModel(n_classes, args.backbone, pretrained=True).to(device_name)
if stage == "threshold":
state_dict = torch.load(os.path.join(save_path, "ranking_best.pth"))[
"state_dict"
]
model.load_state_dict(state_dict)
parameters = list(model.fc.parameters())
model = model.to(device_name)
else:
parameters = list(model.fc.parameters())
optimizer = torch.optim.Adam(parameters, lr=1.0e-4, weight_decay=1.0e-5)
schedual = torch.optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.9)
for epoch_idx in range(n_epoch):
start_time = time.time()
# Training
model = model.train()
running_stats = {}
for iter_idx, (images, labels) in enumerate(train_loader):
model.zero_grad()
optimizer.zero_grad()
images = images.to(device_name)
labels = labels.to(device_name)
scores, thresholds = model(images)
if stage == "ranking":
loss = criterion(scores, labels)
elif stage == "threshold":
loss = threshold_criterion(scores, thresholds, labels)
losses = {"%s_loss" % stage: loss}
loss.backward()
optimizer.step()
losses = {key: val.detach().cpu().item() for key, val in losses.items()}
for key, val in losses.items():
if key not in running_stats:
running_stats[key] = [val]
else:
running_stats[key].append(val)
if (iter_idx + 1) % preprint_freq == 0:
print("(%d/%d) %.6f" % (iter_idx + 1, len(train_loader), loss))
average_stats = {key: np.mean(val) for key, val in running_stats.items()}
for key, val in average_stats.items():
if key not in stats["train"]:
stats["train"][key] = [val]
else:
stats["train"][key].append(val)
# Validation
model = model.eval()
running_stats = {}
with torch.no_grad():
for batch in val_loader:
scores, thresholds = model(images)
if stage == "ranking":
loss = criterion(scores, labels)
elif stage == "threshold":
loss = threshold_criterion(scores, thresholds, labels)
losses = {"%s_loss" % stage: loss}
losses = {key: val.detach().cpu().item() for key, val in losses.items()}
for key, val in losses.items():
if key not in running_stats:
running_stats[key] = [val]
else:
running_stats[key].append(val)
average_stats = {key: np.mean(val) for key, val in running_stats.items()}
for key, val in average_stats.items():
if key not in stats["val"]:
stats["val"][key] = [val]
else:
stats["val"][key].append(val)
end_time = time.time()
if (epoch_idx + 1) % plot_freq == 0:
save_plot(stats, epoch_idx + 1, loss_path, prefix=stage)
if (epoch_idx + 1) % save_freq == 0:
torch.save(
{"state_dict": model.state_dict(), "stats": stats},
os.path.join(save_path, "ckpt_%d.pth" % (epoch_idx + 1)),
)
last_train_loss = sum(val[-1] for _, val in stats["train"].items())
last_val_loss = sum(val[-1] for _, val in stats["val"].items())
duration = end_time - start_time
print(
"%s: Epoch %d: Train: %.6f, Val: %.6f, Time: %.2f"
% (stage, epoch_idx + 1, last_train_loss, last_val_loss, duration)
)
if last_val_loss < best_val_loss:
best_val_loss = last_val_loss
torch.save(
{"state_dict": model.state_dict(), "stats": stats},
os.path.join(save_path, "%s_best.pth" % stage),
)
schedual.step()