-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtrainers.py
445 lines (369 loc) · 15.3 KB
/
trainers.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#
# Copyright (C) 2023 Apple Inc. All rights reserved.
#
"""Training methods for ERM, Knowledge Distillation, and Dataset Reinforcement."""
from abc import ABC
import time
import logging
from typing import Callable, Dict, Any, Type
import torch
from torch import Tensor
import torch.nn as nn
from torch.utils.data import DataLoader, Subset
from torch.nn import functional as F
from utils import AverageMeter, CosineLR, ProgressMeter, Summary, accuracy
from models import move_to_device, load_model, create_model
from transforms import MixingTransforms
class Trainer(ABC):
"""Abstract class for various training methodologies."""
def get_model(self) -> nn.Module:
"""Create and initialize the model to train using self.config."""
raise NotImplementedError("Implement `get_model` to initialize a model.")
def get_criterion(self) -> nn.Module:
"""Return the training criterion."""
raise NotImplementedError("Implement `get_criterion`.")
def train(
self,
train_loader: DataLoader,
model: torch.nn.Module,
criterion: torch.nn.Module,
optimizer: torch.optim.Optimizer,
epoch: int,
config: Dict[str, Any],
lr_scheduler: Type[CosineLR],
) -> Dict[str, Any]:
"""Train a model for a single epoch and return training metrics dictionary."""
raise NotImplementedError("Implement `train` method.")
def validate_pretrained(self, *args, **kwargs) -> None:
"""Validate pretrained teacher model."""
pass
def validate(self, *args, **kwargs) -> Dict[str, Any]:
"""Validate the model that is being trained and return a metrics dictionary."""
return validate(*args, **kwargs)
def get_trainer(config: Dict[str, Any]) -> Trainer:
"""Initialize a trainer given a configuration dictionary."""
trainer_type = config["trainer"]
if trainer_type == "ERM":
return ERMTrainer(config)
elif trainer_type == "KD":
return KDTrainer(config)
elif trainer_type == "DR":
return ReinforcedTrainer(config)
raise NotImplementedError("Trainer not implemented.")
class ERMTrainer(Trainer):
"""Trainer class for Empirical Risk Minimization (ERM) with cross-entropy."""
def __init__(self, config: Dict[str, Any]) -> None:
"""Initialize ERMTrainer."""
self.config = config
self.label_smoothing = config["loss"].get("label_smoothing", 0.0)
def get_model(self) -> torch.nn.Module:
"""Create and initialize the model to train using self.config."""
arch = self.config["arch"]
model = create_model(arch, self.config)
model = move_to_device(model, self.config)
return model
def get_criterion(self) -> torch.nn.Module:
"""Return the training criterion."""
criterion = nn.CrossEntropyLoss(label_smoothing=self.label_smoothing).cuda(
self.config["gpu"]
)
return criterion
def train(
self,
train_loader: DataLoader,
model: torch.nn.Module,
criterion: torch.nn.Module,
optimizer: torch.optim.Optimizer,
epoch: int,
config: Dict[str, Any],
lr_scheduler: Type[CosineLR],
) -> Dict[str, Any]:
"""Train a model for a single epoch and return training metrics dictionary."""
batch_time = AverageMeter("Time", ":6.3f")
data_time = AverageMeter("Data", ":6.3f")
losses = AverageMeter("Loss", ":.6f")
top1 = AverageMeter("Acc@1", ":6.2f")
top5 = AverageMeter("Acc@5", ":6.2f")
lrs = AverageMeter("Lr", ":.4f")
conf = AverageMeter("Confidence", ":.5f")
progress = ProgressMeter(
len(train_loader),
[batch_time, data_time, losses, top1, top5, lrs, conf],
prefix="Epoch: [{}]".format(epoch),
)
# switch to train mode
model.train()
mixing_transforms = MixingTransforms(
config["image_augmentation"], config["num_classes"]
)
end = time.time()
for i, (images, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
if config["gpu"] is not None:
images = images.cuda(config["gpu"], non_blocking=True)
target = target.cuda(config["gpu"], non_blocking=True)
# apply mixup / cutmix
mix_images, mix_target = mixing_transforms(images, target)
# compute output
output = model(mix_images)
# classification loss
loss = criterion(output, mix_target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1, images.size(0))
top5.update(acc5, images.size(0))
lrs.update(lr_scheduler.get_last_lr()[0])
# measure confidence
prob = torch.nn.functional.softmax(output, dim=1)
conf.update(prob.max(1).values.mean().item(), images.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()
lr_scheduler.step()
if i % config["print_freq"] == 0:
progress.display(i)
if config["distributed"]:
top1.all_reduce()
top5.all_reduce()
metrics = {
"train_accuracy@top1": top1.avg,
"train_accuracy@top5": top5.avg,
"train_loss": losses.avg,
"lr": lrs.avg,
"train_confidence": conf.avg,
}
return metrics
class ReinforcedTrainer(ERMTrainer):
"""Trainer with a reinforced dataset. Same as ERM Trainer with KL loss."""
def get_criterion(self) -> Callable[[Tensor, Tensor], Tensor]:
"""Return KL loss instead of cross-entropy."""
return lambda output, target: F.kl_div(
F.log_softmax(output, dim=1), target, reduction="batchmean"
)
class KDTrainer(ERMTrainer):
"""Trainer for Knowledge Distillation."""
def __init__(self, config: Dict[str, Any]) -> None:
"""Initialize trainer and set hyperparameters of KD."""
# Loss config
self.lambda_kd = config["loss"].get("lambda_kd", 1.0)
self.lambda_cls = config["loss"].get("lambda_cls", 0.0)
self.temperature = config["loss"].get("temperature", 1.0)
assert self.temperature > 0, "Softmax with temperature=0 is undefined."
self.label_smoothing = config["loss"].get("label_smoothing", 0.0)
self.config = config
self.teacher_model = None
def get_model(self) -> torch.nn.Module:
"""Create and initialize student and teacher models."""
config = self.config
# Instantiate student model for training.
student_arch = config["student"]["arch"]
model = create_model(student_arch, config["student"])
model = move_to_device(model, self.config)
# Instantiate teacher model
teacher_model = load_model(config["gpu"], config["teacher"])
if config["gpu"] is not None:
torch.cuda.set_device(config["gpu"])
teacher_model = teacher_model.cuda(config["gpu"])
else:
teacher_model.cuda()
# Set teacher to eval mode
teacher_model.eval()
self.teacher_model = teacher_model
return model
def validate_pretrained(
self,
val_loader: DataLoader,
model: torch.nn.Module,
criterion: torch.nn.Module,
config: Dict[str, Any],
) -> None:
"""Validate teacher accuracy before training."""
teacher_model = self.teacher_model
do_validate = config.get("teacher", {}).get("validate", True)
if teacher_model is not None and do_validate:
logging.info(
"Validation loader resizes to standard 256x256 resolution"
" which is necessarily the optimal resolution for the teacher."
)
val_metrics = validate(val_loader, teacher_model, criterion, config)
logging.info(
"Teacher accuracy@top1: {}, @top5: {}".format(
val_metrics["val_accuracy@top1"], val_metrics["val_accuracy@top5"]
)
)
def train(
self,
train_loader: DataLoader,
model: torch.nn.Module,
criterion: torch.nn.Module,
optimizer: torch.optim.Optimizer,
epoch: int,
config: Dict[str, Any],
lr_scheduler: Type[CosineLR],
) -> Dict[str, Any]:
"""Train a model for a single epoch and return training metrics dictionary."""
batch_time = AverageMeter("Time", ":6.3f")
data_time = AverageMeter("Data", ":6.3f")
losses = AverageMeter("Loss", ":.6f")
kd_losses = AverageMeter("KD Loss", ":.6f")
overall_losses = AverageMeter("Loss", ":.6f")
top1 = AverageMeter("Acc@1", ":6.2f")
top5 = AverageMeter("Acc@5", ":6.2f")
lrs = AverageMeter("Lr", ":.4f")
progress = ProgressMeter(
len(train_loader),
[batch_time, data_time, losses, kd_losses, overall_losses, top1, top5, lrs],
prefix="Epoch: [{}]".format(epoch),
)
# Switch to train mode
model.train()
mixing_transforms = MixingTransforms(
config["image_augmentation"], config["num_classes"]
)
end = time.time()
for i, (images, target) in enumerate(train_loader):
# Measure data loading time
data_time.update(time.time() - end)
if config["gpu"] is not None:
images = images.cuda(config["gpu"], non_blocking=True)
target = target.cuda(config["gpu"], non_blocking=True)
# Apply mixup / cutmix
mix_images, mix_target = mixing_transforms(images, target)
# Compute output for differing resolution. Support only 224 student
mix_images_small = mix_images
if mix_images.shape[-1] != 224:
mix_images_small = F.interpolate(
mix_images, size=(224, 224), mode="bilinear"
)
output = model(mix_images_small)
# Classification loss
loss = criterion(output, mix_target)
losses.update(loss.item(), images.size(0))
# Distillation loss
# Get teacher's output for this input
with torch.no_grad():
teacher_probs = self.teacher_model(
mix_images, return_prob=True, temperature=self.temperature
).detach()
kd_loss = F.kl_div(
F.log_softmax(output / self.temperature, dim=1),
teacher_probs,
reduction="batchmean",
) * (self.temperature**2)
kd_losses.update(kd_loss.item(), images.size(0))
# Overall loss is a combination of kd loss and classification loss
loss = self.lambda_cls * loss + self.lambda_kd * kd_loss
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
overall_losses.update(loss.item(), images.size(0))
top1.update(acc1, images.size(0))
top5.update(acc5, images.size(0))
lrs.update(lr_scheduler.get_last_lr()[0])
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
lr_scheduler.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % config["print_freq"] == 0:
progress.display(i)
if config["distributed"]:
top1.all_reduce()
top5.all_reduce()
metrics = {
"train_accuracy@top1": top1.avg,
"train_accuracy@top5": top5.avg,
"train_loss_ce": losses.avg,
"train_loss_kd": kd_losses.avg,
"train_loss_total": overall_losses.avg,
"lr": lrs.avg,
}
return metrics
def validate(
val_loader: DataLoader,
model: torch.nn.Module,
criterion: torch.nn.Module,
config: Dict[str, Any],
) -> Dict[str, Any]:
"""Validate the model that is being trained and return a metrics dictionary."""
def run_validate(loader: DataLoader, base_progress: int = 0) -> None:
with torch.no_grad():
end = time.time()
for i, (images, target) in enumerate(val_loader):
i = base_progress + i
if config["gpu"] is not None:
images = images.cuda(config["gpu"], non_blocking=True)
target = target.cuda(config["gpu"], non_blocking=True)
# compute output
output = model(images)
# for validation, compute standard CE loss without label smoothing
loss = F.cross_entropy(output, target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1, images.size(0))
top5.update(acc5, images.size(0))
# measure confidence
prob = torch.nn.functional.softmax(output, dim=1)
conf.update(prob.max(1).values.mean().item(), images.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % config["print_freq"] == 0:
progress.display(i)
batch_time = AverageMeter("Time", ":6.3f", Summary.NONE)
losses = AverageMeter("Loss", ":.6f", Summary.NONE)
top1 = AverageMeter("Acc@1", ":6.2f", Summary.AVERAGE)
top5 = AverageMeter("Acc@5", ":6.2f", Summary.AVERAGE)
conf = AverageMeter("Confidence", ":.5f", Summary.AVERAGE)
progress = ProgressMeter(
len(val_loader)
+ (
config["distributed"]
and (
len(val_loader.sampler) * config["world_size"] < len(val_loader.dataset)
)
),
[batch_time, losses, top1, top5],
prefix="Test: ",
)
# switch to evaluate mode
model.eval()
# run validation using all nodes in a distributed env and aggregate results
run_validate(val_loader)
if config["distributed"]:
top1.all_reduce()
top5.all_reduce()
if config["distributed"] and (
len(val_loader.sampler) * config["world_size"] < len(val_loader.dataset)
):
aux_val_dataset = Subset(
val_loader.dataset,
range(
len(val_loader.sampler) * config["world_size"], len(val_loader.dataset)
),
)
aux_val_loader = torch.utils.data.DataLoader(
aux_val_dataset,
batch_size=config["batch_size"],
shuffle=False,
num_workers=config["workers"],
pin_memory=True,
)
run_validate(aux_val_loader, len(val_loader))
progress.display_summary()
metrics = {
"val_loss": losses.avg,
"val_accuracy@top1": top1.avg,
"val_accuracy@top5": top5.avg,
"val_confidence": conf.avg,
}
return metrics