-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmodel.py
More file actions
1706 lines (1387 loc) · 55.1 KB
/
model.py
File metadata and controls
1706 lines (1387 loc) · 55.1 KB
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 numpy as np
import torch.nn as nn
import torch
import torch.nn.functional as F
from scipy.spatial.transform import Rotation as Rot
from camera import (
get_rotation_matrix,
get_camera_mat,
get_random_pose,
uvr_to_pose
)
import torch.nn as nn
import torch.nn.functional as F
import torch
from common import (
arange_pixels, image_points_to_world, origin_to_world
)
import math
from op import FusedLeakyReLU, fused_leaky_relu, upfirdn2d, conv2d_gradfix
import random
############################### GIRAFFE ###############################
def from_euler(rval):
device = rval.device
angle = rval * 2 * np.pi
cos = torch.cos(angle).to(device)
sin = torch.sin(angle).to(device)
one = torch.ones_like(angle)
zero = torch.zeros_like(angle)
R_flat = (cos, -sin, zero, sin, cos, zero, zero, zero, one)
return torch.stack(R_flat, -1).reshape(angle.shape + (3, 3))
class BoundingBoxGenerator(nn.Module):
''' Bounding box generator class
Args:
n_boxes (int): number of bounding boxes (excluding background)
scale_range_min (list): min scale values for x, y, z
scale_range_max (list): max scale values for x, y, z
translation_range_min (list): min values for x, y, z translation
translation_range_max (list): max values for x, y, z translation
rotation_range (list): min and max rotation value (between 0 and 1)
fix_scale_ratio (bool): whether the x/y/z scale ratio should be fixed
'''
def __init__(
self,
device,
scale_range_min=[0.5, 0.5, 0.5],
scale_range_max=[0.5, 0.5, 0.5],
translation_range_min=[-0.75, -0.75, 0.],
translation_range_max=[0.75, 0.75, 0.],
rotation_range=[0., 1.],
fix_scale_ratio=True,
**kwargs
):
super().__init__()
self.n_boxes = 1
self.device = device
self.scale_min = torch.tensor(scale_range_min).reshape(1, 1, 3)
self.scale_range = (torch.tensor(scale_range_max) - torch.tensor(scale_range_min)).reshape(1, 1, 3)
self.translation_min = torch.tensor(translation_range_min).reshape(1, 1, 3)
self.translation_range = (torch.tensor(translation_range_max) - torch.tensor(translation_range_min)).reshape(1, 1, 3)
self.rotation_range = rotation_range
self.fix_scale_ratio = fix_scale_ratio
def get_random_offset(self, batch_size):
n_boxes = self.n_boxes
# Sample sizes
if self.fix_scale_ratio:
s_rand = torch.rand(batch_size, n_boxes, 1)
else:
s_rand = torch.rand(batch_size, n_boxes, 3)
s = self.scale_min + s_rand * self.scale_range
# Sample translations
t = self.translation_min + torch.rand(batch_size, n_boxes, 3) * self.translation_range
def r_val(): return self.rotation_range[0] + np.random.rand() * (
self.rotation_range[1] - self.rotation_range[0])
rval = torch.tensor([r_val() for _ in range(batch_size * self.n_boxes)]).float().view(-1, 1).to(self.device)
R = from_euler(rval)
return s, t, R, rval
def forward(self, batch_size, return_rval=False):
s, t, R, rval = self.get_random_offset(batch_size)
if return_rval:
return s, t, R, rval
return s, t, R
class Decoder(nn.Module):
''' Decoder class.
Predicts volume density and color from 3D location, viewing
direction, and latent code z.
Args:
hidden_size (int): hidden size of Decoder network
n_blocks (int): number of layers
n_blocks_view (int): number of view-dep layers
skips (list): where to add a skip connection
use_viewdirs: (bool): whether to use viewing directions
n_freq_posenc (int), max freq for positional encoding (3D location)
n_freq_posenc_views (int), max freq for positional encoding (
viewing direction)
z_dim (int): dimension of latent code z
rgb_out_dim (int): output dimension of feature / rgb prediction
final_sigmoid_activation (bool): whether to apply a sigmoid activation
to the feature / rgb output
downscale_by (float): downscale factor for input points before applying
the positional encoding
positional_encoding (str): type of positional encoding
gauss_dim_pos (int): dim for Gauss. positional encoding (position)
gauss_dim_view (int): dim for Gauss. positional encoding (
viewing direction)
gauss_std (int): std for Gauss. positional encoding
use_z_app (bool): whether use z_app/z_shape for feature
'''
def __init__(
self,
hidden_size=128,
n_blocks=8,
n_blocks_view=1,
skips=[4],
use_viewdirs=False,
n_freq_posenc=10,
n_freq_posenc_views=4,
z_dim=64,
rgb_out_dim=128,
final_sigmoid_activation=False,
downscale_p_by=2.,
positional_encoding='normal',
gauss_dim_pos=10,
gauss_dim_view=4,
gauss_std=4.,
use_z_app=False,
**kwargs
):
super().__init__()
self.n_freq_posenc = n_freq_posenc
self.n_freq_posenc_views = n_freq_posenc_views
self.downscale_p_by = downscale_p_by
self.z_dim = z_dim
self.n_blocks = n_blocks
self.use_viewdirs = use_viewdirs
self.use_z_app = use_z_app
assert(positional_encoding in ('normal', 'gauss'))
self.positional_encoding = positional_encoding
if positional_encoding == 'gauss':
np.random.seed(42)
# remove * 2 because of cos and sin
self.B_pos = gauss_std * \
torch.from_numpy(np.random.randn(
1, gauss_dim_pos * 3, 3)).float().cuda()
self.B_view = gauss_std * \
torch.from_numpy(np.random.randn(
1, gauss_dim_view * 3, 3)).float().cuda()
dim_embed = 3 * gauss_dim_pos * 2
dim_embed_view = 3 * gauss_dim_view * 2
else:
dim_embed = 3 * self.n_freq_posenc * 2
dim_embed_view = 3 * self.n_freq_posenc_views * 2
# Density Prediction Layers
self.dense_layers = DenseLayers(
z_dim, hidden_size, dim_embed, n_blocks, skips)
# Feature Prediction Layers
self.feat_layers = FeatLayers(
z_dim, hidden_size, dim_embed_view, rgb_out_dim, use_viewdirs, n_blocks_view, final_sigmoid_activation)
def transform_points(self, p, views=False):
# Positional encoding
# normalize p between [-1, 1]
p = p / self.downscale_p_by
# we consider points up to [-1, 1]
# so no scaling required here
if self.positional_encoding == 'gauss':
B = self.B_view if views else self.B_pos
p_transformed = (B @ (np.pi * p.permute(0, 2, 1))).permute(0, 2, 1)
p_transformed = torch.cat(
[torch.sin(p_transformed), torch.cos(p_transformed)], dim=-1)
else:
L = self.n_freq_posenc_views if views else self.n_freq_posenc
p_transformed = torch.cat([torch.cat(
[torch.sin((2 ** i) * np.pi * p),
torch.cos((2 ** i) * np.pi * p)],
dim=-1) for i in range(L)], dim=-1)
return p_transformed
def forward(self, p_in, ray_d=None, z_shape=None, z_app=None, **kwargs):
p = self.transform_points(p_in)
if self.use_viewdirs and ray_d is not None:
ray_d = ray_d / torch.norm(ray_d, dim=-1, keepdim=True)
ray_d = self.transform_points(ray_d, views=True)
sigma_out, net = self.dense_layers(p, z_shape)
if self.use_z_app:
feat_out = self.feat_layers(net, z_app, ray_d)
else:
feat_out = self.feat_layers(net, z_shape, ray_d)
return feat_out, sigma_out
class DenseLayers(nn.Module):
def __init__(self, z_dim, hidden_size, dim_embed, n_blocks, skips):
super().__init__()
self.skips = skips
self.fc_in = nn.Linear(dim_embed, hidden_size)
if z_dim > 0:
self.fc_z = nn.Linear(z_dim, hidden_size)
self.blocks = nn.ModuleList([
nn.Linear(hidden_size, hidden_size) for i in range(n_blocks - 1)
])
n_skips = sum([i in skips for i in range(n_blocks - 1)])
if n_skips > 0:
self.fc_z_skips = nn.ModuleList(
[nn.Linear(z_dim, hidden_size) for i in range(n_skips)]
)
self.fc_p_skips = nn.ModuleList([
nn.Linear(dim_embed, hidden_size) for i in range(n_skips)
])
self.sigma_out = nn.Linear(hidden_size, 1)
def forward(self, p, z):
net = self.fc_in(p)
net = net + self.fc_z(z).unsqueeze(1)
net = F.relu(net)
skip_idx = 0
for idx, layer in enumerate(self.blocks):
net = F.relu(layer(net))
if (idx + 1) in self.skips and (idx < len(self.blocks) - 1):
net = net + self.fc_z_skips[skip_idx](z).unsqueeze(1)
net = net + self.fc_p_skips[skip_idx](p)
skip_idx += 1
sigma_out = self.sigma_out(net).squeeze(-1)
return sigma_out, net
class FeatLayers(nn.Module):
def __init__(self, z_dim, hidden_size, dim_embed_view, rgb_out_dim, use_viewdirs, n_blocks_view, final_sigmoid_activation):
super().__init__()
self.final_sigmoid_activation = final_sigmoid_activation
self.use_viewdirs = use_viewdirs
self.n_blocks_view = n_blocks_view
self.fc_z_view = nn.Linear(z_dim, hidden_size)
self.feat_view = nn.Linear(hidden_size, hidden_size)
self.fc_view = nn.Linear(dim_embed_view, hidden_size)
self.feat_out = nn.Linear(hidden_size, rgb_out_dim)
if use_viewdirs and n_blocks_view > 1:
self.blocks_view = nn.ModuleList(
[nn.Linear(dim_embed_view + hidden_size, hidden_size)
for i in range(n_blocks_view - 1)])
def forward(self, net, z, ray_d):
net = self.feat_view(net)
net = net + self.fc_z_view(z).unsqueeze(1)
if self.use_viewdirs and ray_d is not None:
net = net + self.fc_view(ray_d)
net = F.relu(net)
if self.n_blocks_view > 1:
for layer in self.blocks_view:
net = F.relu(layer(net))
feat_out = self.feat_out(net)
if self.final_sigmoid_activation:
feat_out = torch.sigmoid(feat_out)
return feat_out
class GIRAFFEGenerator(nn.Module):
''' GIRAFFE Generator Class.
Args:
device (pytorch device): pytorch device
z_dim (int): dimension of latent code z
z_dim_bg (int): dimension of background latent code z_bg
resolution_vol (int): resolution of volume-rendered image
range_u (tuple): rotation range (0 - 1)
range_v (tuple): elevation range (0 - 1)
n_ray_samples (int): number of samples per ray
range_radius(tuple): radius range
depth_range (tuple): near and far depth plane
fov (float): field of view
bg_translation_range_min (list): min values for bg x, y, z translation
bg_translation_range_max (list): max values for bg x, y, z translation
bg_rotation_range (list): background rotation range (0 - 1)
use_max_composition (bool): whether to use the max
composition operator instead
pos_share (bool): whether enable position sharing
'''
def __init__(
self,
device,
z_dim=256,
z_dim_bg=128,
resolution_vol=16,
rgb_out_dim=3,
range_u=(0, 0),
range_v=(0.25, 0.25),
n_ray_samples=64,
range_radius=(2.732, 2.732),
depth_range=[0.5, 6.],
fov=49.13,
use_max_composition=False,
scale_range_min=[0.5, 0.5, 0.5],
scale_range_max=[0.5, 0.5, 0.5],
translation_range_min=[-0.75, -0.75, 0.],
translation_range_max=[0.75, 0.75, 0.],
rotation_range=[0, 1],
bg_translation_range_min=[-0.75, -0.75, 0.],
bg_translation_range_max=[0.75, 0.75, 0.],
bg_rotation_range=[0, 0],
pos_share=False,
use_viewdirs=False,
use_z_app=False,
**kwargs
):
super().__init__()
self.n_ray_samples = n_ray_samples
self.range_u = range_u
self.range_v = range_v
self.resolution_vol = resolution_vol
self.range_radius = range_radius
self.depth_range = depth_range
self.fov = fov
self.bg_rotation_range = bg_rotation_range
self.z_dim = z_dim
self.z_dim_bg = z_dim_bg
self.use_max_composition = use_max_composition
self.device = device
self.pos_share = pos_share
self.bg_translation_min = torch.tensor(
bg_translation_range_min).reshape(1, 3)
self.bg_translation_range = (torch.tensor(
bg_translation_range_max) - torch.tensor(bg_translation_range_min)
).reshape(1, 3)
self.camera_matrix = get_camera_mat(fov=fov)
self.decoder = Decoder(
z_dim=z_dim,
rgb_out_dim=rgb_out_dim,
use_viewdirs=use_viewdirs,
use_z_app=use_z_app
)
self.background_generator = Decoder(
z_dim=z_dim_bg,
hidden_size=64,
rgb_out_dim=rgb_out_dim,
n_blocks=4,
downscale_p_by=12,
skips=[],
use_viewdirs=use_viewdirs,
use_z_app=use_z_app
)
self.bounding_box_generator = BoundingBoxGenerator(
device=device,
z_dim=z_dim,
scale_range_max=scale_range_max,
scale_range_min=scale_range_min,
translation_range_max=translation_range_max,
translation_range_min=translation_range_min,
rotation_range=rotation_range,
)
def reform_representation(self, img_rep):
'''
compose latent_codes, camera_matrices, transformations out of representation list
representation list: [z_s_fg, z_a_fg, z_s_bg, z_a_bg, u, v, radius, s, t, rval]
'''
batch = img_rep[0].size(0)
device = img_rep[0].device
z_s_fg, z_a_fg, z_s_bg, z_a_bg, u, v, radius, s, t, rval = img_rep
R = from_euler(rval)
world_mat = uvr_to_pose((u, v, radius))
latent_codes = (
z_s_fg.unsqueeze(1), z_a_fg.unsqueeze(1), z_s_bg, z_a_bg)
camera_matrices = (
self.camera_matrix.repeat(batch, 1, 1).to(device), world_mat)
transformations = (s.unsqueeze(1), t.unsqueeze(1), R)
uvr = (u, v, radius)
return latent_codes, camera_matrices, transformations, uvr, rval
def img_representation(self, latent_codes, uvr, transformations, rval):
'''
transform latent_codes, transformations, uvr, rval into representation list
'''
device = latent_codes[0].device
z_s_fg, z_a_fg, z_s_bg, z_a_bg = latent_codes
s, t, _ = transformations
u, v, radius = uvr
if u.device != device:
u = u.to(device)
v = v.to(device)
radius = radius.to(device)
batch_size = z_s_fg.size(0)
return [r.view(batch_size, -1) for r in [
z_s_fg, z_a_fg, z_s_bg, z_a_bg, u, v, radius, s, t, rval]]
def get_latent_codes(self, batch_size, tmp=1.):
z_dim, z_dim_bg = self.z_dim, self.z_dim_bg
n_boxes = 1
z_shape_obj = self.sample_z((batch_size, n_boxes, z_dim), tmp=tmp)
z_app_obj = self.sample_z((batch_size, n_boxes, z_dim), tmp=tmp)
z_shape_bg = self.sample_z((batch_size, z_dim_bg), tmp=tmp)
z_app_bg = self.sample_z((batch_size, z_dim_bg), tmp=tmp)
return z_shape_obj, z_app_obj, z_shape_bg, z_app_bg
def sample_z(self, size, tmp=1.):
z = torch.randn(*size) * tmp
z = z.to(self.device)
return z
def get_random_camera(self, batch_size):
camera_mat = self.camera_matrix.repeat(batch_size, 1, 1)
world_mat, uvr = get_random_pose(
self.range_u, self.range_v, self.range_radius, batch_size)
world_mat = world_mat.to(self.device)
camera_mat = camera_mat.to(self.device)
return (camera_mat, world_mat), uvr
def get_random_transformations(self, batch_size):
device = self.device
s, t, R, rval = self.bounding_box_generator(
batch_size, return_rval=True)
s, t, R = s.to(device), t.to(device), R.to(device)
return (s, t, R), rval
def get_rand_rep(self, batch_size):
latent_codes = self.get_latent_codes(batch_size)
_, uvr = self.get_random_camera(batch_size)
transformations, rval = self.get_random_transformations(batch_size)
img_rep = self.img_representation(latent_codes, uvr, transformations, rval)
return img_rep
def get_random_bg_rotation(self, batch_size):
if self.bg_rotation_range != [0., 0.]:
bg_r = self.bg_rotation_range
r_random = bg_r[0] + np.random.rand() * (bg_r[1] - bg_r[0])
R_bg = [
torch.from_numpy(Rot.from_euler(
'z', r_random * 2 * np.pi).as_dcm()
) for i in range(batch_size)]
R_bg = torch.stack(R_bg, dim=0).reshape(
batch_size, 3, 3).float()
else:
R_bg = torch.eye(3).unsqueeze(0).repeat(batch_size, 1, 1).float()
R_bg = R_bg.to(self.device)
return R_bg
def get_random_bg_transformations(self, batch_size):
bg_t = self.bg_translation_min + torch.rand(batch_size, 3) * self.bg_translation_range
bg_t = bg_t.to(self.device)
return bg_t
def add_noise_to_interval(self, di):
di_mid = .5 * (di[..., 1:] + di[..., :-1])
di_high = torch.cat([di_mid, di[..., -1:]], dim=-1)
di_low = torch.cat([di[..., :1], di_mid], dim=-1)
noise = torch.rand_like(di_low)
ti = di_low + (di_high - di_low) * noise
return ti
def transform_points_to_box(self, p, transformations, box_idx=0,
scale_factor=1.):
bb_s, bb_t, bb_R = transformations
p_box = (bb_R[:, box_idx] @ (p - bb_t[:, box_idx].unsqueeze(1)
).permute(0, 2, 1)).permute(
0, 2, 1) / bb_s[:, box_idx].unsqueeze(1) * scale_factor
return p_box
def transform_points_to_box_bg(self, p, transformations):
bb_t, bb_R = transformations
p_box = (bb_R @ (p - bb_t.unsqueeze(1)
).permute(0, 2, 1)).permute(0, 2, 1)
return p_box
def get_evaluation_points_bg(self, pixels_world, camera_world, di,
bg_transformations):
batch_size = pixels_world.shape[0]
n_steps = di.shape[-1]
pixels_world_bg = self.transform_points_to_box_bg(
pixels_world, bg_transformations)
camera_world_bg = self.transform_points_to_box_bg(
camera_world, bg_transformations)
ray_bg = pixels_world_bg - camera_world_bg
p = camera_world_bg.unsqueeze(-2).contiguous() + \
di.unsqueeze(-1).contiguous() * \
ray_bg.unsqueeze(-2).contiguous()
r = ray_bg.unsqueeze(-2).repeat(1, 1, n_steps, 1)
assert(p.shape == r.shape)
p = p.reshape(batch_size, -1, 3)
r = r.reshape(batch_size, -1, 3)
return p, r
def get_evaluation_points(self, pixels_world, camera_world, di,
transformations, i):
batch_size = pixels_world.shape[0]
n_steps = di.shape[-1]
pixels_world_i = self.transform_points_to_box(
pixels_world, transformations, i)
camera_world_i = self.transform_points_to_box(
camera_world, transformations, i)
ray_i = pixels_world_i - camera_world_i
p_i = camera_world_i.unsqueeze(-2).contiguous() + \
di.unsqueeze(-1).contiguous() * ray_i.unsqueeze(-2).contiguous()
ray_i = ray_i.unsqueeze(-2).repeat(1, 1, n_steps, 1)
assert(p_i.shape == ray_i.shape)
p_i = p_i.reshape(batch_size, -1, 3)
ray_i = ray_i.reshape(batch_size, -1, 3)
return p_i, ray_i
def composite_function(self, sigma, feat):
n_boxes = sigma.shape[0]
if n_boxes > 1:
if self.use_max_composition:
bs, rs, ns = sigma.shape[1:]
sigma_sum, ind = torch.max(sigma, dim=0)
feat_weighted = feat[ind, torch.arange(bs).reshape(-1, 1, 1),
torch.arange(rs).reshape(
1, -1, 1), torch.arange(ns).reshape(
1, 1, -1)]
else:
denom_sigma = torch.sum(sigma, dim=0, keepdim=True)
denom_sigma[denom_sigma == 0] = 1e-4
w_sigma = sigma / denom_sigma
sigma_sum = torch.sum(sigma, dim=0)
feat_weighted = (feat * w_sigma.unsqueeze(-1)).sum(0)
else:
sigma_sum = sigma.squeeze(0)
feat_weighted = feat.squeeze(0)
return sigma_sum, feat_weighted
def calc_volume_weights(self, z_vals, ray_vector, sigma, last_dist=1e10):
dists = z_vals[..., 1:] - z_vals[..., :-1]
dists = torch.cat([dists, torch.ones_like(
z_vals[..., :1]) * last_dist], dim=-1)
dists = dists * torch.norm(ray_vector, dim=-1, keepdim=True)
alpha = 1.-torch.exp(-F.relu(sigma)*dists)
weights = alpha * \
torch.cumprod(torch.cat([
torch.ones_like(alpha[:, :, :1]),
(1. - alpha + 1e-10), ], dim=-1), dim=-1)[..., :-1]
return weights
def get_2Dbbox(self, img_rep, return_size, n_steps=256, render_size=256, padd=0.1):
'''
get 3D bounding box projected 2D bounding box
'''
device = self.device
res = return_size
if return_size > render_size:
res = render_size
n_points = res * res
depth_range = self.depth_range
camera_matrices, transformations = self.reform_representation(img_rep)[1:3]
batch_size = camera_matrices[0].size(0)
# Arange Pixels
pixels = arange_pixels((res, res), batch_size,
invert_y_axis=False)[1].to(device)
pixels[..., -1] *= -1.
pixels_world = image_points_to_world(
pixels, camera_mat=camera_matrices[0],
world_mat=camera_matrices[1])
camera_world = origin_to_world(
n_points, camera_mat=camera_matrices[0],
world_mat=camera_matrices[1])
ray_vector = pixels_world - camera_world
# batch_size x n_points x n_steps
di = depth_range[0] + \
torch.linspace(0., 1., steps=n_steps).reshape(1, 1, -1) * (
depth_range[1] - depth_range[0])
di = di.repeat(batch_size, n_points, 1).to(device)
p_i = self.get_evaluation_points(
pixels_world, camera_world, di, transformations, 0)[0]
# Mask out values outside
# padd = 0.1
mask_box = torch.all(
p_i <= 1. + padd, dim=-1) & torch.all(
p_i >= -1. - padd, dim=-1)
# Get 2d bbox
bbox_sigma = torch.ones(
batch_size, n_points*n_steps).to(device) * 100
bbox_sigma[mask_box == 0] = 0.
bbox_sigma = bbox_sigma.reshape(batch_size, n_points, n_steps)
weights_bbox = self.calc_volume_weights(
di, ray_vector, bbox_sigma, last_dist=0.)
bbox = torch.sum(weights_bbox, dim=-1, keepdim=True)
bbox = bbox.permute(0, 2, 1).reshape(
batch_size, -1, res, res)
bbox = bbox.permute(0, 1, 3, 2)
if res != return_size:
bbox = F.interpolate(bbox, size=return_size, mode='bilinear')
return bbox
def volume_render_image(
self,
latent_codes,
camera_matrices,
transformations,
bg_transformations,
mode='train',
not_render_background=False,
only_render_background=False,
):
res = self.resolution_vol
device = self.device
n_steps = self.n_ray_samples
n_points = res * res
depth_range = self.depth_range
batch_size = latent_codes[0].shape[0]
z_shape_obj, z_app_obj, z_shape_bg, z_app_bg = latent_codes
assert(not (not_render_background and only_render_background))
# Arange Pixels
pixels = arange_pixels((res, res), batch_size,
invert_y_axis=False)[1].to(device)
pixels[..., -1] *= -1.
# Project to 3D world
pixels_world = image_points_to_world(
pixels, camera_mat=camera_matrices[0],
world_mat=camera_matrices[1])
camera_world = origin_to_world(
n_points, camera_mat=camera_matrices[0],
world_mat=camera_matrices[1])
ray_vector = pixels_world - camera_world
# batch_size x n_points x n_steps
di = depth_range[0] + \
torch.linspace(0., 1., steps=n_steps).reshape(1, 1, -1) * (
depth_range[1] - depth_range[0])
di = di.repeat(batch_size, n_points, 1).to(device)
if mode == 'train':
di = self.add_noise_to_interval(di)
n_boxes = latent_codes[0].shape[1]
feat, sigma = [], []
n_iter = n_boxes if not_render_background else n_boxes + 1
if only_render_background:
n_iter = 1
n_boxes = 0
for i in range(n_iter):
if i < n_boxes: # Object
p_i, r_i = self.get_evaluation_points(
pixels_world, camera_world, di, transformations, i)
z_shape_i, z_app_i = z_shape_obj[:, i], z_app_obj[:, i]
feat_i, sigma_i = self.decoder(p_i, r_i, z_shape_i, z_app_i)
if mode == 'train':
# As done in NeRF, add noise during training
sigma_i += torch.randn_like(sigma_i)
# Mask out values outside
padd = 0.1
mask_box = torch.all(
p_i <= 1. + padd, dim=-1) & torch.all(
p_i >= -1. - padd, dim=-1)
sigma_i[mask_box == 0] = 0.
# Reshape
sigma_i = sigma_i.reshape(batch_size, n_points, n_steps)
feat_i = feat_i.reshape(batch_size, n_points, n_steps, -1)
else: # Background
p_bg, r_bg = self.get_evaluation_points_bg(
pixels_world, camera_world, di, bg_transformations)
feat_i, sigma_i = self.background_generator(
p_bg, r_bg, z_shape_bg, z_app_bg)
sigma_i = sigma_i.reshape(batch_size, n_points, n_steps)
feat_i = feat_i.reshape(batch_size, n_points, n_steps, -1)
if mode == 'train':
# As done in NeRF, add noise during training
sigma_i += torch.randn_like(sigma_i)
feat.append(feat_i)
sigma.append(sigma_i)
sigma = F.relu(torch.stack(sigma, dim=0))
feat = torch.stack(feat, dim=0)
# Composite
sigma_sum, feat_weighted = self.composite_function(sigma, feat)
# Get Volume Weights
weights = self.calc_volume_weights(di, ray_vector, sigma_sum)
feat_map = torch.sum(weights.unsqueeze(-1) * feat_weighted, dim=-2)
# Reformat output
feat_map = feat_map.permute(0, 2, 1).reshape(
batch_size, -1, res, res) # B x feat x h x w
feat_map = feat_map.permute(0, 1, 3, 2) # new to flip x/y
return feat_map
def forward(
self,
img_rep,
mode='train',
not_render_background=False,
only_render_background=False,
):
latent_codes, camera_matrices, transformations, uvr, rval = \
self.reform_representation(img_rep)
batch_size = latent_codes[0].size(0)
bg_R = self.get_random_bg_rotation(batch_size)
bg_t = torch.zeros([batch_size, 3], device=self.device)
# randomly translate bg during training
if mode == 'train':
bg_t = self.get_random_bg_transformations(batch_size)
if self.pos_share:
bg_t[:, 2] = transformations[1][:, 0, 2] # obj scene z share
bg_transformations = (bg_t, bg_R)
img_rep = self.img_representation(
latent_codes, uvr, transformations, rval)
rgb_v = self.volume_render_image(
latent_codes,
camera_matrices,
transformations,
bg_transformations,
mode=mode,
not_render_background=not_render_background,
only_render_background=only_render_background,
)
return rgb_v
############################### Stylegan Generator ###############################
class style_Blur(nn.Module):
def __init__(self, kernel, pad, upsample_factor=1):
super().__init__()
kernel = make_kernel(kernel)
if upsample_factor > 1:
kernel = kernel * (upsample_factor ** 2)
self.register_buffer('kernel', kernel)
self.pad = pad
def forward(self, input):
out = upfirdn2d(input, self.kernel, pad=self.pad)
return out
class PixelNorm(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input):
return input * torch.rsqrt(torch.mean(input ** 2, dim=1, keepdim=True) + 1e-8)
def make_kernel(k):
k = torch.tensor(k, dtype=torch.float32)
if k.ndim == 1:
k = k[None, :] * k[:, None]
k /= k.sum()
return k
class Upsample(nn.Module):
def __init__(self, kernel, factor=2):
super().__init__()
self.factor = factor
kernel = make_kernel(kernel) * (factor ** 2)
self.register_buffer('kernel', kernel)
p = kernel.shape[0] - factor
pad0 = (p + 1) // 2 + factor - 1
pad1 = p // 2
self.pad = (pad0, pad1)
def forward(self, input):
out = upfirdn2d(input, self.kernel, up=self.factor, down=1, pad=self.pad)
return out
class EqualConv2d(nn.Module):
def __init__(
self, in_channel, out_channel, kernel_size, stride=1, padding=0, bias=True
):
super().__init__()
self.weight = nn.Parameter(
torch.randn(out_channel, in_channel, kernel_size, kernel_size)
)
self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)
self.stride = stride
self.padding = padding
if bias:
self.bias = nn.Parameter(torch.zeros(out_channel))
else:
self.bias = None
def forward(self, input):
out = conv2d_gradfix.conv2d(
input,
self.weight * self.scale,
bias=self.bias,
stride=self.stride,
padding=self.padding,
)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]},'
f' {self.weight.shape[2]}, stride={self.stride}, padding={self.padding})'
)
class EqualLinear(nn.Module):
def __init__(
self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None
):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
if bias:
self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
else:
self.bias = None
self.activation = activation
self.scale = (1 / math.sqrt(in_dim)) * lr_mul
self.lr_mul = lr_mul
def forward(self, input):
if self.activation:
out = F.linear(input, self.weight * self.scale)
out = fused_leaky_relu(out, self.bias * self.lr_mul)
else:
out = F.linear(
input, self.weight * self.scale, bias=self.bias * self.lr_mul
)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
)
class ModulatedConv2d(nn.Module):
def __init__(
self,
in_channel,
out_channel,
kernel_size,
style_dim,
demodulate=True,
upsample=False,
downsample=False,
blur_kernel=[1, 3, 3, 1],
fused=True,
):
super().__init__()
self.eps = 1e-8
self.kernel_size = kernel_size
self.in_channel = in_channel
self.out_channel = out_channel
self.upsample = upsample
self.downsample = downsample
if upsample:
factor = 2
p = (len(blur_kernel) - factor) - (kernel_size - 1)
pad0 = (p + 1) // 2 + factor - 1
pad1 = p // 2 + 1
self.blur = style_Blur(blur_kernel, pad=(pad0, pad1), upsample_factor=factor)
if downsample:
factor = 2
p = (len(blur_kernel) - factor) + (kernel_size - 1)
pad0 = (p + 1) // 2
pad1 = p // 2
self.blur = style_Blur(blur_kernel, pad=(pad0, pad1))
fan_in = in_channel * kernel_size ** 2
self.scale = 1 / math.sqrt(fan_in)
self.padding = kernel_size // 2
self.weight = nn.Parameter(
torch.randn(1, out_channel, in_channel, kernel_size, kernel_size)
)
self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)
self.demodulate = demodulate
self.fused = fused
def __repr__(self):
return (
f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, '
f'upsample={self.upsample}, downsample={self.downsample})'
)
def forward(self, input, style):
batch, in_channel, height, width = input.shape
if not self.fused:
weight = self.scale * self.weight.squeeze(0)
style = self.modulation(style)
if self.demodulate:
w = weight.unsqueeze(0) * style.view(batch, 1, in_channel, 1, 1)
dcoefs = (w.square().sum((2, 3, 4)) + 1e-8).rsqrt()
input = input * style.reshape(batch, in_channel, 1, 1)
if self.upsample:
weight = weight.transpose(0, 1)
out = conv2d_gradfix.conv_transpose2d(
input, weight, padding=0, stride=2
)
out = self.blur(out)
elif self.downsample:
input = self.blur(input)
out = conv2d_gradfix.conv2d(input, weight, padding=0, stride=2)
else: