-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtrainer.py
215 lines (178 loc) · 7.87 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
import torch
import numpy as np
def fit(train_loader, val_loader, model, loss_fn, optimizer, scheduler, n_epochs, log_interval, metrics=[],
start_epoch=0, train_hist=None, val_hist=None, ckpter=None, logging=None):
"""
fit model and test model
:param train_loader:
:param val_loader:
:param model:
:param loss_fn: loss function
:param optimizer:
:param scheduler:
:param n_epochs: total epochs
:param log_interval: print message every log_interval steps
:param metrics: Accuracy or Non-zero triplets.
:param start_epoch:
:return: None
"""
for epoch in range(0, start_epoch):
scheduler.step()
for epoch in range(start_epoch + 1, n_epochs + 1):
scheduler.step()
# train stage
train_loss, metrics = train_epoch(train_loader, model, loss_fn, optimizer, log_interval, metrics)
train_logs = dict()
train_logs['loss'] = train_loss
for metric in metrics:
train_logs[metric.name()] = metric.value()
if train_hist is not None:
train_hist.add(logs=train_logs, epoch=epoch)
# message = 'Epoch: {}/{}. Train set: Average loss: {:.4f}.'.format(epoch + 1, n_epochs, train_loss)
# for metric in metrics:
# message += '\t{}: {}'.format(metric.name(), metric.value())
# test stage
if type(val_loader) is dict:
for key in val_loader.keys():
val_loss, metrics = test_epoch(val_loader[key], model, loss_fn, metrics)
val_loss /= len(val_loader[key])
val_logs = dict()
val_logs['loss'] = val_loss
for metric in metrics:
val_logs[metric.name()] = metric.value()
if val_hist is not None:
val_hist[key].add(logs=val_logs, epoch=epoch)
if val_hist is not None:
train_hist.clear()
train_hist.plot()
for key in val_loader.keys():
val_hist[key].plot()
if logging is not None:
logging.info('Epoch{:04d}, {:15}, {}'.format(epoch, train_hist.name, str(train_hist.recent)))
for key in val_loader.keys():
logging.info('Epoch{:04d}, {:15}, {}'.format(epoch, val_hist[key].name, str(val_hist[key].recent)))
if ckpter is not None:
ckpter.check_on(epoch=epoch, monitor='acc', loss_acc=val_hist['bc'].recent)
else:
val_loss, metrics = test_epoch(val_loader, model, loss_fn, metrics)
val_loss /= len(val_loader)
val_logs = dict()
val_logs['loss'] = val_loss
for metric in metrics:
val_logs[metric.name()] = metric.value()
if val_hist is not None:
val_hist.add(logs=val_logs, epoch=epoch)
if val_hist is not None:
train_hist.clear()
train_hist.plot()
val_hist.plot()
if logging is not None:
logging.info('Epoch{:04d}, {:15}, {}'.format(epoch, train_hist.name, str(train_hist.recent)))
logging.info('Epoch{:04d}, {:15}, {}'.format(epoch, val_hist.name, str(val_hist.recent)))
if ckpter is not None:
ckpter.check_on(epoch=epoch, monitor='acc', loss_acc=val_hist.recent)
def train_epoch(train_loader, model, loss_fn, optimizer, log_interval, metrics):
for metric in metrics:
metric.reset()
model.train()
losses = []
total_loss = 0
for batch_idx, (data, target) in enumerate(train_loader):
target = target if len(target) > 0 else None
if not type(data) in (tuple, list):
data = (data,)
data = tuple(d.cuda() for d in data)
if target is not None:
target = target.cuda()
optimizer.zero_grad()
outputs = model(*data)
if type(outputs) not in (tuple, list):
outputs = (outputs,)
loss_inputs = outputs
if target is not None:
target = (target, )
loss_inputs += target
loss_outputs = loss_fn(*loss_inputs)
loss = loss_outputs[0] if type(loss_outputs) in (tuple, list) else loss_outputs
losses.append(loss.item())
total_loss += loss.item()
loss.backward()
optimizer.step()
for metric in metrics:
metric(outputs, target, loss_outputs)
if batch_idx % log_interval == 0:
message = 'Train: [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(batch_idx * len(data[0]), len(train_loader.dataset),
100 * batch_idx / len(train_loader), np.mean(losses))
for metric in metrics:
message += '\t{}: {}'.format(metric.name(), metric.value())
print(message)
losses = []
total_loss /= (batch_idx + 1)
return total_loss, metrics
def test_epoch(val_loader, model, loss_fn, metrics):
with torch.no_grad():
for metric in metrics:
metric.reset()
model.eval()
val_loss = 0
for batch_idx, (data, target) in enumerate(val_loader):
target = target if len(target) > 0 else None
if not type(data) in (tuple, list):
data = (data,)
data = tuple(d.cuda() for d in data)
if target is not None:
target = target.cuda()
outputs = model(*data)
if type(outputs) not in (tuple, list):
outputs = (outputs,)
loss_inputs = outputs
if target is not None:
target = (target,)
loss_inputs += target
loss_outputs = loss_fn(*loss_inputs)
loss = loss_outputs[0] if type(loss_outputs) in (tuple, list) else loss_outputs
val_loss += loss.item()
for metric in metrics:
metric(outputs, target, loss_outputs)
return val_loss, metrics
def multi_device_train_epoch(train_loader, model, loss_fn, optimizer, log_interval, metrics):
for metric in metrics:
metric.reset()
model.train()
losses = []
total_loss = 0
total_batch = float(len(train_loader['a'].dataset)) / 180.0 * float(len(train_loader['b'].dataset)) / 180.0
bc_batchs = float(len(train_loader['b'].dataset)) / 180.0
for batch_idx, data_A in enumerate(train_loader['a']):
for batch_idy, (data_B, data_C) in enumerate(zip(train_loader['b'], train_loader['c'])):
data = torch.cat((data_A[0], data_B[0], data_C[0]), dim=0)
target = torch.cat((data_A[1], data_B[1], data_C[1]), dim=0)
if not type(data) in (tuple, list):
data = (data,)
data = tuple(d.cuda() for d in data)
if target is not None:
target = target.cuda()
optimizer.zero_grad()
outputs = model(*data)
if type(outputs) not in (tuple, list):
outputs = (outputs,)
loss_inputs = outputs
if target is not None:
target = (target, )
loss_inputs += target
loss_outputs = loss_fn(*loss_inputs)
loss = loss_outputs[0] if type(loss_outputs) in (tuple, list) else loss_outputs
losses.append(loss.item())
total_loss += loss.item()
loss.backward()
optimizer.step()
for metric in metrics:
metric(outputs, target, loss_outputs)
cur_batch = batch_idx * bc_batchs + batch_idy
if cur_batch % log_interval == 0:
message = 'Train: [({:.0f}%)]\tLoss: {:.6f}'.format(100.0 * cur_batch / total_batch,
np.mean(losses))
print(message)
losses = []
total_loss /= ((batch_idx + 1) * (batch_idy + 1))
return total_loss, metrics