-
Notifications
You must be signed in to change notification settings - Fork 5
/
main_attenStereoNet.py
1573 lines (1370 loc) · 81.1 KB
/
main_attenStereoNet.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
# !/usr/bin/env python3
# -*-coding:utf-8-*-
# @file: train_attenStereoNet.py
# @brief:
# @author: Changjiang Cai, [email protected], [email protected]
# @version: 0.0.1
# @creation date: 17-10-2019
# @last modified: Sat 08 Aug 2020 02:00:13 AM EDT
from __future__ import print_function
from math import log10
import math
from src.baselines.GANet.libs.GANet.modules.GANet import MyLoss2
import sys
import shutil
import os
from os.path import join as pjoin
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import cv2
from torch.autograd import Variable
from torch.utils.data import DataLoader
import torch.nn.functional as F
from src.loaddata.data import get_training_set, load_test_data, test_transform
from src.loaddata.dataset import get_virtual_kitti2_filelist
from torch.utils.tensorboard import SummaryWriter
#from src.utils import writeKT15FalseColors # this is numpy fuction, it is SO SLOW !!!
# this is cython fuction, it is SO QUICK !!!
from src.cython import writeKT15FalseColor as KT15FalseClr
from src.cython import writeKT15ErrorLogColor as KT15LogClr
#combine them to the following:
from src.dispColor import colormap_jet_batch_image,KT15FalseColorDisp,KT15LogColorDispErr
import numpy as np
import src.pfmutil as pfm
from src.modules.embednetwork import get_embed_losses
import time
import json
from datetime import datetime
import random
""" compressed embeddings to k (e.g., k = 3) dimensions by PCA for visualization """
def pca_embedding(embedding, k = 3, isChanelLast = True):
#print( "[***] embedding shape = ", embedding.shape)
embedding = embedding.permute(0,2,3,1)
embedding = embedding.contiguous()
N, H, W, C = embedding.size()[:]
#print( "[***] permute embedding shape = ", embedding.shape)
embedding = embedding.view(-1, C)
u, s, _ = torch.svd(embedding)
#print( "[***] u shape = ", u.shape, " s shape = ", s.shape)
# first k singular values;
s_k = s[0:k] # in shape [k,k]
u_k = u[:,0:k] # in shape [-1, k]
output = torch.mm(u_k, torch.diag(s_k)).view(N,H,W,k)
if not isChanelLast:
output = output.permute(0, 3, 1, 2)
return output
""" ASN: Attension Stereomatching Network """
class attenStereoNet(object):
def __init__(self, args):
self.args = args
self.max_disp = args.max_disp
self.model_name = args.model_name
#self.isFreezeEmbed = (str(args.isFreezeEmbed) == 'true')
#self.is_embed = str(args.is_embed).lower() == 'true'
self.lr = args.lr
self.kitti2012 = args.kitti2012
self.kitti2015 = args.kitti2015
self.virtual_kitti2 = args.virtual_kitti2
self.checkpoint_dir = args.checkpoint_dir
self.log_summary_step = args.log_summary_step
self.isTestingMode = (str(args.mode).lower() == 'test')
self.is_semantic = (str(args.is_semantic).lower() == 'true')
self.cost_filter_grad = (str(args.cost_filter_grad).lower() == 'true')
self.is_quarter_size_cost_volume_gcnet = str(args.is_quarter_size_cost_volume_gcnet).lower() == 'true'
# newly added for lr schedule, especially for DFN+PSM;
#self.is_fixed_lr = str(args.is_fixed_lr).lower() == 'true'
self.lr_adjust_epo_thred = args.lr_adjust_epo_thred
self.lr_scheduler = str(args.lr_scheduler).lower()
self.lr_epoch_steps = [int(i) for i in str(args.lr_epoch_steps).split("-")] if args.lr_epoch_steps is not "" else []
#self.is_kt12_gray = (str(args.is_kt12_gray).lower() == 'true')
self.kt12_image_mode = str(args.kt12_image_mode).lower()
self.is_data_augment = str(args.is_data_augment).lower() == 'true'
#print ("[***] is_fixed_lr = ", self.is_fixed_lr)
print ("[***] is_data_augment = ", self.is_data_augment)
# I find complicated data_augment is not helpful here;
assert self.is_data_augment == False
if self.kitti2012:
self.is_semantic = False
#update args for saving it to a json file;
args.is_semantic = 'false'
print("[***]processing kitti2012 {} images, and maunally setting self.is_semantic = {}".format(
self.kt12_image_mode, self.is_semantic))
if self.model_name == 'ASN-Embed-GANet-Deep':
from src.modules.attenStereoNet_embed_ganet_deep import AttenStereoNet
elif self.model_name == 'ASN-Embed-GANet11': # i.e., GANet-11
from src.modules.attenStereoNet_embed_ganet11 import AttenStereoNet
elif self.model_name == 'ASN-Embed-PSM':
from src.modules.attenStereoNet_embed_psm import AttenStereoNet
elif self.model_name == 'ASN-Embed-GCNet':
from src.modules.attenStereoNet_embed_gcnet import AttenStereoNet
#elif self.model_name == 'ASN-Embed-DispNetC-V0':
# from src.modules.attenStereoNet_embed_dispnetc_v0 import AttenStereoNet
elif self.model_name == 'ASN-Embed-DispNetC':
from src.modules.attenStereoNet_embed_dispnetc import AttenStereoNet
elif self.model_name == 'ASN-DFN-DispNetC':
from src.modules.attenStereoNet_dfn_dispnetc import AttenStereoNet
elif self.model_name == 'ASN-DFN-PSM':
from src.modules.attenStereoNet_dfn_psm import AttenStereoNet
elif self.model_name == 'ASN-DFN-GCNet':
from src.modules.attenStereoNet_dfn_gcnet import AttenStereoNet
elif self.model_name == 'ASN-DFN-GANet-Deep':
from src.modules.attenStereoNet_dfn_ganet_deep import AttenStereoNet
elif self.model_name == 'ASN-PAC-GANet-Deep':
from src.modules.attenStereoNet_pac_ganet_deep import AttenStereoNet
elif self.model_name == 'ASN-PAC-PSM':
from src.modules.attenStereoNet_pac_psm import AttenStereoNet
elif self.model_name == 'ASN-PAC-GCNet':
from src.modules.attenStereoNet_pac_gcnet import AttenStereoNet
elif self.model_name == 'ASN-PAC-DispNetC':
from src.modules.attenStereoNet_pac_dispnetc import AttenStereoNet
elif self.model_name == 'ASN-SGA-PSM':
from src.modules.attenStereoNet_sga_psm import AttenStereoNet
elif self.model_name == 'ASN-SGA-GCNet':
from src.modules.attenStereoNet_sga_gcnet import AttenStereoNet
elif self.model_name == 'ASN-SGA-DispNetC':
from src.modules.attenStereoNet_sga_dispnetc import AttenStereoNet
else:
raise Exception("No suitable model found ...")
self.cuda = args.cuda
if not self.isTestingMode: # training mode
print('===> Loading datasets')
train_set = get_training_set(args.data_path, args.training_list,
[args.crop_height, args.crop_width],
args.kitti2012, args.kitti2015, args.virtual_kitti2,
args.shift,
self.is_semantic,
#self.is_kt12_gray
self.kt12_image_mode,
self.is_data_augment
)
self.training_data_loader = DataLoader(dataset=train_set,
num_workers=args.threads, batch_size=args.batchSize,
shuffle=True, drop_last=True)
self.train_loader_len = len(self.training_data_loader)
self.criterion = MyLoss2(thresh=3, alpha=2)
if not os.path.exists(self.checkpoint_dir):
os.makedirs(self.checkpoint_dir)
print('===> Building model')
if self.model_name.find('GCNet') != -1:# including `GCNet`
my_kwargs = {
'is_kendall_version': str(args.is_kendall_version).lower() == 'true',
'is_quarter_size_cost_volume_gcnet': self.is_quarter_size_cost_volume_gcnet,
}
else:
my_kwargs = {}
if self.model_name in ['ASN-DFN-PSM','ASN-DFN-DispNetC', 'ASN-DFN-GANet-Deep', 'ASN-DFN-GCNet']:
print ('[!!!] loading ASN-DFN-X net')
self.is_dfn = str(args.is_dfn).lower() == 'true'
self.dfn_kernel_size = args.dfn_kernel_size
self.is_embed = False
self.isFreezeEmbed = False
self.is_semantic = False
my_kwargs.update({
'maxdisp': args.max_disp,
'kernel_size': args.dfn_kernel_size,
'crop_img_h': args.crop_height,
'crop_img_w': args.crop_width,
'isDFN': self.is_dfn,
'dilation': args.dilation,
'cost_filter_grad': self.cost_filter_grad
})
elif self.model_name in ['ASN-SGA-PSM', 'ASN-SGA-DispNetC', 'ASN-SGA-GCNet']:
print ('[!!!] loading ASN-SGA-X net')
self.is_sga_guide_from_img = str(args.is_sga_guide_from_img).lower() == 'true'
#self.is_quarter_size = str(args.is_quarter_size).lower() == 'true'
self.downsample_scale = args.sga_downsample_scale
self.is_lga = str(args.is_lga).lower() == 'true'
if self.is_sga_guide_from_img:
self.is_embed = False
self.isFreezeEmbed = False
self.is_semantic = False
else:
self.is_embed = True
self.isFreezeEmbed = False
self.is_semantic = True
self.is_dfn = False
self.is_pac = False
my_kwargs.update({
'maxdisp': args.max_disp,
'is_sga_guide_from_img': self.is_sga_guide_from_img,
#'is_quarter_size': self.is_quarter_size,
'downsample_scale': self.downsample_scale,
'is_lga': self.is_lga,
'cost_filter_grad': self.cost_filter_grad
})
elif self.model_name in ['ASN-PAC-PSM', 'ASN-PAC-DispNetC', 'ASN-PAC-GANet-Deep', 'ASN-PAC-GCNet']:
if self.model_name == 'ASN-PAC-GANet-Deep':
self.pac_in_channels = 64
self.pac_out_channels = 64
print ('[!!!] loading ASN-PAC-GANet-Deep')
elif self.model_name == 'ASN-PAC-PSM':
self.pac_in_channels = 64
self.pac_out_channels = 64
print ('[!!!] loading ASN-PAC-PSM net')
elif self.model_name == 'ASN-PAC-GCNet':
self.pac_in_channels = 64
self.pac_out_channels = 64
print ('[!!!] loading ASN-PAC-GCNet')
elif self.model_name == 'ASN-PAC-DispNetC':
self.pac_in_channels = self.max_disp // 4
self.pac_out_channels = self.max_disp // 4
print ('[!!!] loading ASN-PAC-DispNetC net')
self.is_pac = str(args.is_pac).lower() == 'true'
self.pac_kernel_size = args.pac_kernel_size
self.is_embed = str(args.is_embed).lower() == 'true'
self.isFreezeEmbed = (str(args.isFreezeEmbed).lower() == 'true')
if not self.is_embed:
self.is_semantic = False
self.is_dfn = False
my_kwargs.update({
'maxdisp': args.max_disp,
'kernel_size': args.pac_kernel_size,
'isPAC': self.is_pac,
'isEmbed': self.is_embed,
'pac_in_channels': self.pac_in_channels,
'pac_out_channels': self.pac_out_channels,
'dilation': args.dilation,
'cost_filter_grad': self.cost_filter_grad,
'native_impl': str(args.pac_native_imple).lower() == 'true'
})
else: # embedding bilateral filtering (EBF);
print ('[!!!] loading ', self.model_name)
self.is_dfn = False
self.is_pac = False
self.isFreezeEmbed = (str(args.isFreezeEmbed) == 'true')
self.is_embed = str(args.is_embed).lower() == 'true'
if not self.is_embed:
self.is_semantic = False
my_kwargs.update({
'maxdisp': args.max_disp,
'sigma_s': args.bilateral_sigma_s,
'sigma_v': args.bilateral_sigma_v,
'isEmbed': self.is_embed,
'dilation': args.dilation,
'cost_filter_grad': self.cost_filter_grad,
})
#----------------
# get the model
#----------------
self.model = AttenStereoNet(**my_kwargs)
print('[***]Number of {} parameters: {}'.format(
self.model_name,
sum([p.data.nelement() for p in self.model.parameters()])))
#print('[***]where, number of {} sga_costAgg.get_g_from_img parameters: {}'.format(
# self.model_name,
# sum([p.data.nelement() for n,p in self.model.named_parameters() if 'sga_costAgg.get_g_from_img' in n])))
#for i, (n, p) in enumerate(self.model.named_parameters()):
# print (i, " layer ", n, "has # param : ", p.data.nelement())
#sys.exit()
if not self.isTestingMode: # training mode
""" We need to set requires_grad == False to freeze the parameters
so that the gradients are not computed in backward();
Parameters of newly constructed modules have requires_grad=True by default;
"""
if self.is_embed and self.isFreezeEmbed:
print("Freeze EmbeddingNet Module during training!!!")
for param in self.model.embednet.parameters():
param.requires_grad = False
#Freeze Bilateral Filter
if self.is_embed:
# for some cases, no bifilter attribute exists;
if hasattr(self.model, 'bifilter'):
if isinstance(self.model.bifilter, torch.nn.Module):
#print ("Freeze Bilateral Filter Module during training!!!")
#for param in self.model.bifilter.parameters():
# param.requires_grad = False
# print ("Freeze Bilateral Filter Module during training!!!")
for name, param in self.model.bifilter.named_parameters():
param.requires_grad = False
print ("[***]During training, Freeze Bilateral Filter Module: ", name)
# updated for the cases where some subnetwork was forzen!!!
params_to_update = [p for p in self.model.parameters() if p.requires_grad]
if 0:
print ('[****] params_to_update = ')
for p in params_to_update:
print (type(p.data), p.size())
self.optimizer= optim.Adam(params_to_update, lr = args.lr, betas=(0.9,0.999))
self.writer = SummaryWriter(args.train_logdir)
# saving settings into a json file
tmp_dir = pjoin(self.checkpoint_dir, self.model_name)
if not os.path.exists(tmp_dir):
os.makedirs(tmp_dir)
print ('makedirs {}'.format(tmp_dir))
json_file = pjoin(tmp_dir, 'train_args.json')
with open(json_file, 'wt') as f_json:
# 't' refers to the text mode.
# There is no difference between 'r' and 'rt'
# or 'w' and 'wt' since text mode is the default.
json.dump(vars(args), f_json, indent = 4)
json.dump(my_kwargs, f_json, indent = 4)
print ("[***] Saving args to json file ", json_file)
if self.is_embed and os.path.isfile(args.saved_embednet_checkpoint):
""" loading pre-trained embedding network model"""
print ('[**] For pretrained embedding net model loading: saved_embednet_checkpoint = ',
args.saved_embednet_checkpoint)
embed_checkpoint = self.load_checkpts(args.saved_embednet_checkpoint)
if embed_checkpoint is not None:
self.model.embednet.load_state_dict(embed_checkpoint['model_state_dict'])
else:
print("Embednet saved checkpoint load failed ... neglected\n Start Training ...")
if self.cuda:
self.model = torch.nn.DataParallel(self.model).cuda()
if self.isTestingMode:
assert os.path.isfile(args.resume) == True, "Model Test but NO checkpoint found at {}".format(args.resume)
if args.resume:
if os.path.isfile(args.resume):
print("[***] => loading checkpoint '{}'".format(args.resume))
checkpoint = torch.load(args.resume)
"""debug DFN saved checkpoint """
#n = 0
#for k,v in checkpoint['state_dict'].items():
# print ('idx = %d' %n, k, v.shape)
# n += 1
#sys.exit()
self.model.load_state_dict(checkpoint['state_dict'], strict=False)
if not self.isTestingMode and hasattr(checkpoint, 'optimizer'):
self.optimizer.load_state_dict(checkpoint['optimizer'])
else:
print("=> no checkpoint found at {}".format(args.resume))
#print ("[***] {} weights inilization done!".format(self.model_name))
def save_checkpoint(self, epoch, state_dict, is_best=False):
saved_checkpts = pjoin(self.checkpoint_dir, self.model_name)
if not os.path.exists(saved_checkpts):
os.makedirs(saved_checkpts)
print ('makedirs {}'.format(saved_checkpts))
#./checkpoint/sceneflow
filename = pjoin(saved_checkpts, "model_epoch_%05d.tar" % epoch)
torch.save(state_dict, filename)
print ('Saved checkpoint at %s' % filename)
if is_best:
best_fname = pjoin(saved_checkpts, 'model_best.tar')
shutil.copyfile(filename, best_fname)
def adjust_learning_rate(self, epoch):
#if epoch <= 300:
#lr_adjust_epo = 300
#if self.model_name.find('PSM') != -1: # PSMNet
# lr_adjust_epo = 200
#else:
# lr_adjust_epo = 300
#if lr_epoch_steps is None:
# lr_epoch_steps = [self.lr_adjust_epo_thred]
old_lr = self.lr
print ("decrease lr by 10 at these epochs: ", self.lr_epoch_steps)
if epoch in self.lr_epoch_steps:
self.lr *= 0.1
print ("[!!!]Epo={}, adjust lr from {} to {}".format(epoch, old_lr, self.lr))
#if epoch <= self.lr_adjust_epo_thred:
# self.lr = self.args.lr
#else:
# self.lr = self.args.lr * 0.1
print('[***]learning rate = ', self.lr, ' and epo = ', epoch)
for param_group in self.optimizer.param_groups:
param_group['lr'] = self.lr
# Newly added for DFN-PSM case, fine-tuning on Virtual KITTI 2;
# This function keeps the learning rate at 0.001 for the first ten epochs
# and decreases it exponentially after that.
def fine_tuning_scheduler(self, epoch, lr_min = 1.0e-4):
#lr_adjust_epo = 2
if epoch <= self.lr_adjust_epo_thred:
self.lr = self.args.lr
else:
self.lr = self.args.lr * math.exp(0.1 * (self.lr_adjust_epo_thred - epoch))
self.lr = max(self.lr, lr_min)
print('learning rate = ', self.lr, ' and epo = ', epoch)
for param_group in self.optimizer.param_groups:
param_group['lr'] = self.lr
def verify_lr_scheduler(self, nEpochs):
# Add some assertion:
# fine-tuning on small dataset, so we need large epochs, like nEpochs = 400;
if nEpochs > 200:
return self.lr_adjust_epo_thred >= 100
elif 50 < nEpochs <= 200:
return self.lr_adjust_epo_thred >= 60
# fine-tuning on large dataset, so we need small epochs, like nEpochs = 20;
elif 10 < nEpochs <= 50:
return self.lr_adjust_epo_thred <= 8
# training from scratch on scene flow dataset, typically we set nEpochs = 10
elif 1 < nEpochs <= 10:
return self.lr_adjust_epo_thred > 8
def load_checkpts(self, saved_checkpts = ''):
print(" [*] Reading checkpoint %s" % saved_checkpts)
checkpoint = None
if saved_checkpts and saved_checkpts != '':
try: #Exception Handling
f = open(saved_checkpts, 'rb')
except IsADirectoryError as error:
print (error)
else:
checkpoint = torch.load(saved_checkpts)
return checkpoint
def build_train_summaries(self, imgl, imgr, disp0, disp1, disp2, disp_gt, global_step, loss,
err0, err1, err2, embed = None, embed_loss = None, dfn_filter = None, dfn_bias = None, is_KT15Color = False):
""" loss and epe error """
self.writer.add_scalar(tag = 'train_loss', scalar_value = loss, global_step = global_step)
if self.is_semantic and embed_loss is not None:
self.writer.add_scalar(tag = 'train_lossEmbed', scalar_value = embed_loss, global_step = global_step)
if err0 is not None:
self.writer.add_scalar(tag = 'train_err0', scalar_value = err0, global_step = global_step)
if err1 is not None:
self.writer.add_scalar(tag = 'train_err1', scalar_value = err1, global_step = global_step)
if err2 is not None:
self.writer.add_scalar(tag = 'train_err2', scalar_value = err2, global_step = global_step)
""" learning rate """
self.writer.add_scalar(tag = 'train_lr', scalar_value = self.lr, global_step = global_step)
""" Add batched image data to summary:
Note: add_images(img_tensor): img_tensor could be torch.Tensor, numpy.array, or string/blobname;
so we could use torch.Tensor or numpy.array !!!
"""
self.writer.add_images(tag='train_imgl',img_tensor=imgl, global_step = global_step, dataformats='NCHW')
if imgr is not None:
self.writer.add_images(tag='train_imgr',img_tensor=imgr, global_step = global_step, dataformats='NCHW')
def show_dfn(batch_dfn_filter, dfn_kernel_size = 9):
"""Convert a Tensor to numpy image."""
#batch_dfn_filter = batch_dfn_filter.cpu().numpy().transpose((0,2,3,1))# change to [N,H,W,C]
batch_dfn_filter = batch_dfn_filter.cpu().numpy() # change to [N,C,H,W]
N, C, H, W = batch_dfn_filter.shape[:]
res = np.zeros([N,1, H, W])
assert (dfn_kernel_size **2 == C)
k_half = (dfn_kernel_size -1)//2
#print ("[***]k_half = ", k_half)
for i in range(k_half, H - k_half, dfn_kernel_size): # along height
for j in range(k_half, W - k_half, dfn_kernel_size): # along width
tmp_idx = 0
for ki in range(-k_half, k_half+1): # along kernel_height
for kj in range(-k_half, k_half+1): # along kernel_width
res[:,0,i+ki,j+kj] = batch_dfn_filter[:,tmp_idx,i,j]
tmp_idx += 1
return res
with torch.set_grad_enabled(False):
if is_KT15Color:
my_disp_clr_func = KT15FalseColorDisp
else:
my_disp_clr_func = colormap_jet_batch_image
if disp0 is not None:
self.writer.add_images(tag='train_disp0',img_tensor=my_disp_clr_func(disp0), global_step = global_step, dataformats='NHWC')
if disp1 is not None:
self.writer.add_images(tag='train_disp1',img_tensor=my_disp_clr_func(disp1), global_step = global_step, dataformats='NHWC')
if disp2 is not None:
self.writer.add_images(tag='train_disp2', img_tensor=my_disp_clr_func(disp2), global_step = global_step, dataformats='NHWC')
self.writer.add_images(tag='train_dispGT',img_tensor=my_disp_clr_func(disp_gt), global_step = global_step, dataformats='NHWC')
self.writer.add_images(tag='train_dispErr',img_tensor=KT15LogColorDispErr(disp2, disp_gt), global_step = global_step, dataformats='NHWC')
if embed is not None:
embed_pca = pca_embedding(embed, k=3,isChanelLast=False)
self.writer.add_images(tag='train_embed_pca3',img_tensor= embed_pca, global_step = global_step, dataformats='NCHW')
if dfn_filter is not None:
#dfn_filter_pca = pca_embedding(dfn_filter, k=3,isChanelLast=False)
dfn_filter_vis = show_dfn(dfn_filter, dfn_kernel_size = self.dfn_kernel_size)
self.writer.add_images(tag='train_vis_dfn_filter',img_tensor= dfn_filter_vis, global_step = global_step, dataformats='NCHW')
if dfn_bias is not None:
self.writer.add_images(tag='train_vis_dfn_bias',img_tensor= dfn_bias, global_step = global_step, dataformats='NCHW')
#---------------------
#---- Training -------
#---------------------
def train(self,
epoch,# epoch idx
nEpochs = 400 # total # of epoches for training
):
"""Set up TensorBoard """
epoch_loss = 0
epoch_error0 = 0
epoch_error1 = 0
epoch_error2 = 0
valid_iteration = 0
#for iteration, batch_data in enumerate(self.training_data_loader):
# print (" [***] iteration = %d/%d" % (iteration, self.train_loader_len))
# input1 = batch_data[0].float() # False by default;
# input2 = batch_data[1].float()
# target = batch_data[2].float()
# left_rgb = batch_data[3].float()
#sys.exit()
# setting to train mode;
self.model.train()
# Add some assertion:
assert self.verify_lr_scheduler(self.args.startEpoch + nEpochs), "lr_scheduler=%f is not CORRECT !!!" %(self.lr_adjust_epo_thred)
# 1) piecewise: lr = 1e-3 if epoch <= lr_adjust_epo_thred else 1e-4
# 2) exponential: lr = 1e-3 if epoch <= lr_adjust_epo_thred else 1e-3 * math.exp(0.1 * ( lr_adjust_epo_thred - epoch))
# 3) constant: lr = 1e-3, i.e., constant learning rate;
if self.lr_scheduler == "piecewise":
self.adjust_learning_rate(epoch)
elif self.lr_scheduler == "exponential":
self.fine_tuning_scheduler(epoch)
elif self.lr_scheduler == "constant":
print("fixed learning rate!")
else:
raise Exception("No suitable lr_scheduler type found ...")
""" running log loss """
log_running_loss = 0.0
log_running_embed_loss = 0.0
log_running_err0 = 0.0
log_running_err1 = 0.0
log_running_err2 = 0.0
for iteration, batch_data in enumerate(self.training_data_loader):
start = time.time()
#print (" [***] iteration = %d" % iteration)
input1 = batch_data[0].float() # False by default;
#print ("[???] input1 require_grad = ", input1.requires_grad) # False
input2 = batch_data[1].float()
target = batch_data[2].float()
left_rgb = batch_data[3].float()
#right_rgb = batch_data[4].float()
semantic_label=batch_data[5].float()
# from GANet
#input1, input2, target = Variable(batch_data[0], requires_grad=True), Variable(batch_data[1], requires_grad=True), Variable(batch_data[2], requires_grad=False)
if self.cuda:
input1 = input1.cuda()
input2 = input2.cuda()
target = target.cuda()
semantic_label = semantic_label.cuda()
target = torch.squeeze(target,1)
#mask = target < self.max_disp
# valid pixels: 0 < disparity < max_disp
mask = (target - self.max_disp)*target < 0
mask.detach_()
valid_disp = target[mask].size()[0]
if valid_disp > 0:
self.optimizer.zero_grad()
if self.model_name == 'ASN-Embed-GANet-Deep':
disp0, disp1, disp2, embed = self.model(input1, input2)
loss0 = F.smooth_l1_loss(disp0[mask], target[mask], reduction='mean')
loss1 = F.smooth_l1_loss(disp1[mask], target[mask], reduction='mean')
if self.kitti2012 or self.kitti2015:
loss2 = self.criterion(disp2[mask], target[mask])
else:
loss2 = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
loss = 0.2*loss0 + 0.6*loss1 + loss2
if self.is_semantic:
semantic_label = F.interpolate(semantic_label, [semantic_label.size()[2]//3, semantic_label.size()[3]//3],
mode='bilinear', align_corners=False)
embed_loss, _, _, _ = get_embed_losses(embed, semantic_label, args_dict = None)
loss += self.args.embed_loss_weight * embed_loss
elif self.model_name == 'ASN-PAC-GANet-Deep':
disp0, disp1, disp2, pac_guide_fea = self.model(input1, input2)
loss0 = F.smooth_l1_loss(disp0[mask], target[mask], reduction='mean')
loss1 = F.smooth_l1_loss(disp1[mask], target[mask], reduction='mean')
if self.kitti2012 or self.kitti2015:
loss2 = self.criterion(disp2[mask], target[mask])
else:
loss2 = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
loss = 0.2*loss0 + 0.6*loss1 + loss2
if self.is_semantic:
embed = pac_guide_fea
semantic_label = F.interpolate(semantic_label, [semantic_label.size()[2]//3, semantic_label.size()[3]//3],
mode='bilinear', align_corners=False)
embed_loss, _, _, _ = get_embed_losses(embed, semantic_label, args_dict = None)
loss += self.args.embed_loss_weight * embed_loss
elif self.model_name == 'ASN-Embed-GANet11':
disp1, disp2, embed = self.model(input1, input2)
disp0 = (disp1 + disp2)/2
loss0 = F.smooth_l1_loss(disp0[mask], target[mask], reduction='mean')
loss1 = F.smooth_l1_loss(disp1[mask], target[mask], reduction='mean')
if self.kitti2012 or self.kitti2015:
loss2 = self.criterion(disp2[mask], target[mask])
else:
loss2 = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
#loss = 0*loss0 + 0.4*loss1 + 1.2*loss2
loss = 0.4*loss1 + 1.2*loss2
if self.is_semantic:
semantic_label = F.interpolate(semantic_label, [semantic_label.size()[2]//3, semantic_label.size()[3]//3],
mode='bilinear', align_corners=False)
embed_loss, _, _, _ = get_embed_losses(embed, semantic_label, args_dict = None)
loss += self.args.embed_loss_weight * embed_loss
elif self.model_name in ['ASN-Embed-PSM']:
# disp in shape [N, H, W]
disp0, disp1, disp2, embed = self.model(input1, input2)
loss0 = F.smooth_l1_loss(disp0[mask], target[mask], reduction='mean')
loss1 = F.smooth_l1_loss(disp1[mask], target[mask], reduction='mean')
loss2 = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
loss = 0.5*loss0 + 0.7*loss1 + loss2
if self.is_semantic:
semantic_label = F.interpolate(semantic_label, [semantic_label.size()[2]//4,
semantic_label.size()[3]//4], mode='bilinear', align_corners=False)
embed_loss, _, _, _ = get_embed_losses(embed, semantic_label, args_dict = None)
loss += self.args.embed_loss_weight * embed_loss
elif self.model_name in ['ASN-Embed-GCNet']:
# disp in shape [N, H, W]
disp2, embed = self.model(input1, input2)
loss = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
if self.kitti2012 or self.kitti2015:
loss = 0.4*loss + 0.6*self.criterion(disp2[mask], target[mask])
if self.is_quarter_size_cost_volume_gcnet:
tmp_scale = 4
else:
tmp_scale = 2
if self.is_semantic:
semantic_label = F.interpolate(semantic_label,
[semantic_label.size()[2]//tmp_scale, semantic_label.size()[3]//tmp_scale],
mode='bilinear', align_corners=False)
embed_loss, _, _, _ = get_embed_losses(embed, semantic_label, args_dict = None)
loss += self.args.embed_loss_weight * embed_loss
elif self.model_name == 'ASN-PAC-GCNet':
disp2, pac_guide_fea = self.model(input1, input2)
loss = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
if self.kitti2012 or self.kitti2015:
loss = 0.4*loss + 0.6*self.criterion(disp2[mask], target[mask])
if self.is_quarter_size_cost_volume_gcnet:
tmp_scale = 4
else:
tmp_scale = 2
if self.is_semantic:
embed = pac_guide_fea
semantic_label = F.interpolate(semantic_label, [semantic_label.size()[2]//tmp_scale, semantic_label.size()[3]//tmp_scale],
mode='bilinear', align_corners=False)
embed_loss, _, _, _ = get_embed_losses(embed, semantic_label, args_dict = None)
loss += self.args.embed_loss_weight * embed_loss
elif self.model_name == 'ASN-SGA-GCNet':
disp2, g_in = self.model(input1, input2)
loss = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
if self.kitti2012 or self.kitti2015:
loss = 0.4*loss + 0.6*self.criterion(disp2[mask], target[mask])
if self.is_quarter_size_cost_volume_gcnet:
tmp_scale = 4
else:
tmp_scale = 2
if self.is_semantic:
embed = g_in
semantic_label = F.interpolate(semantic_label, [semantic_label.size()[2]//tmp_scale, semantic_label.size()[3]//tmp_scale],
mode='bilinear', align_corners=False)
embed_loss, _, _, _ = get_embed_losses(embed, semantic_label, args_dict = None)
loss += self.args.embed_loss_weight * embed_loss
elif self.model_name in ['ASN-DFN-GCNet']:
# disp in shape [N, H, W]
disp2, dfn_filter, dfn_bias = self.model(input1, input2)
loss = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
if self.kitti2012 or self.kitti2015:
loss = 0.4*loss + 0.6*self.criterion(disp2[mask], target[mask])
elif self.model_name in ['ASN-Embed-DispNetC']:
# NOTE: three outputs at the same scale: H x W
disp0, disp1, disp2, embed = self.model(input1, input2)
loss0 = F.smooth_l1_loss(disp0[mask], target[mask], reduction='mean')
loss1 = F.smooth_l1_loss(disp1[mask], target[mask], reduction='mean')
loss2 = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
loss = 0.5*loss0 + 0.7*loss1 + loss2
if self.kitti2012 or self.kitti2015:
loss = 0.4*loss + 0.6*self.criterion(disp2[mask], target[mask])
if self.is_semantic:
semantic_label = F.interpolate(semantic_label, [semantic_label.size()[2]//4,
semantic_label.size()[3]//4], mode='bilinear', align_corners=False)
embed_loss, _, _, _ = get_embed_losses(embed, semantic_label, args_dict = None)
loss += self.args.embed_loss_weight * embed_loss
elif self.model_name in ['ASN-DFN-DispNetC']:
# NOTE: three outputs at the same scale: H x W
disp0, disp1, disp2, dfn_filter, dfn_bias = self.model(input1, input2)
loss0 = F.smooth_l1_loss(disp0[mask], target[mask], reduction='mean')
loss1 = F.smooth_l1_loss(disp1[mask], target[mask], reduction='mean')
loss2 = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
loss = 0.5*loss0 + 0.7*loss1 + loss2
if self.kitti2012 or self.kitti2015:
loss = 0.4*loss + 0.6*self.criterion(disp2[mask], target[mask])
elif self.model_name in ['ASN-DFN-PSM']:
# disp in shape [N, H, W]
disp0, disp1, disp2, dfn_filter, dfn_bias = self.model(input1, input2)
loss0 = F.smooth_l1_loss(disp0[mask], target[mask], reduction='mean')
loss1 = F.smooth_l1_loss(disp1[mask], target[mask], reduction='mean')
loss2 = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
loss = 0.5*loss0 + 0.7*loss1 + loss2
elif self.model_name in ['ASN-DFN-GANet-Deep']:
# disp in shape [N, H, W]
disp0, disp1, disp2, dfn_filter, dfn_bias = self.model(input1, input2)
loss0 = F.smooth_l1_loss(disp0[mask], target[mask], reduction='mean')
loss1 = F.smooth_l1_loss(disp1[mask], target[mask], reduction='mean')
if self.kitti2012 or self.kitti2015:
loss2 = self.criterion(disp2[mask], target[mask])
else:
loss2 = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
loss = 0.2*loss0 + 0.6*loss1 + loss2
#print ('[???] finished DFN-GANet-Deep 1 Iteration , disp0 and loss devices = ', disp0.get_device(), loss.get_device())
elif self.model_name in ['ASN-SGA-PSM']:
# disp in shape [N, H, W]
disp0, disp1, disp2, g_in = self.model(input1, input2)
loss0 = F.smooth_l1_loss(disp0[mask], target[mask], reduction='mean')
loss1 = F.smooth_l1_loss(disp1[mask], target[mask], reduction='mean')
loss2 = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
loss = 0.5*loss0 + 0.7*loss1 + loss2
if self.is_semantic:
embed = g_in
semantic_label = F.interpolate(semantic_label, [semantic_label.size()[2]//4,
semantic_label.size()[3]//4], mode='bilinear', align_corners=False)
embed_loss, _, _, _ = get_embed_losses(embed, semantic_label, args_dict = None)
loss += self.args.embed_loss_weight * embed_loss
elif self.model_name in ['ASN-SGA-DispNetC']:
# NOTE: three outputs at the same scale: H x W
disp0, disp1, disp2, g_in = self.model(input1, input2)
loss0 = F.smooth_l1_loss(disp0[mask], target[mask], reduction='mean')
loss1 = F.smooth_l1_loss(disp1[mask], target[mask], reduction='mean')
loss2 = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
loss = 0.5*loss0 + 0.7*loss1 + loss2
if self.kitti2012 or self.kitti2015:
loss = 0.4*loss + 0.6*self.criterion(disp2[mask], target[mask])
if self.is_semantic:
embed = g_in
semantic_label = F.interpolate(semantic_label, [semantic_label.size()[2]//4,
semantic_label.size()[3]//4], mode='bilinear', align_corners=False)
embed_loss, _, _, _ = get_embed_losses(embed, semantic_label, args_dict = None)
loss += self.args.embed_loss_weight * embed_loss
elif self.model_name in ['ASN-PAC-DispNetC']:
# NOTE: three outputs at the same scale: H x W
disp0, disp1, disp2, pac_guide_fea = self.model(input1, input2)
loss0 = F.smooth_l1_loss(disp0[mask], target[mask], reduction='mean')
loss1 = F.smooth_l1_loss(disp1[mask], target[mask], reduction='mean')
loss2 = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
loss = 0.5*loss0 + 0.7*loss1 + loss2
if self.kitti2012 or self.kitti2015:
loss = 0.4*loss + 0.6*self.criterion(disp2[mask], target[mask])
if self.is_semantic:
embed = pac_guide_fea
semantic_label = F.interpolate(semantic_label, [semantic_label.size()[2]//4,
semantic_label.size()[3]//4], mode='bilinear', align_corners=False)
embed_loss, _, _, _ = get_embed_losses(embed, semantic_label, args_dict = None)
loss += self.args.embed_loss_weight * embed_loss
elif self.model_name in ['ASN-PAC-PSM']:
# disp in shape [N, H, W]
disp0, disp1, disp2, pac_guide_fea = self.model(input1, input2)
loss0 = F.smooth_l1_loss(disp0[mask], target[mask], reduction='mean')
loss1 = F.smooth_l1_loss(disp1[mask], target[mask], reduction='mean')
loss2 = F.smooth_l1_loss(disp2[mask], target[mask], reduction='mean')
loss = 0.5*loss0 + 0.7*loss1 + loss2
if self.is_semantic:
embed = pac_guide_fea
semantic_label = F.interpolate(semantic_label, [semantic_label.size()[2]//4,
semantic_label.size()[3]//4], mode='bilinear', align_corners=False)
embed_loss, _, _, _ = get_embed_losses(embed, semantic_label, args_dict = None)
loss += self.args.embed_loss_weight * embed_loss
else:
raise Exception("No suitable model found ...")
loss.backward()
#print ('[???] finished DFN-GANet-Deep 1 Iteration , loss backward = ', loss.get_device())
self.optimizer.step()
#print ('[???] finished DFN-GANet-Deep 1 Iteration , optimizer.step() = ', loss.get_device())
# MAE error
if (self.model_name.find('GCNet') != -1): # GCNet
error2 = torch.mean(torch.abs(disp2[mask] - target[mask]))
epoch_error2 += error2.item()
# epoch - 1: here argument `epoch` is starting from 1, instead of 0 (zer0);
train_global_step = (epoch-1)*self.train_loader_len + iteration
message_info = "===> Epoch[{}]({}/{}): Step {}, Loss: {:.3f} - LossEmbed: {:.2f}; EPE: {:.2f}; {:.2f} s/step".format(
epoch, iteration, self.train_loader_len, train_global_step,
loss.item(), embed_loss.item() if self.is_semantic else -1.0,
error2.item(), time.time() - start )
#sys.stdout.flush()
# save summary for tensorboard visualization
log_running_err2 += error2.item()
log_running_loss += loss.item()
else:
error0 = torch.mean(torch.abs(disp0[mask] - target[mask]))
error1 = torch.mean(torch.abs(disp1[mask] - target[mask]))
error2 = torch.mean(torch.abs(disp2[mask] - target[mask]))
epoch_error0 += error0.item()
epoch_error1 += error1.item()
epoch_error2 += error2.item()
# save summary for tensorboard visualization
log_running_err0 += error0.item()
log_running_err1 += error1.item()
log_running_err2 += error2.item()
log_running_loss += loss.item()
# epoch - 1: here argument `epoch` is starting from 1, instead of 0 (zer0);
train_global_step = (epoch-1)*self.train_loader_len + iteration
message_info = "===> Epoch[{}]({}/{}): Step {}, Loss: {:.3f} - Loss0/1/2/embed: ({:.2f} {:.2f} {:.2f} {:.2f}); EPE: ({:.2f} {:.2f} {:.2f}); {:.2f} s/step".format(
epoch, iteration, self.train_loader_len, train_global_step,
loss.item(), loss0.item(), loss1.item(), loss2.item(),
embed_loss.item() if self.is_semantic else -1.0,
error0.item(), error1.item(), error2.item(), time.time() -start)
#sys.stdout.flush()
#----------------------
print (message_info)
epoch_loss += loss.item()
valid_iteration += 1
if self.is_semantic:
log_running_embed_loss += embed_loss.item()
if iteration % self.log_summary_step == (self.log_summary_step - 1):
#NOTE: For tensorboard visulization, we could just show half size version, i.e., [H/2, W/2],
# for saving the disk space;
# disp0 in size [N, H, W]
# in the latest versions of PyTorch you can add a new axis by indexing with None
# in size [N, 1, H/2, W/2]
with torch.set_grad_enabled(False):
H, W = disp2.size()[-2:]
left_rgb_vis = F.interpolate(left_rgb, size=[H//2, W//2], mode='bilinear', align_corners = True)
#NOTE: In the latest versions of PyTorch you can add a new axis by indexing with None
# > see: https://discuss.pytorch.org/t/what-is-the-difference-between-view-and-unsqueeze/1155;
#torch.unsqueeze(disp0, dim=1) ==> disp0[:,None]
if (self.model_name.find('GCNet') != -1): # GCNet
disp0_vis = None
disp1_vis = None
log_running_err0 = None
log_running_err1 = None
else:
disp0_vis = F.interpolate(disp0[:,None,...], size=[H//2, W//2], mode='bilinear', align_corners = True)
disp1_vis = F.interpolate(disp1[:,None,...], size=[H//2, W//2], mode='bilinear', align_corners = True)
log_running_err0 /= self.log_summary_step
log_running_err1 /= self.log_summary_step
log_running_err2 /= self.log_summary_step
log_running_loss /= self.log_summary_step
disp2_vis = F.interpolate(disp2[:,None,...], size=[H//2, W//2], mode='bilinear', align_corners = True)
target_vis = F.interpolate(target[:,None,...], size=[H//2, W//2], mode='bilinear', align_corners = True)
self.build_train_summaries(
#left_rgb,
left_rgb_vis,
None, #right_rgb,
#disp0[:,None], disp1[:,None],
#disp2[:,None], target[:,None],
disp0_vis, disp1_vis, disp2_vis, target_vis,
train_global_step,
log_running_loss, log_running_err0, log_running_err1, log_running_err2,
# upsample embed to original image size for tensorboard visulization;
#F.interpolate(embed, [input1.size()[2], input1.size()[3]], mode='bilinear', align_corners=False) if self.is_embed else None,
# upsample embed to half image size for tensorboard visulization;
F.interpolate(embed, [H//2, W//2], mode='bilinear', align_corners=False) if self.is_embed else None,
log_running_embed_loss/self.log_summary_step,
# upsample dfn to half image size for tensorboard visulization;
F.interpolate(dfn_filter, [H//2, W//2], mode='bilinear', align_corners=False) if self.is_dfn else None,
F.interpolate(dfn_bias, [H//2, W//2], mode='bilinear', align_corners=False) if self.is_dfn else None
)
# reset to zeros
log_running_loss = 0.0
log_running_embed_loss = 0.0
log_running_err0 = 0.0
log_running_err1 = 0.0
log_running_err2 = 0.0
# end of data_loader
# save the checkpoints
avg_loss = epoch_loss / valid_iteration
avg_err0 = epoch_error0/valid_iteration
avg_err1 = epoch_error1/valid_iteration
avg_err2 = epoch_error2/valid_iteration
print("===> Epoch {} Complete: Avg. Loss: {:.4f}, Avg. EPE Error: ({:.4f} {:.4f} {:.4f})".format(
epoch, avg_loss, avg_err0, avg_err1, avg_err2 ))
is_best = False
model_state_dict = {
'epoch': epoch,
'state_dict': self.model.state_dict(),
'optimizer' : self.optimizer.state_dict(),
'loss': avg_loss,
'err0': avg_err0,
'err1': avg_err1,
'err2': avg_err2,
}
#if nEpochs > 500:
if nEpochs > 900:
save_epo_step = 50
elif 300 < nEpochs <= 900:
save_epo_step = 25
elif 200 < nEpochs <= 300:
save_epo_step = 20
elif 100 <= nEpochs <= 200:
save_epo_step = 10
elif 50 <= nEpochs < 100:
save_epo_step = 5
else:
save_epo_step = 25
if self.kitti2012 or self.kitti2015: