-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyTTrain.py
More file actions
403 lines (312 loc) · 15.1 KB
/
Copy pathPyTTrain.py
File metadata and controls
403 lines (312 loc) · 15.1 KB
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
import torch
from torch._C import device, dtype
from torch.functional import Tensor
from torch.serialization import save
from torch.utils.data import DataLoader
from torch import optim
from pathlib import Path
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from PyTorchGTK.conf import SegIniReader, OptIniReader, IniReader
import optuna
import numpy as np
from datetime import datetime
from torch .utils import tensorboard as tb
class FitModel:
def __init__(self, dL : DataLoader = None,
dLV : DataLoader = None,
model = None,
optF : optim.Optimizer = optim.SGD,
nEpochs : int = 5,
lr : float = 0.5,
startEp : int = 0,
storPath : Path = Path('.'),
logdir : Path = Path('logs'),
weightsName : str = 'weights',
dev = None,
dtype = torch.float32,
conf : IniReader | None = None) -> None:
super().__init__()
self.rs = np.random.RandomState(np.random.randint(1000))
self.accuracy = {'Acc': lambda x , y: torch.Tensor(0.0) }
self.device = dev if not dev in [None, ''] else torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
self.dL = dL
self.dLV = dLV
self.model = model
self.optF = optF
self.nEpochs = nEpochs
self.stEpoch = startEp
self.ie = startEp
self.lr = lr
self.nCheck = 1
self.bestAcc = {'Acc': -np.Inf}
self.bestLoss = {'Acc': -np.Inf}
self._ep_lossCalc = torch.zeros(1, device=self.device, requires_grad=False)
self._ep_vAcc = torch.zeros(1, device=self.device, requires_grad=False)
self._ep_vLos = torch.zeros(1, device=self.device, requires_grad=False)
self._optimiser = None
self.storPath = str(storPath)
self.logdir = logdir
self.wName = weightsName
self.dtype = dtype
print("training on ", self.device)
def setLoaders(self, dL : DataLoader, dLV : DataLoader):
self.dL = dL
self.dLV = dLV
def setModel(self, model, optF : optim.Optimizer, nEpochs : int, lr : float):
self.model = model
self.optF = optF
self.nEpochs = nEpochs
self.lr = lr
def _prepTraining(self):
self.tbWriter = SummaryWriter(self.logdir)
self.bestAcc = {ik: -np.Inf for ik in self.accuracy.keys()}
self.bestLoss = {ik: -np.Inf for ik in self.accuracy.keys()}
self.lossFunc.to(self.device, dtype = self.dtype)
self.model.to(self.device, dtype = self.dtype)
# It must be after the model being sent to device.
self._optimiser = self.optF(self.model.parameters(), lr = self.lr)
"""
CHECK THAT IT WORKS !!
"""
if not self.loadPath == None and Path(self.loadPath).exists():
nend = self.nEpochs
self.load(self.loadPath)
# self._optimiser.param_groups[0]['lr'] = self.lr
self.nEpochs = nend if self.nEpochs < nend else self.nEpochs + nend
def prepBatch(self, b):
return b
def _ep_train(self):
self.model.train()
self._ep_lossCalc = torch.zeros(1, device=self.device, requires_grad=False)
self._ep_acc = {ik : torch.zeros(1, device=self.device, requires_grad=False) for ik in self.accuracy.keys()}
for b in tqdm(self.dL):
xb, yb = self.prepBatch(b)
xb = xb.to(self.device, dtype= self.dtype)
yb = yb.to(self.device, dtype= self.dtype)
self._optimiser.zero_grad()
preds = self.model(xb)
loss = self.lossFunc(preds, yb)
self._ep_lossCalc += loss.detach()
with torch.no_grad():
for iacc in self.accuracy.keys():
self._ep_acc[iacc] += self.accuracy[iacc](preds, yb).detach()
loss.backward()
self._optimiser.step()
# p.step()
self._ep_lossCalc /= len(self.dL)
for iacc in self.accuracy.keys():
self._ep_acc[iacc] /= len(self.dL)
return self._ep_lossCalc, self._ep_acc
def _ep_Val(self):
self._ep_vAcc = {ik : torch.zeros(1, device=self.device, requires_grad=False) for ik in self.accuracy.keys()}
self._ep_vLos = torch.zeros(1, device=self.device, requires_grad=False)
if len(self.dLV) == 0:
return self._ep_vLos, self._ep_vAcc
self.model.eval()
with torch.no_grad():
for b in tqdm(self.dLV):
xv, yv = self.prepBatch(b)
xv = xv.to(self.device)
yv = yv.to(self.device)
vPred = self.model(xv)
loss = self.lossFunc(vPred, yv)
self._ep_vLos += loss.detach()
for iacc in self.accuracy.keys():
self._ep_vAcc[iacc] += self.accuracy[iacc](vPred, yv).detach()
self._ep_vLos /= len(self.dLV)
for iacc in self.accuracy.keys():
self._ep_vAcc[iacc] /= len(self.dLV)
return self._ep_vLos, self._ep_vAcc
def _ep_end(self):
with torch.set_grad_enabled(False):
self._ep_lossCalc = self._ep_lossCalc.item()
self._ep_acc = {ik : iv.item() for ik, iv in self._ep_acc.items()}
self._ep_vLos = self._ep_vLos.item()
self._ep_vAcc = {ik : iv.item() for ik, iv in self._ep_vAcc.items()}
if self.ie % self.nCheck == 0:
print("Epoch ", self.ie, "L-train: ", self._ep_lossCalc, " Acc-train: ", self._ep_acc,
" L-val: ", self._ep_vLos, " Acc-val: ", self._ep_vAcc)
self.tbWriter.add_scalars('Loss', {'train': self._ep_lossCalc, 'val': self._ep_vLos}, self.ie)
for ik in self.accuracy:
self.tbWriter.add_scalars(ik, {'train': self._ep_acc[ik], 'val': self._ep_vAcc[ik]}, self.ie)
if self._ep_vAcc[ik] > self.bestAcc[ik]:
self.bestAcc[ik] = self._ep_vAcc[ik]
self.bestLoss[ik] = self._ep_lossCalc
self.save(Path(self.storPath) / (self.wName + '_' + ik + '.best'))
def _end_training(self):
with torch.set_grad_enabled(False):
self.save(Path(self.storPath) / (self.wName + '.last'))
self.tbWriter.flush()
self.tbWriter.close()
def lossFunc(self, x : Tensor, targ : Tensor) -> Tensor:
return torch.sum(((x - targ)^2).view(-1))
def fitModel(self, loadPath : str = None):
self.loadPath = loadPath
self._prepTraining()
for self.ie in range(self.stEpoch, self.nEpochs):
self._ep_train()
self._ep_Val()
self._ep_end()
self._end_training()
def load(self, fpath : Path) -> None:
saved = torch.load(fpath, map_location=self.device)
self.model.load_state_dict(saved['model_state_dict'])
self.nEpochs = saved['nEpochs']
self.stEpoch = saved['iEpoch'] + 1
self.ie = self.stEpoch
self._optimiser.load_state_dict(saved['opt_state_dict'])
self.bestAcc = saved['Acc']
self.bestLoss = saved['Loss']
def save(self, fpath : Path) -> None:
torch.save({
'nEpochs': self.nEpochs,
'iEpoch': self.ie,
'opt_state_dict': self._optimiser.state_dict(),
'model_state_dict': self.model.state_dict(),
'Acc': self.bestAcc,
'Loss': self.bestLoss
}, fpath)
class FitModelMixedPrec(FitModel):
def __init__(self, dL : DataLoader = None,
dLV : DataLoader = None,
model = None,
optF : optim.Optimizer = optim.SGD,
nEpochs : int = 5,
lr : float = 0.5,
startEp : int = 0,
storPath : Path = Path('.'),
logdir : Path = Path('logs'),
weightsName : str = 'weights',
dev = None,
dtype = torch.float32,
conf : IniReader | None = None) -> None:
super().__init__(dL=dL, dLV=dLV, model=model, optF=optF, nEpochs=nEpochs, lr=lr, startEp=startEp, storPath=storPath, logdir=logdir, weightsName=weightsName, dev=dev, dtype=dtype)
self.scaler = torch.cuda.amp.GradScaler()
def _ep_train(self):
self.model.train()
self._ep_lossCalc = torch.zeros(1, device=self.device, requires_grad=False)
self._ep_acc = {ik : torch.zeros(1, device=self.device, requires_grad=False) for ik in self.accuracy.keys()}
for b in tqdm(self.dL):
xb, yb = self.prepBatch(b)
xb = xb.to(self.device, dtype= self.dtype)
yb = yb.to(self.device, dtype= self.dtype)
self._optimiser.zero_grad()
with torch.cuda.amp.autocast():
preds = self.model(xb)
loss = self.lossFunc(preds, yb)
self._ep_lossCalc += loss.detach()
with torch.no_grad():
for iacc in self.accuracy.keys():
self._ep_acc[iacc] += self.accuracy[iacc](preds, yb).detach()
self.scaler.scale(loss).backward()
self.scaler.step(self._optimiser)
self.scaler.update()
self._ep_lossCalc /= len(self.dL)
for iacc in self.accuracy.keys():
self._ep_acc[iacc] /= len(self.dL)
return self._ep_lossCalc, self._ep_acc
from typing import Any
class OptimModel(object):
def __init__(self, fitClass, conf : OptIniReader) -> None:
self.conf = conf
# Initialize the stepping process
self.conf.__iter__()
self.fitClass = fitClass
self.dLoaderVal = None
self.dataPath = Path(self.conf['DATASET']['root'])
self.resFolder = self.dataPath / self.conf['DATASET']['store'] / ('res_' + self.conf['GENERAL']['name_id'])
if not (self.dataPath / self.conf['DATASET']['store']).exists():
(self.dataPath / self.conf['DATASET']['store']).mkdir()
if not self.resFolder.exists():
self.resFolder.mkdir()
self.current_time = datetime.now().strftime('%b%d-%H-%M-%S')
self.logsFold = self.resFolder / ('logs' + self.current_time)
if not self.logsFold.exists(): self.logsFold.mkdir()
def optimise(self, trial):
self.trial = trial
self.conf.trial = self.trial
self.conf.__next__()
icID = self.conf.getItId().replace('_', '-')
dl, dlV = self.conf.prepObject('DATASET')
device = self.conf['GENERAL']['device'] if not self.conf['GENERAL']['device'] in [None, ''] else torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
bSize = self.conf['DATASET']['batch']
swloop = tb.writer.SummaryWriter(self.logsFold / icID)
swloop.add_text('parameters/' + icID, self.conf.itStr().replace('\n', '<br />'), 0)
self.acc2Check = iter(self.conf['TRAINING']['acc'].keys()).__next__()
try:
model = self.conf.getModel()
model.to(device=device)
except Exception:
print('cannot make a model')
raise optuna.exceptions.TrialPruned()
loss, acc = self.conf.prepObject('TRAINING')
opt = self.conf.getOptim()
self.conf.writeConfig(self.resFolder)
if 'learning_rate' in self.conf['TRAINING']:
lrate = self.conf['TRAINING']['learning_rate']
else:
lrz = self.conf['TRAINING']['learning_rate_z']
lrn = self.conf['TRAINING']['learning_rate_n']
lrate = pow(10,-lrz) * lrn
self.FM = self.fitClass(dl, dlV, model, optF = opt,
nEpochs = self.conf['TRAINING']['epochs'], lr = lrate,
storPath = self.resFolder / self.conf.getItId(), logdir = self.logsFold / (icID + '-plot'),
dtype = self.conf['MODEL']['data_type'], conf = self.conf )
self.FM.lossFunc = loss
self.FM.accuracy = acc
self._old_ep_end, self._old_prepTraining = self.FM._ep_end, self.FM._prepTraining
self.FM._ep_end, self.FM._prepTraining = self._ep_end, self._prepTraining
try:
self.FM.fitModel()
except Exception as ex:
if hasattr(self.FM, 'bestAcc'):
swloop.add_text('Result/' + icID, 'Acc: ' + str(self.FM.bestAcc) + ' Loss: ' + str(self.FM.bestLoss))
with open(str(self.dataPath / self.conf['DATASET']['store'] / (self.conf['GENERAL']['name_id'] + '_optstd.txt')), 'a') as fid:
fid.write(icID + ';' + self.current_time + ';' +
'Acc:' + str(self.FM.bestAcc) + ';Loss:' + str(self.FM.bestLoss) + ';' +
self.conf.itStr().replace('\n', ';') +
'\n')
swloop.flush()
swloop.close()
dl.dataset.__del__()
dlV.dataset.__del__()
dl, dlV = [], []
model = []
opt = []
if type(ex) == optuna.exceptions.TrialPruned:
raise ex
if hasattr(self.FM, 'bestAcc'):
return self.FM.bestAcc[self.acc2Check]
elif hasattr(self.FM, '_ep_vAcc'):
return self.FM._ep_vAcc[self.acc2Check]
else:
return 0.
with open(str(self.dataPath / self.conf['DATASET']['store'] / (self.conf['GENERAL']['name_id'] + '_optstd.txt')), 'a') as fid:
fid.write(icID + ';' + self.current_time + ';' +
'Acc:' + str(self.FM.bestAcc) + ';Loss:' + str(self.FM.bestLoss) + ';' +
self.conf.itStr().replace('\n', ';') +
'\n')
swloop.add_text('Result/' + icID, 'Acc: ' + str(self.FM.bestAcc) + ' Loss: ' + str(self.FM.bestLoss))
swloop.flush()
swloop.close()
dl.dataset.__del__()
dlV.dataset.__del__()
dl, dlV = [], []
model = []
opt = []
return self.FM.bestAcc[self.acc2Check]
def _ep_end(self):
self._old_ep_end()
try:
self.trial.report(self.FM._ep_vAcc[self.acc2Check], self.FM.ie)
except Exception:
self.FM._end_training()
raise optuna.exceptions.TrialPruned()
if self.trial.should_prune():
self.FM._end_training()
raise optuna.exceptions.TrialPruned()
def _prepTraining(self):
torch.manual_seed(self.conf['GENERAL']['rand_seed'])
self.rs = np.random.RandomState(self.conf['GENERAL']['rand_seed'])
return self._old_prepTraining()