-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
1324 lines (1047 loc) · 56.5 KB
/
train.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
import os
import re
import time
import random
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from tqdm.autonotebook import tqdm
from torchvision.transforms import v2
from torch.utils.data import DataLoader, Subset
from torch.utils.tensorboard import SummaryWriter
from kitti360_dataset import Kitti360Dataset
from custom_transforms import SegmentationIdToTrainId
from invhuberloss import InvHuberLoss
from metrics import MeanIoU, RMSE
from log import LogMetric
from moviepy_frame_inference import create_moviepy_visualisation_in_tensorboard
def main(form_data, kitti360, HYPERPARAMETERS, model, save_model, checkpoint, debug):
print(f"=> Selected model: {model}")
# Normalise an image into mean ~= 0 and std ~= 1
normalise = v2.Normalize(mean=[0.3242, 0.3529, 0.3242], std=[0.2892, 0.3015, 0.3077])
transform = v2.Compose([
v2.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.1),
# v2.RandomResizedCrop(size=(128, 416), scale=(0.9, 1.0)),
v2.ToImage(),
v2.ToDtype(torch.float32, scale=True),
# v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
# v2.Normalize(mean=[0.3242, 0.3529, 0.3242], std=[0.2892, 0.3015, 0.3077])
normalise
])
val_transform = v2.Compose([
v2.ToImage(),
v2.ToDtype(torch.float32, scale=True)
])
segm_transform = v2.Compose([
SegmentationIdToTrainId(Kitti360Dataset.labels),
v2.ToImage(),
# v2.ToDtype(torch.uint8, scale=True)
v2.ToDtype(torch.long, scale=False)
])
dep_transform = v2.Compose([
v2.ToImage(),
v2.ToDtype(torch.float32, scale=True),
])
horizontal_flip = v2.RandomHorizontalFlip(p=0.5)
kt360 = Kitti360Dataset(
root=kitti360,
form_dir=form_data,
train=True,
transform=transform,
segm_only_transform=segm_transform,
dep_only_transform=dep_transform
)
kt360 = horizontal_flip(kt360)
kt360_val = Kitti360Dataset(
root=kitti360,
form_dir=form_data,
train=False,
transform=val_transform,
segm_only_transform=segm_transform,
dep_only_transform=dep_transform
)
#kt360_val = horizontal_flip(kt360_val)
# DataLoader
kt360_loader = DataLoader(
kt360,
batch_size=HYPERPARAMETERS['batch_size'],
pin_memory=True,
shuffle=True
)
# DataLoader
kt360_val_loader = DataLoader(
kt360_val,
batch_size=HYPERPARAMETERS['batch_size'],
pin_memory=True,
shuffle=False
)
device = (
"cuda"
if torch.cuda.is_available()
else "mps"
if torch.backends.mps.is_available()
else "cpu"
)
print(f"=> Using {device} device")
trainId = sorted(set([x.trainId for x in kt360.labels if x.trainId != 255 and x.trainId != -1]))
weights = None
loss_fn = None
model_name = model
if model == "semantic":
from SEM_LRefineNet import net
# Load model
model = net(len(trainId))
model.to(device)
optimiser = optim.Adam(model.parameters(), lr=HYPERPARAMETERS['learning_rate'])
seg_loss_function = nn.CrossEntropyLoss(ignore_index=255)
loss_fn = (seg_loss_function, None)
seg_weight = 1.0
weights = (seg_weight, None)
elif model == "depth":
from DEPTH_LRefineNet import net
# Load model
model = net(len(trainId))
model.to(device)
optimiser = optim.Adam(model.parameters(), lr=HYPERPARAMETERS['learning_rate'])
depth_loss_function = InvHuberLoss(ignore_index=0)
loss_fn = (None, depth_loss_function)
depth_weight = 1.0
weights = (None, depth_weight)
elif model == "dispnet":
from DispNetS import DispNetS as net
# Load model
model = net()
model.to(device)
optimiser = optim.Adam(model.parameters(), lr=HYPERPARAMETERS['learning_rate'])
depth_loss_function = InvHuberLoss(ignore_index=0)
loss_fn = (None, depth_loss_function)
depth_weight = 1.0
weights = (None, depth_weight)
elif model == "multi-task":
from MLRefineNet import net
# Load model
model = net(len(trainId))
model.to(device)
optimiser = optim.Adam(model.parameters(), lr=HYPERPARAMETERS['learning_rate'])
seg_loss_function = nn.CrossEntropyLoss(ignore_index=255)
depth_loss_function = InvHuberLoss(ignore_index=0)
loss_fn = (seg_loss_function, depth_loss_function)
seg_weight, depth_weight = (0.5, 0.5)
weights = (seg_weight, depth_weight)
elif model == "author":
from AUTHOR_MLRefineNet import net
# Load model
model = net(num_classes=len(trainId), num_tasks=2)
model.to(device)
optimiser = optim.Adam(model.parameters(), lr=HYPERPARAMETERS['learning_rate'])
seg_loss_function = nn.CrossEntropyLoss(ignore_index=255)
depth_loss_function = InvHuberLoss(ignore_index=0)
loss_fn = (seg_loss_function, depth_loss_function)
seg_weight, depth_weight = (0.5, 0.5)
weights = (seg_weight, depth_weight)
elif model == "no-relu-author":
from NO_RELU_AUTHOR_MLRefineNet import net
# Load model
model = net(num_classes=len(trainId), num_tasks=2)
model.to(device)
optimiser = optim.Adam(model.parameters(), lr=HYPERPARAMETERS['learning_rate'])
seg_loss_function = nn.CrossEntropyLoss(ignore_index=255)
depth_loss_function = InvHuberLoss(ignore_index=0)
loss_fn = (seg_loss_function, depth_loss_function)
seg_weight, depth_weight = (0.5, 0.5)
weights = (seg_weight, depth_weight)
else:
raise RuntimeError("Unexpected Error: model was not selected, please select one of the following: "
"'semantic', 'depth', 'dispnet', 'multi-task', 'author' or 'no-relu-author' (in terminal `--semantic`, `--depth`, `--dispnet`, `--multi-task`, `--author` or `--no-relu-author`)")
if weights is None or loss_fn is None:
raise RuntimeError(f"Unexpected Error: training has None values on weights values {weights} and/or loss function {loss_fn}")
#############################################################################
# TRAINING & TESTING LOOPS #
# #
# NOTE: SEE BELOW AFTER THE 2 FUNCTION TO FIND EXECUTION OF THESE FUNCTIONS #
#############################################################################
def train_loop(data_loader, model, model_name, optimiser, loss_fn, weights, epoch, writer, n_iter, start_timestamp, checkpoint):
model.train()
def semantic_loop(n_iter):
meaniou = MeanIoU(len(trainId))
# Initialize tqdm with dynamic postfix
progress_bar = tqdm(data_loader, desc="Training", leave=False)
for X, (y_seg, _) in progress_bar:
# Tensors to Device
X, y_seg, _ = X.to(device), y_seg.to(device), _.to(device)
# Compute prediction and loss
pred_seg = model(X)
loss_fn_seg, _ = loss_fn
seg_weight, _ = weights
loss_seg = loss_fn_seg(pred_seg.squeeze(dim=1), y_seg.squeeze(dim=1))
loss = seg_weight * loss_seg
writer.add_scalar('Total_Loss_per_batch', loss, n_iter)
writer.add_scalar('Loss_Seg_per_batch', loss_seg, n_iter)
# Backpropagation
loss.backward()
optimiser.step()
optimiser.zero_grad()
with torch.no_grad():
meaniou.update(pred_seg.squeeze(dim=1).cpu().numpy(), y_seg.squeeze(dim=1).cpu().numpy())
writer.add_scalar('Train_MeanIoU_over_batch', meaniou.val(), n_iter)
# Update tqdm with loss information
progress_bar.set_postfix({
"MeanIoU": f"{meaniou.val() * 100:.2f}%",
"Loss": loss.item(),
"Loss_Seg": loss_seg.item(),
})
n_iter += 1 # Increment iteration for `writer` tensorboard
# checkpoints_path = f"{save_model}/checkpoints/{model_name}/{start_timestamp}_run/"
checkpoints_path = os.path.join(save_model, "checkpoints", model_name, f"{start_timestamp}_run/")
os.makedirs(checkpoints_path, exist_ok=True)
timestamp = time.strftime("%Y%m%d_%H%M%S")
torch.save({
'epoch': epoch,
'n_iter': n_iter,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimiser.state_dict(),
'loss': loss.item(),
}, os.path.join(checkpoints_path, f"{model_name}_model_checkpoints_epoch{epoch}_miou{meaniou.val() * 100:.2f}_{timestamp}.pt"))
# , f"{checkpoints_path}{model_name}_model_checkpoints_epoch{epoch}_miou{meaniou.val() * 100:.2f}_{timestamp}.pt")
# Reset metrics
meaniou.reset()
return n_iter
def depth_loop(n_iter):
rmse1 = RMSE()
rmse2 = RMSE()
rmse3 = RMSE()
rmse4 = RMSE()
# Initialize tqdm with dynamic postfix
progress_bar = tqdm(data_loader, desc="Training", leave=False)
for X, (_, y_depth) in progress_bar:
# Tensors to Device
X, _, y_depth = X.to(device), _.to(device), y_depth.to(device)
# Compute prediction and loss
disp1, disp2, disp3, disp4 = model(X)
pred_depth = [disp.squeeze(dim=1) for disp in [disp1, disp2, disp3, disp4]]
y_depth = [
y_depth,
y_depth[:, :, ::2, ::2],
y_depth[:, :, ::2*2, ::2*2],
y_depth[:, :, ::2*2*2, ::2*2*2]
]
gt_depth = [gt_dep for gt_dep in y_depth]
y_depth = [y_dep.squeeze(dim=1) for y_dep in y_depth]
_, loss_fn_depth = loss_fn
_, depth_weight = weights
loss_depth1 = loss_fn_depth(pred_depth[0], y_depth[0])
loss_depth2 = loss_fn_depth(pred_depth[1], y_depth[1])
loss_depth3 = loss_fn_depth(pred_depth[2], y_depth[2])
loss_depth4 = loss_fn_depth(pred_depth[3], y_depth[3])
loss_depth = (1/4 * loss_depth1 + 1/4 * loss_depth2 + 1/4 * loss_depth3 + 1/4 * loss_depth4)
loss = depth_weight * loss_depth
writer.add_scalar('Total_Loss_per_batch', loss, n_iter)
writer.add_scalar('Loss_Depth_per_batch', loss_depth, n_iter)
# Per Depth scale
writer.add_scalar('Loss_Depth1_per_batch', loss_depth1, n_iter)
writer.add_scalar('Loss_Depth2_per_batch', loss_depth2, n_iter)
writer.add_scalar('Loss_Depth3_per_batch', loss_depth3, n_iter)
writer.add_scalar('Loss_Depth4_per_batch', loss_depth4, n_iter)
# Backpropagation
loss.backward()
optimiser.step()
optimiser.zero_grad()
with torch.no_grad():
rmse1.update(disp1.squeeze(dim=1).cpu().numpy(), gt_depth[0].squeeze(dim=1).cpu().numpy())
rmse2.update(disp2.squeeze(dim=1).cpu().numpy(), gt_depth[1].squeeze(dim=1).cpu().numpy())
rmse3.update(disp3.squeeze(dim=1).cpu().numpy(), gt_depth[2].squeeze(dim=1).cpu().numpy())
rmse4.update(disp4.squeeze(dim=1).cpu().numpy(), gt_depth[3].squeeze(dim=1).cpu().numpy())
writer.add_scalar('Train_RMSE1_over_batch', rmse1.val(), n_iter)
writer.add_scalar('Train_RMSE2_over_batch', rmse2.val(), n_iter)
writer.add_scalar('Train_RMSE3_over_batch', rmse3.val(), n_iter)
writer.add_scalar('Train_RMSE4_over_batch', rmse4.val(), n_iter)
# Update tqdm with loss information
progress_bar.set_postfix({
"RMSE_1": rmse1.val(),
"RMSE_2": rmse2.val(),
"RMSE_3": rmse3.val(),
"RMSE_4": rmse4.val(),
"Loss": loss.item(),
"Loss_Depth": loss_depth.item()
})
n_iter += 1 # Increment iteration for `writer` tensorboard
# checkpoints_path = f"{save_model}/checkpoints/{model_name}/{start_timestamp}_run/"
checkpoints_path = os.path.join(save_model, "checkpoints", model_name, f"{start_timestamp}_run/")
os.makedirs(checkpoints_path, exist_ok=True)
timestamp = time.strftime("%Y%m%d_%H%M%S")
torch.save({
'epoch': epoch,
'n_iter': n_iter,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimiser.state_dict(),
'loss': loss.item(),
}, os.path.join(checkpoints_path, f"{model_name}_model_checkpoints_epoch{epoch}_rmse1d{rmse1.val():>8f}_rmse2d{rmse2.val():>8f}_rmse3d{rmse3.val():>8f}_rmse4d{rmse4.val():>8f}_{timestamp}.pt"))
#, f"{checkpoints_path}{model_name}_model_checkpoints_epoch{epoch}_rmse1d{rmse1.val():>8f}_rmse2d{rmse2.val():>8f}_rmse3d{rmse3.val():>8f}_rmse4d{rmse4.val():>8f}_{timestamp}.pt")
# Reset metrics
rmse1.reset()
rmse2.reset()
rmse3.reset()
rmse4.reset()
return n_iter
def multi_task_loop(n_iter):
meaniou = MeanIoU(len(trainId))
rmse1 = RMSE()
rmse2 = RMSE()
rmse3 = RMSE()
rmse4 = RMSE()
# Initialize tqdm with dynamic postfix
progress_bar = tqdm(data_loader, desc="Training", leave=False)
for X, (y_seg, y_depth) in progress_bar:
# Tensors to Device
X, y_seg, y_depth = X.to(device), y_seg.to(device), y_depth.to(device)
# Compute prediction and loss
disp1, disp2, disp3, disp4, pred_seg = model(X)
pred_depth = [disp.squeeze(dim=1) for disp in [disp1, disp2, disp3, disp4]]
y_depth = [
y_depth,
y_depth[:, :, ::2, ::2],
y_depth[:, :, ::2*2, ::2*2],
y_depth[:, :, ::2*2*2, ::2*2*2]
]
gt_depth = [gt_dep for gt_dep in y_depth]
y_depth = [y_dep.squeeze(dim=1) for y_dep in y_depth]
loss_fn_seg, loss_fn_depth = loss_fn
seg_weight, depth_weight = weights
loss_seg = loss_fn_seg(pred_seg.squeeze(dim=1), y_seg.squeeze(dim=1))
loss_depth1 = loss_fn_depth(pred_depth[0], y_depth[0])
loss_depth2 = loss_fn_depth(pred_depth[1], y_depth[1])
loss_depth3 = loss_fn_depth(pred_depth[2], y_depth[2])
loss_depth4 = loss_fn_depth(pred_depth[3], y_depth[3])
loss_depth = (1/4 * loss_depth1 + 1/4 * loss_depth2 + 1/4 * loss_depth3 + 1/4 * loss_depth4)
loss = seg_weight * loss_seg + depth_weight * loss_depth
writer.add_scalar('Total_Loss_per_batch', loss, n_iter)
writer.add_scalar('Loss_Seg_per_batch', loss_seg, n_iter)
writer.add_scalar('Loss_Depth_per_batch', loss_depth, n_iter)
# Per Depth scale
writer.add_scalar('Loss_Depth1_per_batch', loss_depth1, n_iter)
writer.add_scalar('Loss_Depth2_per_batch', loss_depth2, n_iter)
writer.add_scalar('Loss_Depth3_per_batch', loss_depth3, n_iter)
writer.add_scalar('Loss_Depth4_per_batch', loss_depth4, n_iter)
# Backpropagation
loss.backward()
optimiser.step()
optimiser.zero_grad()
with torch.no_grad():
meaniou.update(pred_seg.squeeze(dim=1).cpu().numpy(), y_seg.squeeze(dim=1).cpu().numpy())
rmse1.update(disp1.squeeze(dim=1).cpu().numpy(), gt_depth[0].squeeze(dim=1).cpu().numpy())
rmse2.update(disp2.squeeze(dim=1).cpu().numpy(), gt_depth[1].squeeze(dim=1).cpu().numpy())
rmse3.update(disp3.squeeze(dim=1).cpu().numpy(), gt_depth[2].squeeze(dim=1).cpu().numpy())
rmse4.update(disp4.squeeze(dim=1).cpu().numpy(), gt_depth[3].squeeze(dim=1).cpu().numpy())
writer.add_scalar('Train_MeanIoU_over_batch', meaniou.val(), n_iter)
writer.add_scalar('Train_RMSE1_over_batch', rmse1.val(), n_iter)
writer.add_scalar('Train_RMSE2_over_batch', rmse2.val(), n_iter)
writer.add_scalar('Train_RMSE3_over_batch', rmse3.val(), n_iter)
writer.add_scalar('Train_RMSE4_over_batch', rmse4.val(), n_iter)
# Update tqdm with loss information
progress_bar.set_postfix({
"MeanIoU": f"{meaniou.val() * 100:.2f}%",
"RMSE_1": rmse1.val(),
"RMSE_2": rmse2.val(),
"RMSE_3": rmse3.val(),
"RMSE_4": rmse4.val(),
"Loss": loss.item(),
"Loss_Seg": loss_seg.item(),
"Loss_Depth": loss_depth.item()
})
n_iter += 1 # Increment iteration for `writer` tensorboard
# checkpoints_path = f"{save_model}/checkpoints/{model_name}/{start_timestamp}_run/"
checkpoints_path = os.path.join(save_model, "checkpoints", model_name, f"{start_timestamp}_run/")
os.makedirs(checkpoints_path, exist_ok=True)
timestamp = time.strftime("%Y%m%d_%H%M%S")
torch.save({
'epoch': epoch,
'n_iter': n_iter,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimiser.state_dict(),
'loss': loss.item(),
}, os.path.join(checkpoints_path, f"{model_name}_model_checkpoints_epoch{epoch}_miou{meaniou.val() * 100:.2f}_rmse1d{rmse1.val():>8f}_rmse2d{rmse2.val():>8f}_rmse3d{rmse3.val():>8f}_rmse4d{rmse4.val():>8f}_{timestamp}.pt"))
#, f"{checkpoints_path}{model_name}_model_checkpoints_epoch{epoch}_miou{meaniou.val() * 100:.2f}_rmse1d{rmse1.val():>8f}_rmse2d{rmse2.val():>8f}_rmse3d{rmse3.val():>8f}_rmse4d{rmse4.val():>8f}_{timestamp}.pt")
# Reset metrics
meaniou.reset()
rmse1.reset()
rmse2.reset()
rmse3.reset()
rmse4.reset()
return n_iter
def author_loop(n_iter):
meaniou = MeanIoU(len(trainId))
rmse1 = RMSE()
# Initialize tqdm with dynamic postfix
progress_bar = tqdm(data_loader, desc="Training", leave=False)
for X, (y_seg, y_depth) in progress_bar:
# Tensors to Device
X, y_seg, y_depth = X.to(device), y_seg.to(device), y_depth.to(device)
# Compute prediction and loss
pred_seg, pred_depth = model(X)
pred_seg = F.interpolate(pred_seg, size=(128, 416), mode='nearest')
pred_depth = F.interpolate(pred_depth, size=(128, 416), mode='bilinear', align_corners=False)
loss_fn_seg, loss_fn_depth = loss_fn
seg_weight, depth_weight = weights
loss_seg = loss_fn_seg(pred_seg.squeeze(dim=1), y_seg.squeeze(dim=1))
loss_depth = loss_fn_depth(pred_depth.squeeze(dim=1), y_depth.squeeze(dim=1))
loss = seg_weight * loss_seg + depth_weight * loss_depth
writer.add_scalar('Total_Loss_per_batch', loss, n_iter)
writer.add_scalar('Loss_Seg_per_batch', loss_seg, n_iter)
writer.add_scalar('Loss_Depth_per_batch', loss_depth, n_iter)
# Backpropagation
loss.backward()
optimiser.step()
optimiser.zero_grad()
with torch.no_grad():
meaniou.update(pred_seg.squeeze(dim=1).cpu().numpy(), y_seg.squeeze(dim=1).cpu().numpy())
rmse1.update(pred_depth.squeeze(dim=1).cpu().numpy(), y_depth.squeeze(dim=1).cpu().numpy())
writer.add_scalar('Train_MeanIoU_over_batch', meaniou.val(), n_iter)
writer.add_scalar('Train_RMSE1_over_batch', rmse1.val(), n_iter)
# Update tqdm with loss information
progress_bar.set_postfix({
"MeanIoU": f"{meaniou.val() * 100:.2f}%",
"RMSE1": rmse1.val(),
"Loss": loss.item(),
"Loss_Seg": loss_seg.item(),
"Loss_Depth": loss_depth.item()
})
n_iter += 1 # Increment iteration for `writer` tensorboard
# checkpoints_path = f"{save_model}/checkpoints/{model_name}/{start_timestamp}_run/"
checkpoints_path = os.path.join(save_model, "checkpoints", model_name, f"{start_timestamp}_run/")
os.makedirs(checkpoints_path, exist_ok=True)
timestamp = time.strftime("%Y%m%d_%H%M%S")
torch.save({
'epoch': epoch,
'n_iter': n_iter,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimiser.state_dict(),
'loss': loss.item(),
}, os.path.join(checkpoints_path, f"{model_name}_model_checkpoints_epoch{epoch}_miou{meaniou.val() * 100:.2f}_rmse1d{rmse1.val():>8f}_{timestamp}.pt"))
# , f"{checkpoints_path}{model_name}_model_checkpoints_epoch{epoch}_miou{meaniou.val() * 100:.2f}_rmse1d{rmse1.val():>8f}_{timestamp}.pt")
# Reset metrics
meaniou.reset()
rmse1.reset()
return n_iter
if checkpoint and n_iter == 1:
# checkpoints_path = f"{save_model}checkpoints/{model_name}/{checkpoint['run']}/{checkpoint['filename']}"
checkpoints_path = os.path.join(save_model, "checkpoints", model_name, checkpoint['run'], checkpoint['filename'])
model_checkpoint = torch.load(checkpoints_path, weights_only=True, map_location=device)
model.load_state_dict(model_checkpoint['model_state_dict'])
optimiser.load_state_dict(model_checkpoint['optimizer_state_dict'])
n_iter += (model_checkpoint['epoch'] * len(data_loader))
# print(f"model_checkpoint['epoch']: {model_checkpoint['epoch']}")
# print(f"(model_checkpoint['epoch'] * len(data_loader)): {(model_checkpoint['epoch'] * len(data_loader))}")
# print(f"n_iter: {n_iter}")
# raise RuntimeError("STILL DEBUGGING")
# n_iter += model_checkpoint['n_iter']
#################
# Training Loop #
#################
if model_name == "semantic":
n_iter = semantic_loop(n_iter=n_iter)
elif model_name == "depth" or model_name == "dispnet":
n_iter = depth_loop(n_iter=n_iter)
elif model_name == "multi-task":
n_iter = multi_task_loop(n_iter=n_iter)
elif model_name == "author" or model_name == "no-relu-author":
n_iter = author_loop(n_iter=n_iter)
else:
raise RuntimeError(f"Unexpected Error: Train Loop have both seg_weight and depth_weight being ({seg_weight}, {depth_weight})")
return n_iter
@torch.no_grad()
def test_loop(data_loader, model, model_name, loss_fn, weights, writer, log_for_best, start_timestamp):
model.eval()
#########################################
# HELPERS - COLOURING AND SAVING IMAGES #
#########################################
# Function to create a color mapping from train_id to RGB color
def create_colour_mapping(classes):
return {cls.trainId: cls.color for cls in classes}
# Function to apply color to the semantic segmentation mask
def apply_colour_map(target_tensor, color_mapping):
# Ensure the input tensor has the correct shape
batch_size, _, h, w = target_tensor.shape
# Create an empty tensor to hold the colored images
colored_target = torch.zeros((batch_size, 3, h, w), dtype=torch.uint8)
# Iterate over the batch
for i in range(batch_size):
# Get the 2D mask for the ith image
mask = target_tensor[i, 0] # Shape: (128, 416)
# Apply the color mapping
for train_id, color in color_mapping.items():
mask_indices = (mask == train_id)
if mask_indices.any(): # Only assign if there are any matching pixels
color_tensor = torch.tensor(color, dtype=torch.uint8).view(3, 1, 1)
colored_target[i][:, mask_indices] = color_tensor.view(3, -1)
return colored_target
def apply_turbo_colourmap(depth_tensor):
# Convert the depth tensor to a numpy array
depth_numpy = depth_tensor.squeeze().cpu().numpy()
# Normalize the depth values to [0, 1] for proper colormap application
depth_normalized = (depth_numpy - depth_numpy.min()) / (depth_numpy.max() - depth_numpy.min())
# Apply the turbo colormap
turbo_colormap = plt.colormaps['turbo']
depth_colored = turbo_colormap(depth_normalized)[:, :, :3] # Drop the alpha channel
# Convert the colormap back to a tensor and permute the dimensions to match NCHW
depth_colored_tensor = torch.from_numpy(depth_colored).permute(2, 0, 1)
return depth_colored_tensor
def save_sample_images(model, num_samples, model_name):
num_samples = num_samples # Number of images to retrieve
X_batch = []
y_seg_batch = []
y_depth_batch = []
for i in range(num_samples):
# Randomly select an index from the dataset
random_index = random.randint(0, len(kt360_val) - 1)
# Retrieve the sample using the random index
X, (y_seg, y_depth) = kt360_val[random_index]
# Append each sample to the respective batch list
X_batch.append(X.unsqueeze(0)) # Add batch dimension
y_seg_batch.append(y_seg.unsqueeze(0)) # Add batch dimension
y_depth_batch.append(y_depth.unsqueeze(0)) # Add batch dimension
# Concatenate lists into batches
X_batch = torch.cat(X_batch, dim=0) # X.shape = (10, 3, 128, 416)
y_seg_batch = torch.cat(y_seg_batch, dim=0) # y_seg.shape = (10, 1, 128, 416)
y_depth_batch = torch.cat(y_depth_batch, dim=0) # y_depth.shape = (10, 1, 128, 416)
# Normalize the input images
X_input = X_batch.clone() # Clone for non-normalized RGB images
X_batch = normalise(X_batch) # Apply normalization
# Tensors to Device
X_batch, y_seg_batch, y_depth_batch = (
X_batch.to(device),
y_seg_batch.to(device),
y_depth_batch.to(device),
)
if model_name == "semantic":
# Get predictions from the model
pred_seg = model(X_batch)
# Process segmentation predictions
pred_seg = torch.argmax(pred_seg, dim=1, keepdim=True)
# Apply color mapping
pred_seg = apply_colour_map(pred_seg, create_colour_mapping(Kitti360Dataset.labels))
y_seg_batch = apply_colour_map(y_seg_batch, create_colour_mapping(Kitti360Dataset.labels))
# Write images to TensorBoard
writer.add_images("Qualitative_Results_RGB", X_input, epoch, dataformats='NCHW')
writer.add_images("Qualitative_Results_Prediction_Semantic", pred_seg, epoch, dataformats='NCHW')
writer.add_images("Qualitative_Results_Ground_Truth_Semantic", y_seg_batch, epoch, dataformats='NCHW')
elif model_name == "depth" or model_name == "dispnet":
# Get predictions from the model
pred_depth = model(X_batch)
# Apply the turbo colormap to depth predictions and ground truth
pred_depth_colored = torch.stack([apply_turbo_colourmap(d) for d in pred_depth])
y_depth_colored = torch.stack([apply_turbo_colourmap(d) for d in y_depth_batch])
# Write images to TensorBoard
writer.add_images("Qualitative_Results_RGB", X_input, epoch, dataformats='NCHW')
writer.add_images("Qualitative_Results_Prediction_Depth", pred_depth_colored, epoch, dataformats='NCHW')
writer.add_images("Qualitative_Results_Ground_Truth_Depth", y_depth_colored, epoch, dataformats='NCHW')
elif model_name == "multi-task":
# Get predictions from the model
pred_depth, pred_seg = model(X_batch)
# Process segmentation predictions
pred_seg = torch.argmax(pred_seg, dim=1, keepdim=True)
# Apply color mapping
pred_seg = apply_colour_map(pred_seg, create_colour_mapping(Kitti360Dataset.labels))
y_seg_batch = apply_colour_map(y_seg_batch, create_colour_mapping(Kitti360Dataset.labels))
# Apply the turbo colormap to depth predictions and ground truth
pred_depth_colored = torch.stack([apply_turbo_colourmap(d) for d in pred_depth])
y_depth_colored = torch.stack([apply_turbo_colourmap(d) for d in y_depth_batch])
# Write images to TensorBoard
writer.add_images("Qualitative_Results_RGB", X_input, epoch, dataformats='NCHW')
writer.add_images("Qualitative_Results_Prediction_Semantic", pred_seg, epoch, dataformats='NCHW')
writer.add_images("Qualitative_Results_Ground_Truth_Semantic", y_seg_batch, epoch, dataformats='NCHW')
writer.add_images("Qualitative_Results_Prediction_Depth", pred_depth_colored, epoch, dataformats='NCHW')
writer.add_images("Qualitative_Results_Ground_Truth_Depth", y_depth_colored, epoch, dataformats='NCHW')
elif model_name == "author" or model_name == "no-relu-author":
# Get predictions from the model
pred_seg, pred_depth = model(X_batch)
pred_seg = F.interpolate(pred_seg, size=(128, 416), mode='nearest')
pred_depth = F.interpolate(pred_depth, size=(128, 416), mode='bilinear', align_corners=False)
# Process segmentation predictions
pred_seg = torch.argmax(pred_seg, dim=1, keepdim=True)
# Apply color mapping
pred_seg = apply_colour_map(pred_seg, create_colour_mapping(Kitti360Dataset.labels))
y_seg_batch = apply_colour_map(y_seg_batch, create_colour_mapping(Kitti360Dataset.labels))
# Apply the turbo colormap to depth predictions and ground truth
pred_depth_colored = torch.stack([apply_turbo_colourmap(d) for d in pred_depth])
y_depth_colored = torch.stack([apply_turbo_colourmap(d) for d in y_depth_batch])
# Write images to TensorBoard
writer.add_images("Qualitative_Results_RGB", X_input, epoch, dataformats='NCHW')
writer.add_images("Qualitative_Results_Prediction_Semantic", pred_seg, epoch, dataformats='NCHW')
writer.add_images("Qualitative_Results_Ground_Truth_Semantic", y_seg_batch, epoch, dataformats='NCHW')
writer.add_images("Qualitative_Results_Prediction_Depth", pred_depth_colored, epoch, dataformats='NCHW')
writer.add_images("Qualitative_Results_Ground_Truth_Depth", y_depth_colored, epoch, dataformats='NCHW')
#########################################
def semantic_loop():
num_batches = len(data_loader)
test_loss = 0
meaniou = MeanIoU(len(trainId))
# Initialize tqdm with dynamic postfix
progress_bar = tqdm(data_loader, desc="Testing", leave=False)
for X, (y_seg, _) in progress_bar:
X_input = X.clone() # Clean copy of RGB image that is not normalised
X = normalise(X)
# Tensors to Device
X, y_seg, _ = X.to(device), y_seg.to(device), _.to(device)
pred_seg = model(X)
loss_fn_seg, _ = loss_fn
seg_weight, _ = weights
loss_seg = loss_fn_seg(pred_seg.squeeze(dim=1), y_seg.squeeze(dim=1))
loss = seg_weight * loss_seg
test_loss += loss
meaniou.update(pred_seg.squeeze(dim=1).cpu().numpy(), y_seg.squeeze(dim=1).cpu().numpy())
# Update tqdm with metrics information
progress_bar.set_postfix({
"MeanIoU": f"{meaniou.val() * 100:.2f}%",
"Loss": loss.item(),
"Loss_Seg": loss_seg.item(),
})
writer.add_scalar("MeanIoU_per_epoch", meaniou.val(), epoch)
# Save qualitative images results:
# ==================================
save_sample_images(model=model, num_samples=16, model_name=model_name)
# ==================================
# best_models_path = f"{save_model}/best_models/{model_name}/{start_timestamp}_run/"
best_models_path = os.path.join(save_model, "best_models", model_name, f"{start_timestamp}_run/")
os.makedirs(best_models_path, exist_ok=True)
test_loss /= num_batches
previous_meaniou = log_for_best.getMetric()
previous_loss = log_for_best.getLoss()
# Loss lower is better!
if meaniou.val() >= previous_meaniou and test_loss <= previous_loss:
# timestamp = time.strftime("%Y%m%d_%H%M%S")
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimiser.state_dict(),
'loss': loss.item(),
}, os.path.join(best_models_path, f"{model_name}_best_model.pt"))
# , f"{best_models_path}{model_name}_best_model.pt")
tqdm.write(f"Test Error: \n MeanIoU: {meaniou.val() * 100:.2f}%, Avg loss: {test_loss:>8f} \n")
# Update `log_for_best` with current metrics and loss
log_for_best.update(meaniou.val(), test_loss)
# Reset metrics
meaniou.reset()
def depth_loop():
num_batches = len(data_loader)
test_loss = 0
rmse = RMSE()
# Initialize tqdm with dynamic postfix
progress_bar = tqdm(data_loader, desc="Testing", leave=False)
for X, (_, y_depth) in progress_bar:
X_input = X.clone() # Clean copy of RGB image that is not normalised
X = normalise(X)
# Tensors to Device
X, _, y_depth = X.to(device), _.to(device), y_depth.to(device)
pred_depth = model(X)
_, loss_fn_depth = loss_fn
_, depth_weight = weights
loss_depth = loss_fn_depth(pred_depth.squeeze(dim=1), y_depth.squeeze(dim=1))
loss = depth_weight * loss_depth
test_loss += loss
rmse.update(pred_depth.squeeze(dim=1).cpu().numpy(), y_depth.squeeze(dim=1).cpu().numpy())
# Update tqdm with metrics information
progress_bar.set_postfix({
"RMSE": rmse.val(),
"Loss": loss.item(),
"Loss_Depth": loss_depth.item()
})
writer.add_scalar("RMSE_per_epoch", rmse.val(), epoch)
# Save qualitative images results:
# ==================================
save_sample_images(model=model, num_samples=16, model_name=model_name)
# ==================================
# best_models_path = f"{save_model}/best_models/{model_name}/{start_timestamp}_run/"
best_models_path = os.path.join(save_model, "best_models", model_name, f"{start_timestamp}_run/")
os.makedirs(best_models_path, exist_ok=True)
test_loss /= num_batches
previous_rmse = log_for_best.getMetric()
previous_loss = log_for_best.getLoss()
# Loss lower is better!
if rmse.val() >= previous_rmse and test_loss <= previous_loss:
# timestamp = time.strftime("%Y%m%d_%H%M%S")
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimiser.state_dict(),
'loss': loss.item(),
}, os.path.join(best_models_path, f"{model_name}_best_model.pt"))
# , f"{best_models_path}{model_name}_best_model.pt")
tqdm.write(f"Test Error: \n RMSE: {(rmse.val()):>8f}, Avg loss: {test_loss:>8f} \n")
# Update `log_for_best` with current metrics and loss
log_for_best.update(rmse.val(), test_loss)
# Reset metrics
rmse.reset()
def multi_task_loop():
num_batches = len(data_loader)
test_loss = 0
meaniou = MeanIoU(len(trainId))
rmse = RMSE()
# Initialize tqdm with dynamic postfix
progress_bar = tqdm(data_loader, desc="Testing", leave=False)
for X, (y_seg, y_depth) in progress_bar:
X_input = X.clone() # Clean copy of RGB image that is not normalised
X = normalise(X)
# Tensors to Device
X, y_seg, y_depth = X.to(device), y_seg.to(device), y_depth.to(device)
pred_depth, pred_seg = model(X)
loss_fn_seg, loss_fn_depth = loss_fn
seg_weight, depth_weight = weights
loss_seg = loss_fn_seg(pred_seg.squeeze(dim=1), y_seg.squeeze(dim=1))
loss_depth = loss_fn_depth(pred_depth.squeeze(dim=1), y_depth.squeeze(dim=1))
loss = seg_weight * loss_seg + depth_weight * loss_depth
test_loss += loss
meaniou.update(pred_seg.squeeze(dim=1).cpu().numpy(), y_seg.squeeze(dim=1).cpu().numpy())
rmse.update(pred_depth.squeeze(dim=1).cpu().numpy(), y_depth.squeeze(dim=1).cpu().numpy())
# Update tqdm with metrics information
progress_bar.set_postfix({
"MeanIoU": f"{meaniou.val() * 100:.2f}%",
"RMSE": rmse.val(),
"Loss": loss.item(),
"Loss_Seg": loss_seg.item(),
"Loss_Depth": loss_depth.item()
})
writer.add_scalar("MeanIoU_per_epoch", meaniou.val(), epoch)
writer.add_scalar("RMSE_per_epoch", rmse.val(), epoch)
# Save qualitative images results:
# ==================================
save_sample_images(model=model, num_samples=16, model_name=model_name)
# ==================================
# best_models_path = f"{save_model}/best_models/{model_name}/{start_timestamp}_run/"
best_models_path = os.path.join(save_model, "best_models", model_name, f"{start_timestamp}_run/")
os.makedirs(best_models_path, exist_ok=True)
test_loss /= num_batches
previous_meaniou, previous_rmse = log_for_best.getMetric()
previous_loss = log_for_best.getLoss()
# Loss lower is better!
if (meaniou.val() >= previous_meaniou or rmse.val() >= previous_rmse) and test_loss <= previous_loss:
# timestamp = time.strftime("%Y%m%d_%H%M%S")
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimiser.state_dict(),
'loss': loss.item(),
}, os.path.join(best_models_path, f"{model_name}_best_model.pt"))
# , f"{best_models_path}{model_name}_best_model.pt")
tqdm.write(f"Test Error: \n MeanIoU: {meaniou.val() * 100:.2f}%, RMSE: {(rmse.val()):>8f}, Avg loss: {test_loss:>8f} \n")
# Update `log_for_best` with current metrics and loss
log_for_best.update_tuple((meaniou.val(), rmse.val()), test_loss)
# Reset metrics
meaniou.reset()
rmse.reset()
def author_loop():
num_batches = len(data_loader)
test_loss = 0
meaniou = MeanIoU(len(trainId))
rmse = RMSE()
# Initialize tqdm with dynamic postfix
progress_bar = tqdm(data_loader, desc="Testing", leave=False)
for X, (y_seg, y_depth) in progress_bar:
X_input = X.clone() # Clean copy of RGB image that is not normalised
X = normalise(X)
# Tensors to Device
X, y_seg, y_depth = X.to(device), y_seg.to(device), y_depth.to(device)
pred_seg, pred_depth, = model(X)
pred_seg = F.interpolate(pred_seg, size=(128, 416), mode='nearest')
pred_depth = F.interpolate(pred_depth, size=(128, 416), mode='bilinear', align_corners=False)
loss_fn_seg, loss_fn_depth = loss_fn
seg_weight, depth_weight = weights
loss_seg = loss_fn_seg(pred_seg.squeeze(dim=1), y_seg.squeeze(dim=1))
loss_depth = loss_fn_depth(pred_depth.squeeze(dim=1), y_depth.squeeze(dim=1))
loss = seg_weight * loss_seg + depth_weight * loss_depth
test_loss += loss
meaniou.update(pred_seg.squeeze(dim=1).cpu().numpy(), y_seg.squeeze(dim=1).cpu().numpy())
rmse.update(pred_depth.squeeze(dim=1).cpu().numpy(), y_depth.squeeze(dim=1).cpu().numpy())
# Update tqdm with metrics information
progress_bar.set_postfix({
"MeanIoU": f"{meaniou.val() * 100:.2f}%",
"RMSE": rmse.val(),
"Loss": loss.item(),
"Loss_Seg": loss_seg.item(),
"Loss_Depth": loss_depth.item()
})
writer.add_scalar("MeanIoU_per_epoch", meaniou.val(), epoch)
writer.add_scalar("RMSE_per_epoch", rmse.val(), epoch)
# Save qualitative images results:
# ==================================
save_sample_images(model=model, num_samples=16, model_name=model_name)
# ==================================
# best_models_path = f"{save_model}/best_models/{model_name}/{start_timestamp}_run/"
best_models_path = os.path.join(save_model, "best_models", model_name, f"{start_timestamp}_run/")
os.makedirs(best_models_path, exist_ok=True)
test_loss /= num_batches
previous_meaniou, previous_rmse = log_for_best.getMetric()
previous_loss = log_for_best.getLoss()
# Loss lower is better!
if (meaniou.val() >= previous_meaniou or rmse.val() >= previous_rmse) and test_loss <= previous_loss:
# timestamp = time.strftime("%Y%m%d_%H%M%S")
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimiser.state_dict(),
'loss': loss.item(),
}, os.path.join(best_models_path, f"{model_name}_best_model.pt"))
# , f"{best_models_path}{model_name}_best_model.pt")
tqdm.write(f"Test Error: \n MeanIoU: {meaniou.val() * 100:.2f}%, RMSE: {(rmse.val()):>8f}, Avg loss: {test_loss:>8f} \n")
# Update `log_for_best` with current metrics and loss
log_for_best.update_tuple((meaniou.val(), rmse.val()), test_loss)