-
Notifications
You must be signed in to change notification settings - Fork 4
/
models.py
1511 lines (1271 loc) · 66.3 KB
/
models.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
import sys
from turtle import forward
import torchvision
from types import coroutine
import numpy as np
from time import time
from functools import partial
from torch.nn import functional as F
# Must be imported before large libs
# try:
# import open3d as o3d
# except ImportError:
# raise ImportError("Please install open3d with `pip install open3d`.")
from extra_utils import EmptyModule
import torch
import torch.nn as nn
import torch.utils.data
from blocks import MLP, MVAgregate
import MinkowskiEngine as ME
M = np.array(
[
[0.80656762, -0.5868724, -0.07091862],
[0.3770505, 0.418344, 0.82632997],
[-0.45528188, -0.6932309, 0.55870326],
]
)
# assert (
# int(o3d.__version__.split(".")[1]) >= 8
# ), f"Requires open3d version >= 0.8, the current version is {o3d.__version__}"
# if not os.path.exists("ModelNet40"):
# logging.info("Downloading the pruned ModelNet40 dataset...")
# subprocess.run(["sh", "./examples/download_modelnet40.sh"])
###############################################################################
# Utility functions
###############################################################################
# def PointCloud(points, colors=None):
# pcd = o3d.geometry.PointCloud()
# pcd.points = o3d.utility.Vector3dVector(points)
# if colors is not None:
# pcd.colors = o3d.utility.Vector3dVector(colors)
# return pcd
class MyPruning(nn.Module):
def __init__(self, **kwargs):
super().__init__()
self.prune = ME.MinkowskiPruning(**kwargs)
def forward(self,sin,keep):
if keep.sum() > 0:
return self.prune(sin, keep)
else:
return sin
class SRFHead(nn.Module):
def __init__(self, in_channel=13,out_channels_with_density=13,strides=1,head_depth=1):
super().__init__()
self.in_channel = in_channel
self.head_depth = head_depth
self.out_channels_with_density = out_channels_with_density
self.head_conv = self.srf_conv_block(self.head_depth, self.in_channel-1, self.out_channels_with_density-1, strides=strides)
def forward(self, stensor):
densities = ME.SparseTensor(stensor.F[:,0][...,None], coordinate_map_key=stensor.coordinate_map_key,
coordinate_manager=stensor.coordinate_manager)
stensor = ME.SparseTensor(stensor.F[:, 1::], coordinate_map_key=stensor.coordinate_map_key,
coordinate_manager=stensor.coordinate_manager)
stensor = self.head_conv(stensor)
return ME.cat(densities, stensor)
def srf_conv_block(self,depth,in_channels, out_channels, strides=1):
layers = [self.srf_conv_layer(in_channels, out_channels, strides=strides) for _ in range(depth)]
return nn.Sequential(*layers)
def srf_conv_layer(self, in_channels, out_channels, strides=1):
return nn.Sequential(ME.MinkowskiConvolution(in_channels, out_channels, kernel_size=2, stride=strides, dimension=3,
),
ME.MinkowskiBatchNorm(out_channels),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(
out_channels, out_channels, kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(out_channels),
ME.MinkowskiELU(),
)
class SparseFeaturesConcater(nn.Module):
def __init__(self, append_cam_features=False, append_img_features=False, append_time_features=False):
super().__init__()
self.append_cam_features = append_cam_features
self.append_img_features = append_img_features
self.append_time_features = append_time_features
def forward(self, stensor, cam_feats, img_feats,time_feats):
if self.append_cam_features:
stensor = self.concat_feats_with_sparse(stensor, cam_feats)
if self.append_img_features:
stensor = self.concat_feats_with_sparse(stensor, img_feats)
if self.append_time_features:
stensor = self.concat_feats_with_sparse(stensor, time_feats)
return stensor
def concat_feats_with_sparse(self, stensor, feats):
feats = self.cast_feats_to_sparse(stensor, feats)
feats = ME.SparseTensor(feats, coordinate_map_key=stensor.coordinate_map_key,
coordinate_manager=stensor.coordinate_manager)
return ME.cat(stensor, feats)
def pad_zeros_with_sparse(self, stensor,zeros_pad=0):
if zeros_pad == 0:
return stensor
feats = torch.zeros((stensor.F.shape[0], zeros_pad)).to(stensor.F.device)
feats = ME.SparseTensor(feats, coordinate_map_key=stensor.coordinate_map_key,
coordinate_manager=stensor.coordinate_manager)
return ME.cat(stensor, feats)
def cast_feats_to_sparse(self, stensor, feats):
"""
casts a batched torch tensor `feats` into a batched ME.sparse tensor `stensor`
"""
bs = feats.shape[0]
comb_feats = []
for jj in range(bs):
try:
c_feat_size = stensor.features_at(jj).shape[0]
comb_feats.append(feats[jj][None, ...].repeat(c_feat_size,1))
except: # if stensor[jj] is empty
continue
return torch.cat(comb_feats, dim=0)
class SRFEncoder(nn.Module):
ENC_CHANNELS = [16, 64, 256, 512]
def __init__(self, srf_encoder_depth = 1,resolution=128, in_nchannel=512, out_nchannel=512, strides=3, normalize="const", added_cam_latent_channels=0, added_img_latent_channels=0, pooling_method="mean", added_time_latent_channels=0 ,** kwargs):
nn.Module.__init__(self)
self.resolution = resolution
self.srf_encoder_depth = srf_encoder_depth
append_cam_features = added_cam_latent_channels != 0
append_img_features = added_img_latent_channels != 0
append_time_features = added_time_latent_channels != 0
self.in_nchannel = in_nchannel
self.out_nchannel = out_nchannel
self.feat_concater = SparseFeaturesConcater(append_cam_features=append_cam_features, append_img_features=append_img_features, append_time_features=append_time_features)
self.added_cam_latent_channels = added_cam_latent_channels
self.added_img_latent_channels = added_img_latent_channels
self.added_time_latent_channels = added_time_latent_channels
self.added_latent_channels = added_cam_latent_channels + added_img_latent_channels + added_time_latent_channels
upconv = True # strides != 1
self.expand_coordinates = upconv
self.strides = strides
self.upconv = ME.MinkowskiGenerativeConvolutionTranspose if upconv else ME.MinkowskiConvolution
self.normalize = ME.MinkowskiTanh() if normalize == "tanh" else EmptyModule(1)
self.globalpooling = ME.MinkowskiGlobalAvgPooling() if pooling_method == "mean" else ME.MinkowskiGlobalMaxPooling()
# Input sparse tensor must have tensor stride 128.
enc_ch = self.ENC_CHANNELS
enc_ch[0] = self.in_nchannel
enc_ch[-1] = self.out_nchannel
# Encoder
self.enc_block_s1 = self.srf_conv_layer(self.in_nchannel, enc_ch[0], strides=1)
self.enc_block_s2s4 = self.srf_conv_layer(enc_ch[0], enc_ch[1], strides=self.strides)
layers = [self.srf_conv_layer(enc_ch[2], enc_ch[2], strides=1) for _ in range(self.srf_encoder_depth-1)]
self.enc_block_s4s8 = nn.Sequential(self.srf_conv_layer(enc_ch[1], enc_ch[2], strides=self.strides), *layers)
self.enc_block_s8s16 = self.srf_conv_layer(enc_ch[2], enc_ch[3], strides=1)
def srf_conv_layer(self, in_channels,out_channels,strides=1):
return nn.Sequential(ME.MinkowskiConvolution(in_channels, out_channels, kernel_size=2, stride=strides, dimension=3,
),
ME.MinkowskiBatchNorm(out_channels),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(
out_channels, out_channels, kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(out_channels),
ME.MinkowskiELU(),
)
def forward(self, partial_in):
# print("\n\n\n\partial_in", "$$$$$$$$$$$$$$$$$$",partial_in.coordinates.max(), partial_in.features.shape)
enc_s1 = self.enc_block_s1(partial_in)
# print("\n\n\n\nenc_s1","$$$$$$$$$$$$$$$$$$",enc_s1.coordinates.max(),enc_s1.features.shape)
enc_s4 = self.enc_block_s2s4(enc_s1)
# print("enc_s4","$$$$$$$$$$$$$$$$$$",enc_s4.coordinates.max(),enc_s4.features.shape)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
# APPENDING LATENT FEATURES
# enc_s4 = self.feat_concater(enc_s4, c2ws_feats, img_feats)
# print("enc_s4", "$$$$$$$$$$$$$$$$$$",enc_s4.coordinates.max(), enc_s4.features.shape)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
enc_s8 = self.enc_block_s4s8(enc_s4)
# print("enc_s8","$$$$$$$$$$$$$$$$$$",enc_s8.coordinates.max(),enc_s8.features.shape)
enc_s16 = self.enc_block_s8s16(enc_s8)
# print("enc_s16","$$$$$$$$$$$$$$$$$$",enc_s16.coordinates.max(),enc_s16.features.shape)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
# APPENDING LATENT FEATURES
# enc_s16 = self.feat_concater(enc_s16, c2ws_feats, img_feats)
# print("enc_s16", "$$$$$$$$$$$$$$$$$$",enc_s16.coordinates.max(), enc_s16.features.shape)
out_feats = self.globalpooling(enc_s16)
return out_feats.F
class MiniCompletionNet(nn.Module):
ENC_CHANNELS = [16, 64, 128, 512]
DEC_CHANNELS = [16, 64, 128, 512]
def __init__(self,head_depth, resolution=128, in_nchannel=512, out_nchannel=512, batch_size=2, enable_pruning=False, prune_last_layer=False, strides=3, normalize="const", added_cam_latent_channels=0, added_img_latent_channels=0, added_time_latent_channels=0, joint_heads=False, ** kwargs):
nn.Module.__init__(self)
self.resolution = resolution
self.joint_heads = joint_heads
append_cam_features = added_cam_latent_channels != 0
append_img_features = added_img_latent_channels != 0
append_time_features = added_time_latent_channels!= 0
self.in_nchannel = in_nchannel
self.out_nchannel = out_nchannel
self.feat_concater = SparseFeaturesConcater(append_cam_features=append_cam_features, append_img_features=append_img_features, append_time_features=append_time_features)
self.added_cam_latent_channels = added_cam_latent_channels
self.added_img_latent_channels = added_img_latent_channels
self.added_time_latent_channels = added_time_latent_channels
self.added_latent_channels = added_cam_latent_channels + added_img_latent_channels + added_time_latent_channels
# print("FFFFFFFFFFFFF", self.added_cam_latent_channels,self.added_img_latent_channels,self.added_time_latent_channels)
upconv = True # strides != 1
self.expand_coordinates = upconv
self.strides = strides
size_tensor = torch.empty((batch_size, self.out_nchannel, self.resolution, self.resolution, self.resolution)).size()
self.upconv = ME.MinkowskiGenerativeConvolutionTranspose if upconv else ME.MinkowskiConvolution
self.normalize = ME.MinkowskiTanh() if normalize == "tanh" else EmptyModule(1)
# Input sparse tensor must have tensor stride 128.
enc_ch = self.ENC_CHANNELS
dec_ch = self.DEC_CHANNELS
dec_ch[0] = self.out_nchannel
enc_ch[0] = self.out_nchannel
self.head = SRFHead(self.out_nchannel, self.out_nchannel,head_depth=head_depth) if not self.joint_heads else EmptyModule(1)
# Encoder
self.enc_block_s1 = nn.Sequential(
ME.MinkowskiConvolution(
self.in_nchannel, enc_ch[0], kernel_size=3, stride=1, dimension=3),
ME.MinkowskiBatchNorm(enc_ch[0]),
ME.MinkowskiELU(),
)
self.enc_block_s2s4 = nn.Sequential(
ME.MinkowskiConvolution(
enc_ch[0], enc_ch[1], kernel_size=2, stride=self.strides, dimension=3,
),
ME.MinkowskiBatchNorm(enc_ch[1]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(
enc_ch[1], enc_ch[1], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(enc_ch[1]),
ME.MinkowskiELU(),
)
self.enc_block_s4s8 = nn.Sequential(
ME.MinkowskiConvolution(
enc_ch[1]+self.added_latent_channels, enc_ch[2], kernel_size=2, stride=self.strides, dimension=3,
),
ME.MinkowskiBatchNorm(enc_ch[2]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(
enc_ch[2], enc_ch[2], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(enc_ch[2]),
ME.MinkowskiELU(),
)
self.enc_block_s8s16 = nn.Sequential(
ME.MinkowskiConvolution(
enc_ch[2], enc_ch[3], kernel_size=2, stride=1, dimension=3,
),
ME.MinkowskiBatchNorm(enc_ch[3]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(
enc_ch[3], enc_ch[3], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(enc_ch[3]),
ME.MinkowskiELU(),
)
self.dec_block_s64s32 = nn.Sequential(
# ME.MinkowskiGenerativeConvolutionTranspose(
# self.upconv(
ME.MinkowskiConvolution(
enc_ch[3]+self.added_latent_channels,
dec_ch[2],
kernel_size=4,
stride=1,
dimension=3,
),
ME.MinkowskiBatchNorm(dec_ch[2]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(
dec_ch[2], dec_ch[2], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(dec_ch[2]),
ME.MinkowskiELU(),
)
self.dec_s32_cls = ME.MinkowskiConvolution(
dec_ch[2], 1, kernel_size=1, bias=True, dimension=3) if enable_pruning else EmptyModule(1)
self.dec_block_s16s8 = nn.Sequential(
# ME.MinkowskiGenerativeConvolutionTranspose(
self.upconv(
dec_ch[2],
dec_ch[1]+self.added_latent_channels,
kernel_size=2,
stride=self.strides,
dimension=3,
),
ME.MinkowskiBatchNorm(dec_ch[1]+self.added_latent_channels),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(
dec_ch[1]+self.added_latent_channels, dec_ch[1]+self.added_latent_channels, kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(dec_ch[1]+self.added_latent_channels),
ME.MinkowskiELU(),
)
self.dec_s8_cls = ME.MinkowskiConvolution(
dec_ch[1], 1, kernel_size=1, bias=True, dimension=3) if enable_pruning else EmptyModule(1)
self.dec_block_s8s4 = nn.Sequential(
# ME.MinkowskiGenerativeConvolutionTranspose(
self.upconv(
dec_ch[1]+2*self.added_latent_channels,
dec_ch[0],
kernel_size=2,
stride=self.strides,
dimension=3,
),
ME.MinkowskiBatchNorm(dec_ch[0]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(
dec_ch[0], dec_ch[0], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(dec_ch[0]),
ME.MinkowskiELU(),
)
self.dec_s4_cls = ME.MinkowskiConvolution(
dec_ch[0]+self.added_latent_channels, enc_ch[3], 1, kernel_size=1, bias=True, dimension=3) if enable_pruning else EmptyModule(1)
self.dec_block_s2s1 = nn.Sequential(
# ME.MinkowskiGenerativeConvolutionTranspose(
# self.upconv(
ME.MinkowskiConvolution(
dec_ch[0],
self.out_nchannel,
kernel_size=2,
stride=1,
dimension=3,
),
ME.MinkowskiBatchNorm(self.out_nchannel),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(
self.out_nchannel, self.out_nchannel, kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(self.out_nchannel),
ME.MinkowskiELU(),
)
self.dec_s1_cls = ME.MinkowskiConvolution(
self.out_nchannel, 1, kernel_size=1, bias=True, dimension=3) if enable_pruning else EmptyModule(1)
# pruning
self.pruning = MyPruning() if enable_pruning else EmptyModule(1)
self.pruning_last = MyPruning() if prune_last_layer else EmptyModule(1)
self.to_dense = ME.MinkowskiToDenseTensor(size_tensor)
def forward(self, partial_in, c2ws_feats, img_feats,time_feats):
enc_s1 = self.enc_block_s1(partial_in)
# print("\n\n\n\nenc_s1","$$$$$$$$$$$$$$$$$$",enc_s1.coordinates.max(),enc_s1.features.shape)
enc_s4 = self.enc_block_s2s4(enc_s1)
# print("enc_s4","$$$$$$$$$$$$$$$$$$",enc_s4.coordinates.max(),enc_s4.features.shape)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
# APPENDING LATENT FEATURES
enc_s4 = self.feat_concater(enc_s4, c2ws_feats, img_feats,time_feats)
# print("enc_s4", "$$$$$$$$$$$$$$$$$$",enc_s4.coordinates.max(), enc_s4.features.shape)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
enc_s8 = self.enc_block_s4s8(enc_s4)
# print("enc_s8","$$$$$$$$$$$$$$$$$$",enc_s8.coordinates.max(),enc_s8.features.shape)
enc_s16 = self.enc_block_s8s16(enc_s8)
# print("enc_s16","$$$$$$$$$$$$$$$$$$",enc_s16.coordinates.max(),enc_s16.features.shape)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
# APPENDING LATENT FEATURES
enc_s16 = self.feat_concater(enc_s16, c2ws_feats, img_feats,time_feats)
# print("enc_s16", "$$$$$$$$$$$$$$$$$$",enc_s16.coordinates.max(), enc_s16.features.shape)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
# Decoder 64 -> 32
##################################################
dec_s32 = self.dec_block_s64s32(enc_s16)
# print("dec_s32","$$$$$$$$$$$$$$$$$$",dec_s32.coordinates.max(),dec_s32.features.shape)
# Add encoder features
dec_s32 = dec_s32 + enc_s8
dec_s32_cls = self.dec_s32_cls(dec_s32)
keep_s32 = (dec_s32_cls.F > 0).squeeze()
dec_s32 = self.pruning(dec_s32, keep_s32)
##################################################
# Decoder 16 -> 8
##################################################
dec_s8 = self.dec_block_s16s8(dec_s32)
# print("dec_s8","$$$$$$$$$$$$$$$$$$",dec_s8.coordinates.max(),dec_s8.features.shape)
# Add encoder features
dec_s8 = dec_s8 + enc_s4
dec_s8_cls = self.dec_s8_cls(dec_s8)
keep_s8 = (dec_s8_cls.F > 0).squeeze()
# Remove voxels s16
dec_s8 = self.pruning(dec_s8, keep_s8)
# APPENDING LATENT FEATURES
dec_s8 = self.feat_concater(dec_s8, c2ws_feats, img_feats,time_feats)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
dec_s2 = self.dec_block_s8s4(dec_s8)
# print("dec_s2","$$$$$$$$$$$$$$$$$$",dec_s2.coordinates.max(),dec_s2.features.shape)
# Add encoder features
dec_s2 = dec_s2 + enc_s1
dec_s2_cls = self.dec_s4_cls(dec_s2)
keep_s2 = (dec_s2_cls.F > 0).squeeze()
# Remove voxels s2
dec_s2 = self.pruning(dec_s2, keep_s2)
##################################################
# Decoder 2 -> 1
##################################################
dec_s1 = self.dec_block_s2s1(dec_s2)
# print("dec_s1", "$$$$$$$$$$$$$$$$$$",dec_s1.coordinates.max(), dec_s1.features.shape)
dec_s1_cls = self.dec_s1_cls(dec_s1)
# Add encoder features
dec_s1 = dec_s1 + enc_s1
dec_s1_cls = self.dec_s1_cls(dec_s1)
keep_s1 = (dec_s1_cls.F > 0).squeeze()
dec_s1 = self.pruning_last(dec_s1, keep_s1)
dec_s1 = self.head(dec_s1)
dec_s1 = self.normalize(dec_s1)
# print("dec_s1","$$$$$$$$$$$$$$$$$$",dec_s1.coordinates.max(),dec_s1.features.shape)
return dec_s1 # , self.to_dense(dec_s1)
class CompletionNet(nn.Module):
ENC_CHANNELS = [16, 32, 64, 128, 256, 512, 1024]
DEC_CHANNELS = [16, 32, 64, 128, 256, 512, 1024]
def __init__(self,head_depth, resolution=128, in_nchannel=512, out_nchannel=512, batch_size=2, enable_pruning=False, prune_last_layer=False, strides=3, normalize="const", added_cam_latent_channels=0, added_img_latent_channels=0, added_time_latent_channels=0,joint_heads=False, ** kwargs):
nn.Module.__init__(self)
self.resolution = resolution
self.joint_heads = joint_heads
append_cam_features = added_cam_latent_channels != 0
append_img_features = added_img_latent_channels != 0
append_time_features = added_time_latent_channels != 0
self.in_nchannel = in_nchannel
self.out_nchannel = out_nchannel
self.feat_concater = SparseFeaturesConcater(append_cam_features=append_cam_features, append_img_features=append_img_features, append_time_features=append_time_features)
self.added_cam_latent_channels = added_cam_latent_channels
self.added_img_latent_channels = added_img_latent_channels
self.added_time_latent_channels = added_time_latent_channels
self.added_latent_channels = added_cam_latent_channels + added_img_latent_channels + added_time_latent_channels
upconv = strides != 1
self.expand_coordinates = upconv
self.strides = strides
size_tensor = torch.empty((batch_size, self.out_nchannel, self.resolution, self.resolution, self.resolution)).size()
self.upconv = ME.MinkowskiGenerativeConvolutionTranspose if upconv else ME.MinkowskiConvolution
self.normalize = ME.MinkowskiTanh() if normalize=="tanh" else EmptyModule(1)
# Input sparse tensor must have tensor stride 128.
enc_ch = self.ENC_CHANNELS
dec_ch = self.DEC_CHANNELS
dec_ch[0] = self.out_nchannel
enc_ch[0] = self.out_nchannel
self.head = SRFHead(self.out_nchannel,self.out_nchannel,head_depth=head_depth) if not self.joint_heads else EmptyModule(1)
# Encoder
self.enc_block_s1 = nn.Sequential(
ME.MinkowskiConvolution(self.in_nchannel, enc_ch[0], kernel_size=3, stride=1, dimension=3),
ME.MinkowskiBatchNorm(enc_ch[0]),
ME.MinkowskiELU(),
)
self.enc_block_s1s2 = nn.Sequential(
ME.MinkowskiConvolution(
enc_ch[0], enc_ch[1], kernel_size=2, stride=1, dimension=3,
),
ME.MinkowskiBatchNorm(enc_ch[1]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(enc_ch[1], enc_ch[1], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(enc_ch[1]),
ME.MinkowskiELU(),
)
self.enc_block_s2s4 = nn.Sequential(
ME.MinkowskiConvolution(
enc_ch[1], enc_ch[2], kernel_size=2, stride=self.strides, dimension=3,
),
ME.MinkowskiBatchNorm(enc_ch[2]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(enc_ch[2], enc_ch[2], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(enc_ch[2]),
ME.MinkowskiELU(),
)
self.enc_block_s4s8 = nn.Sequential(
ME.MinkowskiConvolution(
enc_ch[2]+self.added_latent_channels, enc_ch[3], kernel_size=2, stride=self.strides, dimension=3,
),
ME.MinkowskiBatchNorm(enc_ch[3]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(enc_ch[3], enc_ch[3], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(enc_ch[3]),
ME.MinkowskiELU(),
)
self.enc_block_s8s16 = nn.Sequential(
ME.MinkowskiConvolution(
enc_ch[3], enc_ch[4], kernel_size=2, stride=self.strides, dimension=3,
),
ME.MinkowskiBatchNorm(enc_ch[4]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(enc_ch[4], enc_ch[4], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(enc_ch[4]),
ME.MinkowskiELU(),
)
self.enc_block_s16s32 = nn.Sequential(
ME.MinkowskiConvolution(
enc_ch[4], enc_ch[5], kernel_size=2, stride=1, dimension=3,
),
ME.MinkowskiBatchNorm(enc_ch[5]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(enc_ch[5], enc_ch[5], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(enc_ch[5]),
ME.MinkowskiELU(),
)
self.enc_block_s32s64 = nn.Sequential(
ME.MinkowskiConvolution(
enc_ch[5], enc_ch[6], kernel_size=2, stride=1, dimension=3,
),
ME.MinkowskiBatchNorm(enc_ch[6]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(enc_ch[6], enc_ch[6], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(enc_ch[6]),
ME.MinkowskiELU(),
)
# Decoder
self.dec_block_s64s32 = nn.Sequential(
# ME.MinkowskiGenerativeConvolutionTranspose(
# self.upconv(
ME.MinkowskiConvolution(
enc_ch[6]+self.added_latent_channels,
dec_ch[5],
kernel_size=4,
stride=1,
dimension=3,
),
ME.MinkowskiBatchNorm(dec_ch[5]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(dec_ch[5], dec_ch[5], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(dec_ch[5]),
ME.MinkowskiELU(),
)
self.dec_s32_cls = ME.MinkowskiConvolution(dec_ch[5], 1, kernel_size=1, bias=True, dimension=3) if enable_pruning else EmptyModule(1)
self.dec_block_s32s16 = nn.Sequential(
# ME.MinkowskiGenerativeConvolutionTranspose(
self.upconv(
enc_ch[5],
dec_ch[4],
kernel_size=2,
stride=self.strides,
dimension=3,
),
ME.MinkowskiBatchNorm(dec_ch[4]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(dec_ch[4], dec_ch[4], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(dec_ch[4]),
ME.MinkowskiELU(),
)
self.dec_s16_cls = ME.MinkowskiConvolution(dec_ch[4], 1, kernel_size=1, bias=True, dimension=3) if enable_pruning else EmptyModule(1)
self.dec_block_s16s8 = nn.Sequential(
# ME.MinkowskiGenerativeConvolutionTranspose(
self.upconv(
dec_ch[4],
dec_ch[3],
kernel_size=2,
stride=self.strides,
dimension=3,
),
ME.MinkowskiBatchNorm(dec_ch[3]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(dec_ch[3], dec_ch[3], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(dec_ch[3]),
ME.MinkowskiELU(),
)
self.dec_s8_cls = ME.MinkowskiConvolution(
dec_ch[3], 1, kernel_size=1, bias=True, dimension=3) if enable_pruning else EmptyModule(1)
self.dec_block_s8s4 = nn.Sequential(
# ME.MinkowskiGenerativeConvolutionTranspose(
self.upconv(
dec_ch[3],
dec_ch[2],
kernel_size=2,
stride=self.strides,
dimension=3,
),
ME.MinkowskiBatchNorm(dec_ch[2]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(dec_ch[2], dec_ch[2], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(dec_ch[2]),
ME.MinkowskiELU(),
)
self.dec_s4_cls = ME.MinkowskiConvolution(dec_ch[2]+self.added_latent_channels, enc_ch[3], 1, kernel_size=1, bias=True, dimension=3) if enable_pruning else EmptyModule(1)
self.dec_block_s4s2 = nn.Sequential(
# ME.MinkowskiGenerativeConvolutionTranspose(
# self.upconv(
ME.MinkowskiConvolution(
dec_ch[2]+self.added_latent_channels,
dec_ch[1],
kernel_size=2,
stride=1,
dimension=3,
),
ME.MinkowskiBatchNorm(dec_ch[1]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(dec_ch[1], dec_ch[1], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(dec_ch[1]),
ME.MinkowskiELU(),
)
self.dec_s2_cls = ME.MinkowskiConvolution(dec_ch[1], 1, kernel_size=1, bias=True, dimension=3) if enable_pruning else EmptyModule(1)
self.dec_block_s2s1 = nn.Sequential(
# ME.MinkowskiGenerativeConvolutionTranspose(
# self.upconv(
ME.MinkowskiConvolution(
dec_ch[1],
dec_ch[0],
kernel_size=2,
stride=1,
dimension=3,
),
ME.MinkowskiBatchNorm(dec_ch[0]),
ME.MinkowskiELU(),
ME.MinkowskiConvolution(dec_ch[0], dec_ch[0], kernel_size=3, dimension=3),
ME.MinkowskiBatchNorm(dec_ch[0]),
ME.MinkowskiELU(),
)
self.dec_s1_cls = ME.MinkowskiConvolution(dec_ch[0], 1, kernel_size=1, bias=True, dimension=3) if enable_pruning else EmptyModule(1)
# pruning
self.pruning = MyPruning() if enable_pruning else EmptyModule(1)
self.pruning_last = MyPruning() if prune_last_layer else EmptyModule(1)
self.to_dense = ME.MinkowskiToDenseTensor(size_tensor)
# if self.out_nchannel != self.in_nchannel:
# self.in_to_output_skip = nn.Sequential(ME.MinkowskiConvolution(self.in_nchannel, self.out_nchannel, kernel_size=1, stride=1, dimension=3),ME.MinkowskiBatchNorm(self.out_nchannel),
# ME.MinkowskiELU(),
# )
# else :
# self.in_to_output_skip = EmptyModule(1)
def get_target(self, out, target_key, kernel_size=1):
with torch.no_grad():
target = torch.zeros(len(out), dtype=torch.bool, device=out.device)
cm = out.coordinate_manager
strided_target_key = cm.stride(
target_key, out.tensor_stride[0],
)
kernel_map = cm.kernel_map(
out.coordinate_map_key,
strided_target_key,
kernel_size=kernel_size,
region_type=1,
)
for k, curr_in in kernel_map.items():
target[curr_in[0].long()] = 1
return target
def valid_batch_map(self, batch_map):
for b in batch_map:
if len(b) == 0:
return False
return True
def forward(self, partial_in, c2ws_feats,img_feats,time_feats):
# out_cls, targets = [], []
# print("\n\n\n\nenc_s1", "$$$$$$$$$$$$$$$$$$", self.in_nchannel,partial_in.coordinates.max(), partial_in.features.shape)
enc_s1 = self.enc_block_s1(partial_in)
# print("\n\n\n\nenc_s1","$$$$$$$$$$$$$$$$$$",enc_s1.coordinates.max(),enc_s1.features.shape)
enc_s2 = self.enc_block_s1s2(enc_s1)
# print("enc_s2","$$$$$$$$$$$$$$$$$$",enc_s2.coordinates.max(),enc_s2.features.shape)
enc_s4 = self.enc_block_s2s4(enc_s2)
# print("enc_s4","$$$$$$$$$$$$$$$$$$",enc_s4.coordinates.max(),enc_s4.features.shape)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
# APPENDING LATENT FEATURES
enc_s4 = self.feat_concater(enc_s4, c2ws_feats, img_feats, time_feats)
# print("enc_s4", "$$$$$$$$$$$$$$$$$$",enc_s4.coordinates.max(), enc_s4.features.shape)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
enc_s8 = self.enc_block_s4s8(enc_s4)
# print("enc_s8","$$$$$$$$$$$$$$$$$$",enc_s8.coordinates.max(),enc_s8.features.shape)
enc_s16 = self.enc_block_s8s16(enc_s8)
# print("enc_s16","$$$$$$$$$$$$$$$$$$",enc_s16.coordinates.max(),enc_s16.features.shape)
enc_s32 = self.enc_block_s16s32(enc_s16)
# print("enc_s32","$$$$$$$$$$$$$$$$$$",enc_s32.coordinates.max(),enc_s32.features.shape)
enc_s64 = self.enc_block_s32s64(enc_s32)
# print("enc_s32","$$$$$$$$$$$$$$$$$$",enc_s32.coordinates.max(),enc_s32.features.shape)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
# APPENDING LATENT FEATURES
enc_s64 = self.feat_concater(enc_s64, c2ws_feats, img_feats, time_feats)
# print("enc_s32","$$$$$$$$$$$$$$$$$$",enc_s32.coordinates.max(),enc_s32.features.shape)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
# Decoder 64 -> 32
##################################################
dec_s32 = self.dec_block_s64s32(enc_s64)
# print("dec_s32","$$$$$$$$$$$$$$$$$$",dec_s32.coordinates.max(),dec_s32.features.shape)
# Add encoder features
dec_s32 = dec_s32 + enc_s32
dec_s32_cls = self.dec_s32_cls(dec_s32)
keep_s32 = (dec_s32_cls.F > 0).squeeze()
# target = self.get_target(dec_s32, target_key)
# targets.append(target)
# out_cls.append(dec_s32_cls)
# if self.training:
# keep_s32 += target
# Remove voxels s32
dec_s32 = self.pruning(dec_s32, keep_s32)
##################################################
# Decoder 32 -> 16
##################################################
dec_s16 = self.dec_block_s32s16(dec_s32)
# print("dec_s16","$$$$$$$$$$$$$$$$$$",dec_s16.coordinates.max(),dec_s16.features.shape)
# Add encoder features
dec_s16 = dec_s16 + enc_s16
dec_s16_cls = self.dec_s16_cls(dec_s16)
keep_s16 = (dec_s16_cls.F > 0).squeeze()
# target = self.get_target(dec_s16, target_key)
# targets.append(target)
# out_cls.append(dec_s16_cls)
# if self.training:
# keep_s16 += target
# Remove voxels s16
dec_s16 = self.pruning(dec_s16, keep_s16)
##################################################
# Decoder 16 -> 8
##################################################
dec_s8 = self.dec_block_s16s8(dec_s16)
# print("dec_s8","$$$$$$$$$$$$$$$$$$",dec_s8.coordinates.max(),dec_s8.features.shape)
# Add encoder features
dec_s8 = dec_s8 + enc_s8
dec_s8_cls = self.dec_s8_cls(dec_s8)
keep_s8 = (dec_s8_cls.F > 0).squeeze()
# target = self.get_target(dec_s8, target_key)
# targets.append(target)
# out_cls.append(dec_s8_cls)
# if self.training:
# keep_s8 += target
# Remove voxels s16
dec_s8 = self.pruning(dec_s8, keep_s8)
##################################################
# Decoder 8 -> 4
##################################################
dec_s4 = self.dec_block_s8s4(dec_s8)
# print("dec_s4","$$$$$$$$$$$$$$$$$$",dec_s4.coordinates.max(),dec_s4.features.shape)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
# APPENDING LATENT FEATURES
dec_s4 = self.feat_concater(dec_s4, c2ws_feats, img_feats, time_feats)
####################################CCCCCCCCCCCCCCCCCCCCCCCCCCCC#######################################################
# Add encoder features
dec_s4 = dec_s4 + enc_s4
dec_s4_cls = self.dec_s4_cls(dec_s4)
keep_s4 = (dec_s4_cls.F > 0).squeeze()
# target = self.get_target(dec_s4, target_key)
# targets.append(target)
# out_cls.append(dec_s4_cls)
# if self.training:
# keep_s4 += target
# Remove voxels s4
dec_s4 = self.pruning(dec_s4, keep_s4)
##################################################
# Decoder 4 -> 2
##################################################
dec_s2 = self.dec_block_s4s2(dec_s4)
# print("dec_s2","$$$$$$$$$$$$$$$$$$",dec_s2.coordinates.max(),dec_s2.features.shape)
# Add encoder features
dec_s2 = dec_s2 + enc_s2
dec_s2_cls = self.dec_s2_cls(dec_s2)
keep_s2 = (dec_s2_cls.F > 0).squeeze()
# target = self.get_target(dec_s2, target_key)
# targets.append(target)
# out_cls.append(dec_s2_cls)
# if self.training:
# keep_s2 += target
# Remove voxels s2
dec_s2 = self.pruning(dec_s2, keep_s2)
##################################################
# Decoder 2 -> 1
##################################################
dec_s1 = self.dec_block_s2s1(dec_s2)
# print("dec_s1","$$$$$$$$$$$$$$$$$$",dec_s1.coordinates.max(),dec_s1.features.shape)
dec_s1_cls = self.dec_s1_cls(dec_s1)
# Add encoder features
dec_s1 = dec_s1 + enc_s1
dec_s1_cls = self.dec_s1_cls(dec_s1)
keep_s1 = (dec_s1_cls.F > 0).squeeze()
# target = self.get_target(dec_s1, target_key)
# targets.append(target)
# out_cls.append(dec_s1_cls)
# Last layer does not require adding the target
# if self.training:
# keep_s1 += target
# Remove voxels s1
# dec_s1 = self.pruning(dec_s1, keep_s1)
dec_s1 = self.pruning_last(dec_s1, keep_s1)
dec_s1 = self.head(dec_s1)
dec_s1 = self.normalize(dec_s1)
# print("dec_s1","$$$$$$$$$$$$$$$$$$",dec_s1.coordinates.max(),dec_s1.features.shape)
return dec_s1 # , self.to_dense(dec_s1)
def conv3d(in_channels, out_channels, kernel_size, bias, padding):
return nn.Conv3d(in_channels, out_channels, kernel_size, padding=padding, bias=bias)
def create_conv(in_channels, out_channels, kernel_size, order, num_groups, padding):
"""
Create a list of modules with together constitute a single conv layer with non-linearity
and optional batchnorm/groupnorm.
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
kernel_size(int or tuple): size of the convolving kernel
order (string): order of things, e.g.
'cr' -> conv + ReLU
'gcr' -> groupnorm + conv + ReLU
'cl' -> conv + LeakyReLU
'ce' -> conv + ELU
'bcr' -> batchnorm + conv + ReLU
num_groups (int): number of groups for the GroupNorm
padding (int or tuple): add zero-padding added to all three sides of the input
Return:
list of tuple (name, module)
"""
assert 'c' in order, "Conv layer MUST be present"
assert order[0] not in 'rle', 'Non-linearity cannot be the first operation in the layer'
modules = []
for i, char in enumerate(order):
if char == 'r':
modules.append(('ReLU', nn.ReLU(inplace=True)))
elif char == 'l':
modules.append(('LeakyReLU', nn.LeakyReLU(inplace=True)))
elif char == 'e':
modules.append(('ELU', nn.ELU(inplace=True)))
elif char == 'c':
# add learnable bias only in the absence of batchnorm/groupnorm
bias = not ('g' in order or 'b' in order)
modules.append(('conv', conv3d(in_channels, out_channels, kernel_size, bias, padding=padding)))
elif char == 'g':
is_before_conv = i < order.index('c')
if is_before_conv:
num_channels = in_channels
else:
num_channels = out_channels
# use only one group if the given number of groups is greater than the number of channels
if num_channels < num_groups:
num_groups = 1
assert num_channels % num_groups == 0, f'Expected number of channels in input to be divisible by num_groups. num_channels={num_channels}, num_groups={num_groups}'
modules.append(('groupnorm', nn.GroupNorm(num_groups=num_groups, num_channels=num_channels)))
elif char == 'b':
is_before_conv = i < order.index('c')
if is_before_conv:
modules.append(('batchnorm', nn.BatchNorm3d(in_channels)))
else:
modules.append(('batchnorm', nn.BatchNorm3d(out_channels)))
else:
raise ValueError(f"Unsupported layer type '{char}'. MUST be one of ['b', 'g', 'r', 'l', 'e', 'c']")
return modules
class SingleConv(nn.Sequential):
"""
Basic convolutional module consisting of a Conv3d, non-linearity and optional batchnorm/groupnorm. The order
of operations can be specified via the `order` parameter
Args:
in_channels (int): number of input channels
out_channels (int): number of output channels
kernel_size (int or tuple): size of the convolving kernel
order (string): determines the order of layers, e.g.
'cr' -> conv + ReLU
'crg' -> conv + ReLU + groupnorm
'cl' -> conv + LeakyReLU
'ce' -> conv + ELU
num_groups (int): number of groups for the GroupNorm
padding (int or tuple):
"""
def __init__(self, in_channels, out_channels, kernel_size=3, order='gcr', num_groups=8, padding=1):
super(SingleConv, self).__init__()
for name, module in create_conv(in_channels, out_channels, kernel_size, order, num_groups, padding=padding):
self.add_module(name, module)
class DoubleConv(nn.Sequential):
"""
A module consisting of two consecutive convolution layers (e.g. BatchNorm3d+ReLU+Conv3d).
We use (Conv3d+ReLU+GroupNorm3d) by default.