-
Notifications
You must be signed in to change notification settings - Fork 4
/
morpheus.py
1578 lines (1173 loc) · 68.2 KB
/
morpheus.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
# package import
import os
import cv2
import copy
import math
import time
import yaml
import torch
import mcubes
import random
import imageio
import nerfacc
import trimesh
import argparse
import threading
import numpy as np
import open3d as o3d
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from shutil import copyfile
from torch.optim import Adam
from rich.console import Console
from nerfacc import OccGridEstimator
from torch.utils.data import DataLoader
from torchmetrics import PearsonCorrCoef
# local import
from models.optimizer import Adan
from models.clip_encoders import ImageEncoder
from models.model import scene_representation
from datasets.dataset import DeformDataset
from tools.culling import eval_mesh, eval_depthL1
from tools.vis import make_video, set_c2w, set_K, gl2cv
from utils import sample_pdf, get_GPU_mem, custom_meshgrid
from utils import coordinates, get_sdf_loss, seed_everything, mse2psnr, safe_normalize
# Set seed in code-release version to improve reproducibility
seed_everything(2024)
class MorpheuS(nn.Module):
def __init__(self, config, backup=True, is_train=True):
super().__init__()
self.config = config
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.create_log()
self.dataset = self.get_dataset()
self.bound, self.bounding_box = self.get_bound()
self.model = self.get_model()
if is_train:
self.guidance = self.get_guidance()
self.embeddings = self.get_embeddings(kf_every=self.config['train']['kf_every'])
self.clip_encoder = self.get_clip_encoder()
# Geometric initialization
# NOTE: This is not used, but can potentially be used for initialization
#self.geometric_init(radius=self.config['exp']['geo_radius'])
self.optimizer, self.scaler, self.ema = self.get_optimizer()
self.occupancy_grid = self.get_occ_grid(self.aabb_train, resolution=128)
if backup:
self.file_backup()
def file_backup(self):
'''
Backup the code and config files
'''
file_path_all =[ './', './models', './datasets']
os.makedirs(os.path.join(self.workspace, 'recording'), exist_ok=True)
for file_path in file_path_all:
cur_dir = os.path.join(self.workspace, 'recording', file_path)
os.makedirs(cur_dir, exist_ok=True)
files = os.listdir(file_path)
for f_name in files:
if f_name[-3:] == '.py':
copyfile(os.path.join(file_path, f_name), os.path.join(cur_dir, f_name))
def create_log(self):
'''
Create log file and console
'''
self.epoch = 0
self.console = Console()
self.workspace = os.path.join(self.config['exp']['output'], self.config['exp']['exp_name'])
os.makedirs(self.workspace, exist_ok=True)
log_path = os.path.join(self.workspace, self.config['exp']['log'])
self.log_ptr = open(log_path, 'a+')
self.global_step = 0
self.freeze_lr = True # Freeze deformation field to ensure a good initialization
def get_dataset(self):
'''
return dataset
'''
dataset = DeformDataset(self.config)
return dataset
def get_bound(self):
'''
Create bounding box for scene representation
'''
bound = self.dataset.bound.to(self.device)
bounding_box = torch.stack((self.dataset.bounding_box[:3], self.dataset.bounding_box[3:])).to(self.device)
aabb_train = torch.FloatTensor([-bound, -bound, -bound, bound, bound, bound])
aabb_infer = aabb_train.clone()
self.register_buffer('aabb_train', aabb_train)
self.register_buffer('aabb_infer', aabb_infer)
print('Bounding_box: ', bounding_box)
return bound, bounding_box
def get_model(self):
print('Create scene representation')
return scene_representation(self.config, self.bound,
num_frames=self.dataset.num_frames,
deform_dim=self.config['model']['deform_dim'],
use_app=self.config['model']['use_app'],
use_t=self.config['model']['use_t'],
amb_dim=self.config['model']['amb_dim'],
color_grid=self.config['model']['color_grid'],
use_joint=self.config['model']['use_joint'],
encode_topo=self.config['model']['encode_topo']
).to(self.device)
def get_optimizer(self):
'''
Get optimizer, scaler and ema
'''
if self.config['train']['optim'] == 'adan':
print('Use ADAN optimizer')
# Adan usually requires a larger LR
optimizer = Adan(self.model.get_params_all(5 * self.config['train']['lr']),
eps=1e-8, weight_decay=2e-5, max_grad_norm=5.0, foreach=False)
else: # adam
print('Use Adam optimizer')
optimizer = Adam(self.model.get_params_all(self.config['train']['lr']),
betas=(0.9, 0.99), eps=1e-15)
print(self.model.get_params_all(self.config['train']['lr']))
scaler = torch.cuda.amp.GradScaler(enabled=self.config['exp']['fp16'])
if self.config['train']['ema_decay'] > 0:
from torch_ema import ExponentialMovingAverage
ema = ExponentialMovingAverage(self.model.parameters(), decay=self.config['train']['ema_decay'])
else:
ema = None
return optimizer, scaler, ema
def get_clip_encoder(self):
return ImageEncoder()
def get_guidance(self):
'''
Load diffusion prior. Here we use Zero123.
NOTE: Other models can also be added here.
NOTE: We find that using Zero123-XL may not lead to better results. You may
need to tune guidance scale and other parameters to get better results. For
anyone who is interested in using Zero123-XL, I would suggest to try it on
frog sequence, then you will see notable difference between Zero123 and Zero123-XL.
I guess this might be because of the domain gap between the training data and
the real data. More synthetic data may not lead to better results in real data.
'''
guidance = {}
if 'zero123' in self.config['guidance']['model']:
print('Use zero123 guidance')
from models.guidance.zero123_utils import Zero123
guidance['zero123'] = Zero123(device=self.device,
fp16=self.config['exp']['fp16'],
config=self.config['guidance']['zero123_config'],
ckpt=self.config['guidance']['zero123_ckpt'],
vram_O=self.config['guidance']['vram_O'],
t_range=self.config['guidance']['t_range'],
opt=self.config['guidance'])
return guidance
def get_occ_grid(self, aabb, resolution=128):
'''
Get occupancy grid estimator (NeRFAcc)
'''
return OccGridEstimator(
roi_aabb=aabb,
resolution=resolution)
def get_kf(self, num_frames, kf_every=None):
'''
A very simple way to select keyframes
NOTE: A more advanced way, for instance, select kf
based on relative angles, can also be used. We keep it simple here.
'''
frame_idx = torch.arange(0, num_frames, kf_every).long()
if (num_frames - 1) not in frame_idx:
frame_idx = torch.cat([frame_idx, torch.tensor([num_frames-1])])
return frame_idx
@torch.no_grad()
def get_embeddings(self, kf_every=2):
'''
Pre-compute latent vectors for each kf
'''
# Select keyframes (a straightforward way is to select
# every n frames, but other strategies can also be used)
num_frames = self.dataset.num_frames
frame_idx = self.get_kf(num_frames, kf_every=kf_every)
self.log('Use frame_idx: ', frame_idx)
self.embedding_idx = frame_idx
# Get angles and relative angles for weight gradient
self.angles = torch.stack([self.dataset.get_radius(frame_idx),
torch.deg2rad(self.dataset.theta[frame_idx]),
torch.deg2rad(self.dataset.phi[frame_idx])],
dim=-1)
self.angle_rel = self.guidance['zero123'].angle_between(self.angles, self.angles)
# Get embeddings
embeddings = {'zero123': {}}
for i in frame_idx:
images = self.dataset.images[i]
masks = self.dataset.masks[i]
assert len(images.shape) == 3, 'The shape of images should be (H, W, 3)'
assert len(masks.shape) == 2, 'The shape of images should be (H, W)'
masks[masks>0.5]= 1
masks[masks<=0.5] = 0
# Masked image (Bs, C, H, W)
masked_img = images * masks[...,None] + (1 - masks[...,None])
masked_img = cv2.resize(masked_img, (256, 256), interpolation=cv2.INTER_AREA).astype(np.float32)
masked_img = torch.from_numpy(masked_img)[None, ...].permute(0,3,1,2).contiguous().to(self.device)
# Compute embeddings
guidance_embeds = self.guidance['zero123'].get_img_embeds(masked_img)
embeddings['zero123'][int(i.item())] = {
'zero123_ws' : [1], # [1]
'c_crossattn' : guidance_embeds[0],
'c_concat' : guidance_embeds[1],
'ref_polars' : [self.dataset.theta[i]], # [90]
'ref_azimuths' : [self.dataset.phi[i]], # [0]
'ref_radii' : [self.dataset.get_radius(i)], # [3]
}
mem = get_GPU_mem()[0]
print(f'GPU={mem:.1f}GB.')
return embeddings
def geometric_init(self, sample_points=128, radius=0.3, chunk=1024*2048, eps=1e-8):
'''
Initialize the geometry to be a sphere by training the model
NOTE: We use another initialization method, so this is not used.
However, we keep this function here in case that it helps.
'''
volume = self.bounding_box[1, :] - self.bounding_box[0, :]
center = self.bounding_box[0, :] + volume / 2
print('Volume:', volume)
print('Center:', center)
print('geometric initialisation')
ckpt_path = self.config['exp']['ckpt_init']
if os.path.exists(ckpt_path):
print('Reloading:', self.config['exp']['ckpt_init'])
self.model.load_state_dict(torch.load(ckpt_path), strict=False)
else:
optimizer = Adam([
{'params': self.model.encoder.parameters(), 'weight_decay': 1e-6},
{'params': self.model.sigma_net.parameters(), 'eps': 1e-15}
], lr=1e-3, betas=(0.9, 0.99))
loss = 0
pbar = tqdm(range(self.config['exp']['sphere_iters']))
for _ in pbar:
optimizer.zero_grad()
coords = coordinates(sample_points - 1, device).float().t()
pts = (coords + torch.rand_like(coords)) * volume / sample_points + self.bounding_box[0, :]
for i in range(0, pts.shape[0], chunk):
optimizer.zero_grad()
sdf = self.model.density(pts[i:i+chunk], cano=True)['sdf'].squeeze()
target_sdf = (pts[i:i+chunk]- center).norm(dim=-1) - radius
loss = torch.nn.functional.mse_loss(sdf, target_sdf)
pbar.set_postfix({'loss': loss.cpu().item()})
loss.backward()
optimizer.step()
if loss.item() < eps:
break
self.model.zero_grad()
torch.save(self.model.state_dict(), ckpt_path)
def load_ckpt(self, ckpt_path):
model_dict = torch.load(ckpt_path)
self.model.load_state_dict(model_dict['model'])
self.optimizer.load_state_dict(model_dict['optimizer'])
self.epoch = model_dict['epoch']
self.global_step = model_dict['global_step']
if self.ema is not None:
self.ema.load_state_dict(model_dict['ema'])
self.scaler.load_state_dict(model_dict['scaler'])
self.occupancy_grid.load_state_dict(model_dict['estimator'])
print('Load ckpt from ', ckpt_path)
def save_ckpt(self, save_path):
save_dict = {}
save_dict['model'] = self.model.state_dict()
save_dict['optimizer'] = self.optimizer.state_dict()
save_dict['epoch'] = self.epoch
save_dict['global_step'] = self.global_step
save_dict['ema'] = self.ema.state_dict() if self.ema is not None else None
save_dict['scaler'] = self.scaler.state_dict()
save_dict['estimator'] = self.occupancy_grid.state_dict()
torch.save(save_dict, save_path)
print('Save ckpt to ', save_path)
def log(self, *args, **kwargs):
self.console.print(*args, **kwargs)
if self.log_ptr:
print(*args, file=self.log_ptr)
self.log_ptr.flush() # write immediately to file
@torch.no_grad()
def export_mesh(self, mesh_savepath, resolution=128, S=128, t=None, cano=False, color_mesh=True):
"""
Export the mesh from our scene representation.
Args:
mesh_savepath (str): The file path to save the exported mesh.
resolution (int, optional): The resolution of the mesh. Defaults to 128.
S (int, optional): The size of each subgrid. Defaults to 128.
t (float, optional): The timestep.
cano (bool, optional): Whether to extract canonical shape.
color_mesh (bool, optional): Whether to color the mesh. Defaults to True.
"""
os.makedirs(os.path.dirname(mesh_savepath), exist_ok=True)
density_thresh = 0
sigmas = np.zeros([resolution, resolution, resolution], dtype=np.float32)
# query
X = torch.linspace(-1, 1, resolution).split(S)
Y = torch.linspace(-1, 1, resolution).split(S)
Z = torch.linspace(-1, 1, resolution).split(S)
for xi, xs in enumerate(X):
for yi, ys in enumerate(Y):
for zi, zs in enumerate(Z):
xx, yy, zz = torch.meshgrid(xs, ys, zs, indexing='ij')
pts = torch.cat([xx.reshape(-1, 1), yy.reshape(-1, 1), zz.reshape(-1, 1)], dim=-1) # [S, 3]
val = self.model.density(pts.to(self.device), t=t, cano=cano)
sigmas[xi * S: xi * S + len(xs), yi * S: yi * S + len(ys), zi * S: zi * S + len(zs)] = val['sdf'].reshape(len(xs), len(ys), len(zs)).detach().cpu().numpy() # [S, 1] --> [x, y, z]
print(f'[INFO] marching cubes thresh: {density_thresh} ({sigmas.min()} ~ {sigmas.max()})')
vertices, triangles = mcubes.marching_cubes(sigmas, density_thresh)
vertices = vertices / (resolution - 1.0) * 2 - 1
if color_mesh:
color = self.model.density(torch.from_numpy(vertices).to(torch.float32).to(self.device), t=t, cano=cano)['albedo'].cpu().data.numpy()
else:
color = None
mesh = trimesh.Trimesh(vertices, triangles, process=False, vertex_colors=color)
mesh.export(mesh_savepath)
def export_all_meshes(self, mesh_all_savepath, resolution=128, S=128, color=False):
"""
Export all meshes of the entire video sequence.
"""
for i in range(self.dataset.num_frames):
t = i / self.dataset.num_frames
self.export_mesh(os.path.join(mesh_all_savepath, f'mesh_{self.epoch:04d}_{i:04d}.ply'), resolution=resolution, S=S, t=t, color_mesh=color)
def render_all_meshes(self, mesh_dir, save_images_dir, save_video_dir, epoch, scale=4,
view_360=False, video_name="video_real", save_depths_dir=None, save_video=True):
K = copy.deepcopy(self.dataset.intrinsics)
H, W = self.dataset.H, self.dataset.W
H *= scale
W *= scale
K[0, :] *= scale
K[1, :] *= scale
video_name += "_{:04d}".format(epoch)
depth_np = {}
for i in tqdm(range(self.dataset.num_frames)):
mesh = o3d.io.read_triangle_mesh(os.path.join(mesh_dir, "mesh_{:04d}_{:04d}.ply".format(epoch, i)))
mesh = mesh.compute_vertex_normals()
vis = o3d.visualization.Visualizer()
vis.create_window(width=W, height=H)
vis.get_render_option().mesh_show_back_face = True
vis.add_geometry(mesh)
if not view_360:
R, t = self.model.get_RT(torch.tensor([i]))
deltaT = torch.eye(4)
deltaT[:3, :3] = R.squeeze()
deltaT[:3, -1] = t.squeeze()
c2w = deltaT @ self.dataset.poses[i]
else:
thetas = torch.FloatTensor([self.config["data"]["default_polar"]])
phis = torch.FloatTensor([i / self.dataset.num_frames * 360])
c2w, _ = self.dataset.get_c2w_from_polar(t=i, theta=thetas, phi=phis)
c2w = c2w[0]
if isinstance(c2w, torch.Tensor):
c2w = c2w.detach().cpu().numpy()
set_c2w(vis, gl2cv(c2w))
set_K(vis, K, H, W)
vis.poll_events()
vis.capture_screen_image(os.path.join(save_images_dir, "{:04d}.png".format(i)), False)
if save_depths_dir is not None:
vis.capture_depth_image(os.path.join(save_depths_dir, "{:04d}.png".format(i)), False)
depth_np["depth_{}".format(i)] = np.array(vis.capture_depth_float_buffer())
vis.destroy_window()
vis.close()
if save_video:
make_video(save_video_dir, save_images_dir, video_name)
if save_depths_dir is not None:
np.savez(os.path.join(save_depths_dir, "depths.npz"), **depth_np)
def update_learning_rate(self, scale_factor=1):
'''
A function that updates the learning rate
Adapted from NDR (https://github.com/USTC3DV/NDR-code)
'''
print('update lr')
if self.epoch < self.config['train']['warm_up_end']:
if self.epoch < 100:
learning_factor = 0.01
else:
learning_factor = 0.01 + (self.epoch - 100) / (self.config['train']['warm_up_end'] - 100) * 0.99
else:
alpha = 0.05
progress = (self.epoch - self.config['train']['warm_up_end']) / (self.config['train']['n_epochs'] - self.config['train']['warm_up_end'])
learning_factor = (np.cos(np.pi * progress) + 1.0) * 0.5 * (1 - alpha) + alpha
learning_factor *= scale_factor
current_learning_rate = self.config['train']['lr'] * learning_factor
self.current_learning_rate = current_learning_rate
for g in self.optimizer.param_groups:
if g['name'] in ['pose']:
g['lr'] = current_learning_rate * 1e-1
elif g['name'] in ['encoder_sdf']:
g['lr'] = current_learning_rate
elif g['name'] in ['encoder_color']:
# NOTE: We fix lr here to reduce the complexity of the code
g['lr'] = current_learning_rate
else:
g['lr'] = current_learning_rate
def freeze_lr_deform(self):
'''
Freeze the learning rate of deformation field
(Deformation code + Deformation net + topology net)
'''
for g in self.optimizer.param_groups:
if g['name'] in ['code_deform', 'decoder_deform', 'decoder_topo']:
g['lr'] = 0.0
def reset_lr_deform(self):
for g in self.optimizer.param_groups:
if g['name'] in ['code_deform', 'decoder_deform', 'decoder_topo']:
g['lr'] = self.current_learning_rate
def get_ortho_normal_dir(self, normals):
'''
Get direction that orthogonal to the normal
'''
n = F.normalize(normals, dim=-1)
u = F.normalize(n[...,[1,0,2]] * torch.tensor([1., -1., 0.], device=n.device), dim=-1)
v = torch.cross(n, u, dim=-1)
phi = torch.rand(list(normals.shape[:-1]) + [1], device=normals.device) * 2. * np.pi
w = torch.cos(phi) * u + torch.sin(phi) * v
return w
def get_normal_smoothness_loss(self, rays_o, rays_d, rays_t, depth):
num_trunc_points = int(self.config['train']['trunc'] * 100 + 1)
trunc_normal = torch.linspace(-0.5*self.config['train']['trunc'], 0.5*self.config['train']['trunc'], num_trunc_points)
trunc_normal = trunc_normal + 0.01 * torch.rand_like(trunc_normal)
# 11, bs
surf_pts = (depth + trunc_normal[:,None].to(depth))[..., None] * rays_d[None, ...] + rays_o[None, ...]
surf_pts = surf_pts.view(-1, 3)
surf_rays_t = rays_t[None, ...].repeat(num_trunc_points, 1, 1).view(-1, 1)
surf_pts_norm = torch.linalg.norm(surf_pts, ord=2, dim=-1, keepdim=False)
surf_pts = surf_pts[surf_pts_norm < 1.1]
surf_normals, normal_raw = self.model.normal(surf_pts, t=surf_rays_t[surf_pts_norm < 1.1])
w = self.get_ortho_normal_dir(surf_normals)
surf_pts2 = surf_pts + w * self.config['train']['smoothness_std']
surf_normals2, normal_raw = self.model.normal(surf_pts2, t=surf_rays_t[surf_pts_norm < 1.1])
normal_reg = torch.mean(torch.square(surf_normals - surf_normals2))
return normal_reg
def render_rays(self, rays_o, rays_d, rays_t, rays_id,
H, W,
perturb=True,
bg_color=None,
ambient_ratio=1.0,
light_d=None,
shading='albedo',
real_view=True,
cano=False,
rays_depth=None,
rays_mask=None,
optimize_pose=False):
'''
Core function for rendering
Params:
- rays_o: origin of rays [B=1, N=H*W, 3]
- rays_d: direction of rays [B=1, N=H*W, 3]
- rays_t: time of rays
- rays_id: id of rays
- H: height of the image
- W: width of the image
- perturb: whether to perturb points
- bg_color: pre-computed random background color [BN, 3] in range [0, 1]
- ambient_ratio: ambient ratio
- light_d: light direction
- shading: shading type
- real_view: whether to train on observations
- cano: whether to directly supervise canonical field (Not used)
- rays_depth: depth of rays (None if using virtual view)
- rays_mask: mask of rays (None if using virtual view)
- optimize_pose: whether to optimize the camera pose
Return:
- image: rendered image [B, N, 3]
- depth: rendered depth [B, N]
'''
prefix = rays_o.shape[:-1]
rays_o = rays_o.contiguous().view(-1, 3)
rays_d = rays_d.contiguous().view(-1, 3)
rays_t = rays_t.contiguous().view(-1, 1)
rays_id = rays_id.contiguous().view(-1, 1)
if not cano and optimize_pose:
# Apply pose optimization
rays_o, rays_d = self.model.pose_optimisation(rays_o, rays_d, rays_id)
if rays_depth is not None:
rays_depth = rays_depth.contiguous().view(-1, 1)
if rays_mask is not None:
rays_mask = rays_mask.contiguous().view(-1, 1)
N = rays_o.shape[0]
results = {}
# We found this part may not improve the results
# So we did not use it in sampling
def sigma_fn(t_starts, t_ends, ray_indices):
t_starts, t_ends = t_starts[..., None], t_ends[..., None]
t_origins = rays_o[ray_indices]
t_positions = (t_starts + t_ends) / 2.0
t_dirs = rays_d[ray_indices]
positions = t_origins + t_dirs * t_positions
time_step = rays_t[ray_indices]
return self.model.density(positions, time_step, allow_shape=True, cano=cano)['sigma']
with torch.no_grad():
ray_indices, t_starts_, t_ends_ = self.occupancy_grid.sampling(
rays_o,
rays_d,
sigma_fn=None,
render_step_size=self.config['render']['step_size'],
alpha_thre=0,
stratified=True,
cone_angle=0.0,
early_stop_eps=0
)
if light_d is None:
light_d = safe_normalize(rays_o + torch.randn(3, device=rays_o.device))
ray_indices = ray_indices.long()
t_starts, t_ends = t_starts_[..., None], t_ends_[..., None]
t_origins = rays_o[ray_indices]
t_dirs = rays_d[ray_indices]
t_light_positions = light_d[ray_indices]
t_positions = (t_starts + t_ends) / 2.0
xyzs = t_origins + t_dirs * t_positions
time_step = rays_t[ray_indices]
if rays_depth is not None:
t_gt = rays_depth[ray_indices]
if rays_mask is not None:
t_mask = rays_mask[ray_indices]
t_dirs = safe_normalize(t_dirs)
# If no points are sampled, return a white image
# This usually happens when target object occupies
# a small portion of the image
if xyzs.shape[0] == 0:
image = torch.ones([*prefix, 3], device=rays_o.device)
depth = torch.zeros([*prefix], device=rays_o.device)
weights = None
opacity = None
normals = None
deform = None
normal_raw = None
else:
sdf, sigmas, rgbs, normals, deform, normal_raw = self.model(xyzs, time_step, t_light_positions, ratio=ambient_ratio, shading=shading, cano=cano)
weights, _, _ = nerfacc.render_weight_from_density(
t_starts[..., 0],
t_ends[..., 0],
sigmas,
ray_indices=ray_indices,
n_rays=N,
)
opacity = nerfacc.accumulate_along_rays(weights, values=None, ray_indices=ray_indices, n_rays=N)
depth = nerfacc.accumulate_along_rays(weights, values=t_positions, ray_indices=ray_indices, n_rays=N)
rgbs = nerfacc.accumulate_along_rays(weights, values=rgbs, ray_indices=ray_indices, n_rays=N)
if bg_color is None:
if self.config['model']['bg_radius'] > 0 and cano and (not real_view):
# use the bg model to calculate bg_color
bg_color = self.model.background(rays_d, rays_t) # [N, 3]
else:
bg_color = 1
image = rgbs + (1 - opacity) * bg_color
image = image.view(*prefix, 3)
depth = depth.view(*prefix)
results['image'] = image
results['depth'] = depth
results['sdf'] = sdf
results['weights'] = weights
results['weights_sum'] = opacity
results['normal'] = normals
results['deform'] = deform
results['normal_raw'] = normal_raw
if self.model.training:
if self.config['train']['ori_weight'] > 0 and normals is not None and (not real_view):
# orientation loss
loss_orient = weights.detach() * (normals * t_dirs).sum(-1).clamp(min=0) ** 2
results['loss_orient'] = loss_orient.sum(-1).mean()
if self.config['train']['normal_smooth_3d'] > 0 and normals is not None:
# normal regularization
if self.config['train']['normal_dir']:
# perturb the point based on normal direction (Not used in final version)
w = self.get_ortho_normal_dir(normals)
xyzs_perturb = xyzs + w * self.config['train']['smoothness_std']
else:
# Random perturbation
xyzs_perturb = xyzs + torch.randn_like(xyzs) * self.config['train']['smoothness_std']
if self.config['train']['topo_none']:
# NOTE: topo_none is an option that here we always use the zero topo for reg
# We find that this way of canonical space reg can be better than the else branch
# for scenes without large motion
# NOTE: Ideally, it worth trying regularization other than normal
# We leave this to potential future work.
# NOTE: The reason why we did not use deformation net is because we
# find this might easily lead to some over-smooth, de-generated solution.
normals_perturb, normal_raw = self.model.normal(xyzs_perturb, topo=None, cano=cano)
else:
topo = self.model.get_topo(xyzs_perturb, t=time_step)
normals_perturb, normal_raw = self.model.normal(xyzs_perturb, topo=topo, cano=cano)
results['loss_normal_perturb'] = (normals - normals_perturb).abs().mean()
if self.config['train']['normal_smooth_3d_t'] > 0:
# normal smoothness with perturbation on time, easily lead to over-smooth results,
# so we did not use this in the final version
topo_t = self.model.get_topo(xyzs, t=time_step + torch.rand_like(time_step) * 1/self.dataset.num_frames)
normals_perturb_t, normal_raw = self.model.normal(xyzs, topo=topo_t, cano=cano)
results['loss_normal_perturb_t'] = (normals - normals_perturb_t).abs().mean()
if self.config['train']['deform_smooth'] > 0 and not cano:
# deformation smoothness, would degrade results when we have large motion.
# Unfortunately, this is always the case for real-world data used in this paper
deform_perturb, topo_perturb, app_code_perturb = self.model.warp(xyzs_perturb, t=time_step)
results['loss_deform_perturb'] = (deform - deform_perturb).abs().mean()
if (self.config['train']['deform_smooth_t'] > 0 or self.config['train']['topo_smooth_t'] > 0) and not cano:
# Another deformation smoothness, w/ perturbation on time, not used in final version
deform_perturb_t, topo_perturb_t, app_code_perturb_t = self.model.warp(xyzs, t=time_step + torch.rand_like(time_step) * 1/self.dataset.num_frames)
results['loss_deform_perturb_t'] = (deform - deform_perturb_t).abs().mean()
results['loss_topo_perturb_t'] = (topo - topo_perturb_t).abs().mean()
if self.config['train']['code_reg'] > 0 and not cano:
# Code regularization
# NOTE: This may not improve the quantitative results. However,
# can avoid some tiny jittering effects.
sample_time_step = time_step[:1]
code = self.model.get_deform_code(sample_time_step)
code_prev = self.model.get_deform_code(sample_time_step - 1/self.dataset.num_frames)
code_next = self.model.get_deform_code(sample_time_step + 1/self.dataset.num_frames)
results['loss_code'] = torch.square(2 * code - code_prev - code_next).mean()
if (self.config['train']['normal_smooth_2d'] > 0) and (normals is not None) and (not real_view):
normal_image = nerfacc.accumulate_along_rays(weights, values=(normals + 1) / 2, ray_indices=ray_indices, n_rays=N)
results['normal_image'] = normal_image
if self.config['train']['normal_smoothness'] > 0:
# rays_o (Bs, 3)
# rays_d (Bs, 3)
# depth (1, Bs)
# L_smooth, our normal smoothness loss in observation space,
# only apply to points that are close to the surface to save computation
# This part is really costly, so we only sample a small number of the points
results['normal_reg'] = self.get_normal_smoothness_loss(rays_o, rays_d, rays_t, depth)
if rays_depth is not None:
fs_loss, sdf_loss = get_sdf_loss(t_positions, t_gt, sdf, self.config['train']['trunc'], mask = t_mask)
results['sdf_loss'] = sdf_loss
results['fs_loss'] = fs_loss
else:
fs_loss, sdf_loss = torch.tensor(0.0, device=rays_o.device), torch.tensor(0.0, device=rays_o.device)
return results
def progressive_view(self, exp_iter_ratio):
'''
Progressive view expansion. We found this might not improve the results.
'''
if self.config['train']['progressive_view']:
r = min(1.0, self.config['train']['progressive_view_init_ratio'] + 2.0*exp_iter_ratio)
self.config['data']['phi_range'] = [self.config['data']['default_azimuth'] * (1 - r) + self.config['data']['full_phi_range'][0] * r,
self.config['data']['default_azimuth'] * (1 - r) + self.config['data']['full_phi_range'][1] * r]
self.config['data']['theta_range'] = [self.config['data']['default_polar'] * (1 - r) + self.config['data']['full_theta_range'][0] * r,
self.config['data']['default_polar'] * (1 - r) + self.config['data']['full_theta_range'][1] * r]
def progressive_level(self, exp_iter_ratio):
'''
Coarse-to-fine training
'''
if self.config['train']['progressive_level']:
self.model.max_level = min(1.0, 0.5 + 0.5*exp_iter_ratio)
def sample_view(self, real_view, cano):
'''
Sample view for training
return:
- data: sampled view (Virtual view or real view)
'''
if real_view and cano: # Not used
# Use first frame as canonical shape
data = self.dataset.sample_real_view_rays(idx=0)
elif real_view and (not cano):
data = self.dataset.sample_real_view_rays(ray_num=2048)
elif (not real_view) and cano: # Not used
data = self.dataset.get_virtual_view_rays(t=0)
else:
data = self.dataset.get_virtual_view_rays()
return data
def get_rays_from_data(self, data, real_view):
'''
Get rays from view data.Return extra data
(depth + mask) for real view
'''
rays_o = data['rays_o'].to(self.device) # [B, N, 3]
rays_d = data['rays_d'].to(self.device) # [B, N, 3]
rays_t = data['rays_t'].to(self.device) # [B, N, 1]
rays_id = data['rays_id'].to(self.device) # [B, N, 1]
B, N = rays_o.shape[:2]
if real_view:
rays_depth = data['depth'].view(B, -1, 1).to(self.device) # [B, N, 1]
rays_mask = data['mask'].view(B, -1, 1).to(self.device) # [B, N, 1]
else:
rays_depth = None
rays_mask = None
# Add small noise to the real view rays, outdated option
# Keep it here for potential future use
if self.config['train']['real_view_noise'] > 0:
rays_o = rays_o + torch.randn(3, device=self.device) * self.config['train']['real_view_noise']
rays_d = rays_d + torch.randn(3, device=self.device) * self.config['train']['real_view_noise']
return rays_o, rays_d, rays_t, rays_id, rays_depth, rays_mask
def get_shading(self, exp_iter_ratio, real_view):
'''
Get shading model for rendering
'''
if real_view:
ambient_ratio = 1.0 # Real view would use albedo only
shading = 'albedo_normal' # return normal as well, but still albedo as ambient_ratio=1.0
else:
if exp_iter_ratio <= self.config['train']['albedo_iter_ratio']: # default 0.0
ambient_ratio = 1.0
shading = 'albedo'
# Random shading
else:
min_ambient_ratio = self.config['train']['min_ambient_ratio']
ambient_ratio = min_ambient_ratio + (1.0-min_ambient_ratio) * random.random()
if random.random() >= (1.0 - self.config['train']['textureless_ratio']):
shading = 'textureless' # color = lambertian, nothing to do with albedo
else:
shading = 'lambertian'
return ambient_ratio, shading
def get_bg_color(self, real_view, B=None, N=None):
'''
Get background color for rendering
'''
if real_view:
bg_color = torch.rand((B * N, 3), device=self.device)
else:
# random background
if self.config['model']['bg_radius'] > 0 and random.random() > 0.5:
bg_color = None # use bg_net
else:
bg_color = torch.rand(3).to(self.device) # single color random bg
return bg_color
def update_occ_grid(self, rays_t, cano):
'''
Update occ grid for rendering
'''
def occ_eval_fn(x):
return self.model.density(x, rays_t, allow_shape=True, cano=cano)['sigma'] * self.config['render']['step_size'] # step size
self.occupancy_grid.update_every_n_steps(step=self.global_step-1, occ_eval_fn=occ_eval_fn)
def get_pred_from_outputs(self, outputs, B, H, W):
pred_depth = outputs['depth'].reshape(B, 1, H, W)
pred_mask = outputs['weights_sum'].reshape(B, 1, H, W)
if 'normal_image' in outputs:
pred_normal = outputs['normal_image'].reshape(B, H, W, 3)
else:
pred_normal = None
pred_rgb = outputs['image'].reshape(B, H, W, 3).permute(0, 3, 1, 2).contiguous() # [B, 3, H, W]
pred_sdf = outputs['sdf']
return pred_rgb, pred_depth, pred_mask, pred_normal, pred_sdf
def get_gt_from_data(self, data, bg_color, B, H, W):
gt_rgb = data['image'].to(self.device) # [B, 3, H, W]
gt_depth = data['depth'].to(self.device) # [B, H, W]
gt_mask = data['mask'].to(self.device) # [B, H, W]
if len(gt_rgb.shape) == 3:
gt_mask = gt_mask.unsqueeze(0)
gt_rgb = gt_rgb.unsqueeze(0)
gt_depth = gt_depth.unsqueeze(0)
gt_mask[gt_mask>0.5] = 1.0
gt_mask[gt_mask<=0.5] = 0.0
gt_rgb = gt_rgb * gt_mask[:, None].float() + bg_color.reshape(B, H, W, 3).permute(0,3,1,2).contiguous() * (1 - gt_mask[:, None].float())
return gt_rgb, gt_depth, gt_mask
def get_real_view_render_loss(self, pred_rgb, pred_depth, pred_mask,
gt_rgb, gt_depth, gt_mask,
rays_o, rays_d):
loss = 0
# Color loss
if self.config['train']['rgb_weight'] > 0:
color_loss = self.config['train']['rgb_weight'] * F.mse_loss(pred_rgb, gt_rgb)
loss += color_loss
# Mask loss
if self.config['train']['mask_weight'] > 0:
mask_loss = self.config['train']['mask_weight'] * F.binary_cross_entropy(pred_mask[:, 0].clip(1e-5, 1.0 - 1e-5), gt_mask.float()) #F.mse_loss(pred_mask[:, 0], gt_mask.float())
loss += mask_loss
# Depth loss
if self.config['train']['depth_weight'] > 0:
# Handle outliers
depth_mask = torch.ones_like(gt_depth)
depth_mask[gt_depth<=0] = 0
xyzs = rays_o + gt_depth.reshape(1, -1, 1) * rays_d
pts_norm = torch.linalg.norm(xyzs, ord=2, dim=-1, keepdim=True)
outside = pts_norm > 1.1
depth_mask[outside.view(*depth_mask.shape)] = 0
depth_mask[gt_mask<=0.5] = 0
valid_gt_depth = gt_depth * depth_mask # [B,]
valid_pred_depth = pred_depth[:, 0] * depth_mask# [B,]
depth_loss = self.config['train']['depth_weight'] * F.mse_loss(valid_pred_depth, valid_gt_depth)
loss += depth_loss
return loss
def get_real_view_point_loss(self, gt_rgb, gt_depth, gt_mask,
rays_o, rays_d, rays_t, outputs):
loss = 0
# SDF loss
if self.config['train']['sdf_weight'] > 0:
loss += self.config['train']['sdf_weight'] * outputs['sdf_loss']
# SDF regularization
if self.config['train']['sdf_reg'] > 0:
loss += self.config['train']['sdf_reg'] * torch.mean(pred_sdf**2)
# Free space loss
if self.config['train']['fs_weight'] > 0:
loss += self.config['train']['fs_weight'] * outputs['fs_loss']