-
Notifications
You must be signed in to change notification settings - Fork 5
/
exp_runner.py
2267 lines (2111 loc) · 94.6 KB
/
exp_runner.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 logging
import argparse
import numpy as np
import cv2 as cv
import trimesh
import torch
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from shutil import copyfile
from tqdm import tqdm
from pyhocon import ConfigFactory
from models.dataset import Dataset
from models.fields import RenderingNetwork, SDFNetwork, SingleVarianceNetwork, NeRF
from models.renderer import NeuSRenderer
from models.barf_fields import BarfSDFNetwork, BarfRenderingNetwork
import models.camera as camera
from models.camera import to_hom
import imageio
from utils.textured_mesh import textured_mesh
from utils.nope_nerf_utils_poses.align_traj import align_ate_c2b_use_a2b
from utils.nope_nerf_utils_poses.comp_ate import compute_ATE, compute_rpe
from utils.nope_nerf_utils_poses.vis_cam_traj import vis_poses, vis_simple_traj
from models.picture_pose import LearnPoseGF, SegLearnPose
from models.pixel_pose import SegDeepPixelPose
from utils.util import *
import traceback
np.random.seed(2024)
torch.manual_seed(2024)
from utils.align_poses import align_poses, align_poses_wo_virtual
# the following is for debugging
def get_gradients(params):
norms = []
for param in params:
if param.grad is not None:
norms.append(param.grad.abs().mean().cpu().item())
norms = np.array(norms)
if len(norms) == 0:
return 0, 0, 0
return np.min(norms), np.max(norms), np.mean(norms)
class Runner:
def __init__(
self,
conf_path,
mode="train",
case="CASE_NAME",
dataset="DTU",
is_continue=False,
start_at=-1,
start_img_idx=0,
gradient_analysis=False,
exp_dir=None,
has_global_conf=False,
flow_interval=-1,
reset_rot_degree=-1,
image_interval=-1,
):
self.case = case
self.device = torch.device("cuda")
self.gradient_analysis = gradient_analysis
# Configuration
self.conf_path = conf_path
f = open(self.conf_path)
conf_text = f.read()
conf_text = conf_text.replace("CASE_NAME", case).replace("DATA_SET", dataset)
f.close()
self.conf = ConfigFactory.parse_string(conf_text)
if exp_dir is not None:
self.base_exp_dir = exp_dir
else:
self.base_exp_dir = self.conf["general.base_exp_dir"]
if not has_global_conf and "global_reset_exp" not in self.base_exp_dir:
print("Remove global conf...")
self.base_exp_dir = self.base_exp_dir + "_wo_global_conf"
else:
print("Use global conf...")
if flow_interval > 0:
self.base_exp_dir += f"_m{flow_interval}"
self.conf.put("train.flow_interval", flow_interval)
if reset_rot_degree > 0:
self.base_exp_dir += f"_r{reset_rot_degree}"
self.conf.put("train.reset_rot_threshold", reset_rot_degree)
if image_interval > 0:
self.base_exp_dir += f"_i{image_interval}"
self.conf.put("train.image_interval", image_interval)
self.conf.put("train.max_pro_iteration", 1000 * image_interval)
self.conf.put("train.pro_warm_up_end", 500 * image_interval)
self.conf.put(
"train.current_image", image_interval
) # this is very important!!!
if flow_interval > 0 or reset_rot_degree > 0 or image_interval > 0:
# save_freq = 50000
self.conf.put("train.save_freq", 30000)
print("updated confs--------------")
print(self.conf)
print("updated confs--------------")
if start_img_idx > 0:
self.base_exp_dir += f"_start_at_{start_img_idx}"
os.makedirs(self.base_exp_dir, exist_ok=True)
self.conf.put("dataset.start_idx", start_img_idx)
self.dataset = Dataset(self.conf["dataset"], exp_dir)
self.iter_step = 0
# Training parameters
self.end_iter = self.conf.get_int("train.end_iter")
self.save_freq = self.conf.get_int("train.save_freq")
self.report_freq = self.conf.get_int("train.report_freq")
self.val_freq = self.conf.get_int("train.val_freq")
self.val_mesh_freq = self.conf.get_int("train.val_mesh_freq")
self.pose_freq = self.conf.get_int("train.pose_freq", 1000)
self.batch_size = self.conf.get_int("train.batch_size")
self.validate_resolution_level = self.conf.get_int(
"train.validate_resolution_level"
)
self.learning_rate = self.conf.get_float("train.learning_rate")
self.learning_rate_alpha = self.conf.get_float("train.learning_rate_alpha")
self.use_white_bkgd = self.conf.get_bool("train.use_white_bkgd")
self.warm_up_end = self.conf.get_float("train.warm_up_end", default=0.0)
self.anneal_end = self.conf.get_float("train.anneal_end", default=0.0)
self.mask_guided_sampling = self.conf.get_bool(
"train.mask_guided_sampling", default=False
)
# Weights
self.igr_weight = self.conf.get_float("train.igr_weight")
self.mask_weight = self.conf.get_float("train.mask_weight")
self.flow_weight = self.conf.get_float("train.flow_weight", default=0.0)
self.unit_sphere_weight = self.conf.get_float(
"train.unit_sphere_weight", default=0.0
)
self.depth_weight = self.conf.get_float("train.depth_weight", default=0.0)
self.is_continue = is_continue
self.mode = mode
self.model_list = []
self.writer = None
# Networks
self.progressive = self.conf.get_bool("train.progressive", default=False)
self.image_interval = self.conf.get_int("train.image_interval", default=10)
self.current_image = self.conf.get_int(
"train.current_image", default=self.dataset.n_images
)
self.current_image = min(self.current_image, self.dataset.n_images)
self.max_pro_iteration = self.conf.get_int("train.max_pro_iteration", default=0)
self.pro_warm_up_end = self.conf.get_int("train.pro_warm_up_end", default=0)
params_to_train = []
self.nerf_outside = NeRF(**self.conf["model.nerf"]).to(self.device)
self.deviation_network = SingleVarianceNetwork(
**self.conf["model.variance_network"]
).to(self.device)
if "model.barf" not in self.conf:
self.conf.put("model.barf", False)
self.mask_init = self.conf.get_bool("dataset.mask_init", default=False)
self.mono_init = self.conf.get_bool("train.mono_init", default=False)
self.mesh_warmup_step = self.conf.get_int("train.mesh_warmup_step", default=0)
if self.conf["model.barf"]:
print("Using BARF...")
if self.conf.get("dataset.use_crop_init", False):
# this is for 2nd phase to refine poses
noise_poses = self.dataset.crop_poses
else:
# this is for 1st phase to calculate poss
if self.mask_init:
# we only support the mask initialization method, which is most effective
noise_poses = self.dataset.max_mask_pose[None, ...].repeat(
self.dataset.n_images, 1, 1
)
else:
raise NotImplementedError
self.color_network = BarfRenderingNetwork(
**self.conf["model.rendering_network"]
).to(self.device)
self.sdf_network = BarfSDFNetwork(
noise_poses=noise_poses,
**self.conf["model.sdf_network"],
n_images=self.dataset.n_images,
barf=self.conf["model.barf"],
).to(self.device)
else:
self.color_network = RenderingNetwork(
**self.conf["model.rendering_network"]
).to(self.device)
self.sdf_network = SDFNetwork(**self.conf["model.sdf_network"]).to(
self.device
)
self.pose_type = self.conf.get("model.pose_type", default="None")
self.pose_lr = self.conf.get("train.pose_lr", default=5e-4)
self.pose_alpha = self.conf.get("train.pose_alpha", default=0.5)
self.current_pose_mlp_index = 0
self.pro_iteration = 0
if self.pose_type == "gf":
print("Using GF...")
self.sdf_network.se3_refine.weight.requires_grad_(
False
) # we don't have gradients on this
self.pose_network = LearnPoseGF(
num_cams=self.dataset.n_images, init_c2w=noise_poses
).to(self.device)
params_to_train += list(self.pose_network.parameters())
elif self.pose_type == "seg":
print("Using Seg...")
self.sdf_network.se3_refine.weight.requires_grad_(
False
) # we don't have gradients on this
self.pixel_level = self.conf.get_bool("model.pixel_level", default=False)
if self.pixel_level:
print("Using pixel level...")
self.pose_network = SegDeepPixelPose(
num_cams=self.dataset.n_images,
segment_img_num=self.image_interval,
init_c2w=noise_poses,
).to(self.device)
else:
print("Using picture level...")
emphasize_rot = self.conf.get("train.emphasize_rot", False)
small_rot = self.conf.get("train.small_rot", False)
if emphasize_rot:
print("Using emphasize rotation...")
self.pose_network = SegLearnPose(
num_cams=self.dataset.n_images,
segment_img_num=self.image_interval,
init_c2w=noise_poses,
emphasize_rot=emphasize_rot,
small_rot=small_rot,
).to(self.device)
self.pose_optimizers = []
for pose_mlp in self.pose_network.pose_mlps:
self.pose_optimizers.append(
torch.optim.Adam(pose_mlp.parameters(), lr=self.pose_lr)
)
params_to_train += list(self.nerf_outside.parameters())
params_to_train += list(self.sdf_network.parameters())
params_to_train += list(self.deviation_network.parameters())
params_to_train += list(self.color_network.parameters())
self.optimizer = torch.optim.Adam(params_to_train, lr=self.learning_rate)
self.renderer = NeuSRenderer(
self.nerf_outside,
self.sdf_network,
self.deviation_network,
self.color_network,
**self.conf["model.neus_renderer"],
)
# Load checkpoint
latest_model_name = None
if start_at > 0:
assert False
latest_model_name = "ckpt_{:0>6d}.pth".format(start_at)
else:
if is_continue:
model_list_raw = os.listdir(
os.path.join(self.base_exp_dir, "checkpoints")
)
model_list = []
for model_name in model_list_raw:
if (
model_name[-3:] == "pth" and True
): # int(model_name[5:-4]) <= self.end_iter:
model_list.append(model_name)
model_list.sort()
latest_model_name = model_list[-1]
self.disable_trans_during_warm_up = self.conf.get(
"train.disable_trans_during_warm_up", False
)
if self.disable_trans_during_warm_up:
print("Disable translation during warm up...")
self.reset_based_on_rot = self.conf.get_bool(
"train.reset_based_on_rot", default=False
)
if self.reset_based_on_rot:
print("Reset based on rotation...")
self.prev_pose = None
self.reset_rot_threshold = self.conf.get_float(
"train.reset_rot_threshold", default=60
)
if latest_model_name is not None:
logging.info("Find checkpoint: {}".format(latest_model_name))
self.load_checkpoint(latest_model_name)
# Backup codes and configs for debug
if self.mode[:5] == "train":
self.file_backup()
self.dataset.n_images = self.conf.get_int(
"dataset.n_images", default=self.dataset.n_images
)
print(f"n_images: {self.dataset.n_images}")
self.order_sample = self.conf.get_bool("train.order_sample", default=False)
self.detach_ref = self.conf.get_bool("train.detach_ref", default=False)
self.flow_interval = self.conf.get("train.flow_interval", default=1)
print(
f"order_sample: {self.order_sample}, detach_ref: {self.detach_ref}, flow_interval: {self.flow_interval}"
)
self.only_rotation = self.conf.get_bool("train.only_rotation", default=False)
self.detach_flow_on_sdf = self.conf.get_bool(
"train.detach_flow_on_sdf", default=False
)
self.ensure_sample_inside_sphere = self.conf.get_bool(
"train.ensure_sample_inside_sphere", default=False
)
if self.ensure_sample_inside_sphere:
print("Ensure sample inside sphere...")
self.detach_mesh_at_warm_up = self.conf.get_bool(
"train.detach_mesh_at_warm_up", default=False
)
if self.detach_mesh_at_warm_up:
print("Detach mesh at warm up...")
self.dynamic_pro_iterations = self.conf.get_bool(
"train.dynamic_pro_iterations", default=False
)
if self.dynamic_pro_iterations:
print("Dynamic pro iterations...")
self.mask_guided_patch_size = self.conf.get_int(
"train.mask_guided_patch_size", default=30
)
self.maintain_shape = self.conf.get_bool("train.maintain_shape", default=False)
self.remove_prev_matches = self.conf.get_bool(
"train.remove_prev_matches", default=False
)
if self.remove_prev_matches:
print("Remove previous matches...")
def reset_neus(self):
self.nerf_outside = NeRF(**self.conf["model.nerf"]).to(self.device)
self.deviation_network = SingleVarianceNetwork(
**self.conf["model.variance_network"]
).to(self.device)
noise_poses = torch.eye(4)[None, ...].repeat(self.dataset.n_images, 1, 1)
self.sdf_network = BarfSDFNetwork(
noise_poses=noise_poses,
**self.conf["model.sdf_network"],
n_images=self.dataset.n_images,
barf=self.conf["model.barf"],
).to(self.device)
self.color_network = BarfRenderingNetwork(
**self.conf["model.rendering_network"]
).to(self.device)
params_to_train = []
params_to_train += list(self.nerf_outside.parameters())
params_to_train += list(self.sdf_network.parameters())
params_to_train += list(self.deviation_network.parameters())
params_to_train += list(self.color_network.parameters())
self.optimizer = torch.optim.Adam(params_to_train, lr=self.learning_rate)
self.renderer = NeuSRenderer(
self.nerf_outside,
self.sdf_network,
self.deviation_network,
self.color_network,
**self.conf["model.neus_renderer"],
)
self.iter_step = 0 # we need warming up neus again!
self.mesh_warmup_step = self.conf.get_int("train.mesh_warmup_step", default=0)
pass
def train(self):
# assert False, "we need warm up the neus?"
self.writer = SummaryWriter(log_dir=os.path.join(self.base_exp_dir, "logs"))
if self.pose_type != "seg":
self.update_learning_rate()
res_step = self.end_iter - self.iter_step
if self.maintain_shape:
image_perm = self.get_current_image_perm()
prev_image_perm = self.get_prev_image_perm()
else:
image_perm = self.get_image_perm()
for iter_i in range(res_step):
pose_all = self.dataset.pose_all
if self.conf["model.barf"]:
self.sdf_network.progress.data.fill_(iter_i / res_step)
self.color_network.progress.data.fill_(iter_i / res_step)
if self.pose_type in ["gf", "seg"]:
pose_all = None # can remind that it requires the pose network
else:
pose_refine = camera.lie.se3_to_SE3(
self.sdf_network.se3_refine.weight, only_rot=self.only_rotation
)
pose_all = camera.pose.compose(
[pose_refine, self.sdf_network.noise_poses[:, :3, :]]
)
if (
self.flow_weight > 0.0
and np.random.rand() < 0.5
and self.iter_step > self.mesh_warmup_step
):
use_flow = True
else:
use_flow = False
if self.remove_prev_matches:
# the match quality is not reliable
if np.abs(
image_perm[self.iter_step % len(image_perm)].item()
- self.current_image
) >= self.flow_interval or (
self.current_image == self.dataset.n_images
):
use_flow = False
if use_flow:
img_id_corr = image_perm[self.iter_step % len(image_perm)]
data, pixels_xy, pixels_xy_corr, img_id, depth = (
self.dataset.gen_random_ray_pairs_at(
img_id_corr,
self.batch_size // 2,
pose_network=self.pose_network,
current_img_num=self.current_image,
interval=self.flow_interval,
)
)
if data is None:
img_id = image_perm[self.iter_step % len(image_perm)]
if self.pose_type in ["gf", "seg"]:
pose = self.pose_network(img_id_corr)[:3]
else:
pose = pose_all[img_id_corr, :3]
data, depth = self.dataset.gen_random_rays_at(
img_id,
self.batch_size,
pose=pose,
mask_guided_sampling=self.mask_guided_sampling
and self.iter_step > self.mesh_warmup_step,
)
use_flow = False
else:
pass
# print("we get matches between", img_id_corr, img_id)
else:
img_id = image_perm[self.iter_step % len(image_perm)]
if self.iter_step < self.mesh_warmup_step:
if self.pose_type != "gf":
if self.pose_type == "seg":
for i in range(len(self.pose_network.pose_mlps)):
self.pose_network.pose_mlps[i].disable_grad()
else:
self.sdf_network.se3_refine.requires_grad_(False)
if self.reset_based_on_rot and self.prev_pose is not None:
# select images from [0, self.current_image - 1]
img_id = torch.tensor(
np.random.randint(0, self.current_image)
).long()
else:
img_id = torch.tensor(0).long()
else:
if self.pose_type != "gf":
if self.mesh_warmup_step > 0:
self.mesh_warmup_step = 0
if self.pose_type == "seg":
for i in range(len(self.pose_network.pose_mlps)):
self.pose_network.pose_mlps[i].enable_grad()
else:
self.sdf_network.se3_refine.requires_grad_(True)
if self.pose_type in ["gf", "seg"]:
pose = self.pose_network(img_id)[:3]
else:
pose = pose_all[img_id, :3]
data, depth = self.dataset.gen_random_rays_at(
img_id,
self.batch_size,
pose=pose,
mask_guided_sampling=self.mask_guided_sampling
and self.iter_step > self.mesh_warmup_step,
)
img_id_corr = None
# we additionally sample self.batch_size from previous images
if self.maintain_shape:
additional_img_id = prev_image_perm[
self.iter_step % len(prev_image_perm)
]
if self.iter_step < self.mesh_warmup_step:
if self.pose_type != "gf":
if self.pose_type == "seg":
for i in range(len(self.pose_network.pose_mlps)):
self.pose_network.pose_mlps[i].disable_grad()
else:
self.sdf_network.se3_refine.requires_grad_(False)
additional_img_id = torch.tensor(0).long()
else:
if self.pose_type != "gf":
if self.mesh_warmup_step > 0:
self.mesh_warmup_step = 0
if self.pose_type == "seg":
for i in range(len(self.pose_network.pose_mlps)):
self.pose_network.pose_mlps[i].enable_grad()
else:
self.sdf_network.se3_refine.requires_grad_(True)
if self.pose_type in ["gf", "seg"]:
pose = self.pose_network(additional_img_id)[:3]
else:
pose = pose_all[additional_img_id, :3]
add_data, add_depth = self.dataset.gen_random_rays_at(
additional_img_id,
self.batch_size,
pose=pose,
mask_guided_sampling=self.mask_guided_sampling
and self.iter_step > self.mesh_warmup_step,
)
data = torch.cat([data, add_data], dim=0)
if add_depth is not None:
depth = torch.cat([depth, add_depth], dim=0)
rays_o, rays_d, true_rgb, mask = (
data[:, :3],
data[:, 3:6],
data[:, 6:9],
data[:, 9:10],
)
near, far = self.dataset.near_far_from_sphere(rays_o, rays_d)
background_rgb = None
if self.use_white_bkgd:
background_rgb = torch.ones([1, 3])
if self.mask_weight > 0.0:
mask = (mask > 0.5).float()
else:
mask = torch.ones_like(mask)
mask_sum = mask.sum() + 1e-5
render_out = self.renderer.render(
rays_o,
rays_d,
near,
far,
background_rgb=background_rgb,
cos_anneal_ratio=self.get_cos_anneal_ratio(),
)
color_fine = render_out["color_fine"]
s_val = render_out["s_val"]
cdf_fine = render_out["cdf_fine"]
gradient_error = render_out["gradient_error"]
weight_max = render_out["weight_max"]
weight_sum = render_out["weight_sum"]
# Loss
color_error = (color_fine - true_rgb) * mask
color_fine_loss = (
F.l1_loss(color_error, torch.zeros_like(color_error), reduction="sum")
/ mask_sum
)
psnr = 20.0 * torch.log10(
1.0
/ (
((color_fine - true_rgb) ** 2 * mask).sum() / (mask_sum * 3.0)
).sqrt()
)
eikonal_loss = gradient_error
mask_loss = F.binary_cross_entropy(weight_sum.clip(1e-3, 1.0 - 1e-3), mask)
# test the norms of pts
# if self.iter_step % 100 == 0:
# print(f"max pts norm: {render_out['pts'].norm(dim=-1).max()}")
if self.flow_weight > 0.0 and use_flow:
# order img_id_corr, img_id
pts = render_out["pts"] # (N, 3)
weights = render_out["weights"]
if self.detach_flow_on_sdf:
weights = weights.detach()
# project the points to the next image
# we should sperate based on flags
pts_N = pts.shape[0]
weights_N = weights.shape[0]
if self.maintain_shape:
pts0 = pts[: pts_N // 4]
pts1 = pts[pts_N // 4 : pts_N // 2]
weights0 = weights[: weights_N // 4]
weights1 = weights[weights_N // 4 : weights_N // 2]
else:
pts0 = pts[: pts_N // 2]
pts1 = pts[pts_N // 2 :]
weights0 = weights[: weights_N // 2]
weights1 = weights[weights_N // 2 :]
# the following is pose for img_id, which is "1"
c2w_1 = torch.eye(4)
if self.pose_type in ["gf", "seg"]:
c2w_1[:3] = self.pose_network(img_id)[:3]
else:
c2w_1[:3] = pose_all[img_id]
if self.detach_ref:
c2w_1 = c2w_1.detach()
w2c_1 = torch.inverse(c2w_1)[:3][None, ...].expand(
pts0.shape[0], -1, -1
)
# first half points project points to the next image based on "1"'s w2c
cam_pts = (w2c_1 @ to_hom(pts0).unsqueeze(-1)).squeeze(
-1
) # (N, 3, 4) @ (N, 4, 1) -> (N, 3, 1) -> (N, 3)
K = self.dataset.intrinsics_all[img_id][:3, :3][None, ...].expand(
pts0.shape[0], -1, -1
)
pixel_pts = (K @ cam_pts.unsqueeze(-1)).squeeze(
-1
) # (N, 3, 3) @ (N, 3, 1) -> (N, 3, 1) -> (N, 3)
pixel_pts = pixel_pts[:, :2] / pixel_pts[:, 2:] # (N, 2)
pixel_pts = pixel_pts.reshape(-1, weights0.shape[1], 2)
pixels_xy = pixels_xy[:, None, :].expand(-1, weights0.shape[1], -1)
pixel_error = ((pixel_pts - pixels_xy) * weights0[:, :, None]).sum(
dim=1
)
flow_loss0 = (
F.l1_loss(pixel_error, torch.zeros_like(pixel_error))
* self.flow_weight
)
# the following is pose for img_id_corr, which is "0"
c2w_0 = torch.eye(4)
if self.pose_type in ["gf", "seg"]:
c2w_0[:3] = self.pose_network(img_id_corr)[:3]
else:
c2w_0[:3] = pose_all[img_id_corr]
if self.detach_ref:
c2w_0 = c2w_0.detach()
w2c_0 = torch.inverse(c2w_0)[:3][None, ...].expand(
pts1.shape[0], -1, -1
)
# project pts1 to the img_id_corr
cam_pts = (w2c_0 @ to_hom(pts1).unsqueeze(-1)).squeeze(
-1
) # (N, 3, 4) @ (N, 4, 1) -> (N, 3, 1) -> (N, 3)
K = self.dataset.intrinsics_all[img_id_corr][:3, :3][None, ...].expand(
pts1.shape[0], -1, -1
)
pixel_pts = (K @ cam_pts.unsqueeze(-1)).squeeze(
-1
) # (N, 3, 3) @ (N, 3, 1) -> (N, 3, 1) -> (N, 3)
pixel_pts = pixel_pts[:, :2] / pixel_pts[:, 2:] # (N, 2)
pixel_pts = pixel_pts.reshape(-1, weights1.shape[1], 2)
pixels_xy_corr = pixels_xy_corr[:, None, :].expand(
-1, weights1.shape[1], -1
)
pixel_error = ((pixel_pts - pixels_xy_corr) * weights1[:, :, None]).sum(
dim=1
)
flow_loss1 = (
F.l1_loss(pixel_error, torch.zeros_like(pixel_error))
* self.flow_weight
)
flow_loss = flow_loss0 + flow_loss1
# print(f"flow_loss: {flow_loss}")
else:
flow_loss = 0
if self.depth_weight > 0.0:
depth_fine = render_out["depth_fine"]
depth_mask = ((mask > 0.5) & (depth > 0)).reshape(-1)
depth_fine = depth_fine[depth_mask]
depth = depth[depth_mask]
if depth.shape[0] == 0 or depth_fine.shape[0] == 0:
depth_loss = 0
else:
depth_loss = F.l1_loss(depth_fine, depth) * self.depth_weight
else:
depth_loss = 0
# assert depth loss is not nan
if depth_loss != 0:
assert not torch.isnan(depth_loss), f"depth_loss: {depth_loss}"
if self.unit_sphere_weight > 0:
pts = render_out["pts"]
weights = render_out["weights"].reshape(-1, 1)
outside_mask = (pts.norm(dim=-1) > 1.0).detach()
weights = weights[outside_mask]
unit_sphere_loss = (
F.l1_loss(weights, torch.zeros_like(weights))
* self.unit_sphere_weight
)
else:
unit_sphere_loss = 0
if self.gradient_analysis:
# we want verify the balance of the loss weight
losses = {
"flow_loss": flow_loss,
"color_fine_loss": color_fine_loss,
"mask_loss": mask_loss,
"unit_sphere_loss": unit_sphere_loss,
"depth_loss": depth_loss,
"eikonal_loss": eikonal_loss,
}
params = {
"sdf_network": self.sdf_network,
"pose_network": self.pose_network,
}
for k, v in losses.items():
print(k, v)
self.optimizer.zero_grad()
if v > 0:
v.backward(retain_graph=True)
for name, param in params.items():
min_grad, max_grad, mean_grad = get_gradients(
param.parameters()
)
self.writer.add_scalar(
f"Gradients/{k}_min_{name}", min_grad, self.iter_step
)
self.writer.add_scalar(
f"Gradients/{k}_max_{name}", max_grad, self.iter_step
)
self.writer.add_scalar(
f"Gradients/{k}_mean_{name}", mean_grad, self.iter_step
)
print(
f"Gradients/{k}_{name}",
round(min_grad, 5),
round(max_grad, 5),
round(mean_grad, 5),
self.iter_step,
)
else:
print(f"Gradients/{k}_min", 0, 0, 0, self.iter_step)
print("--------------------")
self.optimizer.zero_grad()
# loss will affect all models
loss = (
color_fine_loss
+ eikonal_loss * self.igr_weight
+ mask_loss * self.mask_weight
+ unit_sphere_loss
+ flow_loss
+ depth_loss
)
# self.optimizer.zero_grad() # so we would only use depth to supervise the sdf network
# if depth_loss > 0:
# # we only affect sdf network
# depth_loss.backward(retain_graph=True)
pose_mlp_index_set = set([img_id.item() // self.image_interval])
if img_id_corr is not None:
pose_mlp_index_set.add(img_id_corr.item() // self.image_interval)
if self.maintain_shape:
pose_mlp_index_set.add(additional_img_id.item() // self.image_interval)
if self.pose_type == "seg":
for pose_mlp_index in pose_mlp_index_set:
self.pose_optimizers[pose_mlp_index].zero_grad()
# flow loss will only affect pose network
# if flow_loss > 0:
# flow_loss.backward(retain_graph=True)
self.optimizer.zero_grad() # this will remove gradients on sdf network from flow loss
loss.backward()
if self.detach_mesh_at_warm_up and self.iter_step > self.mesh_warmup_step:
if (
self.pro_iteration < self.pro_warm_up_end
and self.current_pose_mlp_index in pose_mlp_index_set
):
# disable the gradients of the current pose_mlp
self.optimizer.zero_grad()
self.optimizer.step()
if self.pose_type == "seg":
for pose_mlp_index in pose_mlp_index_set:
self.pose_optimizers[pose_mlp_index].step()
self.iter_step += 1
self.writer.add_scalar("Loss/loss", loss, self.iter_step)
self.writer.add_scalar("Loss/color_loss", color_fine_loss, self.iter_step)
self.writer.add_scalar("Loss/eikonal_loss", eikonal_loss, self.iter_step)
self.writer.add_scalar("Loss/mask_loss", mask_loss, self.iter_step)
self.writer.add_scalar("Loss/flow_loss", flow_loss, self.iter_step)
self.writer.add_scalar("Loss/depth_loss", depth_loss, self.iter_step)
self.writer.add_scalar(
"Loss/unit_sphere_loss", unit_sphere_loss, self.iter_step
)
self.writer.add_scalar("Statistics/s_val", s_val.mean(), self.iter_step)
self.writer.add_scalar(
"Statistics/cdf",
(cdf_fine[:, :1] * mask).sum() / mask_sum,
self.iter_step,
)
self.writer.add_scalar(
"Statistics/weight_max",
(weight_max * mask).sum() / mask_sum,
self.iter_step,
)
self.writer.add_scalar("Statistics/psnr", psnr, self.iter_step)
if self.iter_step % self.report_freq == 0:
print(self.base_exp_dir)
print(
"iter:{:8>d} loss = {} lr={}".format(
self.iter_step, loss, self.optimizer.param_groups[0]["lr"]
)
)
# print all losses
print(
f"color_fine_loss: {color_fine_loss}, eikonal_loss: {eikonal_loss}, mask_loss: {mask_loss}, flow_loss: {flow_loss}, depth_loss: {depth_loss}, unit_sphere_loss: {unit_sphere_loss}"
)
if self.iter_step % self.val_freq == 0:
self.validate_image()
if self.iter_step % self.pose_freq == 0:
self.validate_poses()
if (
self.pose_type == "seg"
and self.pro_iteration >= 0
and self.iter_step > self.mesh_warmup_step
):
self.pro_iteration += 1
if self.pro_iteration == self.max_pro_iteration:
# save the depth map of current image
self.pro_iteration = 0
prev_image = self.current_image
self.current_image = min(
self.current_image + self.image_interval, self.dataset.n_images
)
if self.current_image > prev_image:
if self.reset_based_on_rot:
def rotation_error(pose_error):
a = pose_error[0, 0]
b = pose_error[1, 1]
c = pose_error[2, 2]
d = 0.5 * (a + b + c - 1.0)
rot_error = np.arccos(max(min(d, 1.0), -1.0))
return rot_error * 180 / np.pi
with torch.no_grad():
if self.prev_pose is None:
self.prev_pose = self.pose_network.pose_mlps[0](
torch.tensor(0).long()
)[:3, :3].cpu()
cur_pose = self.pose_network.pose_mlps[
self.current_pose_mlp_index
](torch.tensor(prev_image - 1).long())[:3, :3].cpu()
rel_R = (
(cur_pose @ torch.inverse(self.prev_pose)).cpu().numpy()
)
if rotation_error(rel_R) > self.reset_rot_threshold:
print("reset based on rotation...")
self.reset_neus()
self.prev_pose = cur_pose
prev_pose_mlp_index = self.current_pose_mlp_index
self.current_pose_mlp_index += 1 # pose mlp index increase by 1 since image intavel frames are in a group!
if self.dynamic_pro_iterations:
self.max_pro_iteration = (
self.dataset.pro_iteration_at_frame[
self.current_pose_mlp_index
]
)
self.pro_warm_up_end = self.max_pro_iteration // 3
print(
"dynamic pro iteration",
f"max_pro_iteration: {self.max_pro_iteration}, pro_warm_up_end: {self.pro_warm_up_end}",
)
for i in range(prev_pose_mlp_index + 1):
# disable the gradients of the previous pose_mlp
# and only enable the gradients of the current pose_mlp
self.pose_network.pose_mlps[i].disable_grad()
else:
# finish feeding frames
self.pro_iteration = -1
if self.disable_trans_during_warm_up:
self.pose_network.pose_mlps[
self.current_pose_mlp_index
].disable_trans()
print("reach max pro iteration.........")
print("current_image: ", self.current_image)
print("current_pose_mlp_index: ", self.current_pose_mlp_index)
if self.pro_iteration == self.pro_warm_up_end:
print("finish warm up...")
if False: # self.maintain_shape:
# we would fix the stable poses of previous images
for i in range(1, self.flow_interval):
if self.current_pose_mlp_index - i >= 0:
self.pose_network.pose_mlps[
self.current_pose_mlp_index - i
].enable_grad()
else:
for i in range(self.current_pose_mlp_index):
# enable the gradients of the previous pose_mlp
self.pose_network.pose_mlps[i].enable_grad()
# the following enables predicting the translation
self.pose_network.pose_mlps[
self.current_pose_mlp_index
].finish_warmup()
if self.disable_trans_during_warm_up:
self.pose_network.pose_mlps[
self.current_pose_mlp_index
].enable_trans()
if self.iter_step % self.val_mesh_freq == 0:
self.validate_mesh()
self.update_learning_rate(pose_mlp_index_set)
if self.iter_step % len(image_perm) == 0:
if self.maintain_shape:
image_perm = self.get_current_image_perm()
else:
image_perm = self.get_image_perm()
if self.maintain_shape and self.iter_step % len(prev_image_perm) == 0:
prev_image_perm = self.get_prev_image_perm()
# saving checkpoint should happen at last
if self.iter_step % self.save_freq == 0 and self.iter_step > 0:
self.save_checkpoint()
if "_wo_global_conf" not in self.base_exp_dir:
# only if we have global conf, we can reboot
if (
self.pro_iteration == -1
and self.current_image == self.dataset.n_images
):
self.validate_mesh()
self.save_checkpoint() # we save the final model
# we are ready to reboot for global training
return
def get_image_perm(self):
if self.progressive:
if self.current_image > self.image_interval:
# 80% for [current_image - self.image_interval, current_image - 1], 20% for [0, current_image - self.image_interval - 1]
prev_img_num = self.current_image - self.image_interval
prev_weight = [0.2 / (prev_img_num)] * prev_img_num
cur_weight = [0.8 / (self.image_interval)] * self.image_interval
weight = prev_weight + cur_weight
# use numpy to randomly select the index
indexes = np.random.choice(
self.current_image, self.current_image, p=weight
)
return torch.tensor(indexes)
else:
return torch.randperm(self.current_image)
else:
return torch.randperm(self.dataset.n_images)
def get_prev_image_perm(self):
if self.current_image > self.flow_interval:
prev_img_num = self.current_image - self.flow_interval
return torch.randperm(prev_img_num)
else:
return torch.randperm(self.current_image)
def get_current_image_perm(self):
# current image has 80% possibility to be selected, while the previous image(inside flow interval) has 20% possibility to be selected
# if self.current_image > self.flow_interval:
if self.current_image > (self.image_interval - 1) + self.flow_interval:
# option-1: only support image_interval = 1
# prev_img_num = self.current_image - self.flow_interval
# if self.flow_interval == 1:
# return torch.tensor([prev_img_num])
# prev_weight = [0.2 / (self.flow_interval - 1)] * (self.flow_interval - 1)
# cur_weight = [0.8]
# weight = prev_weight + cur_weight
# # use numpy to randomly select the index: [0, self.flow_interval - 1] + [prev_img_num]
# indexes = np.random.choice(self.flow_interval, self.flow_interval, p=weight) + prev_img_num
# return torch.tensor(indexes)
# option-2: supporting more frames
if self.flow_interval == 1:
# randomly select self.image_interval