-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathrun_nerf.py
1564 lines (1215 loc) · 68.1 KB
/
run_nerf.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, sys
import cv2
import numpy as np
import imageio
import json
import random
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from ssim import ssim
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
from run_nerf_helpers import *
from load_blender import load_blender_data
from load_gibson import load_gibson_data
from load_llff_video import load_video_data
from skimage.io import imread
from skimage.transform import resize
from lpip import models
from torchdiffeq import odeint, odeint_adjoint
from tqdm import tqdm, trange
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
data_device = torch.device("cpu")
np.random.seed(0)
DEBUG = False
percept_model = models.PerceptualLoss(model='net-lin', net='alex', use_gpu=True)
def batchify(fn, chunk):
if chunk is None:
return fn
def ret(inputs):
return torch.cat([fn(inputs[i:i+chunk]) for i in range(0, inputs.shape[0], chunk)], 0)
return ret
def model_copy(model, model_copy):
for p, p_copy in zip(model.parameters(), model_copy.parameters()):
p_copy.data[:] = p.data[:]
def generate_data(loc_t_before, loc_t_after):
diff = 0
while True:
ix = np.random.randint(loc_t_after.size(0))
diff = (loc_t_after[ix] - loc_t_before[ix]).mean().item()
t_step = torch.Tensor([0, diff]).to(loc_t_before.device)
if t_step[1] < 0:
t_step = -1 * t_step
reverse = True
else:
reverse = False
if diff != 0:
return diff, t_step, ix, reverse
def batchify_point(fn, chunk):
if chunk is None:
return fn
def ret(inputs):
return torch.cat([fn.forward_pts(inputs[i:i+chunk], render=True) for i in range(0, inputs.shape[0], chunk)], 0)
return ret
def flatten(arr):
s = arr.shape
return arr.reshape((s[0]*s[1], *s[2:]))
def run_network(inputs, viewdirs, fn, embed_fn, embeddirs_fn, netchunk=1024*64):
inputs_flat = torch.reshape(inputs, [-1, inputs.shape[-1]])
embedded = embed_fn(inputs_flat)
if viewdirs is not None:
input_dirs = viewdirs[:,None].expand(inputs[:, :, :viewdirs.size(1)].shape)
input_dirs_flat = torch.reshape(input_dirs, [-1, input_dirs.shape[-1]])
embedded_dirs = embeddirs_fn(input_dirs_flat)
embedded = torch.cat([embedded, embedded_dirs], -1)
outputs_flat = batchify(fn, netchunk)(embedded)
outputs = torch.reshape(outputs_flat, list(inputs.shape[:-1]) + [outputs_flat.shape[-1]])
return outputs
def run_network_point(inputs, fn, embed_fn, netchunk=1024*64, velocity=False):
inputs_flat = torch.reshape(inputs, [-1, inputs.shape[-1]])
embedded = embed_fn(inputs_flat)
outputs_flat = batchify_point(fn, netchunk)(embedded)
outputs = torch.reshape(outputs_flat, list(inputs.shape[:-1]) + [outputs_flat.shape[-1]])
return outputs
def batchify_rays(rays_flat, chunk=1024*32, **kwargs):
all_ret = {}
for i in range(0, rays_flat.shape[0], chunk):
ret = render_rays(rays_flat[i:i+chunk], **kwargs)
for k in ret:
if k not in all_ret:
all_ret[k] = []
all_ret[k].append(ret[k])
for k in all_ret:
try:
all_ret[k] = torch.cat(all_ret[k], 0)
except:
continue
return all_ret
def render(H, W, focal, chunk=1024*64, rays=None, c2w=None, ndc=True,
near=0., far=1.,
use_viewdirs=False, c2w_staticcam=None, timestep=None,
**kwargs):
if c2w is not None:
# special case to render full image
rays_o, rays_d = get_rays(H, W, focal, c2w)
kwargs['render_image'] = True
else:
# use provided ray batch
rays_o, rays_d = rays
kwargs['render_image'] = False
if timestep is not None:
rays_o = torch.cat([rays_o, torch.ones_like(rays_o)[:, :, :1] * timestep], dim=-1)
if len(rays_d.shape) == 2:
rays_d = rays_d[:, :3]
if use_viewdirs:
# provide ray directions as input
viewdirs = rays_d
if c2w_staticcam is not None:
# special case to visualize effect of viewdirs
rays_o, rays_d = get_rays(H, W, focal, c2w_staticcam)
viewdirs = viewdirs / torch.norm(viewdirs, dim=-1, keepdim=True)
viewdirs = torch.reshape(viewdirs, [-1,3]).float()
if kwargs['use_time']:
s = rays_o.size()
rays_o_flat = rays_o.view(-1, s[-1])
viewdirs = torch.cat([viewdirs, torch.Tensor(rays_o_flat[..., -3:]).to(viewdirs.device)], dim=-1)
sh = rays_d.shape # [..., 3]
if ndc:
# for forward facing scenes
rays_o, rays_d = ndc_rays(H, W, focal, 1., rays_o, rays_d)
# Create ray batch
rays_o = torch.reshape(rays_o, [-1,4]).float()
rays_d = torch.reshape(rays_d, [-1,3]).float()
near, far = near * torch.ones_like(rays_d[...,:1]), far * torch.ones_like(rays_d[...,:1])
rays = torch.cat([rays_o, rays_d, near, far], -1)
if use_viewdirs:
rays = torch.cat([rays, viewdirs], -1)
# Render and reshape
all_ret = batchify_rays(rays, chunk, **kwargs)
for k in all_ret:
if k in ["max_pt", "min_pt"]:
all_ret[k] = all_ret[k]
else:
try:
k_sh = list(sh[:-1]) + list(all_ret[k].shape[1:])
all_ret[k] = torch.reshape(all_ret[k], k_sh)
except:
pass
k_extract = ['rgb_map', 'disp_map', 'acc_map']
ret_list = [all_ret[k] for k in k_extract]
ret_dict = {k : all_ret[k] for k in all_ret if k not in k_extract}
return ret_list + [ret_dict]
def render_path(render_poses, render_timesteps, hwf, chunk, render_kwargs, gt_imgs=None, savedir=None, render_factor=0, velocity=False, render_res=False):
H, W, focal = hwf
if render_factor!=0:
# Render downsampled for speed
H = H//render_factor
W = W//render_factor
focal = focal/render_factor
rgbs = []
disps = []
t = time.time()
# compute statistics for rendering
psnrs = []
mses = []
lpips = []
ssims = []
accs = []
for i, (c2w, timestep) in enumerate(tqdm(zip(render_poses, render_timesteps))):
print(i, time.time() - t)
t = time.time()
if type(focal) == np.ndarray:
focal = float(focal.mean())
if render_res:
rgb, disp, acc, _ = render(2*H, 2*W, focal * 2, chunk=8*1024, c2w=c2w[:3,:4], timestep=timestep, velocity=velocity, **render_kwargs)
else:
rgb, disp, acc, _ = render(H, W, focal, chunk=8*1024, c2w=c2w[:3,:4], timestep=timestep, velocity=velocity, **render_kwargs)
rgbs.append(rgb.cpu().numpy())
disps.append(disp.cpu().numpy() / disp.cpu().numpy().max())
accs.append(acc.cpu().numpy())
if i==0:
print(rgb.shape, disp.shape)
if gt_imgs is not None and render_factor==0:
p = -10. * np.log10(np.mean(np.square(rgb.cpu().numpy() - gt_imgs[i])))
psnrs.append(p)
mse = np.square(rgb.cpu().numpy() - gt_imgs[i]).mean()
mses.append(mse)
gt_img = torch.Tensor(gt_imgs[i]).to(rgb.device)
ssim_val = ssim(rgb[None, :, :, :], gt_img[None, :, :, :])
ssims.append(ssim_val.item())
# Center images for LPIP
rgb = (rgb - 0.5) * 2.0
gt_img = (gt_img - 0.5) * 2.0
with torch.no_grad():
d = percept_model.forward(rgb[None, :, :, :].permute(0, 3, 1, 2), gt_img[None, :, :, :].permute(0, 3, 1, 2))
lpips.append(d.item())
if savedir is not None:
rgb8 = to8b(rgbs[-1])
filename = os.path.join(savedir, '{:03d}.png'.format(i))
imageio.imwrite(filename, rgb8)
print("PSNR ", np.mean(psnrs))
print("MSE ", np.mean(mses))
print("LPIPS ", np.mean(lpips))
print("SSIMS ", np.mean(ssims))
print("here")
rgbs = np.stack(rgbs, 0)
disps = np.stack(disps, 0)
accs = np.stack(accs, 0)
if velocity:
# min_val = accs.min(axis=0).min(axis=0).min(axis=0)
# max_val = accs.max(axis=0).max(axis=0).min(axis=0)
min_val = accs.min()
max_val = accs.max()
accs = np.clip((accs - min_val) / (max_val - min_val + 1e-3), 0, 1)
return rgbs, disps, accs, mses
def compute_contrast(f1, f2, f3=None):
f1 = F.normalize(f1, p=2, dim=-1)
f2 = F.normalize(f2, p=2, dim=-1)
dot_sim = (f1 * f2).sum(dim=-1) / 0.08
f1_expand = f1[:, None, :]
if f3 is not None:
f2_expand = torch.cat([f3[None, :, :], f2[None, :, :]], dim=1)
else:
f2_expand = f2[None, :, :]
partition_func = (f1_expand * f2_expand).sum(dim=-1) / 0.08
partition_func = torch.logsumexp(partition_func, dim=-1)
loss_contrast = -dot_sim + partition_func
loss_contrast = loss_contrast.mean()
return loss_contrast
def create_nerf(args):
embed_fn, input_ch = get_embedder(args.multires, input_dims=4, i=args.i_embed)
# embed_fn, input_ch = get_embedder(args.multires, input_dims=3, i=args.i_embed)
input_ch_views = 0
embeddirs_fn = None
if args.use_viewdirs:
if args.use_time:
embeddirs_fn, input_ch_views = get_embedder(args.multires_views, input_dims=4, i=args.i_embed)
else:
embeddirs_fn, input_ch_views = get_embedder(args.multires_views, input_dims=3, i=args.i_embed)
output_ch = 5 if args.N_importance > 0 else 4
skips = [4]
model = NeRF(D=args.netdepth, W=args.netwidth,
input_ch=input_ch, output_ch=output_ch, skips=skips,
input_ch_views=input_ch_views, no_decomp=args.no_decomp, use_viewdirs=args.use_viewdirs, sin_init=args.sin_init, velocity=args.velocity, embed_fn=embed_fn).to(device)
model_copy = NeRF(D=args.netdepth, W=args.netwidth,
input_ch=input_ch, output_ch=output_ch, skips=skips,
input_ch_views=input_ch_views, no_decomp=args.no_decomp, use_viewdirs=args.use_viewdirs, sin_init=args.sin_init, velocity=args.velocity, embed_fn=embed_fn).to(device)
grad_vars = list(model.parameters())
model_fine = None
model_fine_copy = None
if args.N_importance > 0:
model_fine = NeRF(D=args.netdepth_fine, W=args.netwidth_fine,
input_ch=input_ch, output_ch=output_ch, skips=skips,
input_ch_views=input_ch_views, no_decomp=args.no_decomp, use_viewdirs=args.use_viewdirs, sin_init=args.sin_init, velocity=args.velocity, embed_fn=embed_fn).to(device)
model_fine_copy = NeRF(D=args.netdepth_fine, W=args.netwidth_fine,
input_ch=input_ch, output_ch=output_ch, skips=skips,
input_ch_views=input_ch_views, no_decomp=args.no_decomp, use_viewdirs=args.use_viewdirs, sin_init=args.sin_init, velocity=args.velocity, embed_fn=embed_fn).to(device)
grad_vars += list(model_fine.parameters())
network_query_fn = lambda inputs, viewdirs, network_fn : run_network(inputs, viewdirs, network_fn,
embed_fn=embed_fn,
embeddirs_fn=embeddirs_fn,
netchunk=args.netchunk)
network_query_fn_pt = lambda inputs, network_fn : run_network_point(inputs, network_fn,
embed_fn=embed_fn,
netchunk=args.netchunk)
# Create optimizer
optimizer = torch.optim.Adam(params=grad_vars, lr=args.lrate, betas=(0.9, 0.999))
start = 0
basedir = args.basedir
expname = args.expname
##########################
# Load checkpoints
if args.ft_path is not None and args.ft_path!='None':
ckpts = [args.ft_path]
else:
ckpts = [os.path.join(basedir, expname, f) for f in sorted(os.listdir(os.path.join(basedir, expname))) if '.tar' in f]
print('Found ckpts', ckpts)
if len(ckpts) > 0 and not args.no_reload:
ckpt_path = ckpts[-1]
print('Reloading from', ckpt_path)
ckpt = torch.load(ckpt_path)
start = ckpt['global_step'] + 1
optimizer.load_state_dict(ckpt['optimizer_state_dict'])
# Load model
model.load_state_dict(ckpt['network_fn_state_dict'])
model_copy.load_state_dict(ckpt['network_fn_state_dict'])
if model_fine is not None:
model_fine.load_state_dict(ckpt['network_fine_state_dict'])
model_fine_copy.load_state_dict(ckpt['network_fine_state_dict'])
##########################
render_kwargs_train = {
'network_query_fn' : network_query_fn,
'network_query_fn_pt' : network_query_fn_pt,
'perturb' : args.perturb,
'N_importance' : args.N_importance,
'network_fine' : model_fine,
'network_fine_copy' : model_fine_copy,
'N_samples' : args.N_samples,
'network_fn' : model,
'network_fn_copy' : model_copy,
'use_viewdirs' : args.use_viewdirs,
'white_bkgd' : args.white_bkgd,
'raw_noise_std' : args.raw_noise_std,
'use_time' : args.use_time,
}
# NDC only good for LLFF-style forward facing data
# if args.dataset_type != 'llff' or args.no_ndc:
print('Not ndc!')
render_kwargs_train['ndc'] = False
render_kwargs_train['lindisp'] = args.lindisp
render_kwargs_test = {k : render_kwargs_train[k] for k in render_kwargs_train}
render_kwargs_test['perturb'] = False
render_kwargs_test['raw_noise_std'] = 0.
return render_kwargs_train, render_kwargs_test, start, grad_vars, optimizer
def raw2outputs(raw, z_vals, rays_d, raw_noise_std=0, white_bkgd=False, pytest=False, v_val=None, render_image=False):
""" A helper function for `render_rays`.
"""
white_bkgd = False
raw2alpha = lambda raw, dists, act_fn=F.relu: 1.-torch.exp(-act_fn(raw) * dists)
dists = z_vals[...,1:] - z_vals[...,:-1]
dists = torch.cat([dists, torch.Tensor([1e10]).to(dists.device).expand(dists[...,:1].shape)], -1) # [N_rays, N_samples]
dists = dists * torch.norm(rays_d[...,None,:], dim=-1)
rgb = torch.sigmoid(raw[...,:3]) # [N_rays, N_samples, 3]
noise = 0.
if raw_noise_std > 0.:
noise = torch.randn_like(raw[...,3]) * raw_noise_std
# Overwrite randomly sampled data if pytest
if pytest:
np.random.seed(0)
noise = np.random.rand(*list(raw[...,3].shape)) * raw_noise_std
noise = torch.Tensor(noise)
alpha = raw2alpha(raw[...,3] + noise, dists) # [N_rays, N_samples]
# weights = alpha * tf.math.cumprod(1.-alpha + 1e-10, -1, exclusive=True)
# import pdb
# pdb.set_trace()
# print(alpha)
# print(rgb)
weights = alpha * torch.cumprod(torch.cat([torch.ones((alpha.shape[0], 1)).to(alpha.device), 1.-alpha + 1e-10], -1), -1)[:, :-1]
# import pdb
# pdb.set_trace()
rgb_map = torch.sum(weights[...,None] * rgb, -2) # [N_rays, 3]
weights_depth = torch.sum(weights, dim=-1, keepdim=True)
final_sum = 1 - weights_depth
weights_depth = torch.cat([weights, final_sum], dim=-1)
z_vals_depth = torch.cat([z_vals, torch.ones((z_vals.shape[0], 1)).to(z_vals.device) * 1e5], dim=-1)
depth_map = torch.sum(weights_depth[..., :-1] * z_vals_depth[..., :-1], -1)
disp_map = 1./(1 + depth_map)
if v_val is not None:
# idx = weights.max(dim=1)[1]
# idx = idx[:, None, None].repeat(1, 1, 3)
# acc_map = torch.gather(v_val, 1, idx)[:, 0, :]
acc_map = (weights[:, :, None] * v_val[:, :, :]).sum(dim=1)
else:
acc_map = torch.sum(weights, -1)
if white_bkgd:
rgb_map = rgb_map + (1.-acc_map[...,None])
return rgb_map, disp_map, acc_map, weights, depth_map, alpha
def render_rays(ray_batch,
network_fn,
network_query_fn,
N_samples,
retraw=False,
lindisp=False,
perturb=0.,
N_importance=0,
network_fine=None,
white_bkgd=False,
raw_noise_std=0.,
verbose=False,
pytest=False,
velocity=False,
**kwargs):
N_rays = ray_batch.shape[0]
rays_o, rays_d = ray_batch[:,0:4], ray_batch[:,4:7] # [N_rays, 3] each
if kwargs['use_time']:
viewdirs = ray_batch[:,-4:] if ray_batch.shape[-1] > 8 else None
else:
viewdirs = ray_batch[:,-3:] if ray_batch.shape[-1] > 8 else None
# viewdirs = None
bounds = torch.reshape(ray_batch[...,7:9], [-1,1,2])
near, far = bounds[...,0], bounds[...,1] # [-1,1]
# N_samples = N_samples + random.randint(-20, 20)
t_vals = torch.linspace(0., 1., steps=N_samples).to(bounds.device)
if not lindisp:
z_vals = near * (1.-t_vals) + far * (t_vals)
else:
z_vals = 1./(1./near * (1.-t_vals) + 1./far * (t_vals))
model_fine = network_fine
velocity_module = model_fine.velocity_module
z_vals = z_vals.expand([N_rays, N_samples])
if perturb > 0.:
# get intervals between samples
mids = .5 * (z_vals[...,1:] + z_vals[...,:-1])
upper = torch.cat([mids, z_vals[...,-1:]], -1)
lower = torch.cat([z_vals[...,:1], mids], -1)
# stratified samples in those intervals
t_rand = torch.rand_like(z_vals)
# Pytest, overwrite u with numpy's fixed random numbers
if pytest:
np.random.seed(0)
t_rand = np.random.rand(*list(z_vals.shape))
t_rand = torch.Tensor(t_rand)
z_vals = lower + (upper - lower) * t_rand
pts = torch.cat([rays_o[...,None,:3] + rays_d[...,None,:] * z_vals[...,:,None], rays_o[...,None, 3:].repeat(1, z_vals.size(-1), 1)], dim=-1) # [N_rays, N_samples, 3]
# raw = run_network(pts)
raw = network_query_fn(pts, viewdirs, network_fn)
pts_orig = pts
raw_orig = raw
rgb_map, disp_map, acc_map, weights, depth_map_coarse, alpha = raw2outputs(raw, z_vals, rays_d, raw_noise_std, white_bkgd, pytest=pytest, render_image=kwargs['render_image'])
weights_orig = weights
max_idx = weights.max(dim=1)[1]
max_idx = max_idx[:, None, None].repeat(1, 1, 4)
max_depth_pts = torch.gather(pts, 1, max_idx)
max_pt = pts[:, :, :3].max(dim=0)[0].max(dim=0)[0]
min_pt = pts[:, :, :3].min(dim=0)[0].min(dim=0)[0]
if N_importance > 0:
rgb_map_0, disp_map_0, acc_map_0 = rgb_map, disp_map, acc_map
z_vals_mid = .5 * (z_vals[...,1:] + z_vals[...,:-1])
z_samples = sample_pdf(z_vals_mid, weights[...,1:-1], N_importance, det=(perturb==0.), pytest=pytest)
z_samples = z_samples.detach()
z_vals, _ = torch.sort(torch.cat([z_vals, z_samples], -1), -1)
pts = torch.cat([rays_o[...,None,:3] + rays_d[...,None,:] * z_vals[...,:,None], rays_o[...,None, 3:].repeat(1, z_vals.size(-1), 1)], dim=-1) # [N_rays, N_samples, 3]
run_fn = network_fn if network_fine is None else network_fine
# raw = run_network(pts, fn=run_fn)
raw = network_query_fn(pts, viewdirs, run_fn)
rgb_res = raw[..., -3:]
rgb_pred = raw[..., :3]
if velocity:
pts_list = torch.chunk(pts, 10, dim=0)
v_vals = []
for pts_i in pts_list:
v_vel = velocity_module.forward_velocity(pts_i)
v_vals.append(v_vel)
v_val = torch.cat(v_vals, dim=0)
else:
v_val= None
rgb_map, disp_map, acc_map, weights, depth_map, alpha = raw2outputs(raw, z_vals, rays_d, raw_noise_std, white_bkgd, pytest=pytest, v_val=v_val, render_image=kwargs['render_image'])
ret = {'rgb_map' : rgb_map, 'disp_map' : disp_map, 'depth_map': depth_map, 'depth_map_coarse': depth_map_coarse, 'acc_map' : acc_map, 'min_pt': min_pt, 'max_pt': max_pt, 'rgb_res': rgb_res, 'weights': weights, 'pts': pts, 'alpha': alpha, 'raw_pts': raw, 'z_vals': z_vals, 'rays_d': rays_d, 'rays_o': rays_o}
if retraw:
ret['raw'] = raw
if N_importance > 0:
ret['rgb0'] = rgb_map_0
ret['disp0'] = disp_map_0
ret['acc0'] = acc_map_0
ret['z_std'] = torch.std(z_samples, dim=-1, unbiased=False) # [N_rays]
for k in ret:
if (torch.isnan(ret[k]).any() or torch.isinf(ret[k]).any()) and DEBUG:
print("! [Numerical Error] {} contains nan or inf.".format(k))
return ret
def config_parser():
import configargparse
parser = configargparse.ArgumentParser()
parser.add_argument('--config', is_config_file=True, help='config file path')
parser.add_argument("--expname", type=str, help='experiment name')
parser.add_argument("--basedir", type=str, default='./logs/', help='where to store ckpts and logs')
parser.add_argument("--datadir", type=str, default='./data/llff/fern', help='input data directory')
# training options
parser.add_argument("--netdepth", type=int, default=4, help='layers in network')
parser.add_argument("--netwidth", type=int, default=512, help='channels per layer')
parser.add_argument("--netdepth_fine", type=int, default=4, help='layers in fine network')
parser.add_argument("--netwidth_fine", type=int, default=512, help='channels per layer in fine network')
parser.add_argument("--N_rand", type=int, default=32*32*4, help='batch size (number of random rays per gradient step)')
parser.add_argument("--lrate", type=float, default=5e-4, help='learning rate')
parser.add_argument("--lrate_decay", type=int, default=250000, help='exponential learning rate decay (in 1000 steps)')
parser.add_argument("--chunk", type=int, default=1024*32, help='number of rays processed in parallel, decrease if running out of memory')
parser.add_argument("--netchunk", type=int, default=1024*64, help='number of pts sent through network in parallel, decrease if running out of memory')
parser.add_argument("--no_batching", action='store_true', help='only take random rays from 1 image at a time')
parser.add_argument("--no_reload", action='store_true', help='do not reload weights from saved ckpt')
parser.add_argument("--use_time", action='store_true', help='add time to pose regression')
parser.add_argument("--ft_path", type=str, default=None, help='specific weights npy file to reload for coarse network')
# rendering options
parser.add_argument("--N_samples", type=int, default=64, help='number of coarse samples per ray')
parser.add_argument("--N_importance", type=int, default=0, help='number of additional fine samples per ray')
parser.add_argument("--frames", type=int, default=1000, help='maximum number of frames to load')
parser.add_argument("--perturb", type=float, default=1., help='set to 0. for no jitter, 1. for jitter')
parser.add_argument("--use_viewdirs", action='store_true', help='use full 5D input instead of 3D')
parser.add_argument("--i_embed", type=int, default=0, help='set 0 for default positional encoding, -1 for none')
parser.add_argument("--multires", type=int, default=10, help='log2 of max freq for positional encoding (3D location)')
parser.add_argument("--multires_views", type=int, default=4, help='log2 of max freq for positional encoding (2D direction)')
parser.add_argument("--raw_noise_std", type=float, default=1e0, help='std dev of noise added to regularize sigma_a output, 1e0 recommended')
parser.add_argument("--ood_render", action='store_true', help='render ood')
parser.add_argument("--rotate_render", action='store_true', help='render rotate')
parser.add_argument("--camera_render", action='store_true', help='render the start of the camera')
parser.add_argument("--camera_render_after", action='store_true', help='render the end of the camera')
parser.add_argument("--render_only", action='store_true', help='do not optimize, reload weights and render out render_poses path')
parser.add_argument("--render_test", action='store_true', help='render the test set instead of render_poses path')
parser.add_argument("--noise", action='store_true', help='add noise to images (for video processing)')
parser.add_argument("--pouring", action='store_true', help='pouring fluid')
parser.add_argument("--fern", action='store_true', help='use the fern version of the LLFF instead')
parser.add_argument("--debug", action='store_true', help='debug the model')
parser.add_argument("--render_factor", type=int, default=0, help='downsampling factor to speed up rendering, set 4 or 8 for fast preview')
parser.add_argument("--no_decomp", action='store_true', help='no decomposition of the view direction')
# dataset options
parser.add_argument("--dataset_type", type=str, default='llff', help='options: llff / blender / deepvoxels')
parser.add_argument("--testskip", type=int, default=1, help='will load 1/N images from test/val sets, useful for large datasets like deepvoxels')
## deepvoxels flags
parser.add_argument("--shape", type=str, default='greek', help='options : armchair / cube / greek / vase')
parser.add_argument("--velocity", action='store_true', help='supervise velocity')
parser.add_argument("--surface_loss", action='store_true', help='supervise surface revoery')
parser.add_argument("--vel_loss", action='store_true', help='supervise veloicty_loss')
parser.add_argument("--rgb_loss", action='store_true', help='supervise rgb loss')
parser.add_argument("--grad_penalty", action='store_true', help='penalty of the gradient')
parser.add_argument("--depth_loss", action='store_true', help='supervise rgb loss')
parser.add_argument("--bkg_loss", action='store_true', help='supervise background velocity loss')
parser.add_argument("--uniform_vel_loss", action='store_true', help='the robot has the same velocity')
parser.add_argument("--bkg_no_rgb_loss", action='store_true', help='do not calculate rgb loss on small position change points')
parser.add_argument("--unsup_velocity", action='store_true', help='unsupervised discovery of velocity')
parser.add_argument("--use_past_rays", action='store_true', help='used past rays')
## blender flags
parser.add_argument("--white_bkgd", action='store_true', help='set to render synthetic data on a white bkgd (always use for dvoxels)')
parser.add_argument("--contrast_random", action='store_true', help='contrast with random files as opposed ')
parser.add_argument("--half_res", action='store_true', help='load blender synthetic data at 400x400 instead of 800x800')
parser.add_argument("--camera_depth", action='store_true', help='return the depth of each rays as additional supervision for NeRF')
parser.add_argument("--no_optical_flow", action='store_true', help='don"t enforce optical flow')
## llff flags
parser.add_argument("--factor", type=int, default=8, help='downsample factor for LLFF images')
parser.add_argument("--no_ndc", action='store_true', help='do not use normalized device coordinates (set for non-forward facing scenes)')
parser.add_argument("--sin_init", action='store_true', help='initialize using the sin function')
parser.add_argument("--lindisp", action='store_true', help='sampling linearly in disparity rather than depth')
parser.add_argument("--optical_flow", action='store_true', help='sampling linearly in disparity rather than depth')
parser.add_argument("--scene_flow", action='store_true', help='utilize scene flow to train the model')
parser.add_argument("--scene_flow_unsup", action='store_true', help='utilize scene flow to train the model')
parser.add_argument("--unsup_vel", action='store_true', help='unsupervised discovery of velocity')
parser.add_argument("--spherify", action='store_true', help='set for spherical 360 scenes')
parser.add_argument("--render_res", action='store_true', help='test higher resolution rendering with flow')
parser.add_argument("--llffhold", type=int, default=8, help='will take every 1/N images as LLFF test set, paper uses 8')
# logging/saving options
parser.add_argument("--i_print", type=int, default=100, help='frequency of console printout and metric loggin')
parser.add_argument("--i_img", type=int, default=500, help='frequency of tensorboard image logging')
parser.add_argument("--i_weights", type=int, default=10000, help='frequency of weight ckpt saving')
parser.add_argument("--i_testset", type=int, default=50000, help='frequency of testset saving')
parser.add_argument("--i_video", type=int, default=10000, help='frequency of render_poses video saving')
return parser
def train():
parser = config_parser()
args = parser.parse_args()
# Load data
if args.dataset_type == 'video':
if args.optical_flow:
bds, images, poses, render_poses, render_timesteps, hwf, i_split, timesteps, keypoints, keypoints_timestep, keypoints_pose, depths = load_video_data(args)
keypoints = np.array(keypoints)
keypoints_timestep = np.array(keypoints_timestep)
keypoints_pose = np.array(keypoints_pose)
elif args.scene_flow or args.velocity:
bds, images, poses, render_poses, render_timesteps, hwf, i_split, timesteps, locations, locations_timestep, bounds, depths = load_video_data(args)
locations = np.array(locations)
locations_timestep = np.array(locations_timestep)
else:
bds, images, poses, render_poses, render_timesteps, hwf, i_split, timesteps, depths = load_video_data(args)
print('Loaded blender', images.shape, render_poses.shape, hwf, args.datadir)
i_train = i_split[0]
near, far = bds[0, 0], bds[0, 1]
args.white_bkgd = False
if args.white_bkgd:
images = images[...,:3]*images[...,-1:] + (1.-images[...,-1:])
else:
images = images[...,:3]
elif args.dataset_type == 'blender':
if args.optical_flow:
images, poses, render_poses, render_timesteps, hwf, i_split, timesteps, keypoints, keypoints_timestep, keypoints_pose, depths = load_blender_data(args.datadir, args, args.half_res, args.testskip)
keypoints = np.array(keypoints)
keypoints_timestep = np.array(keypoints_timestep)
keypoints_pose = np.array(keypoints_pose)
elif args.scene_flow or args.velocity:
images, poses, render_poses, render_timesteps, hwf, i_split, timesteps, locations, locations_timestep, bounds, depths = load_blender_data(args.datadir, args, args.half_res, args.testskip)
locations = np.array(locations)
locations_timestep = np.array(locations_timestep)
else:
images, poses, render_poses, render_timesteps, hwf, i_split, timesteps, depths = load_blender_data(args.datadir, args, args.half_res, args.testskip)
# print('Loaded blender', images.shape, render_poses.shape, hwf, args.datadir)
i_train, i_val, i_test = i_split
if args.pouring:
near = 0.
far = 20.
else:
near = 0.
far = 8.
args.white_bkgd = False
if args.white_bkgd:
images = images[...,:3]*images[...,-1:] + (1.-images[...,-1:])
else:
images = images[...,:3]
elif args.dataset_type == 'gibson':
if args.optical_flow:
images, poses, render_poses, render_timesteps, hwf, i_split, timesteps, keypoints, keypoints_timestep, keypoints_pose = load_gibson_data(args.datadir, args, args.half_res, args.testskip)
keypoints = np.array(keypoints)
keypoints_timestep = np.array(keypoints_timestep)
keypoints_pose = np.array(keypoints_pose)
elif args.scene_flow or args.velocity:
images, poses, render_poses, render_timesteps, hwf, i_split, timesteps, locations, locations_timestep, bounds = load_gibson_data(args.datadir, args, args.half_res, args.testskip)
locations = np.array(locations)
locations_timestep = np.array(locations_timestep)
else:
images, poses, render_poses, render_timesteps, hwf, i_split, timesteps, = load_gibson_data(args.datadir, args, args.half_res, args.testskip)
print('Loaded blender', images.shape, render_poses.shape, hwf, args.datadir)
# i_train, i_val, i_test = i_split
i_train = i_split[0]
near = 0.0
far = 8.
args.white_bkgd = False
if args.white_bkgd:
images = images[...,:3]*images[...,-1:] + (1.-images[...,-1:])
else:
images = images[...,:3]
else:
print('Unknown dataset type', args.dataset_type, 'exiting')
return
# print(poses)
# Cast intrinsics to right types
H, W, focal = hwf
H, W = int(H), int(W)
hwf = [H, W, focal]
if args.render_test:
render_poses = np.array(poses[i_test])
render_timesteps = np.array(timesteps[i_test])
# Create log dir and copy the config file
basedir = args.basedir
expname = args.expname
os.makedirs(os.path.join(basedir, expname), exist_ok=True)
f = os.path.join(basedir, expname, 'args.txt')
with open(f, 'w') as file:
for arg in sorted(vars(args)):
attr = getattr(args, arg)
file.write('{} = {}\n'.format(arg, attr))
if args.config is not None:
f = os.path.join(basedir, expname, 'config.txt')
with open(f, 'w') as file:
file.write(open(args.config, 'r').read())
# Create nerf model
render_kwargs_train, render_kwargs_test, start, grad_vars, optimizer = create_nerf(args)
global_step = start
bds_dict = {
'near' : near,
'far' : far,
}
render_kwargs_train.update(bds_dict)
render_kwargs_test.update(bds_dict)
# Move testing data to GPU
render_poses = torch.Tensor(render_poses).to(device)
if args.velocity:
model_fine = render_kwargs_train['network_fine']
velocity_module = model_fine.velocity_module
rtol = 0.001
atol = 0.0001
# rtol = 1e-3
# atol = 1e-4
# rtol = 1e-4
# atol = 1e-5
ode_solver = "dopri5"
# odeint = odeint_adjoint
# Short circuit if only rendering out from trained model
if args.render_only:
print('RENDER ONLY')
with torch.no_grad():
# render_test switches to test poses
images = images
poses = torch.Tensor(poses).to(device)
testsavedir = os.path.join(basedir, expname, 'renderonly_{}_{:06d}'.format('test' if args.render_test else 'path', start))
os.makedirs(testsavedir, exist_ok=True)
print('test poses shape', render_poses.shape)
rgbs, _, _, _ = render_path(poses, timesteps, hwf, args.chunk / 2, render_kwargs_test, gt_imgs=images, savedir=testsavedir, render_factor=args.render_factor)
print('Done rendering', testsavedir)
imageio.mimwrite(os.path.join(testsavedir, 'video.mp4'), to8b(rgbs), fps=30, quality=8)
return
# Prepare raybatch tensor if batching random rays
N_rand = args.N_rand
use_batching = not args.no_batching
if use_batching:
# For random ray batching
print('get rays')
# if args.dataset_type in ["dynamic"]:
# rays = np.stack([get_rays_np(H, W, focal[i], p) for i, p in enumerate(poses[:,:3,:4])], 0) # [N, ro+rd, H, W, 3]
# else:
rays = np.stack([get_rays_np(H, W, focal, p) for i, p in enumerate(poses[:,:3,:4])], 0) # [N, ro+rd, H, W, 3]
print('done, concats')
rays_rgb = np.concatenate([rays, images[:,None]], 1) # [N, ro+rd+rgb, H, W, 3]
rays_rgb = np.transpose(rays_rgb, [0,2,3,1,4]) # [N, H, W, ro+rd+rgb, 3]
rays_rgb = np.stack([rays_rgb[i] for i in i_train], 0) # train images only
if args.camera_depth:
depths = np.stack(depths, 0)
depths = np.reshape(depths, [-1, 1])
s = rays_rgb.shape
timesteps_tile = timesteps[i_train]
timesteps_tile = np.tile(timesteps_tile[:, None, None, None, None], (1, s[1], s[2], s[3], 1))
rays_rgb = np.concatenate([rays_rgb, timesteps_tile], axis=4)
rays_rgb = np.reshape(rays_rgb, [-1,3,4]) # [(N-1)*H*W, ro+rd+rgb, 3]
if args.scene_flow or args.velocity:
loc_before, loc_after = locations[:, 0], locations[:, 1]
loc_t_before, loc_t_after = locations_timestep[:, None, :1], locations_timestep[:, None, 1:]
bounds = np.array(bounds)
# Generate constraints for timestep flow
rays_rgb = rays_rgb.astype(np.float32)
rix = np.random.permutation(rays_rgb.shape[0])
rays_rgb = rays_rgb[rix]
if args.camera_depth:
depths = depths[rix]
depths = torch.Tensor(depths).to(device)
# print('shuffle rays')
# np.random.shuffle(rays_rgb)
print('done')
i_batch = 0
ray_batch = 0
images = torch.Tensor(images).to(device)
poses = torch.Tensor(poses).to(device)
if use_batching:
rays_rgb = torch.Tensor(rays_rgb)
if args.optical_flow:
rays_before = torch.Tensor(rays_before).to(device)
rays_after = torch.Tensor(rays_after).to(device)
elif args.scene_flow or args.velocity:
loc_before, loc_after = torch.Tensor(loc_before), torch.Tensor(loc_after)
loc_t_before, loc_t_after = torch.Tensor(loc_t_before).to(device), torch.Tensor(loc_t_after).to(device)
if len(bounds.shape) == 4:
bounds = torch.Tensor(bounds[:, 0, :])
else:
bounds = torch.Tensor(bounds)
bounds = bounds.cuda()
loc_before = loc_before.cuda()
loc_after = loc_after.cuda()
loc_t_before = loc_t_before.repeat(1, bounds.size(1), 1)
loc_t_after = loc_t_after.repeat(1, bounds.size(1), 1)
loc_t_before = loc_t_before.cuda()
loc_t_after = loc_t_after.cuda()
N_iters = 1000000
print('Begin')
print('TRAIN views are', i_train)
#print('TEST views are', i_test)
#print('VAL views are', i_val)
# Summary writers
# writer = SummaryWriter(os.path.join(basedir, 'summaries', expname))
i = global_step
for i in trange(start, N_iters):
time0 = time.time()
# Sample random ray batch
if use_batching:
# Random over all images
batch = rays_rgb[i_batch:i_batch+N_rand].to(device) # [B, 2+1, 3*?]
if args.camera_depth:
camera_depth = depths[i_batch:i_batch+N_rand].to(device)
#import pdb
#pdb.set_trace()
batch = torch.transpose(batch, 0, 1)
batch_rays, target_s = batch[:2], batch[2,:,:3]
i_batch += N_rand
# ray_batch += N_rand
if i_batch >= rays_rgb.shape[0]:
print("Shuffle data after an epoch!")
rand_idx = torch.randperm(rays_rgb.shape[0])
rays_rgb = rays_rgb[rand_idx]
if args.camera_depth:
depths = depths[rand_idx]
i_batch = 0
else:
# Random from one image
img_i = np.random.choice(i_train)
target = images[img_i]
pose = poses[img_i, :3,:4]
if N_rand is not None:
rays_o, rays_d = get_rays(H, W, focal, torch.Tensor(pose)) # (H, W, 3), (H, W, 3)
coords = torch.stack(torch.meshgrid(torch.linspace(0, H-1, H), torch.linspace(0, W-1, W)), -1) # (H, W, 2)
coords = torch.reshape(coords, [-1,2]) # (H * W, 2)
select_inds = np.random.choice(coords.shape[0], size=[N_rand], replace=False) # (N_rand,)
select_coords = coords[select_inds].long() # (N_rand, 2)
rays_o = rays_o[select_coords[:, 0], select_coords[:, 1]] # (N_rand, 3)
rays_d = rays_d[select_coords[:, 0], select_coords[:, 1]] # (N_rand, 3)
batch_rays = torch.stack([rays_o, rays_d], 0)
target_s = target[select_coords[:, 0], select_coords[:, 1]] # (N_rand, 3)
rgb, disp, acc, extras = render(H, W, focal, chunk=args.chunk, rays=batch_rays,
verbose=i < 10, retraw=True,
**render_kwargs_train)
if args.velocity:
##########################
# Code for integrating scene flow equal to distance
if args.dataset_type == "video":
network_query_fn_pt = render_kwargs_train['network_query_fn_pt']
raw2alpha = lambda raw, dists, act_fn=F.relu: 1.-torch.exp(-act_fn(raw) * dists)
loc_before_i = loc_before[ix, :].to(device)
loc_after_i = loc_after[ix, :].to(device)
select_idx = torch.randperm(loc_before_i.size(0))[:512]
rays_o_before, rays_d_before = loc_before_i[select_idx, :3], loc_before_i[select_idx, 3:]
rays_o_after, rays_d_after = loc_after_i[select_idx, :3], loc_after_i[select_idx, 3:]
t_batch = torch.stack([loc_t_before[ix][select_idx], loc_t_after[ix][select_idx]], dim=0).view(-1)
bounds_i = bounds[ix][select_idx]
rays_o = torch.cat([rays_o_before, rays_o_after], dim=0)
rays_d = torch.cat([rays_d_before, rays_d_after], dim=0)
t_vals = torch.linspace(0., 1., steps=args.N_samples).to(rays_d.device)
z_vals = near * (1.-t_vals) + far * (t_vals)
model = render_kwargs_train['network_fn']
model_fine = render_kwargs_train['network_fine']
N_rays = rays_o.shape[0]
z_vals = z_vals.expand([N_rays, args.N_samples])
mids = .5 * (z_vals[...,1:] + z_vals[...,:-1])
upper = torch.cat([mids, z_vals[...,-1:]], -1)
lower = torch.cat([z_vals[...,:1], mids], -1)
t_rand = torch.rand(z_vals.shape).to(rays_d.device)
z_vals = lower + (upper - lower) * t_rand
dists = z_vals[...,1:] - z_vals[...,:-1]