-
Notifications
You must be signed in to change notification settings - Fork 0
/
UniversalTorchModelTrainer.py
1533 lines (1308 loc) · 63.7 KB
/
UniversalTorchModelTrainer.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# UniversalTorchModelTrainer.py (2024)
# (included own DataLoader for constant Data)
import torch as tt
from torch.utils.data import DataLoader # TensorDataset
# from torch.nn.parallel import DataParallel # Multi-GPU (new)
# from torch.cuda.amp import autocast, GradScaler
from Cos2MinTorchFunctionOptimizer import ElraOptimizer # ELRA_class.py (tbd 2024)
from time import time as time_time
# from os import path # remove, replace, (only path.isfile)
# import glob, pickle, copy
from math import inf # isnan
from DataLoaderFast import DataLdrFast
# class DataLdrFast: was here
class PandasDataFrame:
def __init__(self):
self.losses = []
self.batches = []
self.epochs = []
self.types = []
self.steps = []
self.f_calls = []
self.g_calls = []
return
def AppendFrame(self, loss:float, _bt, ep:int, tstr:str, stp:int, fs:int, gs:int) -> None:
self.losses.append(loss)
self.batches.append(None)
self.epochs.append(ep)
self.types.append(tstr)
self.steps.append(stp)
self.f_calls.append(fs)
self.g_calls.append(gs)
return
def ExtendFrame(self, epoch_losses:list[float], epoch_batches:list[int], ep:int, _tstr:str, stp:int, fs:int, gs:int) -> None:
self.losses.extend(epoch_losses)
self.batches.extend(epoch_batches)
self.epochs.extend(len(epoch_losses) * [ep])
self.types.extend(len(epoch_losses) * ["batch"]) # _tstr
self.steps.extend(stp)
self.f_calls.extend(fs)
self.g_calls.extend(gs)
return
def ReturnFrame(self):
return self.losses, self.batches, self.epochs, self.types, self.steps, self.f_calls, self.g_calls
def CopyLgsFile() -> None:
"backup file once per epoch"
from shutil import copyfile
from os.path import isfile
fn: str = "state_lgs.txt"
if isfile(fn):
copyfile(fn, "epoch_lgs.txt")
def GetGradMax(model: tt.nn.Module) -> float:
"inf-norm of gradients"
# if (model is None): return -1.0
nrm: tt.Tensor = tt.zeros(1, device=next(model.parameters()).device)
for param in model.parameters():
if (param.grad.data is not None):
nrm = tt.max(nrm, tt.linalg.norm(param.grad.data.view(-1), ord=inf)) # max(abs(x))
return nrm.item()
def GetParamxMax(model: tt.nn.Module, device) -> tuple[float, float]:
"inf-norm of x (param)"
if (model is None): return -1.0
nrm2: tt.Tensor = tt.zeros(1, device=device)
nrmM: tt.Tensor = tt.zeros(1, device=device)
for param in model.parameters():
pdv = param.data.view(-1)
nrm2 += tt.square(tt.linalg.norm(pdv, ord=2.0))
nrmM = tt.max(nrmM, tt.linalg.norm(pdv, ord=inf)) # max(abs(x))
return tt.sqrt(nrm2).item(), nrmM.item()
#def FreezeBatchNorm(model: tt.nn.Module) -> None:
# "unused", # model = ResNet50()
# for m in model.modules():
# if isinstance(m, tt.nn.BatchNorm2d):
# m.eval()
# return
def LimitBatchNorm(model: tt.nn.Module, mean_max: float) -> None:
"Limit BatchNorm"
c: int = 0
i: int = 0
e: int = 0
maxn: float = 0.0
# assert(mean_max > 0.0), "positive"
for m in model.modules():
if isinstance(m, tt.nn.BatchNorm2d):
mn: float = tt.linalg.vector_norm(m.running_mean, ord=inf).item()
if (mn < 1e38): maxn = max(mn, maxn) # nan/inf issue
else: e += 1
if (mn > mean_max) and (mean_max >= 1.0):
mi, ma = m.running_mean.min().item(), m.running_mean.max().item()
vmin, vmax = m.running_var.min().item(), m.running_var.max().item()
c += 1
tt.clamp(m.running_mean, min=-mean_max, max=mean_max, out=m.running_mean)
print("BNL(%d,%.3g<%.3g,%.3g<%.3g)" % (i, mi,ma, vmin,vmax), end=" ")
else:
if (mn > 100.0) and (mean_max < 1.0): print("[%d,%.2g]" % (i, mn), end="")
i += 1
if (mean_max < 1.0) or (c > 0): print("LimitBatchNorm(%d/%d, n<%.3g, e=%d)" % (c, i, maxn, e))
return
def ExportBatchNorm(model: tt.nn.Module) -> list[tt.Tensor]:
"Export BatchNorm to Tensor-List"
c: int = 0
bnl = []
for m in model.modules():
if isinstance(m, tt.nn.BatchNorm2d):
c += len(m.running_mean)
bnl.append(m.running_mean.clone())
bnl.append(m.running_var.clone())
print("ExportBatchNorm(lay=%d, nums=%d)" % (len(bnl), c * 2))
return bnl
def ImportBatchNorm(model: tt.nn.Module, bn_list) -> None:
"Import BatchNorm from Tensor-List"
if (bn_list is None) or (len(bn_list) < 1):
for m in model.modules():
if isinstance(m, tt.nn.BatchNorm2d):
m.reset_running_stats()
else:
j: int = 0
for m in model.modules():
if isinstance(m, tt.nn.BatchNorm2d):
assert(len(m.running_mean) == len(bn_list[j])), "wrong Tensor size"
m.running_mean = bn_list[j + 0].clone()
m.running_var = bn_list[j + 1].clone()
j += 2
assert(len(bn_list) == j), "wrong list size"
return
#def ResetBatchNorm(model: tt.nn.Module) -> None:
# "Reset BatchNorm (recover from NaN)"
# i, j = 0, 0
# for m in model.modules():
# if isinstance(m, tt.nn.BatchNorm2d):
# print("BN(%d:%d,mn=%.6f,vn=%.6f), " % (j, len(m.running_mean), m.running_mean.norm().item(), m.running_var.norm().item()), end="")
# m.reset_running_stats()
# j += 1
# i += 1
# print(" BN.done=%d/%d" % (j, i))
# # net.load_state_dict(copy_net.state_dict())
#@tt.no_grad()
#def get_wd_params(model: tt.nn.Module) -> None:
# "unused"
# # Parameters must have a defined order.
# # No sets or dictionary iterations.
# # See https://pytorch.org/docs/stable/optim.html#base-class
# # Parameters for weight decay.
# # all_params = tuple(model.parameters())
# i, j = 0, 0
# wd_params = [] # list()
# for m in model.modules():
# if isinstance( m, (
# tt.nn.Linear,
# tt.nn.Conv1d, tt.nn.Conv2d, tt.nn.Conv3d,
# tt.nn.ConvTranspose1d, tt.nn.ConvTranspose2d, tt.nn.ConvTranspose3d,
# ),
# ):
# # wd_params.append(m.weight)
# j += 1
# i += 1
# print("(WeightDecay: %d/%d)" % (j, i))
# return
def SetParam(model, par: tt.Tensor) -> int:
"x-tensor into model"
assert(len(par) > 0), "empty Tensor"
model.train() # needed if net uses BatchNorm
# normalisation layers use per-batch statistics + (activates Dropout layers)
s = e = 0
for p in model.parameters():
e += tt.numel(p)
p.data = tt.reshape(par[s:e], p.size()).to(p.device, p.data.dtype)
s = e
return e # n=dim
def ParamLoad(model, fn:str="", nofilewarn:bool=True) -> bool:
"load x vector from disk" # TODO
n: int = sum(p.numel() for p in model.parameters())
assert(n >= 1), "empty model"
from os.path import isfile
if (len(fn) < 2):
fn = "startx_*.pt"
fn = fn.replace('*', str(int(n)))
if not isfile(fn):
if nofilewarn:
print("ParamLoad(n=%d:%s)=NoFile." % (n, fn))
return False
# tt.load(model, 'path')
par: tt.Tensor = tt.load(fn, weights_only=True) # model.load_state_dict()
assert(len(par) == n), "wrong dimension"
print("########################################")
SetParam(model, par)
pn: float = tt.linalg.vector_norm(par).item()
print("## ParamLoad(n=%d,av=%.3e,n2=%.3e)=OK" % (n, tt.mean(par), pn))
print("########################################")
return True
def GetParam(model) -> tt.Tensor:
"model to x-tensor"
# params = []
# for p in model.parameters(): params.append( p.data.view(-1) )
params = [param.data.view(-1) for param in model.parameters()]
return tt.cat(params)
def ParamSave(model, fn:str="") -> bool:
"store x vector on disk" # tested
if (model is None):
print("Warn:ParamSave(model=None), skip!")
return False
# tt.save(model, 'path')
n: int = sum(p.numel() for p in model.parameters())
# for p in model.parameters(): n += tt.numel(p)
assert(n >= 1), "empty model"
from os.path import isfile
if (len(fn) < 2):
fn = "lastx_*.pt"
fn = fn.replace('*', str(int(n)))
# if (path.isfile(fn)): print("ParamSave.overwrite(%s)" % fn)
par: tt.Tensor = GetParam(model)
tt.save(par, fn)
pn: float = tt.linalg.vector_norm(par).item()
print("ParamSave(%s,av=%.3e,n2=%.3e)=OK" % (fn, tt.mean(par), pn))
return isfile(fn)
class MyGradScaler:
"private GradScaler"
def __init__(self, init_scale: float = 2.0**15, enabled:bool = True) -> None:
self.good_cnt: int = 0
self.dead_cnt: int = 0
self.maxscale: float = 1.0
self.scaling: float = float(init_scale)
assert(self.scaling >= 1.0), "positive (1..1e6)"
self.inv_scaling: float = 1.0 / self.scaling
assert(enabled), "off = not implemented now"
# self.enabled: bool = enabled
def get_scale(self) -> float:
"get actual scaling"
return self.scaling
def UpdateGradNorm(self, absmax: float) -> float:
"update scale and return actual value"
# absmax: float = GetGradMax(model)
if (absmax < 1e999): # isinf+isnan
if (absmax > self.maxscale):
self.maxscale = absmax
if (self.good_cnt < 100):
self.good_cnt += 1
return self.scaling # default way
else:
ret: float = self.scaling
# print("UpdateGradNorm.upd, max=%.3g, scl=%.3g" % (self.maxscale, self.scaling))
if (self.maxscale <= 65504 * 0.3):
self.scaling = min(2.0 * self.scaling, 65504.0) # float16max=65504
self.inv_scaling = 1.0 / self.scaling
self.maxscale *= 0.5 # not perfect
self.good_cnt = 0
return ret
else:
print("UpdateGradNorm.Down, max=%.3g:%.3g, scl=%.3g" % (self.maxscale, absmax, self.scaling))
self.scaling *= 0.5
self.inv_scaling *= 2.0
assert(self.scaling > 0.1), "zero scaling"
self.maxscale = (self.maxscale * 0.5) if (self.maxscale < inf) else 0.0
self.good_cnt = 0
self.dead_cnt += 1
return 0.0 # inf/nan in gradient
model_boost = None
last_x: tt.Tensor = None # debug only
diff_sum: tt.Tensor = None # debug only
elra_solver: bool = True
dog_solver: bool = None # DoG+LDoG
dog_averager = None # DoG+LDoG
# Creates a GradScaler once at the beginning of training.
scaler = None # GradScaler()
def CheckElraSolver(optim) -> bool:
"verify ELRA class"
global elra_solver, dog_solver
assert(optim is not None), "input <> None"
elra_solver = hasattr(optim, 'GetParamAvg')
name: str = str( type (optim).__name__ )
print("ELRA:", elra_solver, ", name=", name) # ElraOptimizer
if (name.find('DoG') >= 0):
dog_solver = True
return elra_solver
def Interpolx(model, cost_function, dl:DataLoader) -> None:
"debug: valley cut loss"
global last_x
x0 = GetParam(model)
if (last_x is None) or (dl is None):
last_x = x0
return
print("Interpolx:")
last, fvl = 0.0, []
for i in range(101):
f1: float = i * 0.01
par: tt.Tensor = last_x * f1 + x0 * (1.0 - f1)
SetParam(model, par)
loss, _, _, _ = full_batch_loss(model, None, dl, cost_function, x0.device)
d = 0.0 if (not i) else loss-last
fvl.append(loss)
last = loss
print("%.2f %.6f %.4e," % (f1, loss, d), end="")
SetParam(model, x0) # restore
last_x = x0 # double usage (debug only)
print(".done(%.6f<%.6f<%.6f)." % (min(fvl),sum(fvl)/len(fvl),max(fvl)), flush=True)
def WriteDsHist(reset:bool, log) -> None:
"debug: histogram of epoch movement exponents"
global diff_sum
if (log is None) or (diff_sum is None):
return
if (not log.closed):
import numpy as np
_ , e2 = tt.frexp(diff_sum) # get (int) float^2-exponents
# print("HIST(",np.min(e2),"<",np.max(e2),"),",np.mean(e2))
# print("P(1,50,99):",np.percentile(e2, 1),"<",np.percentile(e2, 50),"<",np.percentile(e2, 99))
# #np.median(e2, axis=None, overwrite_input=False)
e2min, e2max = int(tt.min(e2)), int(tt.max(e2))
bins: int = 1 + int(e2max - e2min)
log.write("#hist=%d,s=%.3g,%.3g<%.3g,%d<%d," %
(len(diff_sum),tt.sum(diff_sum), tt.min(diff_sum),tt.max(diff_sum), e2min, e2max))
hist,_ = np.histogram(e2.numpy(), bins=bins, range=(e2min, e2max), density=False)
# print(e2min, e2max, bins, hist);exit()
log.write("%s\n" % str(hist))
log.flush()
if (reset):
diff_sum = None
return
def WriteDominant(x: tt.Tensor, t:int = -1, log=None) -> int:
"debug: plot strong components"
global last_x, diff_sum
if (x is None) or (len(x) < 1): return 0
cpu = tt.device('cpu')
# xmin, xmax = tt.min(x).item(), tt.max(x).item()
# x = x.to(dtype=float)
xsum, xnrm = tt.sum(x).item(), tt.norm(x).item()
if (log is None):
lf,fc = open("path_dom.dat", "a"), True
else:
lf,fc = log, False
if (lf is None) or (lf.closed):
print("WriteDominant(t=%d,n=%d):Error=fopen!" % (t,len(x)))
return -1
if (last_x is None):
print("Dom(0/%d, xs=%.3g,xn=%.3g, init)." % (len(x), xsum,xnrm))
lf.write("##NEW,dim=%d,s=%.6g,n=%.6g\n" % (len(x), xsum, xnrm))
if (fc): lf.close()
last_x = x.clone()
return 0
assert(len(x) == len(last_x)), "length(x_Tensors) differs"
d, last_x = (x - last_x), x
gmin, gmax = tt.min(d).item(), tt.max(d).item()
gsum, gnrm = tt.sum(d).item(), tt.norm(d).item()
th: float = max(abs(gmin), abs(gmax)) * 0.3
db = (tt.abs(d) > th) # [bool]
nc: int = tt.sum(db)
d, db = d.to(cpu), db.cpu()
if (diff_sum is None):
diff_sum = d*d
else:
diff_sum += d*d
# print("Dom(%d/%d, xs=%.3g,xn=%.3g, ds=%.3g,dn=%.3g)." % (nc,len(x), xsum,xnrm, gsum,gnrm))
lf.write("#t=%d,%d/%d, xs=%.3g,xn=%.3g, ds=%.3g,dn=%.3g, th=%.3g\n" %
(t,nc,len(x), xsum,xnrm, gsum,gnrm, th))
lf.write("-1,%.6g,%.6g\n" % (xsum, xnrm))
if (gnrm > 0.0):
x1 = x.to(cpu)
for i in range(len(x)):
if (db[i]):
lf.write("%d,%.6g,%.3g\n" % (i, x1[i], d[i]))
if (fc): lf.close()
return 1
# Device-Cache (new class) ..
utmt_DS: DataLdrFast = DataLdrFast()
utmt_TS: DataLdrFast = DataLdrFast()
def StatListStr(lst: list[float]) -> str:
n : int = len(lst)
if (n < 2):
return ("(len=%d<2!)" % n)
prv : float = lst[0]
sum_ad : float = 0.0
for i in range(1,n):
val : float = lst[i]
sum_ad += abs(val - prv)
prv = val
val = -9.9 if (0.0==sum_ad) else (lst[n-1]-lst[0]) /sum_ad
# print(len(lst),min(lst),sum(lst)/n,max(lst),val); exit(0)
return ("(%d:%.3g<%.3g<%.3g:%.3f)" % (len(lst),min(lst),sum(lst)/n,max(lst),val))
def NormalEval_Labels(model, model2, data_loader:DataLoader, cost_func, device, labels) -> tuple[int,int, float,float]:
"full batch via normal DataLoader + single Label tensor (half D2H-copy)"
i: int = 0
prints: bool = False
img_type: tt.dtype = tt.get_default_dtype() # tt.float32
corr1 = tt.zeros(1, dtype=tt.int64).to(device)
corr2i: int = 0
loss1 = tt.zeros(1, dtype=tt.float32).to(device)
loss2 = 0.0
count: int = len(data_loader.dataset)
t: float = time_time()
bs = data1 = None
# print("NormalEval_Labels ===== ", len(labels), count)
assert(len(labels) == count), "sample counts differ"
pos: int = 0
targets: tt.Tensor = labels.to(device) # 0..5 MB (int16 here)
targets = targets.to(dtype=tt.int64) # optional uint8 (if classes<256)
if (model2 is None):
with tt.no_grad():
for data0, target0 in data_loader:
data = data1
data1 = data0.to(device, img_type, non_blocking=True)
if (bs is None):
bs = len(target0)
continue
pos2: int = pos + bs
target = targets[pos : pos2]
pos = pos2
# ResNet50
# with autocast(device_type='cuda', dtype=tt.float16): # autocasting.
output: tt.Tensor = model(data)
loss1 += cost_func(output, target) # float16
# test_loss += F.nll_loss(output, target, reduction="sum")
pred: tt.Tensor = output.max(1, keepdim=True)[1]
corr1 += pred.eq(target.view_as(pred)).sum()
i += 1
if not (i & 15) and ((time_time() - t) >= 120.0):
print("<2m:%d:%d>" % (i, count), end=" ", flush=True)
prints, t = True, time_time()
loss1 *= bs # len(target)
target = targets[pos : ]
if len(target): # tail
c1, l1 = single_eval(data1, target, model, cost_func)
corr1 += c1; loss1 += l1 * len(target)
else:
corr2 = tt.zeros(1, dtype=tt.int64).to(device)
loss2 = tt.zeros(1, dtype=tt.float32).to(device)
with tt.no_grad():
for data0, target0 in data_loader:
data = data1
data1 = data0.to(device, img_type, non_blocking=True)
if (bs is None):
bs = len(target0)
continue
pos2: int = pos + bs
target = targets[pos : pos2]
pos = pos2
output: tt.Tensor = model(data)
loss1 += cost_func(output, target)
pred: tt.Tensor = output.max(1, keepdim=True)[1]
corr1 += pred.eq(target.view_as(pred)).sum()
# + model2
output = model2(data)
pred: tt.Tensor = output.max(1, keepdim=True)[1]
corr2 += pred.eq(target.view_as(pred)).sum()
loss2 += cost_func(output, target) # len(target)
i += 1
if not (i & 15) and ((time_time() - t) >= 120.0):
print("<2m:%d:%d>" % (i, count), end=" ", flush=True)
prints, t = True, time_time()
loss1 *= bs # len(target)
loss2 *= bs # len(target)
target = targets[pos : ]
if len(target): # tail
c1, l1 = single_eval(data1, target, model, cost_func)
corr1 += c1; loss1 += l1 * len(target)
c1, l1 = single_eval(data1, target, model2, cost_func)
corr2 += c1; loss2 += l1 * len(target)
corr2i, loss2 = corr2.item(), loss2.item()
if (prints):
avg: float = -1.0 if (count < 1) else loss1.item() / count
print(".\n..FBL(%.4g+%.3g-%d)" % (avg, -1.0, 0), end=" ")
# print("NormalEval, inf-errors=", err, count)
return corr1.item(), corr2i, loss1.item(), loss2
def NormalEval(model, model2, data_loader:DataLoader, cost_func, device) -> tuple[int,int, float,float]:
"full batch via normal DataLoader"
i: int = 0
prints: bool = False
img_type: tt.dtype = tt.get_default_dtype() # tt.float32
corr1 = tt.zeros(1, dtype=tt.int64).to(device)
corr2i: int = 0
loss1 = tt.zeros(1, dtype=tt.float32).to(device)
loss2 = 0.0
count: int = len(data_loader.dataset)
t: float = time_time()
bs = None
data1 = target1 = None
if (model2 is None):
with tt.no_grad():
for data0, target0 in data_loader:
data, target = data1, target1
data1, target1 = data0.to(device, img_type, non_blocking=True), \
target0.to(device, non_blocking=True)
if (bs is None):
bs = len(target0)
continue
# ResNet50
# with autocast(device_type='cuda', dtype=tt.float16): # autocasting.
output: tt.Tensor = model(data)
loss1 += cost_func(output, target) # float16
# test_loss += F.nll_loss(output, target, reduction="sum")
pred: tt.Tensor = output.max(1, keepdim=True)[1]
corr1 += pred.eq(target.view_as(pred)).sum()
i += 1
if not (i & 15) and ((time_time() - t) >= 120.0):
print("<2m:%d:%d>" % (i, count), end=" ", flush=True)
prints, t = True, time_time()
loss1 *= bs # len(target)
if len(target1): # tail
c1, l1 = single_eval(data1, target1, model, cost_func)
corr1 += c1; loss1 += l1 * len(target1)
else:
corr2 = tt.zeros(1, dtype=tt.int64).to(device)
loss2 = tt.zeros(1, dtype=tt.float32).to(device)
with tt.no_grad():
for data0, target0 in data_loader:
data, target = data1, target1
data1, target1 = data0.to(device, img_type, non_blocking=True), \
target0.to(device, non_blocking=True)
if (bs is None):
bs = len(target0)
continue
output: tt.Tensor = model(data)
loss1 += cost_func(output, target)
pred: tt.Tensor = output.max(1, keepdim=True)[1]
corr1 += pred.eq(target.view_as(pred)).sum()
# loss1 += cf # len(target)
# + model2
output = model2(data)
pred: tt.Tensor = output.max(1, keepdim=True)[1]
corr2 += pred.eq(target.view_as(pred)).sum()
loss2 += cost_func(output, target) # len(target)
i += 1
if not (i & 15) and ((time_time() - t) >= 120.0):
print("<2m:%d:%d>" % (i, count), end=" ", flush=True)
prints, t = True, time_time()
loss1 *= bs # len(target)
loss2 *= bs # len(target)
if len(target1): # tail
c1, l1 = single_eval(data1, target1, model, cost_func)
corr1 += c1; loss1 += l1 * len(target1)
c1, l1 = single_eval(data1, target1, model2, cost_func)
corr2 += c1; loss2 += l1 * len(target1)
corr2i, loss2 = corr2.item(), loss2.item()
if (prints):
avg: float = -1.0 if (count < 1) else loss1.item() / count
print(".\n..FBL(%.4g+%.3g-%d)" % (avg, -1.0, 0), end=" ")
# print("NormalEval, inf-errors=", err, count)
return corr1.item(), corr2i, loss1.item(), loss2
def FastCacheEval(model, model2, fdl: DataLdrFast, cost_function, device) -> tuple[int,int, float,float]:
"full batch from fast data-loader-cache"
count: int = fdl.dlf_samples # len(data_loader.dataset)
assert(count > 0), "DataLdrFast available"
assert(len(fdl.dlf_Images) > 0), "DataLdrFast, no samples"
n: int = sum(p.numel() for p in model.parameters())
bsize: int = 1024 if (n != 23910152) else 16 # 24mio=Resnet50=TIN
if (n == 11271432): bsize = 64 # TIN-RN18
loss1 = tt.zeros(1, dtype=tt.float32).to(device)
loss2: float = 0.0
corr1: tt.Tensor = tt.zeros(1, dtype=tt.int64).to(device)
corr2i: int = 0
fdl.DirectBatch(-1) # rewind
if (model2 is None):
with tt.no_grad():
# for data, target in utmt_TS.dlf_listXY: # todo: iterator
while 1:
mbs, data, target = fdl.DirectBatch(bsize)
if (not mbs): break
output: tt.Tensor = model(data) # TIN crash here (OOM)
loss1 += cost_function(output, target) * mbs
# assert(cf < 1e30), "Mx1"
pred: tt.Tensor = output.max(1, keepdim=True)[1]
corr1 += pred.eq(target.view_as(pred)).sum() # ,int(utmt_TS_Xsize[i])
else:
corr2: tt.Tensor = tt.zeros(1, dtype=tt.int64).to(device)
loss2 = tt.zeros(1, dtype=tt.float32).to(device)
with tt.no_grad():
# for data, target in utmt_TS.dlf_listXY: # todo: iterator
while 1:
mbs, data, target = fdl.DirectBatch(bsize)
if (not mbs): break
output: tt.Tensor = model(data) # TIN crash here (OOM)
loss1 += cost_function(output, target) * mbs
# assert(cf < 1e30), "Mx2"
pred: tt.Tensor = output.max(1, keepdim=True)[1]
corr1 += pred.eq(target.view_as(pred)).sum()
output: tt.Tensor = model2(data)
pred: tt.Tensor = output.max(1, keepdim=True)[1]
corr2 += pred.eq(target.view_as(pred)).sum()
loss2 += cost_function(output, target) * len(target)
corr2i = corr2.item()
loss2 = loss2.item()
# print("FastCacheEval, inf-errors=", err, count)
fdl.dlf_EpochCount += 1 # Test
return corr1.item(), corr2i, loss1.item(), loss2
def TestEval(model, model2, test_loader:DataLoader, cost_function, device) -> tuple[float,float,float,float]:
"calc Accuracy + TestLoss over full test-dataset"
# model.eval() --
if (test_loader is None) or (len(test_loader.dataset) < 1):
return -1.0, -1.0
global utmt_TS
utmt_TS_samples: int = utmt_TS.dlf_samples
# only_lab: bool = utmt_TS.dlf_only_lab
test_loss: float = 0.0 # tt.zeros(1, dtype=tt.float32).to(device)
test_loss2: float = 0.0
count: int = len(test_loader.dataset)
dt: float = time_time()
if len(test_loader.dataset) != utmt_TS_samples or utmt_TS.dlf_only_lab: # slower
if utmt_TS.dlf_only_lab:
corr, corr2, test_loss, test_loss2 = NormalEval_Labels(
model, model2, test_loader, cost_function, device, utmt_TS.dlf_Labels)
else:
corr, corr2, test_loss, test_loss2 = NormalEval(
model, model2, test_loader, cost_function, device)
else: # tensors already in device-memory/GPU
corr, corr2, test_loss, test_loss2 = \
FastCacheEval(model, model2, utmt_TS, cost_function, device)
print("(%d)TL=%.3fs," % (-0, time_time() - dt), end=" ") # debug
if (count > 0):
s: float = 1.0 / float(count)
assert(corr > 0), "test accu > 0.0"
return corr * s, test_loss * s, corr2 * s, test_loss2 * s
return float('nan'), float('nan'), float('nan'), float('nan')
def FastenDataloader(train_data:DataLoader, test_data:DataLoader, num_classes:int, maxMB:int=800, device=tt.device('cpu')) -> None:
"Intial Load Dataset into CUDA/GPU for FullBatchOperation"
global utmt_TS, utmt_DS
dt: float = time_time()
if (maxMB <= 0) or (train_data is None): # or (str(device).find("cuda") < 0):
if (train_data is None):
utmt_TS.InitVectors()
utmt_DS.InitVectors()
else:
print("FastenDataloader(skip, dev=%s)." % (str(device)))
return # dont skip here, even 2x faster on CPU !
if 1: # bypass (cache) timm-DL to be faster
# classes: int = len(test_data.dataset.classes) if hasattr(test_data.dataset, "classes") else -1
print("FastenDataloader(%d+%d), cls=%d .." % (len(train_data.dataset), len(test_data.dataset), num_classes))
utmt_TS.Import_DataLoader(test_data, num_classes, is_train=False, maxMB=950, device=device)
if (utmt_TS.dlf_samples > 0): # both or none
utmt_DS.Import_DataLoader(train_data, num_classes, is_train=False, maxMB=1400, device=device) # DISABLE DS HERE
else: # for optim.SetClasses()
utmt_DS.dlf_init_mbs = DataLdrFast.EstimBatchSize(train_data)
utmt_DS.dlf_label_max = utmt_TS.dlf_label_max
dt = time_time() - dt
print("FastenDataloader(%d+%d), dt=%.3fs.\n" % (utmt_DS.dlf_samples, utmt_TS.dlf_samples, dt))
DataLdrFast.CheckPair(utmt_DS, utmt_TS) # FilePairConflicts
# print(utmt_DS.GetDsHash(), utmt_TS.GetDsHash()) #;exit() # debug
return
print("FastenDataloader(%d+%d)=SKIP.\n" % (len(train_data.dataset), len(test_data.dataset)))
return
def full_batch_loss(model, model2, data_loader:DataLoader, cost_function, device) -> tuple[float,float,float,float]:
"calc. full batch loss (over all train data), only for printing (no effect on solver)"
if (data_loader is None) or (len(data_loader.dataset) < 1):
return -1.0
global utmt_DS
i: int = 0
t0: float = time_time()
# dc: int = tt.cuda.device_count()
# accumulate loss over batches
total_loss: float = 0.0
total_loss2: float = 0.0
count: int = len(data_loader.dataset)
# print("full_batch_loss", utmt_DS.dlf_only_lab, utmt_DS.dlf_Labels)
if (utmt_DS.dlf_samples > 1): # fast - train
assert(len(data_loader.dataset) <= utmt_DS.dlf_samples) # shrinked < Gpu_DL
corr, corr2, total_loss, total_loss2 = \
FastCacheEval(model, model2, utmt_DS, cost_function, device)
i = 1
if (not i): # tensors not in device-memory/GPU
if utmt_DS.dlf_only_lab:
corr, corr2, total_loss, total_loss2 = NormalEval_Labels(
model, model2, data_loader, cost_function, device, utmt_DS.dlf_Labels)
else:
corr, corr2, total_loss, total_loss2 = \
NormalEval(model, model2, data_loader, cost_function, device)
# utmt_DS.dlf_EpochCount += 1 # Train
t0 = time_time() - t0
if (t0 > 50.0): # or (err > 0):
print("sec=%.0f/%.1f%%(%d), " % (t0, 100.0*count/len(data_loader.dataset),-0), end=" ")
# print(len(data_loader.dataset), len(data_loader)); exit() # [256..,last=96], 60000 235
if (count > 0):
s: float = 1.0 / float(count)
if (model2 is None):
return corr * s, float(total_loss) * s, -1.0, inf
else:
return corr * s, float(total_loss) * s, corr2 * s, float(total_loss2) * s
return float('nan'), float('nan'), float('nan'), float('nan')
# <2m:215:26784> /home/telematik/.venv/lib/python3.11/site-packages/torch/nn/modules/conv.py:456: UserWarning: Plan failed with a cudnnException: CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR: cudnnFinalize Descriptor Failed cudnn_status: CUDNN_STATUS_NOT_SUPPORTED (Triggered internally at ../aten/src/ATen/native/cudnn/Conv_v8.cpp:919.)
# return F.conv2d(input, weight, bias, self.stride,
booster_on: bool = False
# for combined_X() - to be removed here
#combiX_sum = combiX_wsum = None
#combi_fx_min, combi_fx_sum, combi_wsum = 0.0, 0.0, 0.0
#combi_cnt: int = 0
#def combined_X(model, fval:float) -> None:
# "test only: combined x (param) for late improvement" # to be replaced by GetParamAvg()
# return # debug only
# global combiX_sum, combiX_wsum, combi_fx_min, combi_fx_sum, combi_fx_min, combi_wsum, combi_cnt
# if (model is None): # reset
# combiX_sum, combiX_wsum, combi_cnt = None, None, 0
# return
#
# x: tt.Tensor = GetParam(model)
# if (len(x)>>20 > 20) and ((tt.cuda.get_device_properties(0).total_memory >> 30) < 11): # dim>20mio AND vram<15GB
# return # skip both for ResNet50(24mio)
#
# combi_cnt += 1
# if (combiX_sum is None): # first
# combiX_sum = x.clone()
# combi_fx_min, combi_fx_sum = fval, fval
# if (len(x)>>20 < 15) and (fval > 1e-9): # optional
# combi_wsum = 1.0 / fval
# combiX_wsum = x * combi_wsum
# else:
# combi_wsum = 0.0
# return
# combi_fx_min = min(combi_fx_min, fval)
# combi_fx_sum += fval
# combiX_sum += x
# if (len(x)>>20 < 15) and (fval > 1e-9): # skip for ResNet34(11mio)+ResNet50(24mio)
# combi_wsum += 1.0 / fval
# combiX_wsum += x * (1.0 / fval)
# return
def cosine(a: tt.Tensor, b: tt.Tensor) -> float:
"cosine between tensor pair (debug only)"
# return tt.nn.functional.cosine_similarity(a, b, dim=1, eps=1e-30)
assert(len(a) == len(b)), "dot-product dim-conflict"
d: float = tt.dot(a, b)
return 0.0 if (tt.abs(d) < 1e-6) else d / (tt.norm(a) * tt.norm(b))
def PrepareBoostModel(model:tt.nn.Module, device2, optim) -> tuple[tt.nn.Module,int,float]:
"internal init"
global model_boost
boost: bool = booster_on and elra_solver
if not boost: return None, 0, 0.0
bcnt, avg, avg_x = optim.GetParamAvg(True)
if (avg_x is None):
print("Warn:FBL.GetParamAvg(c=%d,f=%.3g), x=None, skip-boost!" % (bcnt, avg))
return None, 0, 0.0
model2: tt.nn.Module = model_boost
assert(model is not None), "need source model"
assert(model2 is not None), "need 2nd model"
if (device2 is not None): model2.to(device2)
ImportBatchNorm(model2, ExportBatchNorm(model)) # copy BN
SetParam(model2, avg_x)
# model2.eval() # optional (batch norm update)
return model2, bcnt, avg
def LossRatio(loss_trn:float, loss_val:float) -> float:
return loss_val/loss_trn if (loss_trn > 0.0) else loss_val-loss_trn
def combined_FBL(model, train_fast, test_data, cost_func, device, optim) -> tuple[float,float,float,float]:
"Calc 4 Loss+Accu f(x + boost) x2 (train + test)"
model2, bcnt, avg = PrepareBoostModel(model, None, optim)
# boost: bool = booster_on and elra_solver
assert len(train_fast) > 0, "empty dataset train"
assert len(test_data) > 0, "empty dataset test"
accu1t, loss1t, accu2t, loss2t = full_batch_loss(model, model2, train_fast, cost_func, device)
accu1v, loss1v, accu2v, loss2v = TestEval(model, model2, test_data, cost_func, device)
t2t: float = LossRatio(loss1t, loss1v)
print("*Train1 (%.3f%% %.6g), Test1 (%.3f%% %.6g), t2t=%.2g, n=%d" % (accu1t*100, loss1t, accu1v*100, loss1v, t2t, bcnt))
if (model2 is not None):
t2t = LossRatio(loss2t, loss2v)
print(" *Boost2 (%.3f%% %.6g), Test2 (%.3f%% %.6g), t2t=%.2g, AvLf=%.3g" % (accu2t*100, loss2t, accu2v*100, loss2v, t2t, avg))
optim.TellTrainBoostLoss(loss2t)
else:
accu2t = loss2t = accu2v = loss2v = -1.0
return accu1t, loss1t, accu2t, loss2t, accu1v, loss1v, accu2v, loss2v
smp_return: tuple = None
def thread_eval(x, y, model, cost_func) -> None:
"internal: threaded SMP/DDP loss"
global smp_return
output: tt.Tensor = model(x)
# loss = cost_func(output, y) # * len(y)
pred: tt.Tensor = output.max(1, keepdim=True)[1]
# corr = pred.eq(y.view_as(pred)).sum()
smp_return = (pred.eq(y.view_as(pred)).sum(), cost_func(output, y))
return
def single_eval(x, y, model, cost_func) -> None:
"internal: single loss+accu"
output: tt.Tensor = model(x)
# loss = cost_func(output, y) # * len(y)
pred: tt.Tensor = output.max(1, keepdim=True)[1]
# corr = pred.eq(y.view_as(pred)).sum()
return pred.eq(y.view_as(pred)).sum(), cost_func(output, y)
def calc_FBL_m2d2(model1, model2, data_loader, cost_func, device1, device2) -> tuple[float,float, float,float]:
"full-batch-eval for 2x model at 2 devices"
global smp_return
from threading import Thread
count: int = len(data_loader.dataset)
assert(count > 1), "empty dataset (FBL)"
img_type: tt.dtype = tt.get_default_dtype()
loss1 = tt.zeros(1, dtype=tt.float32).to(device1)
loss2 = tt.zeros(1, dtype=tt.float32).to(device2)
corr1 = tt.zeros(1, dtype=tt.int64).to(device1)
corr2 = tt.zeros(1, dtype=tt.int64).to(device2)
bs = None
smp_return = None # tuple(2)
with tt.no_grad():
for data0, target0 in data_loader:
x1, y1 = data0.to(device1, img_type, non_blocking=True), \
target0.to(device1, non_blocking=True)
x2, y2 = data0.to(device2, img_type, non_blocking=True), \
target0.to(device2, non_blocking=True)
if (bs is None):
bs = len(target0)
else:
if len(target0) != bs: break
smp_return = None # tuple(2)
th1 = Thread(target=thread_eval, args=(x2,y2, model2, cost_func))
th1.start() # ((((
output: tt.Tensor = model1(x1)
loss1 += cost_func(output, y1) # * len(target0)
pred: tt.Tensor = output.max(1, keepdim=True)[1]
corr1 += pred.eq(y1.view_as(pred)).sum()
th1.join(timeout=40.0) # 40s, ))))
# assert(smp_return is not None), "debug: calc_FBL_m2d2"
c2, l2 = smp_return
corr2 += c2
loss2 += l2
data0 = None
loss1 *= bs; loss2 *= bs
tlen: int = len(target0)
if tlen and tlen < bs:
c2, l2 = single_eval(x1,y1, model1, cost_func)
corr1 += c2; loss1 += l2 * tlen
c2, l2 = single_eval(x2,y2, model2, cost_func)
corr2 += c2; loss2 += l2 * tlen
smp_return = None
s: float = 1.0 / count
return corr2.item() * s, loss1.item() * s, corr2.item() * s, loss2.item() * s
def combined_FBL_smp(model, train_fast, test_data, cost_func, device, device2, optim) -> tuple[float,float,float,float]:
"parallel (SMP = 2 models on 2 GPUs) calc of FullBatchLoss for normal + boost"
model2, bcnt, avg = PrepareBoostModel(model, device2, optim)
dt: float = time_time()
if (model2 is not None):
print("combined_FBL_smp(%s + %s), <<<<<" % (str(device), str(device2)))
accu1t, loss1t, accu2t, loss2t = calc_FBL_m2d2(model, model2, train_fast, cost_func, device, device2)
accu1v, loss1v, accu2v, loss2v = calc_FBL_m2d2(model, model2, test_data, cost_func, device, device2)
dt = time_time() - dt
print("combined_FBL_smp(dt=%.2f) done. >>>>>" % dt)
print("*Train1 (%.3f%% %.6g), Test1 (%.3f%% %.6g), t2t=%.2g, n=%d" % (accu1t*100, loss1t, accu1v*100, loss1v, LossRatio(loss1t, loss1v), bcnt))
print(" *Boost2 (%.3f%% %.6g), Test2 (%.3f%% %.6g), t2t=%.2g, AvLf=%.3g" % (accu2t*100, loss2t, accu2v*100, loss2v, LossRatio(loss2t, loss2v), avg))
optim.TellTrainBoostLoss(loss2t)
else:
accu1t, loss1t, accu2t, loss2t = full_batch_loss(model, None, train_fast, cost_func, device)
accu1v, loss1v, accu2v, loss2v = TestEval(model, None, test_data, cost_func, device)
print("*Train1 (%.3f%% %.6g), Test1 (%.3f%% %.6g), t2t=%.2g, n=%d" % (accu1t*100, loss1t, accu1v*100, loss1v, LossRatio(loss1t, loss1v), bcnt))
accu2t = loss2t = accu2v = loss2v = -1.0
return accu1t, loss1t, accu2t, loss2t, accu1v, loss1v, accu2v, loss2v
class LossHistRb:
"ringbuffer for running average of loss history"
def __init__(self) -> None:
self.hist_loss = tt.zeros(128, dtype=tt.float32, device=tt.device('cpu'))
self.hist_lpos: int = 0
# self.hist_lsum: float = 0.0
return
def add_loss(self, loss: float) -> None:
# pos: int = self.hist_lpos & 127 # mod 128
# self.hist_lsum += loss - self.hist_loss[pos].item()
self.hist_loss[self.hist_lpos & 127] = loss
self.hist_lpos += 1
return
def get_mean_loss(self) -> float:
return tt.mean(self.hist_loss).item()
utmt_LossHist: LossHistRb = LossHistRb()
def CalcLossLimit(loss0: float) -> float:
"loss threshold for retrace"
return loss0 * 1.5 if (loss0 > 0.0) else (loss0 + 1.0) # optim.GetLossLimit()
def train_step_adam(X:tt.tensor, y:tt.tensor, model:tt.nn.Module, loss_func, optim:tt.optim.Optimizer, limitf:float, no_scaler) -> float:
"Training step for Adam/Lion/SGD/DOG."
global utmt_LossHist # hist_loss, hist_lpos
optim.zero_grad(set_to_none=True) # (optional: skip for batch-combining)
loss = loss_func(model(X), y)
loss_item: float = loss.item() # already fix
if (loss_item < 1e999): # isnan(loss_item), 1e999==inf (fastest)
utmt_LossHist.add_loss(loss_item)