-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrainer.py
210 lines (199 loc) · 8.01 KB
/
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
import copy
import logging
from sklearn import metrics
import numpy as np
from tqdm import tqdm
import wandb
import torch
try:
from torch.cuda.amp import autocast, GradScaler
except AttributeError:
raise ImportError("AMP training is used as default")
# cool tricks: https://efficientdl.com/faster-deep-learning-in-pytorch-a-guide/
class Trainer:
"""Trainer with training and validation loops with amp precision"""
def __init__(
self,
model,
dataloaders: dict,
num_classes: int,
criterion,
optimizer,
scheduler,
num_epochs: int,
device,
use_wandb: bool,
):
"""
Args:
model : PyTorch model
dataloaders (dict) : Dict containing train and val dataloaders
num_classes (int) : Number of classes to one hot targets if num_classes <= 2
criterion : pytorch loss function
optimizer : pytorch optimizer function
scheduler : pytorch scheduler function
num_epochs (int) : Number of epochs to train the model
device : torch.device indicating whether device is cpu or gpu
use_wandb (bool) : Log results to wandb.ai
"""
self.model = model
self.train_data = dataloaders["train"]
self.valid_data = dataloaders["val"]
self.num_classes = num_classes
self.criterion = criterion
self.optimizer = optimizer
self.scheduler = scheduler
self.num_epochs = num_epochs
self.device = device
self.use_wandb = use_wandb
self.best_acc = 0.0
self.best_model_wts = copy.deepcopy(self.model.state_dict())
# create a GradScaler once at the beginning of training.
self.scaler = GradScaler()
def train_one_epoch(self):
self.model.train() # Set model to training mode
running_loss = 0.0
running_corrects = 0.0
f1s, recalls, precisions = [], [], []
stream = tqdm(self.train_data, position=0, leave=True)
# Iterate over batch of data.
for _, (inputs, labels) in enumerate(stream):
inputs = inputs.to(self.device, non_blocking=True)
labels = labels.to(self.device, non_blocking=True)
# zero the parameter gradients
self.optimizer.zero_grad(set_to_none=True)
# Runs the forward pass with autocasting.
with autocast():
# forward
# track history if only in train
with torch.set_grad_enabled(True):
# Get model outputs and calculate loss
# backward + optimize only if in training phase
outputs = self.model(inputs)
if self.num_classes <= 2:
onehot_labels = torch.nn.functional.one_hot(
labels, self.num_classes
)
onehot_labels = onehot_labels.type_as(outputs)
loss = self.criterion(outputs, onehot_labels)
else:
labels = labels.long()
loss = self.criterion(outputs, labels)
stream.set_description(
"train_loss: {:.2f}".format(loss.item())
)
# Scales loss. Calls backward() on scaled loss to create scaled gradients.
self.scaler.scale(loss).backward()
# scaler.step() first unscales the gradients of the optimizer's assigned params.
self.scaler.step(self.optimizer)
self.scaler.update()
# statistics
_, preds = torch.max(outputs, 1)
f1s.append(
metrics.f1_score(
labels.cpu().numpy(), preds.cpu().numpy(), average="macro"
)
)
precisions.append(
metrics.precision_score(
labels.cpu().numpy(), preds.cpu().numpy(), average="macro"
)
)
recalls.append(
metrics.recall_score(
labels.cpu().numpy(), preds.cpu().numpy(), average="macro"
)
)
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
self.scheduler.step()
epoch_loss = running_loss / (len(self.train_data.dataset))
epoch_acc = (
running_corrects.double() / (len(self.train_data.dataset))
).item()
epoch_f1 = np.mean(f1s)
epoch_precision = np.mean(precisions)
epoch_recall = np.mean(recalls)
# log to wandb
if self.use_wandb:
wandb.log(
{
"train_epoch_loss": epoch_loss,
"train_epoch_accuracy": epoch_acc,
"train_epoch_f1": epoch_f1,
"train_epoch_precision": epoch_precision,
"train_epoch_recall": epoch_recall,
}
)
return epoch_loss, epoch_acc, epoch_f1, epoch_precision, epoch_recall
def valid_one_epoch(self):
self.model.eval() # Set model to evaluate mode
running_loss = 0.0
running_corrects = 0.0
f1s, recalls, precisions = [], [], []
stream = tqdm(self.valid_data, position=0, leave=True)
# Iterate over batch of data.
for _, (inputs, labels) in enumerate(stream):
inputs = inputs.to(self.device, non_blocking=True)
labels = labels.to(self.device, non_blocking=True)
# forward
# track history if only in train
with torch.set_grad_enabled(False):
outputs = self.model(inputs)
if self.num_classes <= 2:
onehot_labels = torch.nn.functional.one_hot(
labels, self.num_classes
)
onehot_labels = onehot_labels.type_as(outputs)
loss = self.criterion(outputs, onehot_labels)
else:
labels = labels.long()
loss = self.criterion(outputs, labels)
stream.set_description("val_loss: {:.2f}".format(loss.item()))
# statistics
_, preds = torch.max(outputs, 1)
f1s.append(
metrics.f1_score(
labels.cpu().numpy(), preds.cpu().numpy(), average="macro"
)
)
precisions.append(
metrics.precision_score(
labels.cpu().numpy(), preds.cpu().numpy(), average="macro"
)
)
recalls.append(
metrics.recall_score(
labels.cpu().numpy(), preds.cpu().numpy(), average="macro"
)
)
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / (len(self.valid_data.dataset))
epoch_acc = (
running_corrects.double() / (len(self.valid_data.dataset))
).item()
epoch_f1 = np.mean(f1s)
epoch_precision = np.mean(precisions)
epoch_recall = np.mean(recalls)
# log to wandb
if self.use_wandb:
wandb.log(
{
"val_epoch_loss": epoch_loss,
"val_epoch_accuracy": epoch_acc,
"val_epoch_f1": epoch_f1,
"val_epoch_precision": epoch_precision,
"val_epoch_recall": epoch_recall,
}
)
# deep copy the model
if epoch_acc > self.best_acc:
logging.info(
"Val acc improved from {:.4f} to {:.4f}.".format(
self.best_acc, epoch_acc
)
)
self.best_acc = epoch_acc
self.best_model_wts = copy.deepcopy(self.model.state_dict())
return epoch_loss, epoch_acc, epoch_f1, epoch_precision, epoch_recall