forked from nianticlabs/monodepth2
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrainer.py
2946 lines (2434 loc) · 155 KB
/
trainer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
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
# Copyright Niantic 2019. Patent Pending. All rights reserved.
#
# This software is licensed under the terms of the Monodepth2 licence
# which allows for non-commercial use only, the full terms of which are made
# available in the LICENSE file.
from __future__ import absolute_import, division, print_function
import numpy as np
import time
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader, ConcatDataset
from tensorboardX import SummaryWriter
import json
from utils import *
from kitti_utils import *
from layers import *
import datasets
import networks
from IPython import embed
import sys
script_path = os.path.dirname(__file__)
sys.path.append(os.path.join(script_path, '../pytorch-unet'))
# from geometry_plot import draw3DPts
from geometry import gramian, kern_mat, rgb_to_hsv, hsv_to_rgb
sys.path.append(os.path.join(script_path, '../UPSNet'))
from upsnet.models import *
from wrap_to_panoptic import to_panoptic, PanopVis
import threading
from cvo_utils import PtSampleInGrid, PtSampleInGridAngle, PtSampleInGridWithNormal, calc_normal, recall_grad, grid_from_concat_flat_func, save_tensor_to_img, res_normal_dense, NormalFromDepthDense
import torch
torch.manual_seed(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
import warnings
warnings.filterwarnings("ignore")
import math
from pcl_vis import visualize_pcl
from kitti_utils import normalize_width
from datasets.mono_dataset import SamplerForConcat
# import objgraph ## this is for debugging memory leak, but turns out not providing much useful information
def my_collate_fn(batch):
batch_new = {}
for item in batch[0]:
batch_new[item] = {}
if "index" in item:
batch_new[item] = [batchi[item] for batchi in batch]
elif "velo_gt" not in item:
batch_new[item] = torch.stack([batchi[item] for batchi in batch], 0)
else:
batch_new[item] = [batchi[item].unsqueeze(0) for batchi in batch]
return batch_new
class Trainer:
def __init__(self, options, ups_arg, ups_cfg):
self.opt = options
if self.opt.server == "mcity":
self.log_dir = "/mnt/storage8t/minghanz/tmp"
elif self.opt.server == "sunny":
self.log_dir = "/media/sda1/minghanz/tmp"
elif self.opt.server == "home":
self.log_dir = os.path.join(script_path, "tmp")
else:
raise ValueError("server {} not recognized.".format(self.opt.server))
self.log_path = os.path.join(self.log_dir, self.opt.model_name)
torch_vs = (torch.__version__).split('.')
self.torch_version = float(torch_vs[0]) + 0.1 * float(torch_vs[1])
self.models = {}
self.parameters_to_train = []
self.device = torch.device("cpu" if self.opt.no_cuda else "cuda:{}".format(self.opt.cuda_n))
self.num_scales = len(self.opt.scales)
self.num_input_frames = len(self.opt.frame_ids)
self.num_pose_frames = 2 if self.opt.pose_model_input == "pairs" else self.num_input_frames
assert self.opt.frame_ids[0] == 0, "frame_ids must start with 0"
self.use_pose_net = not (self.opt.use_stereo and self.opt.frame_ids == [0])
if self.opt.use_stereo:
self.opt.frame_ids.append("s")
self.models["encoder"] = networks.ResnetEncoder(
self.opt.num_layers, self.opt.weights_init == "pretrained")
self.models["encoder"].to(self.device)
self.parameters_to_train += list(self.models["encoder"].parameters())
self.models["depth"] = networks.DepthDecoder(
self.models["encoder"].num_ch_enc, self.opt.scales)
self.models["depth"].to(self.device)
self.parameters_to_train += list(self.models["depth"].parameters())
if self.use_pose_net:
if self.opt.pose_model_type == "separate_resnet":
self.models["pose_encoder"] = networks.ResnetEncoder(
self.opt.num_layers,
self.opt.weights_init == "pretrained",
num_input_images=self.num_pose_frames)
self.models["pose_encoder"].to(self.device)
self.parameters_to_train += list(self.models["pose_encoder"].parameters())
self.models["pose"] = networks.PoseDecoder(
self.models["pose_encoder"].num_ch_enc,
num_input_features=1,
num_frames_to_predict_for=2)
elif self.opt.pose_model_type == "shared":
self.models["pose"] = networks.PoseDecoder(
self.models["encoder"].num_ch_enc, self.num_pose_frames)
elif self.opt.pose_model_type == "posecnn":
self.models["pose"] = networks.PoseCNN(
self.num_input_frames if self.opt.pose_model_input == "all" else 2)
self.models["pose"].to(self.device)
self.parameters_to_train += list(self.models["pose"].parameters())
if self.opt.predictive_mask:
assert self.opt.disable_automasking, \
"When using predictive_mask, please disable automasking with --disable_automasking"
# Our implementation of the predictive masking baseline has the the same architecture
# as our depth decoder. We predict a separate mask for each source frame.
self.models["predictive_mask"] = networks.DepthDecoder(
self.models["encoder"].num_ch_enc, self.opt.scales,
num_output_channels=(len(self.opt.frame_ids) - 1))
self.models["predictive_mask"].to(self.device)
self.parameters_to_train += list(self.models["predictive_mask"].parameters())
self.model_optimizer = optim.Adam(self.parameters_to_train, self.opt.learning_rate)
if self.opt.use_panoptic:
self.ups_cfg = ups_cfg # is none if self.opt.use_panoptic is None# create models
self.ups_arg = ups_arg
self.panoptic_model = eval(self.ups_cfg.symbol)().to(device=self.device)
# preparing
curr_iter = self.ups_cfg.test.test_iteration
if self.ups_arg.weight_path == '':
self.panoptic_model.load_state_dict(torch.load(os.path.join(os.path.join(os.path.join(self.ups_cfg.output_path, os.path.basename(self.ups_arg.cfg).split('.')[0]),
'_'.join(self.ups_cfg.dataset.image_set.split('+')), self.ups_cfg.model_prefix+str(curr_iter)+'.pth'))), resume=True)
else:
self.panoptic_model.load_state_dict(torch.load(self.ups_arg.weight_path), resume=True)
self.panop_visualizer = PanopVis(num_cls=50)
# from apex import amp
# model, optimizer = amp.initialize(model, optimizer, opt_level="O1") # 这里是“欧一”,不是“零一”
# with amp.scale_loss(loss, optimizer) as scaled_loss:
# scaled_loss.backward()
self.model_lr_scheduler = optim.lr_scheduler.StepLR(
self.model_optimizer, self.opt.scheduler_step_size, 0.1)
if self.opt.load_weights_folder is not None:
self.load_model()
print("Training model named:\n ", self.opt.model_name)
print("Models and tensorboard events files are saved to:\n ", self.log_dir)
print("Training is using:\n ", self.device)
# data
datasets_dict = {"kitti": datasets.KITTIRAWDataset,
"kitti_odom": datasets.KITTIOdomDataset,
"kitti_depth": datasets.KITTIDepthDataset,
"TUM": datasets.TUMRGBDDataset,
"lyft_1024": datasets.LyftDataset,
"vkitti": datasets.VKITTIDataset,
"kitti_filled_depth": datasets.KITTIFilledDepthDataset} # ZMH: kitti_depth originally not shown as an option here
if self.opt.server == "mcity":
datapath_dict = {"kitti": "/mnt/storage8t/minghanz/Datasets/KITTI_data/kitti_data",
"kitti_odom": None,
"kitti_depth": os.path.join(script_path, "kitti_data"),
"TUM": None,
"lyft_1024": "/mnt/storage8t/minghanz/Datasets/lyft_kitti_seq/train",
"vkitti": "/mnt/storage8t/minghanz/Datasets/vKITTI2",
"kitti_filled_depth": "/mnt/storage8t/minghanz/Datasets/KITTI_data/kitti_data"}
elif self.opt.server == "sunny":
datapath_dict = {"kitti": "/media/sda1/minghanz/datasets/kitti/kitti_data",
"kitti_odom": None,
"kitti_depth": "/media/sda1/minghanz/datasets/kitti/kitti_data",
"TUM": None,
"lyft_1024": "/media/sda1/minghanz/datasets/lyft_kitti/train",
"vkitti": None,
"kitti_filled_depth": "/media/sda1/minghanz/datasets/kitti/kitti_data"}
# "lyft_1024": os.path.join(script_path, "data_download/train")} # ZMH: kitti_depth originally not shown as an option here
elif self.opt.server == "home":
datapath_dict = {"kitti": os.path.join(script_path, "kitti_data"),
"kitti_odom": None,
"kitti_depth": os.path.join(script_path, "kitti_data"),
"TUM": None,
"lyft_1024": None,
"vkitti": None,
"kitti_filled_depth": os.path.join(script_path, "kitti_data")}
else:
raise ValueError("server {} not recognized.".format(self.opt.server))
splitfile_dict = {"kitti": "{}_files.txt",
"kitti_odom": None,
"kitti_depth": "{}_files.txt",
"TUM": None,
"lyft_1024": "samp_1024_{}_files.txt",
"kitti_filled_depth": "{}_files.txt"} # ZMH: kitti_depth originally not shown as an option here
self.width_dict = {"kitti": 640,
"kitti_odom": None,
"kitti_depth": 640,
"TUM": None,
"lyft_1024": 512,
"kitti_filled_depth": 640} # ZMH: kitti_depth originally not shown as an option here
self.height_dict = {"kitti": 192,
"kitti_odom": None,
"kitti_depth": 192,
"TUM": None,
"lyft_1024": 224,
"kitti_filled_depth": 192} # ZMH: kitti_depth originally not shown as an option here # change lyft height from 256 to 192 to 224
self.full_res_shape = {}
n_datasets_train = len(self.opt.dataset)
n_datasets_val = len(self.opt.dataset_val)
assert len(self.opt.dataset) == len(self.opt.split_train)
assert len(self.opt.dataset_val) == len(self.opt.split_val)
dataset_train = {}
dataset_val = {}
## construct dataset_train
for i, ds_name in enumerate(self.opt.dataset):
fpath = os.path.join(script_path, "splits", self.opt.split_train[i], splitfile_dict[ds_name])
train_filenames = readlines(fpath.format("train"))
if "kitti" in ds_name:
img_ext = '.png' if self.opt.png else '.jpg'
elif "lyft" in ds_name:
img_ext = '.png'
else:
raise ValueError("This dataset not implemented yet.")
dataset_train[ds_name] = datasets_dict[ds_name](
datapath_dict[ds_name], train_filenames, self.height_dict[ds_name], self.width_dict[ds_name],
self.opt.frame_ids, 4, is_train=True, img_ext=img_ext
)
self.full_res_shape[ds_name] = dataset_train[ds_name].full_res_shape
# checking height and width are multiples of 32
assert self.height_dict[ds_name] % 32 == 0, "'height' must be a multiple of 32"
assert self.width_dict[ds_name] % 32 == 0, "'width' must be a multiple of 32"
num_train_samples = sum( [len(train_set) for train_set in dataset_train.values()] )
self.num_total_steps = num_train_samples // self.opt.batch_size * self.opt.num_epochs
## constuct dataset_val
for i, ds_name in enumerate(self.opt.dataset_val):
fpath = os.path.join(script_path, "splits", self.opt.split_val[i], splitfile_dict[ds_name])
val_filenames = readlines(fpath.format("val"))
if "kitti" in ds_name:
img_ext = '.png' if self.opt.png else '.jpg'
elif "lyft" in ds_name:
img_ext = '.png'
else:
raise ValueError("This dataset not implemented yet.")
dataset_val[ds_name] = datasets_dict[ds_name](
datapath_dict[ds_name], val_filenames, self.height_dict[ds_name], self.width_dict[ds_name],
self.opt.frame_ids, 4, is_train=False, img_ext=img_ext
)
self.full_res_shape[ds_name] = dataset_val[ds_name].full_res_shape
# checking height and width are multiples of 32
assert self.height_dict[ds_name] % 32 == 0, "'height' must be a multiple of 32"
assert self.width_dict[ds_name] % 32 == 0, "'width' must be a multiple of 32"
### from dataset to dataloader
if len(self.opt.dataset) == 1:
self.train_loader = DataLoader(
dataset_train[self.opt.dataset[0]], self.opt.batch_size, not self.opt.no_shuffle,
num_workers=self.opt.num_workers, pin_memory=True, drop_last=True, collate_fn=my_collate_fn)
self.val_loader = DataLoader(
dataset_val[self.opt.dataset_val[0]], self.opt.batch_size, not self.opt.no_shuffle,
num_workers=self.opt.num_workers, pin_memory=True, drop_last=True, collate_fn=my_collate_fn)
print("Using train split:")
for split in self.opt.split_train:
print(split, end=" ")
print("\nfor dataset:")
for name in self.opt.dataset:
print(name, end=" ")
print("\nThere are {:d} training items and {:d} validation items\n".format(
len(dataset_train[self.opt.dataset[0]]), len(dataset_val[self.opt.dataset_val[0]])))
else:
concat_train_set = ConcatDataset( list(dataset_train.values()) )
concat_val_set = ConcatDataset( list(dataset_val.values()) )
concat_sampler_train = SamplerForConcat(concat_train_set, self.opt.batch_size, drop_last=True)
concat_sampler_val = SamplerForConcat(concat_val_set, self.opt.batch_size, drop_last=True)
self.train_loader = DataLoader(
concat_train_set, batch_sampler=concat_sampler_train,
num_workers=self.opt.num_workers, pin_memory=True, collate_fn=my_collate_fn)
self.val_loader = DataLoader(
concat_val_set, batch_sampler=concat_sampler_val,
num_workers=self.opt.num_workers, pin_memory=True, collate_fn=my_collate_fn)
print("Using val split:")
for split in self.opt.split_val:
print(split, end=" ")
print("\nfor dataset:")
for name in self.opt.dataset_val:
print(name, end=" ")
print("\nThere are {:d} training items and {:d} validation items\n".format(
len(concat_train_set), len(concat_val_set)))
self.val_iter = iter(self.val_loader)
self.val_count = 0
self.ctime = time.ctime()
## create the path to log files (opt, model, writer, pcd, ...)
## in order to easily switch all loggers on or off by setting the paths to None
if self.opt.disable_log:
self.path_model = None
self.path_opt = None
self.writers = None
else:
self.path_model = os.path.join(self.log_path, "models" + "_"+self.ctime)
self.path_opt = self.path_model
self.writers = {}
for mode in ["train", "val", "val_set"]:
self.writers[mode] = SummaryWriter(os.path.join(self.log_path, mode + '_' + self.ctime))
if self.opt.save_pic_intv != 0:
self.nkern_path = os.path.join(self.log_path, "nkerns_"+self.ctime)
if not os.path.exists(self.nkern_path):
os.makedirs(self.nkern_path)
else:
self.nkern_path = None
if self.opt.save_pcd_intv != 0:
self.path_pcd = os.path.join(self.log_path, "pcds_"+self.ctime)
if not os.path.exists(self.path_pcd):
os.makedirs(self.path_pcd)
else:
self.path_pcd = None
if not self.opt.no_ssim:
self.ssim = SSIM()
self.ssim.to(self.device)
self.backproject_depth = {}
self.project_3d = {}
for scale in self.opt.scales:
self.backproject_depth[scale] = {}
self.project_3d[scale] = {}
for datasrc in self.opt.dataset+self.opt.dataset_val:
h = self.height_dict[datasrc] // (2 ** scale)
w = self.width_dict[datasrc] // (2 ** scale)
self.backproject_depth[scale][datasrc] = BackprojectDepth(self.opt.batch_size, h, w)
self.backproject_depth[scale][datasrc].to(self.device)
self.project_3d[scale][datasrc] = Project3D(self.opt.batch_size, h, w)
self.project_3d[scale][datasrc].to(self.device)
self.depth_metric_names = [
"de/abs_rel", "de/sq_rel", "de/rms", "de/log_rms", "da/a1", "da/a2", "da/a3"]
self.save_opts()
self.set_other_params_from_opt() # moved from get_innerp_from_grid_flat
if self.opt.cvo_loss_dense and self.opt.dense_flat_grid and self.opt.use_normal_v3:
self.normal_from_depth_v3 = NormalFromDepthDense().to(self.device)
def set_other_params_from_opt(self):
if self.opt.dense_flat_grid:
self.dist_combos = [(0, 1, True, False), (0, 0, True, False), (0, -1, True, False)]
if self.opt.sup_cvo_pose_lidar:
self.dist_combos.append((0, 1, True, True))
self.dist_combos.append((0, -1, True, True))
if self.opt.align_preds:
self.dist_combos.append( (0, 1, False, False) )
self.dist_combos.append( (0, -1, False, False) )
# self.dist_combos = [(0, 1, False, False), (0, -1, False, False)]
# inp_combos = self.inp_combo_from_dist_combo(dist_combos)
if self.opt.use_panoptic:
self.feats_cross = ["xyz", "seman"]
self.feats_self = ["xyz", "panop"]
else:
self.feats_cross = ["xyz", "hsv"]
self.feats_self = ["xyz", "hsv"]
# feats_needed = ["xyz", "hsv"]
self.feats_ell = {}
# self.ell_base = 0.05
self.ell_base = self.opt.ell_geo
# if self.opt.random_ell:
# self.feats_ell["xyz"] = np.abs(self.ell_base* np.random.normal()) + 0.02
# else:
# self.feats_ell["xyz"] = self.ell_base
self.feats_ell["hsv"] = 0.2
self.feats_ell["panop"] = 0.2 # in Angle mode this is not needed
self.feats_ell["seman"] = 0.2 # in Angle mode this is not needed
def set_train(self):
"""Convert all models to training mode
"""
for m in self.models.values():
m.train()
self.train_flag = True
self.run_mode = "train"
def set_eval(self):
"""Convert all models to testing/evaluation mode
"""
for m in self.models.values():
m.eval()
self.train_flag = False
self.run_mode = "val"
def set_eval_set(self):
"""Convert all models to testing/evaluation mode, used in val_set
"""
for m in self.models.values():
m.eval()
self.train_flag = False
self.run_mode = "val_set"
def train(self):
"""Run the entire training pipeline
"""
# with torch.autograd.set_detect_anomaly(True):
# with torch.autograd.detect_anomaly():
self.epoch = 0
self.step = 0
self.start_time = time.time()
if self.opt.val_set_only:
assert self.opt.load_weights_folder_parent is not None, "load_weights_folder_parent not given."
self.run_val_set_only()
else:
for self.epoch in range(self.opt.num_epochs):
torch.manual_seed(self.epoch) ## Jan 17, solve the problem of different shuffling of mini-batches between using and not using cvo trials after epoch 1.
np.random.seed(self.epoch)
self.run_epoch()
if (self.epoch + 1) % self.opt.save_frequency == 0:
self.save_model()
if not self.opt.no_val_set:
self.val_set()
def run_val_set_only(self):
"""
Use pretrained weights to run val set and log error to tensorboard
"""
if "weights" in self.opt.load_weights_folder_parent:
model_folders = [self.opt.load_weights_folder_parent]
else:
model_folder_list = os.listdir(self.opt.load_weights_folder_parent)
# file_name_digit = [int(file_names[i].split('.')[0]) for i in range(len(file_names))]
# file_name_idx = sorted(range(len(file_name_digit)),key=file_name_digit.__getitem__)
# file_names = [file_names[i] for i in file_name_idx]
model_folders = []
model_seq = []
for item in model_folder_list:
path = os.path.join(self.opt.load_weights_folder_parent, item)
if os.path.isdir(path):
model_folders.append(path)
weight_num=float(item.split('_')[-1])
model_seq.append(weight_num)
model_folders_idx = sorted(range(len(model_seq)), key=model_seq.__getitem__)
model_folders = [model_folders[i] for i in model_folders_idx]
self.weight_n = 0
for model_folder in model_folders:
self.opt.load_weights_folder = model_folder
self.load_model()
self.val_set()
self.weight_n += 1
def run_epoch(self):
"""Run a single epoch of training and validation
"""
print("Training")
self.set_train()
self.cur_timing_step = self.step
self.before_op_time = time.time()
for self.batch_idx, inputs in enumerate(self.train_loader):
# before_op_time = time.time()
# if self.batch_idx < 20000:
# self.geo_scale = 1
# elif self.batch_idx < 40000:
# self.geo_scale = 0.5
# else:
# self.geo_scale = 0.1
self.geo_scale = 0.1
self.show_range = self.batch_idx % 1000 == 0
outputs, losses = self.process_batch(inputs)
## ZMH: commented and use effective_batch instead
## https://medium.com/@davidlmorton/increasing-mini-batch-size-without-increasing-memory-6794e10db672
# self.model_optimizer.zero_grad()
# ## losses['loss_cvo/hsv_tog_xyz_ori_'] or 'loss_cos/hsv_tog_xyz_tog_'
# losses["loss"].backward()
# self.model_optimizer.step()
if self.batch_idx > 0 and self.batch_idx % self.opt.iters_per_update == 0:
self.model_optimizer.step()
self.model_optimizer.zero_grad()
# print('optimizer update at', iter_overall)
if self.opt.cvo_as_loss:
# loss = losses["loss_cos/hsv_tog_xyz_tog_"] / self.opt.iters_per_update
# loss = ( losses["loss_cvo/hsv_ori_xyz_ori__2"] + losses["loss_cvo/hsv_ori_xyz_ori__3"] )/2 / self.opt.iters_per_update
# loss = ( losses["loss_inp/hsv_ori_xyz_ori__2"] + losses["loss_inp/hsv_ori_xyz_ori__3"] )/2 / self.opt.iters_per_update
# loss = ( losses["loss_inp/hsv_ori_xyz_ori__0"] + losses["loss_inp/hsv_ori_xyz_ori__1"] + losses["loss_inp/hsv_ori_xyz_ori__2"] + losses["loss_inp/hsv_ori_xyz_ori__3"] ) / self.opt.iters_per_update
loss = ( losses["loss_inp/xyz_ori__0"] + losses["loss_inp/xyz_ori__1"] + losses["loss_inp/xyz_ori__2"] + losses["loss_inp/xyz_ori__3"] ) / self.opt.iters_per_update
# loss = ( losses["loss_cvo/hsv_ori_xyz_ori__0"] + losses["loss_cvo/hsv_ori_xyz_ori__1"] + losses["loss_cvo/hsv_ori_xyz_ori__2"] + losses["loss_cvo/hsv_ori_xyz_ori__3"] ) / self.opt.iters_per_update
else:
loss = losses["loss"] / self.opt.iters_per_update
if self.opt.disp_in_loss:
loss += 0.1 * (losses["loss_disp/0"]+ losses["loss_disp/1"] + losses["loss_disp/2"] + losses["loss_disp/3"]) / self.num_scales / self.opt.iters_per_update ## magnitude of 0.1
if self.opt.depth_in_loss:
loss += 1e-3 * (losses["loss_depth/0"]+ losses["loss_depth/1"] + losses["loss_depth/2"] + losses["loss_depth/3"]) / self.num_scales / self.opt.iters_per_update ## magnitude of 10
if self.opt.supervised_by_gt_depth:
# loss += 0.1 * losses["loss_cos/sum"] / self.num_scales / self.opt.iters_per_update
# loss += 1e-6 * losses["loss_inp/sum"] / self.num_scales / self.opt.iters_per_update
loss += losses["loss_inp/sum"] / self.num_scales / self.opt.iters_per_update
if self.opt.sup_cvo_pose_lidar and not self.opt.dense_flat_grid:
loss += 0.1 * losses["loss_pose/cos_sum"] / self.num_scales / self.opt.iters_per_update
loss.backward()
# log less frequently after the first 2000 steps to save time & disk space
early_phase = self.batch_idx % self.opt.log_frequency == 0 and self.step < 2000
late_phase = self.step % 2000 == 0
if early_phase or late_phase:
cur_time = time.time()
duration = cur_time - self.before_op_time
self.log_time(self.batch_idx, duration, losses["loss"].cpu().data)
self.cur_timing_step = self.step
self.before_op_time = cur_time
if "depth_gt" in inputs:
self.compute_depth_losses(inputs, outputs, losses)
self.log("train", inputs, outputs, losses)
self.val()
self.step += 1
### ZMH: prevent memory leakage: https://discuss.pytorch.org/t/gpu-memory-consumption-increases-while-training/2770
# del loss, losses, outputs, inputs
## ZMH: monitor GPU usage:
if early_phase or late_phase:
allo = torch.cuda.memory_allocated(self.device)/1024/1024
cach = torch.cuda.memory_cached(self.device)/1024/1024
max_allo = torch.cuda.max_memory_allocated(self.device)/1024/1024
max_cach = torch.cuda.max_memory_cached(self.device)/1024/1024
print("GPU memory allocated at the end of iter {}: cur: {:.1f}, {:.1f}; max: {:.1f}, {:.1f}".format(self.step-1, allo, cach, \
max_allo, max_cach ))
# if (self.step-1) % 100 == 0:
if self.writers is not None:
self.writers["train"].add_scalar("Mem/allo", allo, self.step-1)
self.writers["train"].add_scalar("Mem/cach", cach, self.step-1)
self.writers["train"].add_scalar("Mem/max_allo", max_allo, self.step-1)
self.writers["train"].add_scalar("Mem/max_cach", max_cach, self.step-1)
# torch.cuda.reset_peak_stats()
torch.cuda.reset_max_memory_cached(self.device)
torch.cuda.reset_max_memory_allocated(self.device)
# for obj in gc.get_objects():
# try:
# if torch.is_tensor(obj) or (hasattr(obj, 'data') and torch.is_tensor(obj.data)):
# print(type(obj), obj.size())
# except:
# pass
# objgraph.show_most_common_types()
# objgraph.show_growth()
# new_ids = objgraph.get_new_ids()
# objgraph.get_leaking_objects()
# print(self.step, '---------')
self.model_lr_scheduler.step()
def process_batch(self, inputs):
"""Pass a minibatch through the network and generate images and losses
"""
for key, ipt in inputs.items():
if "index" in key:
continue
elif "velo_gt" not in key:
inputs[key] = ipt.to(self.device)
else:
inputs[key] = [ipt_i.to(self.device) for ipt_i in ipt]
### check cur_datasrc for cross-dataset training
if inputs[("color_aug", 0, 0)].shape[-1] == self.width_dict["kitti"]:
self.cur_datasrc = "kitti"
elif inputs[("color_aug", 0, 0)].shape[-1] == self.width_dict["lyft_1024"]:
self.cur_datasrc = "lyft_1024"
else:
raise ValueError("Image with width {} not recognized".format(inputs[("color_aug", 0, 0)].shape[-1]))
if self.opt.pose_model_type == "shared":
# If we are using a shared encoder for both depth and pose (as advocated
# in monodepthv1), then all images are fed separately through the depth encoder.
all_color_aug = torch.cat([inputs[("color_aug", i, 0)] for i in self.opt.frame_ids])
all_features = self.models["encoder"](all_color_aug)
all_features = [torch.split(f, self.opt.batch_size) for f in all_features]
features = {}
for i, k in enumerate(self.opt.frame_ids):
features[k] = [f[i] for f in all_features]
outputs = self.models["depth"](features[0])
else:
# Otherwise, we only feed the image with frame_id 0 through the depth encoder
features = self.models["encoder"](inputs["color_aug", 0, 0])
outputs = self.models["depth"](features)
### ZMH: outputs have disp image of different scales
## ZMH: switch
outputs_others = None
## ZMH: predict depth for each image (other than the host image)
features_others = {} # initialize a dict
outputs_others = {}
for i in self.opt.frame_ids:
if i == 0:
continue
features_others[i] = self.models["encoder"](inputs["color_aug", i, 0])
outputs_others[i] = self.models["depth"](features_others[i] )
if self.opt.use_panoptic:
with torch.no_grad():
for i in self.opt.frame_ids:
list_of_tuple_for_panop = to_panoptic(inputs["color", i, 0], self.ups_cfg)
list_of_panop_feature = []
list_of_seman_feature = []
for ib in range(self.opt.batch_size):
panop_feature, seman_feature = self.panoptic_model( *( list_of_tuple_for_panop[ib] ) ) # 1*Catogories*H*W
panop_feature = F.softmax(panop_feature, dim=1)
seman_feature = F.softmax(seman_feature, dim=1)
list_of_panop_feature.append(panop_feature)
list_of_seman_feature.append(seman_feature)
outputs[("panoptic", i, 0)] = list_of_panop_feature
outputs[("semantic", i, 0)] = torch.cat(list_of_seman_feature, dim=0) # This may not be viable fpr panop because different images may have different number of instances
for scale in self.opt.scales:
if scale == 0:
continue
outputs[("semantic", i, scale)] = F.interpolate(outputs[("semantic", i, 0)], scale_factor=0.5**scale)
outputs[("panoptic", i, scale)] = []
for ib in range(self.opt.batch_size):
rescaled_panop = F.interpolate(outputs[("panoptic", i, 0)][ib], scale_factor=0.5**scale)
outputs[("panoptic", i, scale)].append(rescaled_panop)
# mode = "train" if self.train_flag else "val"
# save_path = os.path.join(self.log_path, mode + '_' + self.ctime )
# self.panop_visualizer.paint(inputs["color", i, 0], outputs["panoptic", i, 0], save_path=save_path, step=self.step )
if self.opt.predictive_mask:
outputs["predictive_mask"] = self.models["predictive_mask"](features)
## ZMH: process depth for each image
if outputs_others is not None:
for i in self.opt.frame_ids:
if i == 0:
continue
outputs_others[i]["predictive_mask"] = self.models["predictive_mask"](features_others[i])
if self.use_pose_net:
outputs.update(self.predict_poses(inputs, features))
# self.generate_depths_pred(inputs, outputs, outputs_others)
# self.generate_images_pred(inputs, outputs)
self.generate_images_pred(inputs, outputs, outputs_others)
losses = self.compute_losses(inputs, outputs, outputs_others)
return outputs, losses
def predict_poses(self, inputs, features):
"""Predict poses between input frames for monocular sequences.
"""
outputs = {}
if self.num_pose_frames == 2:
# In this setting, we compute the pose to each source frame via a
# separate forward pass through the pose network.
# select what features the pose network takes as input
if self.opt.pose_model_type == "shared":
pose_feats = {f_i: features[f_i] for f_i in self.opt.frame_ids}
else:
pose_feats = {f_i: inputs["color_aug", f_i, 0] for f_i in self.opt.frame_ids}
for f_i in self.opt.frame_ids[1:]:
if f_i != "s":
# To maintain ordering we always pass frames in temporal order
if f_i < 0:
pose_inputs = [pose_feats[f_i], pose_feats[0]]
else:
pose_inputs = [pose_feats[0], pose_feats[f_i]]
if self.opt.pose_model_type == "separate_resnet":
pose_inputs = [self.models["pose_encoder"](torch.cat(pose_inputs, 1))]
elif self.opt.pose_model_type == "posecnn":
pose_inputs = torch.cat(pose_inputs, 1)
axisangle, translation = self.models["pose"](pose_inputs)
outputs[("axisangle", 0, f_i)] = axisangle
outputs[("translation", 0, f_i)] = translation
# Invert the matrix if the frame id is negative
outputs[("cam_T_cam", 0, f_i)] = transformation_from_parameters(
axisangle[:, 0], translation[:, 0], invert=(f_i < 0))
else:
# Here we input all frames to the pose net (and predict all poses) together
if self.opt.pose_model_type in ["separate_resnet", "posecnn"]:
pose_inputs = torch.cat(
[inputs[("color_aug", i, 0)] for i in self.opt.frame_ids if i != "s"], 1)
if self.opt.pose_model_type == "separate_resnet":
pose_inputs = [self.models["pose_encoder"](pose_inputs)]
elif self.opt.pose_model_type == "shared":
pose_inputs = [features[i] for i in self.opt.frame_ids if i != "s"]
axisangle, translation = self.models["pose"](pose_inputs)
for i, f_i in enumerate(self.opt.frame_ids[1:]):
if f_i != "s":
outputs[("axisangle", 0, f_i)] = axisangle
outputs[("translation", 0, f_i)] = translation
outputs[("cam_T_cam", 0, f_i)] = transformation_from_parameters(
axisangle[:, i], translation[:, i])
return outputs
def val(self):
"""Validate the model on a single minibatch
"""
self.set_eval()
try:
inputs = self.val_iter.next()
except StopIteration:
self.val_iter = iter(self.val_loader)
inputs = self.val_iter.next()
self.val_count = 0
self.val_count += 1
with torch.no_grad():
outputs, losses = self.process_batch(inputs)
if "depth_gt" in inputs:
self.compute_depth_losses(inputs, outputs, losses)
self.log("val", inputs, outputs, losses)
del inputs, outputs, losses
print("Step:", self.step, "; Val_count:", self.val_count, "Epoch:", self.epoch, "Batch_idx:", self.batch_idx)
self.set_train()
def val_set(self):
self.set_eval_set()
print("------------------")
print("Evaluating on the whole validating set at Epoch {}...".format(self.epoch))
losses_sum = {}
val_start_time = time.time()
with torch.no_grad():
self.geo_scale = 0.1
self.show_range = False
if self.opt.val_set_only:
self.step = 0
# ## for writing a file of samples in the sequence of the iteration during training
# f = open("/root/repos/monodepth2/splits/eigen_zhou/val_files.txt")
# lines = f.readlines()
# g = open("/root/repos/monodepth2/splits/eigen_zhou/val_files_samp.txt", "w")
for batch_idx, inputs in enumerate(self.val_loader):
# ## for writing a file of samples in the sequence of the iteration during training
# # print(inputs["index"])
# line0 = lines[inputs["index"][0]]
# line1 = lines[inputs["index"][1]]
# g.write(line0)
# g.write(line1)
# if batch_idx > 100:
# break
# continue
outputs, losses = self.process_batch(inputs)
if "depth_gt" in inputs:
self.compute_depth_losses(inputs, outputs, losses)
for l, v in losses.items():
if batch_idx == 0:
losses_sum[l] = torch.tensor(0, dtype=torch.float32, device=self.device )
if type(v) != type(losses_sum[l]):
v = torch.tensor(v, dtype=torch.float32, device=self.device )
losses_sum[l] += v
if batch_idx % 200 == 0:
print("Passed {} mini-batches in {:.2f} secs.".format(batch_idx, time.time()-val_start_time) )
if self.opt.val_set_only:
self.step += 1
# ## for writing a file of samples in the sequence of the iteration during training
# f.close()
# g.close()
# return
val_end_time = time.time()
print("Val time: {:.2f}".format(val_end_time - val_start_time) )
print("Total # of mini-batches in val set:", batch_idx+1)
for l, v in losses_sum.items():
losses_sum[l] = v / (batch_idx+1)
print("{}: {:.2f}".format(l, losses_sum[l].item() ) ) # use .item to transform the 0-dim tensor to a python number
self.log("val_set", inputs, outputs, losses_sum)
### ZMH: prevent GPU memory leakage:
del inputs, outputs, losses, losses_sum
self.set_train()
print("--------------------")
### ZMH: make it a function to be repeated for images other than index 0
def from_disp_to_depth(self, disp, scale, force_multiscale=False):
"""ZMH: generate depth of original scale unless self.opt.v1_multiscale
"""
## ZMH: force_multiscale option added by me to adapt to cases where we want multiscale depth
if self.opt.v1_multiscale or force_multiscale:
source_scale = scale
else:
disp = F.interpolate(
disp, [self.height_dict[self.cur_datasrc], self.width_dict[self.cur_datasrc]], mode="bilinear", align_corners=False)
source_scale = 0
_, depth = disp_to_depth(disp, self.opt.min_depth, self.opt.max_depth, self.opt.ref_depth, self.opt.depth_ref_mode)
return depth, source_scale
def gen_pcl_gt(self, inputs, outputs, disp, scale, frame_id, T_inv=None):
### ZMH: for host frame, T_inv is None.
### ZMH: gt depth -> point cloud gt (for other frames, transform the point cloud to host frame)
### ZMH: Due to that ground truth depth image is not valid at every pixel, the length of pointcloud in the mini-batch is not consistent.
### ZMH: Therefore samples are processed one by one in the mini-batch.
cam_points_gt, masks = self.backproject_depth[scale][self.cur_datasrc](
inputs[("depth_gt_scale", frame_id, scale)], inputs[("inv_K", scale)], separate=True)
if T_inv is None:
outputs[("xyz_gt", frame_id, scale)] = cam_points_gt
rgb_gt = {}
for ib in range(self.opt.batch_size):
color = inputs[("color", frame_id, scale)][ib]
color = color.view(1, 3, -1)
color_sel = color[..., masks[ib]]
rgb_gt[ib] = color_sel
outputs[("rgb_gt", frame_id, scale)] = rgb_gt
else:
cam_points_other_gt_in_host = {}
rgb_other_gt = {}
for ib in range(self.opt.batch_size):
T_inv_i = T_inv[ib:ib+1]
cam_points_other_gt_in_host[ib] = torch.matmul(T_inv_i, cam_points_gt[ib] )
color = inputs[("color", frame_id, scale)][ib]
color = color.view(1, 3, -1)
color_sel = color[..., masks[ib]]
rgb_other_gt[ib] = color_sel
outputs[("xyz_gt", frame_id, scale)] = cam_points_other_gt_in_host
outputs[("rgb_gt", frame_id, scale)] = rgb_other_gt
### ZMH: disparity prediction -> depth prediction -> point cloud prediction (for other frames, transform the point cloud to host frame)
depth_curscale, _ = self.from_disp_to_depth(disp, scale, force_multiscale=True)
cam_points_curscale = self.backproject_depth[scale][self.cur_datasrc](
depth_curscale, inputs[("inv_K", scale)])
if T_inv is None:
xyz_is = {}
rgb_is = {}
for ib in range(self.opt.batch_size):
xyz_is[ib] = cam_points_curscale[ib:ib+1, ..., masks[ib]]
rgb_is[ib] = inputs[("color", frame_id, scale)][ib].view(1,3,-1)[..., masks[ib]]
# outputs[("xyz_in_host", 0, scale)] = cam_points_curscale
outputs[("xyz_in_host", frame_id, scale)] = xyz_is
outputs[("rgb_in_host", frame_id, scale)] = rgb_is
else:
outputs[("depth", frame_id, scale)] = depth_curscale
### ZMH: transform points in source frame to host frame
cam_points_other_in_host = torch.matmul(T_inv, cam_points_curscale)
### ZMH: log the 3d points to output (points in source frame transformed to host frame)
### ZMH: to sample the points only at where gt are avaiable:
xyz_is = {}
rgb_is = {}
for ib in range(self.opt.batch_size):
xyz_is[ib] = cam_points_other_in_host[ib:ib+1, ..., masks[ib]]
rgb_is[ib] = inputs[("color", frame_id, scale)][ib].view(1,3,-1)[..., masks[ib]]
# outputs[("xyz_in_host", frame_id, scale)] = cam_points_other_in_host
outputs[("xyz_in_host", frame_id, scale)] = xyz_is
outputs[("rgb_in_host", frame_id, scale)] = rgb_is
def gen_pcl_wrap_host(self, inputs, outputs, scale):
### 1. gt from lidar
cam_points_gt, masks = self.backproject_depth[scale][self.cur_datasrc](
inputs[("depth_gt_scale", 0, scale)], inputs[("inv_K", scale)], separate=True)
outputs[("xyz_gt", 0, scale)] = cam_points_gt
rgb_gt = {}
for ib in range(self.opt.batch_size):
color = inputs[("color", 0, scale)][ib]
color = color.view(1, 3, -1)
color_sel = color[..., masks[ib]]
rgb_gt[ib] = color_sel
outputs[("rgb_gt", 0, scale)] = rgb_gt
### 2. host frame same sampling
masks = inputs[("depth_mask", 0, scale)]
masks = [masks[i].view(-1) for i in range(masks.shape[0]) ]
cam_points_host = self.backproject_depth[scale][self.cur_datasrc](
outputs[("depth_wrap", 0, scale)], inputs[("inv_K", scale)] )
xyz_is = {}
rgb_is = {}
for ib in range(self.opt.batch_size):
xyz_is[ib] = cam_points_host[ib:ib+1, ..., masks[ib]]
rgb_is[ib] = inputs[("color", 0, scale)][ib].view(1,3,-1)[..., masks[ib]]
outputs[("xyz_in_host", 0, scale)] = xyz_is
outputs[("rgb_in_host", 0, scale)] = rgb_is
return masks
def gen_pcl_wrap_other(self, inputs, outputs, scale, frame_id, T_inv, masks):
### 3. host frame by wrapping from adjacent frame
uv_wrap = outputs[("uv_wrap", frame_id, scale)].view(self.opt.batch_size, 2, -1)
ones_ = torch.ones((self.opt.batch_size, 1, uv_wrap.shape[2]), dtype=uv_wrap.dtype, device=uv_wrap.device)
own_id_coords = torch.cat((uv_wrap,
ones_), dim=1) # B*3*N
cam_points_wrap = self.backproject_depth[scale][self.cur_datasrc](
outputs[("depth_wrap", frame_id, scale)], inputs[("inv_K", scale)], own_pix_coords=own_id_coords )
cam_points_other_in_host = torch.matmul(T_inv, cam_points_wrap)
xyz_is = {}
rgb_is = {}
for ib in range(self.opt.batch_size):
xyz_is[ib] = cam_points_other_in_host[ib:ib+1, ..., masks[ib]]
rgb_is[ib] = outputs[("color_wrap", frame_id, scale)][ib].view(1,3,-1)[..., masks[ib]]
outputs[("xyz_in_host", frame_id, scale)] = xyz_is
outputs[("rgb_in_host", frame_id, scale)] = rgb_is
### 4. generate gt for adjacent frames
cam_points_gt, masks = self.backproject_depth[scale][self.cur_datasrc](
inputs[("depth_gt_scale", frame_id, scale)], inputs[("inv_K", scale)], separate=True)
# cam_points_gt_in_host = torch.matmul(T_inv, cam_points_gt)
# outputs[("xyz_gt", frame_id, scale)] = cam_points_gt_in_host
outputs[("xyz_gt", frame_id, scale)] = cam_points_gt
rgb_gt = {}
for ib in range(self.opt.batch_size):
color = inputs[("color", frame_id, scale)][ib]
color = color.view(1, 3, -1)
color_sel = color[..., masks[ib]]
rgb_gt[ib] = color_sel
outputs[("rgb_gt", frame_id, scale)] = rgb_gt