-
Notifications
You must be signed in to change notification settings - Fork 7
/
trainer.py
372 lines (313 loc) · 14.1 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
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
# Built-in libraries
import copy
import datetime
from typing import Dict, List
# Third-party libraries
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader
from sklearn.metrics import f1_score
from tqdm import tqdm
# Local files
from utils import save
from config import LABEL_DICT
class Trainer():
'''
The trainer for training models.
It can be used for both single and multi task training.
Every class function ends with _m is for multi-task training.
'''
def __init__(
self,
model: nn.Module,
epochs: int,
dataloaders: Dict[str, DataLoader],
criterion: nn.Module,
loss_weights: List[float],
clip: bool,
optimizer: torch.optim.Optimizer,
scheduler: torch.optim.lr_scheduler,
device: str,
patience: int,
task_name: str,
model_name: str,
seed: int
):
self.model = model
self.epochs = epochs
self.dataloaders = dataloaders
self.criterion = criterion
self.loss_weights = loss_weights
self.clip = clip
self.optimizer = optimizer
self.scheduler = scheduler
self.device = device
self.patience = patience
self.task_name = task_name
self.model_name = model_name
self.seed = seed
self.datetimestr = datetime.datetime.now().strftime('%Y-%b-%d_%H:%M:%S')
# Evaluation results
self.train_losses = []
self.test_losses = []
self.train_f1 = []
self.test_f1 = []
self.best_train_f1 = 0.0
self.best_test_f1 = 0.0
# Evaluation results for multi-task
self.best_train_f1_m = np.array([0, 0, 0], dtype=np.float64)
self.best_test_f1_m = np.array([0, 0, 0], dtype=np.float64)
def train(self):
for epoch in range(self.epochs):
print(f'Epoch {epoch}')
print('=' * 20)
self.train_one_epoch()
self.test()
print(f'Best test f1: {self.best_test_f1:.4f}')
print('=' * 20)
print('Saving results ...')
save(
(self.train_losses, self.test_losses, self.train_f1, self.test_f1, self.best_train_f1, self.best_test_f1),
f'./save/results/single_{self.task_name}_{self.datetimestr}_{self.best_test_f1:.4f}.pt'
)
def train_one_epoch(self):
self.model.train()
dataloader = self.dataloaders['train']
y_pred_all = None
labels_all = None
loss = 0
iters_per_epoch = 0
for inputs, lens, mask, labels in tqdm(dataloader, desc='Training'):
iters_per_epoch += 1
if labels_all is None:
labels_all = labels.numpy()
else:
labels_all = np.concatenate((labels_all, labels.numpy()))
inputs = inputs.to(device=self.device)
lens = lens.to(device=self.device)
mask = mask.to(device=self.device)
labels = labels.to(device=self.device)
self.optimizer.zero_grad()
with torch.set_grad_enabled(True):
# Forward
logits = self.model(inputs, lens, mask, labels)
_loss = self.criterion(logits, labels)
loss += _loss.item()
y_pred = logits.argmax(dim=1).cpu().numpy()
if y_pred_all is None:
y_pred_all = y_pred
else:
y_pred_all = np.concatenate((y_pred_all, y_pred))
# Backward
_loss.backward()
if self.clip:
torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=10)
self.optimizer.step()
if self.scheduler is not None:
self.scheduler.step()
loss /= iters_per_epoch
f1 = f1_score(labels_all, y_pred_all, average='macro')
print(f'loss = {loss:.4f}')
print(f'Macro-F1 = {f1:.4f}')
self.train_losses.append(loss)
self.train_f1.append(f1)
if f1 > self.best_train_f1:
self.best_train_f1 = f1
def test(self):
self.model.eval()
dataloader = self.dataloaders['test']
y_pred_all = None
labels_all = None
loss = 0
iters_per_epoch = 0
for inputs, lens, mask, labels in tqdm(dataloader, desc='Testing'):
iters_per_epoch += 1
if labels_all is None:
labels_all = labels.numpy()
else:
labels_all = np.concatenate((labels_all, labels.numpy()))
inputs = inputs.to(device=self.device)
lens = lens.to(device=self.device)
mask = mask.to(device=self.device)
labels = labels.to(device=self.device)
with torch.set_grad_enabled(False):
logits = self.model(inputs, lens, mask, labels)
_loss = self.criterion(logits, labels)
y_pred = logits.argmax(dim=1).cpu().numpy()
loss += _loss.item()
if y_pred_all is None:
y_pred_all = y_pred
else:
y_pred_all = np.concatenate((y_pred_all, y_pred))
loss /= iters_per_epoch
f1 = f1_score(labels_all, y_pred_all, average='macro')
print(f'loss = {loss:.4f}')
print(f'Macro-F1 = {f1:.4f}')
self.test_losses.append(loss)
self.test_f1.append(f1)
if f1 > self.best_test_f1:
self.best_test_f1 = f1
self.save_model()
def train_m(self):
for epoch in range(self.epochs):
print(f'Epoch {epoch}')
print('=' * 20)
self.train_one_epoch_m()
self.test_m()
print(f'Best test results A: {self.best_test_f1_m[0]:.4f}')
print(f'Best test results B: {self.best_test_f1_m[1]:.4f}')
print(f'Best test results C: {self.best_test_f1_m[2]:.4f}')
print('=' * 20)
print('Saving results ...')
save(
(self.train_losses, self.test_losses, self.train_f1, self.test_f1, self.best_train_f1_m, self.best_test_f1_m),
f'./save/results/mtl_{self.datetimestr}_{self.best_test_f1_m[0]:.4f}.pt'
)
def train_one_epoch_m(self):
self.model.train()
dataloader = self.dataloaders['train']
y_pred_all_A = None
y_pred_all_B = None
y_pred_all_C = None
labels_all_A = None
labels_all_B = None
labels_all_C = None
loss = 0
iters_per_epoch = 0
for inputs, lens, mask, label_A, label_B, label_C in tqdm(dataloader, desc='Training M'):
iters_per_epoch += 1
inputs = inputs.to(device=self.device)
lens = lens.to(device=self.device)
mask = mask.to(device=self.device)
label_A = label_A.to(device=self.device)
label_B = label_B.to(device=self.device)
label_C = label_C.to(device=self.device)
self.optimizer.zero_grad()
with torch.set_grad_enabled(True):
# Forward
# logits_A, logits_B, logits_C = self.model(inputs, mask)
all_logits = self.model(inputs, lens, mask)
y_pred_A = all_logits[0].argmax(dim=1).cpu().numpy()
y_pred_B = all_logits[1][:, 0:2].argmax(dim=1)
y_pred_C = all_logits[2][:, 0:3].argmax(dim=1)
Non_null_index_B = label_B != LABEL_DICT['b']['NULL']
Non_null_label_B = label_B[Non_null_index_B]
Non_null_pred_B = y_pred_B[Non_null_index_B]
Non_null_index_C = label_C != LABEL_DICT['c']['NULL']
Non_null_label_C = label_C[Non_null_index_C]
Non_null_pred_C = y_pred_C[Non_null_index_C]
labels_all_A = label_A.cpu().numpy() if labels_all_A is None else np.concatenate((labels_all_A, label_A.cpu().numpy()))
labels_all_B = Non_null_label_B.cpu().numpy() if labels_all_B is None else np.concatenate((labels_all_B, Non_null_label_B.cpu().numpy()))
labels_all_C = Non_null_label_C.cpu().numpy() if labels_all_C is None else np.concatenate((labels_all_C, Non_null_label_C.cpu().numpy()))
y_pred_all_A = y_pred_A if y_pred_all_A is None else np.concatenate((y_pred_all_A, y_pred_A))
y_pred_all_B = Non_null_pred_B.cpu().numpy() if y_pred_all_B is None else np.concatenate((y_pred_all_B, Non_null_pred_B.cpu().numpy()))
y_pred_all_C = Non_null_pred_C.cpu().numpy() if y_pred_all_C is None else np.concatenate((y_pred_all_C, Non_null_pred_C.cpu().numpy()))
# f1[0] += self.calc_f1(label_A, y_pred_A)
# f1[1] += self.calc_f1(Non_null_label_B, Non_null_pred_B)
# f1[2] += self.calc_f1(Non_null_label_C, Non_null_pred_C)
_loss = self.loss_weights[0] * self.criterion(all_logits[0], label_A)
_loss += self.loss_weights[1] * self.criterion(all_logits[1], label_B)
_loss += self.loss_weights[2] * self.criterion(all_logits[2], label_C)
loss += _loss.item()
# Backward
_loss.backward()
if self.clip:
torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=10)
self.optimizer.step()
if self.scheduler is not None:
self.scheduler.step()
loss /= iters_per_epoch
f1_A = f1_score(labels_all_A, y_pred_all_A, average='macro')
f1_B = f1_score(labels_all_B, y_pred_all_B, average='macro')
f1_C = f1_score(labels_all_C, y_pred_all_C, average='macro')
print(f'loss = {loss:.4f}')
print(f'A: {f1_A:.4f}')
print(f'B: {f1_B:.4f}')
print(f'C: {f1_C:.4f}')
self.train_losses.append(loss)
self.train_f1.append([f1_A, f1_B, f1_C])
if f1_A > self.best_train_f1_m[0]:
self.best_train_f1_m[0] = f1_A
if f1_B > self.best_train_f1_m[1]:
self.best_train_f1_m[1] = f1_B
if f1_C > self.best_train_f1_m[2]:
self.best_train_f1_m[2] = f1_C
def test_m(self):
self.model.eval()
dataloader = self.dataloaders['test']
loss = 0
iters_per_epoch = 0
y_pred_all_A = None
y_pred_all_B = None
y_pred_all_C = None
labels_all_A = None
labels_all_B = None
labels_all_C = None
for inputs, lens, mask, label_A, label_B, label_C in tqdm(dataloader, desc='Test M'):
iters_per_epoch += 1
labels_all_A = label_A.numpy() if labels_all_A is None else np.concatenate((labels_all_A, label_A.numpy()))
labels_all_B = label_B.numpy() if labels_all_B is None else np.concatenate((labels_all_B, label_B.numpy()))
labels_all_C = label_C.numpy() if labels_all_C is None else np.concatenate((labels_all_C, label_C.numpy()))
inputs = inputs.to(device=self.device)
lens = lens.to(device=self.device)
mask = mask.to(device=self.device)
label_A = label_A.to(device=self.device)
label_B = label_B.to(device=self.device)
label_C = label_C.to(device=self.device)
with torch.set_grad_enabled(False):
all_logits = self.model(inputs, lens, mask)
y_pred_A = all_logits[0].argmax(dim=1).cpu().numpy()
y_pred_B = all_logits[1].argmax(dim=1).cpu().numpy()
y_pred_C = all_logits[2].argmax(dim=1).cpu().numpy()
# f1[0] += self.calc_f1(label_A, y_pred_A)
# f1[1] += self.calc_f1(label_B, y_pred_B)
# f1[2] += self.calc_f1(label_C, y_pred_C)
y_pred_all_A = y_pred_A if y_pred_all_A is None else np.concatenate((y_pred_all_A, y_pred_A))
y_pred_all_B = y_pred_B if y_pred_all_B is None else np.concatenate((y_pred_all_B, y_pred_B))
y_pred_all_C = y_pred_C if y_pred_all_C is None else np.concatenate((y_pred_all_C, y_pred_C))
_loss = self.loss_weights[0] * self.criterion(all_logits[0], label_A)
_loss += self.loss_weights[1] * self.criterion(all_logits[1], label_B)
_loss += self.loss_weights[2] * self.criterion(all_logits[2], label_C)
loss += _loss.item()
loss /= iters_per_epoch
f1_A = f1_score(labels_all_A, y_pred_all_A, average='macro')
f1_B = f1_score(labels_all_B, y_pred_all_B, average='macro')
f1_C = f1_score(labels_all_C, y_pred_all_C, average='macro')
print(f'loss = {loss:.4f}')
print(f'A: {f1_A:.4f}')
print(f'B: {f1_B:.4f}')
print(f'C: {f1_C:.4f}')
self.test_losses.append(loss)
self.test_f1.append([f1_A, f1_B, f1_C])
if f1_A > self.best_test_f1_m[0]:
self.best_test_f1_m[0] = f1_A
self.save_model()
if f1_B > self.best_test_f1_m[1]:
self.best_test_f1_m[1] = f1_B
if f1_C > self.best_test_f1_m[2]:
self.best_test_f1_m[2] = f1_C
# for i in range(len(f1)):
# for j in range(len(f1[0])):
# if f1[i][j] > self.best_test_f1_m[i][j]:
# self.best_test_f1_m[i][j] = f1[i][j]
# if i == 0 and j == 0:
# self.save_model()
def calc_f1(self, labels, y_pred):
return np.array([
f1_score(labels.cpu(), y_pred.cpu(), average='macro'),
f1_score(labels.cpu(), y_pred.cpu(), average='micro'),
f1_score(labels.cpu(), y_pred.cpu(), average='weighted')
], np.float64)
def printing(self, loss, f1):
print(f'loss = {loss:.4f}')
print(f'Macro-F1 = {f1[0]:.4f}')
# print(f'Micro-F1 = {f1[1]:.4f}')
# print(f'Weighted-F1 = {f1[2]:.4f}')
def save_model(self):
print('Saving model...')
if self.task_name == 'all':
filename = f'./save/models/{self.task_name}_{self.model_name}_{self.best_test_f1_m[0]}_seed{self.seed}.pt'
else:
filename = f'./save/models/{self.task_name}_{self.model_name}_{self.best_test_f1}_seed{self.seed}.pt'
save(copy.deepcopy(self.model.state_dict()), filename)