-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_nerf_fusion.py
1825 lines (1501 loc) · 71.3 KB
/
train_nerf_fusion.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
from diffusion_utils.pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline
from pathlib import Path
from PIL import Image
from numpy.linalg import inv, norm
from PIL import ImageDraw
import cv2
import os
import numpy as np
import random
import math
import time
import torch
import torch.nn.functional as F
from torch.distributions import Categorical
from tqdm import tqdm, trange
from nerf_utils.run_nerf_helpers import *
from nerf_utils.radam import RAdam
from nerf_utils.loss import sigma_sparsity_loss, total_variation_loss
from nerf_utils.load_data import load_data
from scipy.spatial.transform import Rotation as R
from scipy.spatial.transform import Slerp
torch.set_default_tensor_type('torch.cuda.FloatTensor')
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# ---------------------------------- #
# --------- nerf functions --------- #
# ---------------------------------- #
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]])
embedded, keep_mask = embed_fn(inputs_flat)
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_flat[~keep_mask, -1] = 0 # set sigma to 0 for invalid points
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)
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, K, 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, K, 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, K, c2w_staticcam)
viewdirs = viewdirs / torch.norm(viewdirs, dim=-1, keepdim=True)
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, K[0][0], 1., rays_o, rays_d)
# Create ray batch
rays_o = torch.reshape(rays_o, [-1,3]).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:
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', 'depth_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_train(render_poses, hwf, K, chunk, render_kwargs, gt_imgs=None, savedir=None):
H, W, focal = hwf
near, far = render_kwargs['near'], render_kwargs['far']
rgbs = []
depths = []
rgb, depth, acc, _ = render(H, W, K, chunk=chunk, c2w=render_poses, **render_kwargs)
rgbs.append(rgb)
# normalize depth to [0,1]
depth = (depth - near) / (far - near)
depths.append(depth)
return rgbs, depths
def create_nerf(args):
"""Instantiate NeRF's MLP model.
"""
embed_fn, input_ch = get_embedder(args.multires, args, i=args.i_embed)
if args.i_embed==1:
# hashed embedding table
embedding_params = list(embed_fn.parameters())
input_ch_views = 0
embeddirs_fn = None
if args.use_viewdirs:
# if using hashed for xyz, use SH for views
embeddirs_fn, input_ch_views = get_embedder(args.multires_views, args, i=args.i_embed_views)
output_ch = 5 if args.N_importance > 0 else 4
skips = [4]
if args.i_embed==1:
model = NeRFSmall(num_layers=2,
hidden_dim=64,
geo_feat_dim=15,
num_layers_color=3,
hidden_dim_color=64,
input_ch=input_ch, input_ch_views=input_ch_views).to(device)
else:
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())
model_fine = None
if args.N_importance > 0:
if args.i_embed==1:
model_fine = NeRFSmall(num_layers=2,
hidden_dim=64,
geo_feat_dim=15,
num_layers_color=3,
hidden_dim_color=64,
input_ch=input_ch, input_ch_views=input_ch_views).to(device)
else:
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)
# Create optimizer
if args.i_embed==1:
optimizer = RAdam([
{'params': grad_vars, 'weight_decay': 1e-6},
{'params': embedding_params, 'eps': 1e-15}
], lr=args.lrate, betas=(0.9, 0.99))
else:
optimizer = torch.optim.Adam(params=grad_vars, lr=args.lrate, betas=(0.9, 0.999))
steps_kwargs = {
'start' : 0,
}
basedir = args.basedir
expname = args.expname
filler = '@'
to_expname_name_list = ['', '',
'box-',
'l', 'h',
]
to_expname_var_list = [str(args.prompt).replace(' ', '-'), str(os.path.basename(args.finetuned_model_path)),
str(args.box_name),
str(args.strength_lower_bound).zfill(3), str(args.strength_higher_bound).zfill(3),
]
for (namee, varr) in zip(to_expname_name_list, to_expname_var_list):
expname = expname + filler + namee + varr
##########################
# Load checkpoints
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]
for ckpttt in ckpts:
if ((args.ckpt_epoch_to_load).zfill(6) + '.tar') in ckpttt:
ckpt_path = ckpttt
print('Reloading from', ckpt_path)
ckpt = torch.load(ckpt_path)
steps_kwargs['start'] = ckpt['global_step']
optimizer.load_state_dict(ckpt['optimizer_state_dict'])
# Load model
model.load_state_dict(ckpt['network_fn_state_dict'])
if model_fine is not None:
model_fine.load_state_dict(ckpt['network_fine_state_dict'])
if args.i_embed==1:
embed_fn.load_state_dict(ckpt['embed_fn_state_dict'])
##########################
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,
'embed_fn': embed_fn,
'use_viewdirs' : args.use_viewdirs,
'raw_noise_std' : args.raw_noise_std,
}
render_kwargs_train['ndc'] = False
return render_kwargs_train, steps_kwargs, grad_vars, optimizer
def raw2outputs(raw, z_vals, rays_d, raw_noise_std=0, white_bkgd=False, pytest=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)
dists = z_vals[...,1:] - z_vals[...,:-1]
dists = torch.cat([dists, torch.Tensor([1e10]).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(raw[...,3].shape) * 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)
# sigma_loss = sigma_sparsity_loss(raw[...,3])
alpha = raw2alpha(raw[...,3] + noise, dists) # [N_rays, N_samples]
# weights = alpha * tf.math.cumprod(1.-alpha + 1e-10, -1, exclusive=True)
weights = alpha * torch.cumprod(torch.cat([torch.ones((alpha.shape[0], 1)), 1.-alpha + 1e-10], -1), -1)[:, :-1]
rgb_map = torch.sum(weights[...,None] * rgb, -2) # [N_rays, 3]
depth_map = torch.sum(weights * z_vals, -1) / torch.sum(weights, -1)
disp_map = 1./torch.max(1e-10 * torch.ones_like(depth_map), depth_map)
acc_map = torch.sum(weights, -1)
if white_bkgd:
rgb_map = rgb_map + (1.-acc_map[...,None])
# Calculate weights sparsity loss
entropy = Categorical(probs = torch.cat([weights, 1.0-weights.sum(-1, keepdim=True)+1e-4], dim=-1)).entropy()
sparsity_loss = entropy
return rgb_map, disp_map, acc_map, weights, depth_map, sparsity_loss
def render_rays(ray_batch,
network_fn,
network_query_fn,
N_samples,
embed_fn=None,
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:
ray_batch: array of shape [batch_size, ...]. All information necessary
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]
rays_o, rays_d = ray_batch[:,0:3], ray_batch[:,3:6] # [N_rays, 3] each
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] # [-1,1]
t_vals = torch.linspace(0., 1., steps=N_samples)
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])
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)
# 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 = rays_o[...,None,:] + rays_d[...,None,:] * z_vals[...,:,None] # [N_rays, N_samples, 3]
raw = network_query_fn(pts, viewdirs, network_fn)
rgb_map, disp_map, acc_map, weights, depth_map, sparsity_loss = raw2outputs(raw, z_vals, rays_d, raw_noise_std, white_bkgd, pytest=pytest)
if N_importance > 0:
rgb_map_0, depth_map_0, acc_map_0, sparsity_loss_0 = rgb_map, depth_map, acc_map, sparsity_loss
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 = 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, sparsity_loss = raw2outputs(raw, z_vals, rays_d, raw_noise_std, white_bkgd, pytest=pytest)
ret = {'rgb_map' : rgb_map, 'depth_map' : depth_map, 'acc_map' : acc_map, 'sparsity_loss': sparsity_loss}
ret['weights'] = weights
if retraw:
ret['raw'] = raw
if N_importance > 0:
ret['rgb0'] = rgb_map_0
ret['depth0'] = depth_map_0
ret['acc0'] = acc_map_0
ret['sparsity_loss0'] = sparsity_loss_0
ret['z_std'] = torch.std(z_samples, dim=-1, unbiased=False) # [N_rays]
return ret
# -------------------------------------------- #
# --------- all customizable configs --------- #
# -------------------------------------------- #
def config_parser():
import configargparse
parser = configargparse.ArgumentParser()
### ~~~ nerf config ~~~ ###
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='dataset/background/default',
help='input data directory')
# training options
parser.add_argument("--netdepth", type=int, default=8,
help='layers in network')
parser.add_argument("--netwidth", type=int, default=256,
help='channels per layer')
parser.add_argument("--netdepth_fine", type=int, default=8,
help='layers in fine network')
parser.add_argument("--netwidth_fine", type=int, default=256,
help='channels per layer in fine network')
parser.add_argument("--N_rand", type=int, default=32*32*4*2,
help='batch size of first stage nerf (number of random rays per gradient step)')
parser.add_argument("--N_rand_mask", type=int, default=32*32*4*2,
help='batch size of masked area (number of random rays per gradient step)')
parser.add_argument("--N_rand_unmask", type=int, default=32*32*4*2,
help='batch size of unmasked area (number of random rays per gradient step)')
parser.add_argument("--lrate", type=float, default=5e-4,
help='learning rate of background nerf training stage')
parser.add_argument("--lrate_decay", type=int, default=250,
help='exponential learning rate decay (in 1000 steps)')
parser.add_argument("--lrate_fusion", type=float, default=5e-4,
help='learning rate of object fusion stage')
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')
# 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("--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=1,
help='set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical')
parser.add_argument("--i_embed_views", type=int, default=2,
help='set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical')
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=0.,
help='std dev of noise added to regularize sigma_a output, 1e0 recommended')
parser.add_argument("--render_image", action='store_true',
help='do not optimize, reload weights and render out render_poses path')
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(
"--ckpt_epoch_to_load",
type=str,
default='0',
help="which saved NeRF model to load, identified by epoch #.",
)
# training options
parser.add_argument("--precrop_iters", type=int, default=0,
help='number of steps to train on central crops')
parser.add_argument("--precrop_frac", type=float,
default=.5, help='fraction of img taken for central crops')
parser.add_argument("--finest_res", type=int, default=512,
help='finest resolultion for hashed embedding')
parser.add_argument("--log2_hashmap_size", type=int, default=19,
help='log2 of hashmap size')
parser.add_argument("--sparse-loss-weight", type=float, default=1e-10,
help='learning rate')
parser.add_argument("--tv-loss-weight", type=float, default=1e-6,
help='learning rate')
# logging/saving options
parser.add_argument("--i_print", type=int, default=100,
help='every # of iters, print training info to screen.')
parser.add_argument("--i_weights", type=int, default=5000,
help='every # of iters, save the NeRF model.')
parser.add_argument("--i_trainset", type=int, default=5000,
help='every # of iters, render ALL training views from NeRF and updating dataset.')
parser.add_argument("--i_visualization", type=int, default=100,
help='every # of iters, visualize ONLY the near views in the updating dataset.')
### ~~~ diffusion model and pose condition config ~~~ ###
parser.add_argument("--finetuned_model_path", type=str, default='dream_outputs/default',
help='fine-tuned diffusion model to load')
parser.add_argument(
"--pivot_name",
type=str,
nargs="?",
default="default.jpg",
help="pivot file name, it is the first view to train for object fusion."
)
parser.add_argument(
"--prompt",
type=str,
nargs="?",
default="",
help="Diffusion model text prompt, used to produce images."
)
parser.add_argument(
"--strength_lower_bound",
type=int,
default=35,
help="Diffusion model noise strength lower bound, used in training. Should range from 0 to 100.",
)
parser.add_argument(
"--strength_higher_bound",
type=int,
default=35,
help="Diffusion model noise strength higher bound, used in training. Should range from 0 to 100.",
)
parser.add_argument(
"--strength_test",
type=int,
default=35,
help="Diffusion model noise strength, used in testing. Should range from 0 to 100.",
)
parser.add_argument(
"--test_num_inference_steps",
type=int,
default=50,
help="Diffusion model inference steps, used in testing.",
)
parser.add_argument(
"--initial_iter",
type=int,
default=20000,
help="# of iters to train on background before object fusion",
)
parser.add_argument(
"--operation_iter",
type=int,
default=10,
help="every # of iters, perform once the periodic dataset update for object fusion",
)
parser.add_argument(
"--new_far_image_iters",
type=int,
default=500,
help="every # of iters, perform once the pose-conditioned dataset update for object fusion "
"(to include new near images)",
)
parser.add_argument(
"--extra_train_on_pivot_iter",
type=int,
default=500,
help="# of extra iters to train on the pivot only when object fusion starts",
)
parser.add_argument(
"--num_Neighbors",
type=int,
default=2,
help="# of new views to be included in pose-conditioned dataset updates",
)
parser.add_argument(
"--box_name",
type=str,
default='default',
help="which bounding box to use",
)
parser.add_argument("--no_vis_box", action='store_true',
help='do not visualize bounding box to save time')
# for rendering videos
parser.add_argument("--render_video", action='store_true',
help='to render video results (test only, no training)')
parser.add_argument(
"--num_Gaps",
type=int,
default=10,
help="# of novel views to render between two images, for video rendering only",
)
parser.add_argument("--video_expname", type=str, default='default',
help='folder name to store the output images, lazy implementation')
parser.add_argument("--video_frames", nargs='+',
help='a list of views of interest where a smooth trajectory renders through'
'note: the trajectory will complete a loop at the end (last view to first view)')
parser.add_argument("--strength_video",
type=int,
default=35,
help="Diffusion model noise strength, used in video rendering. Should range from 0 to 100.",
)
### ~~~ other config ~~~ ###
# for background data rendering boundary: near and far
parser.add_argument(
"--data_near",
type=float,
default=0.1,
help="background data, the nearest distance to render",
)
parser.add_argument(
"--data_far",
type=float,
default=10.0,
help="background data, the farthest distance to render",
)
parser.add_argument(
"--seed",
type=int,
default=0,
help="seed everything (for reproducible sampling)",
)
return parser
def train():
parser = config_parser()
args = parser.parse_args()
# ---------------------------------------- #
# --------- load diffusion model --------- #
# ---------------------------------------- #
model_path = Path(args.finetuned_model_path)
pipe = StableDiffusionInpaintPipeline.from_pretrained(model_path, local_files_only=False)
print('loaded fine-tuned diffusion model from {} !'.format(model_path))
# ---------------------------------------------- #
# --------- load image and camera data --------- #
# ---------------------------------------------- #
import paddle
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
paddle.seed(args.seed)
setup_seed(args.seed)
K = None
images, masks, poses, pivot_id, render_poses, hwf, i_train, bounding_box, fnames_out = load_data(args.datadir, args.pivot_name)
args.bounding_box = bounding_box
print('Number of Images Loaded: {} from {} !'.format(images.shape[0], args.datadir))
print('TRAIN views are', i_train)
print('pivot_id is: {} of image {} !'.format(pivot_id, fnames_out[pivot_id]))
near = args.data_near
far = args.data_far
images = images[...,:3]
# Cast intrinsics to right types
H, W, focal = hwf
H, W = int(H), int(W)
hwf = [H, W, focal]
if K is None:
K = np.array([
[focal, 0, 0.5*W],
[0, focal, 0.5*H],
[0, 0, 1]
])
# --------------------------------------------- #
# --------- save commands to txt file --------- #
# --------------------------------------------- #
# Create log dir and copy the config file
basedir = args.basedir
expname = args.expname
filler = '@'
to_expname_name_list = ['', '',
'box-',
'l', 'h',
]
to_expname_var_list = [str(args.prompt).replace(' ', '-'), str(os.path.basename(args.finetuned_model_path)),
str(args.box_name),
str(args.strength_lower_bound).zfill(3), str(args.strength_higher_bound).zfill(3),
]
for (namee, varr) in zip(to_expname_name_list, to_expname_var_list):
expname = expname + filler + namee + varr
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())
# ----------------------------------- #
# --------- load nerf model --------- #
# ----------------------------------- #
render_kwargs_train, steps_kwargs, grad_vars, optimizer = create_nerf(args)
start = steps_kwargs['start']
global_step = start
bds_dict = {
'near' : near,
'far' : far,
}
render_kwargs_train.update(bds_dict)
# Prepare raybatch tensor if batching random rays
N_rand = args.N_rand
# Move training data to GPU
poses = torch.Tensor(poses).to(device)
# ------------------------------------------------------------- #
# --------- construct a bounding box and visualize it --------- #
# Sorry for the lazy implementation.
# It lacks a convenient UI or automatic way to construct a box.
# Current approach is like:
# - determine a rectangle (adjust a point and two orthogonal vectors)
# - then determine a cube (adjust rectangle surface normal)
# ------------------------------------------------------------- #
# default bounding box
if args.box_name == 'default':
# you may rotate the points as [x, y, z]
# the points are initialized around the center of the scene
# rotate negative-positive the x:y:z axis = lie down right-left : lie down far-come : self-rotate right-left
p0 = np.array([0.0, 0.0, 0.0])
p1 = np.array([1.0, 0.0, 0.0])
p2 = np.array([1.0, 2.0, 0.0])
# adjust rectangle (length and width)
direct_01 = p1 - p0
direct_02 = p2 - p1
p0 = p0 + 0. * direct_01
p1 = p1 + 0. * direct_01
p2 = p2 + 0. * direct_01
p0 = p0 + 0. * direct_02
p1 = p1 + 0. * direct_02
p2 = p2 + 0. * direct_02
# adjust cube (height)
norm_h = 0.5
norm_vec = np.cross(p1-p0, p2-p0)
normalze_val = norm(norm_vec)
if normalze_val == 0:
raise Exception
norm_vec = norm_vec/normalze_val
norm_vec = norm_vec * norm_h
p0 = p0 + 0. * norm_vec
p1 = p1 + 0. * norm_vec
p2 = p2 + 0. * norm_vec
elif args.box_name == 'wooden_table_01':
p0 = np.array([1.0, -0.75, 0.0])
p1 = np.array([0.5, -0.75, 0.75])
p2 = np.array([0.5, 0.75, 0.75])
direct_01 = p1 - p0
direct_02 = p2 - p1
p0 = p0 - 0.2 * direct_01
p1 = p1 + 0.2 * direct_01
p2 = p2 + 0.2 * direct_01
p0 = p0 - 0.2 * direct_02
p1 = p1 - 0.2 * direct_02
p2 = p2 + 0.2 * direct_02
norm_h = 0.5
norm_vec = np.cross(p1 - p0, p2 - p0)
normalze_val = norm(norm_vec)
if normalze_val == 0:
raise Exception
norm_vec = norm_vec / normalze_val
norm_vec = norm_vec * norm_h
elif args.box_name == 'wooden_table_02':
p0 = np.array([1.0, -0.75, 0.0])
p1 = np.array([0.5, -0.75, 0.75])
p2 = np.array([0.5, 0.75, 0.75])
direct_01 = p1 - p0
direct_02 = p2 - p1
p0 = p0 - 0.15 * direct_01
p1 = p1 + 0.05 * direct_01
p2 = p2 + 0.05 * direct_01
p0 = p0 - 0.1 * direct_02
p1 = p1 - 0.1 * direct_02
p2 = p2 + 0.05 * direct_02
norm_h = 0.4
norm_vec = np.cross(p1-p0, p2-p0)
normalze_val = norm(norm_vec)
if normalze_val == 0:
raise Exception
norm_vec = norm_vec/normalze_val
norm_vec = norm_vec * norm_h
p0 = p0 - 0.7 * norm_vec
p1 = p1 - 0.7 * norm_vec
p2 = p2 - 0.7 * norm_vec
elif args.box_name == 'wooden_table_03':
p0 = np.array([1.0, -0.75, 0.0])
p1 = np.array([0.5, -0.75, 0.75])
p2 = np.array([0.5, 0.75, 0.75])
direct_01 = p1 - p0
direct_02 = p2 - p1
p0 = p0 - 0.3 * direct_01
p1 = p1 + 0.2 * direct_01
p2 = p2 + 0.2 * direct_01
p0 = p0 - 0.2 * direct_02
p1 = p1 - 0.2 * direct_02
p2 = p2 + 0.2 * direct_02
norm_h = 0.5
norm_vec = np.cross(p1-p0, p2-p0)
normalze_val = norm(norm_vec)
if normalze_val == 0:
raise Exception
norm_vec = norm_vec/normalze_val
norm_vec = norm_vec * norm_h
p0 = p0 - 0.7 * norm_vec
p1 = p1 - 0.7 * norm_vec
p2 = p2 - 0.7 * norm_vec
elif args.box_name == 'black_table_01':
# rot degree : 0 : 38 : -12
p0 = np.array([0.0, 0.0, 0.0])
p1 = np.array([0.77, -0.21, -0.60])
p2 = np.array([1.08, 1.30, -0.62])
translation = np.array([-0.3, -0.5, -0.3])
p0 = p0 + translation
p1 = p1 + translation
p2 = p2 + translation
direct_01 = p1 - p0
direct_02 = p2 - p1
p0 = p0 + -.4 * direct_01
p1 = p1 + -.4 * direct_01
p2 = p2 + -.4 * direct_01
p0 = p0 + -.1 * direct_01
p1 = p1 + .3 * direct_01
p2 = p2 + .3 * direct_01
p0 = p0 + -.0 * direct_02
p1 = p1 + -.0 * direct_02
p2 = p2 + -.0 * direct_02
p0 = p0 + -.0 * direct_02
p1 = p1 + -.0 * direct_02
p2 = p2 + .2 * direct_02
norm_h = 0.4
norm_vec = np.cross(p1 - p0, p2 - p0)
normalze_val = norm(norm_vec)
if normalze_val == 0:
raise Exception
norm_vec = norm_vec / normalze_val
norm_vec = norm_vec * norm_h
p0 = p0 + .0 * norm_vec
p1 = p1 + .0 * norm_vec
p2 = p2 + .0 * norm_vec
elif args.box_name == 'black_table_02':
# rot degree : 0 : 38 : -12
p0 = np.array([0.0, 0.0, 0.0])
p1 = np.array([0.77, -0.21, -0.60])
p2 = np.array([1.08, 1.30, -0.62])
translation = np.array([-0.3, -0.5, -0.3])
p0 = p0 + translation
p1 = p1 + translation
p2 = p2 + translation
direct_01 = p1 - p0
direct_02 = p2 - p1
p0 = p0 + -.0 * direct_01
p1 = p1 + -.0 * direct_01
p2 = p2 + -.0 * direct_01
p0 = p0 + -.1 * direct_01
p1 = p1 + .3 * direct_01
p2 = p2 + .3 * direct_01
p0 = p0 + -.0 * direct_02
p1 = p1 + -.0 * direct_02
p2 = p2 + -.0 * direct_02
p0 = p0 + -.0 * direct_02
p1 = p1 + -.0 * direct_02
p2 = p2 + .2 * direct_02
norm_h = 0.4
norm_vec = np.cross(p1 - p0, p2 - p0)
normalze_val = norm(norm_vec)
if normalze_val == 0:
raise Exception
norm_vec = norm_vec / normalze_val
norm_vec = norm_vec * norm_h
p0 = p0 + .0 * norm_vec
p1 = p1 + .0 * norm_vec
p2 = p2 + .0 * norm_vec
elif args.box_name == 'sofa_01':
# rot degree : 2 : 40 : 15
p0 = np.array([0.0, 0.0, 0.0])
p1 = np.array([0.74,0.20,-0.64])
p2 = np.array([0.27,2.14,-0.59])
direct_01 = p1 - p0
direct_02 = p2 - p1
p0 = p0 + -0.3 * direct_01
p1 = p1 + 0.2 * direct_01
p2 = p2 + 0.2 * direct_01