forked from snap-research/R2L
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1636 lines (1434 loc) · 64.9 KB
/
main.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, copy, math, random, json, time
import imageio
from tqdm import tqdm, trange
import numpy as np
import lpips as lpips_
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.benchmark as benchmark
from model.nerf_raybased import NeRF, NeRF_v3_2, PositionalEmbedder, PointSampler
from dataset.load_llff import load_llff_data
from dataset.load_deepvoxels import load_dv_data
from dataset.load_blender import load_blender_data, BlenderDataset, BlenderDataset_v2, get_novel_poses
from utils.ssim_torch import ssim as ssim_
from utils.flip_loss import FLIP
from utils.run_nerf_raybased_helpers import sample_pdf, ndc_rays, get_rays, get_embedder, get_rays_np
from utils.run_nerf_raybased_helpers import parse_expid_iter, to_tensor, to_array, mse2psnr, to8b, img2mse
from utils.run_nerf_raybased_helpers import load_weights_v2, get_selected_coords, undataparallel
from smilelogging import Logger
from smilelogging.utils import Timer, LossLine, get_n_params_, get_n_flops_, AverageMeter, ProgressMeter
from option import args
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
np.random.seed(0)
DEBUG = False
# ---------------------------------
# Set up logging directories
logger = Logger(args)
accprint = logger.log_printer.accprint
netprint = logger.log_printer.netprint
ExpID = logger.ExpID
flip = FLIP()
class MyDataParallel(torch.nn.DataParallel):
def __getattr__(self, name):
try:
return super().__getattr__(name)
except AttributeError:
return getattr(self.module, name)
# Update ssim and lpips metric functions
ssim = lambda img, ref: ssim_(torch.unsqueeze(img, 0), torch.unsqueeze(ref, 0))
lpips = lpips_.LPIPS(net=args.lpips_net).to(device)
# ---------------------------------
def batchify(fn, chunk):
"""Constructs a version of 'fn' that applies to smaller batches.
"""
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 run_network(inputs,
viewdirs,
fn,
embed_fn,
embeddirs_fn,
netchunk=1024 * 64):
"""Prepares inputs and applies network 'fn'.
"""
inputs_flat = torch.reshape(
inputs, [-1, inputs.shape[-1]]
) # @mst: shape: torch.Size([65536, 3]), 65536=1024*64 (n_rays * n_sample_per_ray)
embedded = embed_fn(inputs_flat) # shape: [n_rays*n_sample_per_ray, 63]
if viewdirs is not None:
input_dirs = viewdirs[:, None].expand(inputs.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 batchify_rays(rays_flat, chunk=1024 * 32, **kwargs):
"""Render rays in smaller minibatches to avoid OOM.
"""
all_ret = {}
for i in range(0, rays_flat.shape[0], chunk):
ret = render_rays(
rays_flat[i:i + chunk],
**kwargs) # @mst: train, rays_flat.shape(0) = 1024, chunk = 32768
for k in ret:
if k not in all_ret:
all_ret[k] = []
all_ret[k].append(ret[k])
all_ret = {k: torch.cat(all_ret[k], 0) for k in all_ret}
return all_ret
def render(H,
W,
focal,
chunk=1024 * 32,
rays=None,
c2w=None,
ndc=True,
near=0.,
far=1.,
use_viewdirs=False,
c2w_staticcam=None,
**kwargs):
"""Render rays
Args:
H: int. Height of image in pixels.
W: int. Width of image in pixels.
focal: float. Focal length of pinhole camera.
chunk: int. Maximum number of rays to process simultaneously. Used to
control maximum memory usage. Does not affect final results.
rays: array of shape [2, batch_size, 3]. Ray origin and direction for
each example in batch.
c2w: array of shape [3, 4]. Camera-to-world transformation matrix.
ndc: bool. If True, represent ray origin, direction in NDC coordinates.
near: float or array of shape [batch_size]. Nearest distance for a ray.
far: float or array of shape [batch_size]. Farthest distance for a ray.
use_viewdirs: bool. If True, use viewing direction of a point in space in model.
c2w_staticcam: array of shape [3, 4]. If not None, use this transformation matrix for
camera while using other c2w argument for viewing directions.
Returns:
rgb_map: [batch_size, 3]. Predicted RGB values for rays.
disp_map: [batch_size]. Disparity map. Inverse of depth.
acc_map: [batch_size]. Accumulated opacity (alpha) along a ray.
extras: dict with everything returned by render_rays().
"""
if c2w is not None:
# special case to render full image
rays_o, rays_d = get_rays(H, W, focal, c2w)
else:
# use provided ray batch
rays_o, rays_d = rays
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
) # @mst: 'rays_d' is real-world data, needs normalization.
viewdirs = torch.reshape(viewdirs, [-1, 3]).float()
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, 3]).float() # @mst: test: [160000, 3], 400*400; train: [1024, 3]
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:
k_sh = list(sh[:-1]) + list(all_ret[k].shape[1:])
all_ret[k] = torch.reshape(all_ret[k], k_sh)
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,
hwf,
chunk,
render_kwargs,
gt_imgs=None,
savedir=None,
render_factor=0):
H, W, focal = hwf
if render_factor != 0:
# Render downsampled for speed
H = int(H / render_factor)
W = int(W / render_factor)
focal = focal / render_factor
render_kwargs['network_fn'].eval()
rgbs, disps, errors, ssims, psnrs = [], [], [], [], []
# for testing DONERF data
if args.given_render_path_rays:
loaded = torch.load(args.given_render_path_rays)
all_rays_o = loaded['all_rays_o'].to(device) # [N, H*W, 3]
all_rays_d = loaded['all_rays_d'].to(device) # [N, H*W, 3]
if 'gt_imgs' in loaded:
gt_imgs = loaded['gt_imgs'].to(device) # [N, H, W, 3]
print(f'Use given render_path rays: "{args.given_render_path_rays}"')
model = render_kwargs['network_fn']
for i in range(len(all_rays_o)):
torch.cuda.synchronize()
t0 = time.time()
with torch.no_grad():
pts = point_sampler.sample_train(
all_rays_o[i], all_rays_d[i],
perturb=0) # [H*W, n_sample*3]
model_input = positional_embedder(pts)
torch.cuda.synchronize()
t_input = time.time()
if args.learn_depth:
rgbd = model(model_input)
rgb = rgbd[:, :3]
else:
rgb = model(model_input)
torch.cuda.synchronize()
t_forward = time.time()
print(
f'[#{i}] frame, prepare input (embedding): {t_input - t0:.4f}s'
)
print(
f'[#{i}] frame, model forward: {t_forward - t_input:.4f}s')
# reshape to image
if args.dataset_type == 'llff':
H_, W_ = H, W # non-square images
elif args.dataset_type == 'blender':
H_ = W_ = int(math.sqrt(rgb.numel() / 3))
rgb = rgb.view(H_, W_, 3)
disp = rgb # placeholder, to maintain compability
rgbs.append(rgb)
disps.append(disp)
# @mst: various metrics
if gt_imgs is not None:
errors += [(rgb - gt_imgs[i][:H_, :W_, :]).abs()]
psnrs += [mse2psnr(img2mse(rgb, gt_imgs[i, :H_, :W_]))]
ssims += [ssim(rgb, gt_imgs[i, :H_, :W_])]
if savedir is not None:
filename = os.path.join(savedir, '{:03d}.png'.format(i))
imageio.imwrite(filename, to8b(rgbs[-1]))
imageio.imwrite(filename.replace('.png', '_gt.png'),
to8b(gt_imgs[i])) # save gt images
if len(errors):
imageio.imwrite(filename.replace('.png', '_error.png'),
to8b(errors[-1]))
torch.cuda.synchronize()
print(
f'[#{i}] frame, rendering done, time for this frame: {time.time()-t0:.4f}s'
)
print('')
else:
for i, c2w in enumerate(render_poses):
torch.cuda.synchronize()
t0 = time.time()
print(f'[#{i}] frame, rendering begins')
if args.model_name in ['nerf']:
rgb, disp, acc, _ = render(H,
W,
focal,
chunk=chunk,
c2w=c2w[:3, :4],
**render_kwargs)
H_, W_ = H, W
else: # For R2L model
model = render_kwargs['network_fn']
perturb = render_kwargs['perturb']
offsets = torch.zeros((H * W, 1))
# Network forward
with torch.no_grad():
if args.given_render_path_rays: # To test DONERF data using our model
pts = point_sampler.sample_train(
all_rays_o[i], all_rays_d[i],
perturb=0) # [H*W, n_sample*3]
else:
if args.plucker:
pts = point_sampler.sample_test_plucker(
c2w[:3, :4])
else:
pts, offsets = point_sampler.sample_test(
c2w[:3, :4]) # [H*W, n_sample*3]
model_input = positional_embedder(pts)
torch.cuda.synchronize()
t_input = time.time()
if args.learn_depth:
rgbd = model(model_input)
rgb = rgbd[:, :3]
else:
rgb = model(model_input)
torch.cuda.synchronize()
t_forward = time.time()
print(
f'[#{i}] frame, prepare input (embedding): {t_input - t0:.4f}s'
)
print(
f'[#{i}] frame, model forward: {t_forward - t_input:.4f}s'
)
# Reshape to image
if args.dataset_type == 'llff':
H_, W_ = H, W # non-square images
elif args.dataset_type == 'blender':
if args.train_depth:
H_ = W_ = int(math.sqrt(rgb.numel()))
else:
H_ = W_ = int(math.sqrt(rgb.numel() / 3))
print(H_, W_)
if args.train_depth:
rgb = rgb.view(H_, W_, 1)
offsets = offsets.view(H_, W_, 1).to("cuda:0")
rgb = 1/(1/rgb + offsets)
rgb *= args.scaling_factor
rgb = rgb.expand(H_, W_, 3)
else:
rgb = rgb.view(H_, W_, 3)
disp = rgb # Placeholder, to maintain compability
rgbs.append(rgb)
disps.append(disp)
# @mst: various metrics
if gt_imgs is not None:
errors += [(rgb - gt_imgs[i][:H_, :W_, :]).abs()]
psnrs += [mse2psnr(img2mse(rgb, gt_imgs[i, :H_, :W_]))]
ssims += [ssim(rgb, gt_imgs[i, :H_, :W_])]
if savedir is not None:
filename = os.path.join(savedir, '{:03d}.png'.format(i))
imageio.imwrite(filename, to8b(rgbs[-1]))
imageio.imwrite(filename.replace('.png', '_gt.png'),
to8b(gt_imgs[i])) # save gt images
if len(errors):
imageio.imwrite(filename.replace('.png', '_error.png'),
to8b(errors[-1]))
torch.cuda.synchronize()
print(
f'[#{i}] frame, rendering done, time for this frame: {time.time()-t0:.4f}s'
)
print('')
rgbs = torch.stack(rgbs, dim=0)
disps = torch.stack(disps, dim=0)
# https://github.com/richzhang/PerceptualSimilarity
# LPIPS demands input shape [N, 3, H, W] and in range [-1, 1]
misc = {}
if gt_imgs is not None:
rec = rgbs.permute(0, 3, 1, 2) # [N, 3, H, W]
ref = gt_imgs.permute(0, 3, 1, 2) # [N, 3, H, W]
rescale = lambda x, ymin, ymax: (ymax - ymin) / (x.max() - x.min()) * (
x - x.min()) + ymin
rec, ref = rescale(rec, -1, 1), rescale(ref, -1, 1)
lpipses = []
mini_batch_size = 8
for i in np.arange(0, len(gt_imgs), mini_batch_size):
end = min(i + mini_batch_size, len(gt_imgs))
lpipses += [lpips(rec[i:end], ref[i:end])]
lpipses = torch.cat(lpipses, dim=0)
# -- get FLIP loss
# flip standard values
monitor_distance = 0.7
monitor_width = 0.7
monitor_resolution_x = 3840
pixels_per_degree = monitor_distance * (monitor_resolution_x /
monitor_width) * (np.pi / 180)
# flips = flip.compute_flip(rec, ref,
# pixels_per_degree) # shape [N, 1, H, W]
# --
errors = torch.stack(errors, dim=0)
psnrs = torch.stack(psnrs, dim=0)
ssims = torch.stack(ssims, dim=0)
test_loss = img2mse(rgbs,
gt_imgs[:, :H_, :W_]) # @mst-TODO: remove H_, W_
misc['test_loss'] = test_loss
misc['test_psnr'] = mse2psnr(test_loss)
misc['test_psnr_v2'] = psnrs.mean()
misc['test_ssim'] = ssims.mean()
misc['test_lpips'] = lpipses.mean()
# misc['test_flip'] = flips.mean()
misc['errors'] = errors
render_kwargs['network_fn'].train()
torch.cuda.empty_cache()
return rgbs, disps, misc
def render_func(model, pose):
with torch.no_grad():
rgb = model(positional_embedder(point_sampler.sample_test(pose)))
return rgb
def create_nerf(args, near, far):
"""Instantiate NeRF's MLP model.
"""
# set up model
model_fine = network_query_fn = None
global embed_fn
embed_fn, input_ch = get_embedder(args.multires, args.i_embed)
input_ch_views = 0
embeddirs_fn = None
if args.use_viewdirs:
embeddirs_fn, input_ch_views = get_embedder(args.multires_views,
args.i_embed)
# @mst: use external positional embedding for our raybased nerf
global positional_embedder
positional_embedder = PositionalEmbedder(L=args.multires)
grad_vars = []
if args.model_name in ['nerf']:
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,
use_viewdirs=args.use_viewdirs).to(device)
grad_vars += list(model.parameters())
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,
use_viewdirs=args.use_viewdirs).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)
elif args.model_name in ['nerf_v3.2', 'R2L']:
if args.plucker:
input_dim = 6 * positional_embedder.embed_dim
else:
input_dim = args.n_sample_per_ray * 3 * positional_embedder.embed_dim
model = NeRF_v3_2(args, input_dim, 3).to(device)
if not args.freeze_pretrained:
grad_vars += list(model.parameters())
elif args.model_name in ['DeLFT']:
input_dim = args.n_sample_per_ray * 3 * positional_embedder.embed_dim
model = NeRF_v3_2(args, input_dim, 1).to(device)
if not args.freeze_pretrained:
grad_vars += list(model.parameters())
# set up optimizer
optimizer = torch.optim.Adam(params=grad_vars,
lr=args.lrate,
betas=(0.9, 0.999))
# start iteration
history = {'start': 0, 'best_psnr': 0, 'best_psnr_step': 0}
# use DataParallel
if not args.render_only: # when rendering, use just one GPU
model = MyDataParallel(model)
if model_fine is not None:
model_fine = MyDataParallel(model_fine)
if hasattr(model.module, 'input_dim'):
model.input_dim = model.module.input_dim
print(f'Using data parallel')
# load pretrained checkpoint
if args.pretrained_ckpt:
ckpt = torch.load(args.pretrained_ckpt)
if 'network_fn' in ckpt:
model = ckpt['network_fn']
grad_vars = list(model.parameters())
if model_fine is not None:
assert 'network_fine' in ckpt
model_fine = ckpt['network_fine']
grad_vars += list(model_fine.parameters())
optimizer = torch.optim.Adam(params=grad_vars,
lr=args.lrate,
betas=(0.9, 0.999))
print(
f'Use model arch saved in checkpoint "{args.pretrained_ckpt}", and build a new optimizer.'
)
# load state_dict
load_weights_v2(model, ckpt, 'network_fn_state_dict')
if model_fine is not None:
load_weights_v2(model_fine, ckpt, 'network_fine_state_dict')
print(f'Load pretrained ckpt successfully: "{args.pretrained_ckpt}".')
if args.resume:
history['start'] = ckpt['global_step']
history['best_psnr'] = ckpt.get('best_psnr', 0)
history['best_psnr_step'] = ckpt.get('best_psnr_step', 0)
optimizer.load_state_dict(ckpt['optimizer_state_dict'])
print('Resume optimizer successfully.')
# set up training args
render_kwargs_train = {
'network_query_fn': network_query_fn,
'perturb': args.perturb,
'N_importance': args.N_importance,
'network_fine': model_fine,
'N_samples': args.N_samples,
'network_fn': model,
'use_viewdirs': args.use_viewdirs,
'white_bkgd': args.white_bkgd,
'raw_noise_std': args.raw_noise_std,
}
# 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
# set up testing args
render_kwargs_test = {
k: render_kwargs_train[k]
for k in render_kwargs_train
}
render_kwargs_test['perturb'] = args.perturb_test
render_kwargs_test['raw_noise_std'] = 0.
# get FLOPs and params
netprint(model)
n_params = get_n_params_(model)
if args.model_name == 'nerf':
dummy_input = torch.randn(1, input_ch + input_ch_views).to(device)
n_flops = get_n_flops_(model, input=dummy_input, count_adds=False) * (
args.N_samples + args.N_samples + args.N_importance)
elif args.model_name in ['nerf_v3.2', 'R2L', 'DeLFT']:
dummy_input = torch.randn(1, model.input_dim).to(device)
n_flops = get_n_flops_(model, input=dummy_input, count_adds=False)
print(
f'Model complexity per pixel: FLOPs {n_flops/1e6:.10f}M, Params {n_params/1e6:.10f}M'
)
return render_kwargs_train, render_kwargs_test, history, grad_vars, optimizer
def raw2outputs(raw,
z_vals,
rays_d,
raw_noise_std=0,
white_bkgd=False,
pytest=False,
verbose=False):
"""Transforms model's predictions to semantically meaningful values.
Args:
raw: [num_rays, num_samples along ray, 4]. Prediction from model.
z_vals: [num_rays, num_samples along ray]. Integration time.
rays_d: [num_rays, 3]. Direction of each ray.
Returns:
rgb_map: [num_rays, 3]. Estimated RGB color of a ray.
disp_map: [num_rays]. Disparity map. Inverse of depth map.
acc_map: [num_rays]. Sum of weights along each ray.
weights: [num_rays, num_samples]. Weights assigned to each sampled color.
depth_map: [num_rays]. Estimated distance to object.
"""
raw2alpha = lambda raw, dists, act_fn=F.relu: 1. - torch.exp(
-act_fn(raw) * dists) # @mst: opacity
dists = z_vals[..., 1:] - z_vals[..., :-1] # dists for 'distances'
dists = torch.cat(
[dists, to_tensor([1e10]).expand(dists[..., :1].shape)],
-1) # [N_rays, N_samples]
# @mst: 1e10 for infinite distance
dists = dists * torch.norm(rays_d[..., None, :], dim=-1)
rgb = torch.sigmoid(
raw[..., :3]) # [N_rays, N_samples, 3], RGB for each sampled point
noise = 0.
if raw_noise_std > 0.:
noise = torch.randn(raw[..., 3].shape).to(device) * 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 = to_tensor(noise)
alpha = raw2alpha(raw[..., 3] + noise, dists) # [N_rays, N_samples]
# print to check alpha
if verbose and global_step % args.i_print == 0:
for i_ray in range(0, alpha.shape[0], 100):
logtmp = ['%.4f' % x for x in alpha[i_ray]]
netprint('%4d: ' % i_ray + ' '.join(logtmp))
# weights = alpha * tf.math.cumprod(1.-alpha + 1e-10, -1, exclusive=True)
weights = alpha * torch.cumprod(
torch.cat(
[torch.ones((alpha.shape[0], 1)).to(device), 1. - alpha + 1e-10],
-1), -1)[:, :-1] # @mst: [N_rays, N_samples]
rgb_map = torch.sum(weights[..., None] * rgb, -2) # [N_rays, 3]
depth_map = torch.sum(weights * z_vals, -1)
disp_map = 1. / torch.max(1e-10 * torch.ones_like(depth_map).to(device),
depth_map / torch.sum(weights, -1))
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
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):
"""Volumetric rendering.
Args:
for sampling along a ray, including: ray origin, ray direction, min
dist, max dist, and unit-magnitude viewing direction.
network_fn: function. Model for predicting RGB and density at each point
in space.
network_query_fn: function used for passing queries to network_fn.
N_samples: int. Number of different times to sample along each ray.
retraw: bool. If True, include model's raw, unprocessed predictions.
lindisp: bool. If True, sample linearly in inverse depth rather than in depth.
perturb: float, 0 or 1. If non-zero, each ray is sampled at stratified
random points in time.
N_importance: int. Number of additional times to sample along each ray.
These samples are only passed to network_fine.
network_fine: "fine" network with same spec as network_fn.
white_bkgd: bool. If True, assume a white background.
raw_noise_std: ...
verbose: bool. If True, print more debugging info.
Returns:
rgb_map: [num_rays, 3]. Estimated RGB color of a ray. Comes from fine model.
disp_map: [num_rays]. Disparity map. 1 / depth.
acc_map: [num_rays]. Accumulated opacity along each ray. Comes from fine model.
raw: [num_rays, num_samples, 4]. Raw predictions from model.
rgb0: See rgb_map. Output for coarse model.
disp0: See disp_map. Output for coarse model.
acc0: See acc_map. Output for coarse model.
z_std: [num_rays]. Standard deviation of distances along ray for each
sample.
"""
N_rays = ray_batch.shape[
0] # N_rays = 32768 (1024*32) for test, 1024 for train
# @mst: ray_batch.shape, train: [1024, 11]
rays_o, rays_d = ray_batch[:, 0:
3], ray_batch[:, 3:
6] # [N_rays, 3] each, o for 'origin', d for 'direction'
viewdirs = ray_batch[:, -3:] if ray_batch.shape[-1] > 8 else None
bounds = torch.reshape(ray_batch[..., 6:8], [-1, 1, 2])
near, far = bounds[..., 0], bounds[..., 1] # @mst: near=2, far=6, in batch
t_vals = torch.linspace(0., 1., steps=N_samples).to(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))
z_vals = z_vals.expand([N_rays, N_samples])
# @mst: perturbation of depth z, with each depth value at the middle point
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(z_vals.shape).to(device) # uniform dist [0, 1)
# 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 = to_tensor(t_rand)
z_vals = lower + (upper - lower) * t_rand
pts = rays_o[..., None, :] + rays_d[..., None, :] * z_vals[
..., :, None] # [N_rays, N_samples, 3]
# when training: [1024, 1, 3] + [1024, 1, 3] * [1024, 64, 1]
# rays_d range: [-1, 1]
# raw = run_network(pts)
raw = network_query_fn(pts, viewdirs, network_fn)
rgb_map, disp_map, acc_map, weights, depth_map = raw2outputs(
raw,
z_vals,
rays_d,
raw_noise_std,
white_bkgd,
pytest=pytest,
verbose=verbose)
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.cpu(),
weights[..., 1:-1].cpu(),
N_importance,
det=(perturb == 0.),
pytest=pytest)
z_samples = z_samples.detach().to(device)
z_vals, _ = torch.sort(
torch.cat([z_vals, z_samples], -1),
-1) # @mst: sort to merge the fine samples with the coarse samples
pts = rays_o[..., None, :] + rays_d[..., None, :] * z_vals[
..., :, None] # [N_rays, N_samples + N_importance, 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_map, disp_map, acc_map, weights, depth_map = raw2outputs(
raw, z_vals, rays_d, raw_noise_std, white_bkgd, pytest=pytest)
ret = {'rgb_map': rgb_map, 'disp_map': disp_map, 'acc_map': acc_map}
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(f"! [Numerical Error] {k} contains nan or inf.")
return ret
def InfiniteSampler(n):
order = np.random.permutation(n)
i = 0
while True:
yield order[i]
i += 1
if i == n:
order = np.random.permutation(n)
i = 0
from torch.utils import data
class InfiniteSamplerWrapper(data.sampler.Sampler):
def __init__(self, num_samples):
self.num_samples = num_samples
def __iter__(self):
return iter(InfiniteSampler(self.num_samples))
def __len__(self):
return 2**31
def get_dataloader(dataset_type, datadir, pseudo_ratio=0.5):
if dataset_type in ['blender', 'llff']:
if args.data_mode in ['images']:
trainset = BlenderDataset(datadir, pseudo_ratio)
trainloader = torch.utils.data.DataLoader(
dataset=trainset,
batch_size=1,
num_workers=args.num_workers,
pin_memory=True,
sampler=InfiniteSamplerWrapper(len(trainset)))
elif args.data_mode in ['rays']:
if args.model_name in ['DeLFT']:
trainset = BlenderDataset_v2(
datadir,
dim_dir=3,
dim_rgb=1,
hold_ratio=args.pseudo_data_hold_ratio,
pseudo_ratio=args.pseudo_ratio)
trainloader = torch.utils.data.DataLoader(
dataset=trainset,
batch_size=args.N_rand,
num_workers=args.num_workers,
pin_memory=True,
sampler=InfiniteSamplerWrapper(len(trainset)))
else:
trainset = BlenderDataset_v2(
datadir,
dim_dir=3,
dim_rgb=3,
hold_ratio=args.pseudo_data_hold_ratio,
pseudo_ratio=args.pseudo_ratio)
trainloader = torch.utils.data.DataLoader(
dataset=trainset,
batch_size=args.N_rand,
num_workers=args.num_workers,
pin_memory=True,
sampler=InfiniteSamplerWrapper(len(trainset)))
return iter(trainloader), len(trainset)
def get_pseudo_ratio(schedule, current_step):
'''example of schedule: 1:0.2,500000:0.9'''
steps, prs = [], []
for item in schedule.split(','):
step, pr = item.split(':')
step, pr = int(step), float(pr)
steps += [step]
prs += [pr]
# linear scheduling
if current_step < steps[0]:
pr = prs[0]
elif current_step > steps[1]:
pr = prs[1]
else:
pr = (prs[1] - prs[0]) / (steps[1] - steps[0]) * (current_step -
steps[0]) + prs[0]
return pr
def save_onnx(model, onnx_path, dummy_input):
model = copy.deepcopy(model)
if hasattr(model, 'module'):
model = model.module
torch.onnx.export(model.cpu(),
dummy_input.cpu(),
onnx_path,
verbose=True,
export_params=True,
opset_version=11,
do_constant_folding=True,
keep_initializers_as_inputs=False,
input_names=['input'],
output_names=['output'],
dynamic_axes={
'input': {
0: 'batch_size'
},
'output': {
0: 'batch_size'
}
})
del model
#TODO-@mst: move these utility functions to a better place
def check_onnx(model, onnx_path, dummy_input):
r"""Refer to https://pytorch.org/tutorials/advanced/super_resolution_with_onnxruntime.html
"""
import onnx, onnxruntime
model = copy.deepcopy(model)
if hasattr(model, 'module'):
model = model.module
model, dummy_input = model.cpu(), dummy_input.cpu()
torch_out = model(dummy_input)
onnx_model = onnx.load(onnx_path)
onnx.checker.check_model(onnx_model)
ort_session = onnxruntime.InferenceSession(onnx_path)
def to_numpy(tensor):
return tensor.detach().cpu().numpy(
) if tensor.requires_grad else tensor.cpu().numpy()
# compute ONNX Runtime output prediction
ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(dummy_input)}
ort_outs = ort_session.run(None, ort_inputs)
# compare ONNX Runtime and PyTorch results
np.testing.assert_allclose(to_numpy(torch_out),
ort_outs[0],
rtol=1e-03,
atol=1e-05)
print(
"Exported model has been tested with ONNXRuntime, and the result looks good!"
)
def train():
# Load data
if args.dataset_type == 'llff':
images, poses, bds, render_poses, i_test = load_llff_data(
args.datadir,
args.factor,
recenter=True,
bd_factor=.75,
spherify=args.spherify,
n_pose_video=args.n_pose_video)
hwf = poses[0, :3, -1]
poses = poses[:, :3, :4]
print('Loaded llff', images.shape, render_poses.shape, hwf,
args.datadir)
if args.llffhold > 0:
print('Auto LLFF holdout,', args.llffhold)
i_test = np.arange(images.shape[0])[::args.llffhold]
i_val = i_test
i_train = np.array([
i for i in np.arange(int(images.shape[0]))
if (i not in i_test and i not in i_val)
])
print('DEFINING BOUNDS')
if args.no_ndc:
near = np.ndarray.min(bds) * .9
far = np.ndarray.max(bds) * 1.
else:
near = 0.
far = 1.
print('NEAR FAR', near, far)
elif args.dataset_type == 'blender':
if args.train_depth:
images, poses, render_poses, hwf, i_split = load_blender_data(
args.datadir, args.half_res, args.testskip, depth=True)
else:
images, poses, render_poses, hwf, i_split = load_blender_data(
args.datadir, args.half_res, args.testskip)
print('Loaded blender', images.shape, poses.shape, render_poses.shape,
hwf, args.datadir)
# Loaded blender (138, 400, 400, 4) (138, 4, 4) torch.Size([40, 4, 4]) [400, 400, 555.5555155968841] ./data/nerf_synthetic/lego
i_train, i_val, i_test = i_split
near = 2.
far = 6.
if args.white_bkgd:
images = images[..., :3] * images[..., -1:] + (1. -
images[..., -1:])
else:
images = images[..., :3]
elif args.dataset_type == 'deepvoxels':
images, poses, render_poses, hwf, i_split = load_dv_data(
scene=args.shape, basedir=args.datadir, testskip=args.testskip)
print('Loaded deepvoxels', images.shape, render_poses.shape, hwf,
args.datadir)
i_train, i_val, i_test = i_split
hemi_R = np.mean(np.linalg.norm(poses[:, :3, -1], axis=-1))
near = hemi_R - 1.
far = hemi_R + 1.
else:
print('Unknown dataset type', args.dataset_type, 'exiting')
return
# @mst
if hasattr(args, 'trial') and args.trial.near > 0:
assert args.trial.far > args.trial.near
near, far = args.trial.near, args.trial.far
print(f'Use provided near ({near}) and far {far}')