-
Notifications
You must be signed in to change notification settings - Fork 0
/
util_occ.py
3398 lines (2846 loc) · 157 KB
/
util_occ.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 torch
import torch.nn as nn
import torch.nn.functional as F
from time import time
import numpy as np
import math
import spconv
from einops import rearrange, repeat
from einops.layers.torch import Rearrange, Reduce
from torch_scatter import scatter_softmax, scatter_sum,scatter_mul
from pointops2.functions import pointops
from lib import pointnet2_utils as pointutils
LEAKY_RATE = 0.1
use_bn = False
# use_leaky = False
occ_threshold = 0.6
def timeit(tag, t):
print("{}: {}s".format(tag, time() - t))
return time()
def square_distance(src, dst):
"""
Calculate Euclid distance between each two points.
src^T * dst = xn * xm + yn * ym + zn * zm;
sum(src^2, dim=-1) = xn*xn + yn*yn + zn*zn;
sum(dst^2, dim=-1) = xm*xm + ym*ym + zm*zm;
dist = (xn - xm)^2 + (yn - ym)^2 + (zn - zm)^2
= sum(src**2,dim=-1)+sum(dst**2,dim=-1)-2*src^T*dst
Input:
src: source points, [B, N, C]
dst: target points, [B, M, C]
Output:
dist: per-point square distance, [B, N, M]
"""
B, N, _ = src.shape
_, M, _ = dst.shape
dist = -2 * torch.matmul(src, dst.permute(0, 2, 1))
dist += torch.sum(src ** 2, -1).view(B, N, 1)
dist += torch.sum(dst ** 2, -1).view(B, 1, M)
return dist
def index_points(points, idx):
"""
Input:
points: input points data, [B, N, C]
idx: sample index data, [B, S]
Return:
new_points:, indexed points data, [B, S, C]
"""
device = points.device
B,_,C = points.shape
view_shape = list(idx.shape)
view_shape[1:] = [1] * (len(view_shape) - 1)
repeat_shape = list(idx.shape)
repeat_shape[0] = 1
batch_indices = torch.arange(B, dtype=torch.long).to(device).view(view_shape).repeat(repeat_shape)
new_points = points[batch_indices, idx.long(), :]
# points_flatten = points.reshape(-1, C).contiguous()
# idx_flatten = idx.reshape(-1).contiguous().to(device)
# new_points = (points_flatten[idx_flatten, :]).reshape(B,-1,C).contiguous()
return new_points
def farthest_point_sample(xyz, npoint):
"""
Input:
xyz: pointcloud data, [B, N, C]
npoint: number of samples
Return:
centroids: sampled pointcloud index, [B, npoint]
"""
device = xyz.device
B, N, C = xyz.shape
centroids = torch.zeros(B, npoint, dtype=torch.long).to(device)
distance = torch.ones(B, N).to(device) * 1e10
farthest = torch.randint(0, N, (B,), dtype=torch.long).to(device)
batch_indices = torch.arange(B, dtype=torch.long).to(device)
for i in range(npoint):
centroids[:, i] = farthest
centroid = xyz[batch_indices, farthest, :].view(B, 1, 3)
dist = torch.sum((xyz - centroid) ** 2, -1)
mask = dist < distance
distance[mask] = dist[mask]
farthest = torch.max(distance, -1)[1]
return centroids
def knn_point(k, pos1, pos2):
'''
Input:
k: int32, number of k in k-nn search
pos1: (batch_size, ndataset, c) float32 array, input points
pos2: (batch_size, npoint, c) float32 array, query points
Output:
val: (batch_size, npoint, k) float32 array, L2 distances
idx: (batch_size, npoint, k) int32 array, indices to input points
'''
B, N, C = pos1.shape
M = pos2.shape[1]
pos1 = pos1.view(B,1,N,-1).repeat(1,M,1,1)
pos2 = pos2.view(B,M,1,-1).repeat(1,1,N,1)
dist = torch.sum(-(pos1-pos2)**2,-1)
val,idx = dist.topk(k=k,dim = -1)
return torch.sqrt(-val), idx
def query_ball_point(radius, nsample, xyz, new_xyz):
"""
Input:
radius: local region radius
nsample: max sample number in local region
xyz: all points, [B, N, C]
new_xyz: query points, [B, S, C]
Return:
group_idx: grouped points index, [B, S, nsample]
"""
device = xyz.device
B, N, C = xyz.shape
_, S, _ = new_xyz.shape
group_idx = torch.arange(N, dtype=torch.long).to(device).view(1, 1, N).repeat([B, S, 1])
sqrdists = square_distance(new_xyz, xyz)
group_idx[sqrdists > radius ** 2] = N
mask = group_idx != N
cnt = mask.sum(dim=-1)
group_idx = group_idx.sort(dim=-1)[0][:, :, :nsample]
group_first = group_idx[:, :, 0].view(B, S, 1).repeat([1, 1, nsample])
mask = group_idx == N
group_idx[mask] = group_first[mask]
return group_idx, cnt
def sample_and_group(npoint, radius, nsample, xyz, points, returnfps=False):
"""
Input:
npoint:
radius:
nsample:
xyz: input points position data, [B, N, C]
points: input points data, [B, N, D]
Return:
new_xyz: sampled points position data, [B, 1, C]
new_points: sampled points data, [B, 1, N, C+D]
"""
B, N, C = xyz.shape
S = npoint
fps_idx = farthest_point_sample(xyz, npoint) # [B, npoint, C]
new_xyz = index_points(xyz, fps_idx)
idx, _ = query_ball_point(radius, nsample, xyz, new_xyz)
grouped_xyz = index_points(xyz, idx) # [B, npoint, nsample, C]
grouped_xyz_norm = grouped_xyz - new_xyz.view(B, S, 1, C)
if points != None:
grouped_points = index_points(points, idx)
new_points = torch.cat([grouped_xyz_norm, grouped_points], dim=-1) # [B, npoint, nsample, C+D]
else:
new_points = grouped_xyz_norm
if returnfps:
return new_xyz, new_points, grouped_xyz, fps_idx
else:
return new_xyz, new_points
def sample_and_group_all(xyz, points):
"""
Input:
xyz: input points position data, [B, N, C]
points: input points data, [B, N, D]
Return:
new_xyz: sampled points position data, [B, 1, C]
new_points: sampled points data, [B, 1, N, C+D]
"""
device = xyz.device
B, N, C = xyz.shape
new_xyz = torch.zeros(B, 1, C).to(device)
grouped_xyz = xyz.view(B, 1, N, C)
if points != None:
new_points = torch.cat([grouped_xyz, points.view(B, 1, N, -1)], dim=-1)
else:
new_points = grouped_xyz
return new_xyz, new_points
def index_points_group(points, knn_idx):
"""
Input:
points: input points data, [B, N, C]
knn_idx: sample index data, [B, N, K]
Return:
new_points:, indexed points data, [B, N, K, C]
"""
points_flipped = points.permute(0, 2, 1).contiguous()
new_points = pointutils.grouping_operation(points_flipped, knn_idx.int()).permute(0, 2, 3, 1)
return new_points
def group_query(nsample, s_xyz, xyz, s_points):
"""
Input:
nsample: scalar
s_xyz: input points position data, [B, N, C]
s_points: input points data, [B, N, D]
xyz: input points position data, [B, S, C]
Return:
new_xyz: sampled points position data, [B, 1, C]
new_points: sampled points data, [B, 1, N, C+D]
"""
B, N, C = s_xyz.shape
S = xyz.shape[1]
new_xyz = xyz
# idx = knn_point(nsample, s_xyz, new_xyz)[1]
_, idx = pointutils.knn(nsample, new_xyz, s_xyz)
grouped_xyz = index_points_group(s_xyz, idx) # [B, npoint, nsample, C]
grouped_xyz_norm = grouped_xyz - new_xyz.view(B, S, 1, C)
if s_points is not None:
grouped_points = index_points_group(s_points, idx)
new_points = torch.cat([grouped_xyz_norm, grouped_points], dim=-1) # [B, npoint, nsample, C+D]
else:
new_points = grouped_xyz_norm
return new_points, grouped_xyz_norm
class PointNetSetAbstraction(nn.Module):
def __init__(self, npoint, radius, nsample, in_channel, mlp, mlp2 = None, group_all = False):
super(PointNetSetAbstraction, self).__init__()
self.npoint = npoint
self.radius = radius
self.nsample = nsample
self.group_all = group_all
self.mlp_convs = nn.ModuleList()
self.mlp_bns = nn.ModuleList()
self.mlp2_convs = nn.ModuleList()
last_channel = in_channel+3
for out_channel in mlp:
self.mlp_convs.append(nn.Conv2d(last_channel, out_channel, 1, bias = False))
self.mlp_bns.append(nn.BatchNorm2d(out_channel))
last_channel = out_channel
if mlp2 != None:
for out_channel in mlp2:
self.mlp2_convs.append(nn.Sequential(nn.Conv1d(last_channel, out_channel, 1, bias=False),
nn.BatchNorm1d(out_channel)))
last_channel = out_channel
# if group_all:
# self.queryandgroup = pointutils.GroupAll()
# else:
# self.queryandgroup = pointutils.QueryAndGroup(radius, nsample)
def forward(self, xyz, points):
"""
Input:
xyz: input points position data, [B, C, N]
points: input points data, [B, D, N]
Return:
new_xyz: sampled points position data, [B, S, C]
new_points_concat: sample points feature data, [B, S, D']
"""
device = xyz.device
B, C, N = xyz.shape
xyz_t = xyz.permute(0, 2, 1).contiguous()
# if points != None:
# points = points.permute(0, 2, 1).contiguous()
# 选取邻域点
if self.group_all == False:
fps_idx = pointutils.furthest_point_sample(xyz_t, self.npoint) # [B, N]
new_xyz = pointutils.gather_operation(xyz, fps_idx) # [B, C, N]
else:
new_xyz = xyz
# new_points = self.queryandgroup(xyz_t, new_xyz.transpose(2, 1).contiguous(), points) # [B, 3+C, N, S]
new_xyz_t = new_xyz.permute(0,2,1).contiguous()
points_t = points.permute(0,2,1).contiguous()
# new_points = self.queryandgroup(xyz_t, new_xyz.transpose(2, 1).contiguous(), points) # [B, 3+C, N, S]
new_points, grouped_xyz_norm = group_query(self.nsample, xyz_t, new_xyz_t, points_t) # [B, N, S, 3+C]
new_points = new_points.permute(0,3,1,2).contiguous()
# new_xyz: sampled points position data, [B, C, npoint]
# new_points: sampled points data, [B, C+D, npoint, nsample]
for i, conv in enumerate(self.mlp_convs):
bn = self.mlp_bns[i]
new_points = F.relu(bn(conv(new_points)))
new_points = torch.max(new_points, -1)[0]
for i, conv in enumerate(self.mlp2_convs):
new_points = F.relu(conv(new_points))
return new_xyz, new_points, fps_idx
class FlowEmbedding(nn.Module):
def __init__(self, radius, nsample, in_channel, mlp, pooling='max', corr_func='concat', knn = True):
super(FlowEmbedding, self).__init__()
self.radius = radius
self.nsample = nsample
self.knn = knn
self.pooling = pooling
self.corr_func = corr_func
self.mlp_convs = nn.ModuleList()
self.mlp_bns = nn.ModuleList()
if corr_func == 'concat':
last_channel = in_channel*2+3
for out_channel in mlp:
self.mlp_convs.append(nn.Conv2d(last_channel, out_channel, 1, bias=False))
self.mlp_bns.append(nn.BatchNorm2d(out_channel))
last_channel = out_channel
def forward(self, pos1, pos2, feature1, feature2):
"""
Input:
xyz1: (batch_size, 3, npoint)
xyz2: (batch_size, 3, npoint)
feat1: (batch_size, channel, npoint)
feat2: (batch_size, channel, npoint)
Output:
xyz1: (batch_size, 3, npoint)
feat1_new: (batch_size, mlp[-1], npoint)
"""
pos1_t = pos1.permute(0, 2, 1).contiguous()
pos2_t = pos2.permute(0, 2, 1).contiguous()
B, N, C = pos1_t.shape
if self.knn:
_, idx = pointutils.knn(self.nsample, pos1_t, pos2_t)
else:
# If the ball neighborhood points are less than nsample,
# than use the knn neighborhood points
idx, cnt = query_ball_point(self.radius, self.nsample, pos2_t, pos1_t)
# 利用knn取最近的那些点
_, idx_knn = pointutils.knn(self.nsample, pos1_t, pos2_t)
cnt = cnt.view(B, -1, 1).repeat(1, 1, self.nsample)
idx = idx_knn[cnt > (self.nsample-1)]
pos2_grouped = pointutils.grouping_operation(pos2, idx) # [B, 3, N, S]
pos_diff = pos2_grouped - pos1.view(B, -1, N, 1) # [B, 3, N, S]
feat2_grouped = pointutils.grouping_operation(feature2, idx) # [B, C, N, S]
if self.corr_func=='concat':
feat_diff = torch.cat([feat2_grouped, feature1.view(B, -1, N, 1).repeat(1, 1, 1, self.nsample)], dim = 1)
feat1_new = torch.cat([pos_diff, feat_diff], dim = 1) # [B, 2*C+3,N,S]
for i, conv in enumerate(self.mlp_convs):
bn = self.mlp_bns[i]
feat1_new = F.relu(bn(conv(feat1_new)))
feat1_new = torch.max(feat1_new, -1)[0] # [B, mlp[-1], npoint]
return pos1, feat1_new
class PointNetSetUpConv(nn.Module):
def __init__(self, nsample, radius, f1_channel, f2_channel, mlp, mlp2, knn = True):
super(PointNetSetUpConv, self).__init__()
self.nsample = nsample
self.radius = radius
self.knn = knn
self.mlp1_convs = nn.ModuleList()
self.mlp2_convs = nn.ModuleList()
last_channel = f2_channel+3
for out_channel in mlp:
self.mlp1_convs.append(nn.Sequential(nn.Conv2d(last_channel, out_channel, 1, bias=False),
nn.BatchNorm2d(out_channel),
nn.ReLU(inplace=False)))
last_channel = out_channel
if len(mlp) != 0:
last_channel = mlp[-1] + f1_channel
else:
last_channel = last_channel + f1_channel
for out_channel in mlp2:
self.mlp2_convs.append(nn.Sequential(nn.Conv1d(last_channel, out_channel, 1, bias=False),
nn.BatchNorm1d(out_channel),
nn.ReLU(inplace=False)))
last_channel = out_channel
def forward(self, pos1, pos2, feature1, feature2):
"""
Feature propagation from xyz2 (less points) to xyz1 (more points)
Inputs:
xyz1: (batch_size, 3, npoint1)
xyz2: (batch_size, 3, npoint2)
feat1: (batch_size, channel1, npoint1) features for xyz1 points (earlier layers, more points)
feat2: (batch_size, channel1, npoint2) features for xyz2 points
Output:
feat1_new: (batch_size, npoint2, mlp[-1] or mlp2[-1] or channel1+3)
TODO: Add support for skip links. Study how delta(XYZ) plays a role in feature updating.
"""
pos1_t = pos1.permute(0, 2, 1).contiguous()
pos2_t = pos2.permute(0, 2, 1).contiguous()
B,C,N = pos1.shape
if self.knn:
_, idx = pointutils.knn(self.nsample, pos1_t, pos2_t)
else:
idx, _ = query_ball_point(self.radius, self.nsample, pos2_t, pos1_t)
pos2_grouped = pointutils.grouping_operation(pos2, idx)
pos_diff = pos2_grouped - pos1.view(B, -1, N, 1) # [B,3,N1,S]
feat2_grouped = pointutils.grouping_operation(feature2, idx)
feat_new = torch.cat([feat2_grouped, pos_diff], dim = 1) # [B,C1+3,N1,S]
for conv in self.mlp1_convs:
feat_new = conv(feat_new)
# max pooling
feat_new = feat_new.max(-1)[0] # [B,mlp1[-1],N1]
# concatenate feature in early layer
if feature1 != None:
feat_new = torch.cat([feat_new, feature1], dim=1)
# feat_new = feat_new.view(B,-1,N,1)
for conv in self.mlp2_convs:
feat_new = conv(feat_new)
return feat_new
class PointNetFeaturePropogation(nn.Module):
def __init__(self, in_channel, mlp):
super(PointNetFeaturePropogation, self).__init__()
self.mlp_convs = nn.ModuleList()
self.mlp_bns = nn.ModuleList()
last_channel = in_channel
for out_channel in mlp:
self.mlp_convs.append(nn.Conv1d(last_channel, out_channel, 1))
self.mlp_bns.append(nn.BatchNorm1d(out_channel))
last_channel = out_channel
def forward(self, pos1, pos2, feature1, feature2):
"""
Input:
xyz1: input points position data, [B, C, N]
xyz2: sampled input points position data, [B, C, S]
points1: input points data, [B, D, N]
points2: input points data, [B, D, S]
Return:
new_points: upsampled points data, [B, D', N]
"""
pos1_t = pos1.permute(0, 2, 1).contiguous()
pos2_t = pos2.permute(0, 2, 1).contiguous()
B, C, N = pos1.shape
# dists = square_distance(pos1, pos2)
# dists, idx = dists.sort(dim=-1)
# dists, idx = dists[:, :, :3], idx[:, :, :3] # [B, N, 3]
dists,idx = pointutils.three_nn(pos1_t,pos2_t)
dists[dists < 1e-10] = 1e-10
weight = 1.0 / dists
weight = weight / torch.sum(weight, -1,keepdim = True) # [B,N,3]
interpolated_feat = torch.sum(pointutils.grouping_operation(feature2, idx) * weight.view(B, 1, N, 3), dim = -1) # [B,C,N,3]
if feature1 != None:
feat_new = torch.cat([interpolated_feat, feature1], 1)
else:
feat_new = interpolated_feat
for i, conv in enumerate(self.mlp_convs):
bn = self.mlp_bns[i]
feat_new = F.relu(bn(conv(feat_new)))
return feat_new
class PointMixerInterSetLayerGroupMLP(nn.Module):
def __init__(self, in_planes, share_planes, nsample=16, radius=1.0, use_xyz=False):
super().__init__()
self.nsample = nsample
self.radius = radius
self.share_planes = share_planes
self.linear = nn.Linear(in_planes, in_planes//share_planes) # input.shape = [N*K, C]
self.linear_x = nn.Linear(in_planes, in_planes//share_planes) # input.shape = [N*K, C]
self.linear_p = nn.Sequential( # input.shape = [N*K, C]
nn.Linear(3, 3, bias=False),
nn.BatchNorm1d(3),
nn.ReLU(inplace=True),
nn.Linear(3, in_planes))
def forward(self, pos, feats):
"""
Feature propagation from xyz2 (less points) to xyz1 (more points)
Inputs:
xyz1: (batch_size, 3, npoint1)
xyz2: (batch_size, 3, npoint2)
feat1: (batch_size, channel1, npoint1) features for xyz1 points (earlier layers, more points)
feat2: (batch_size, channel1, npoint2) features for xyz2 points
Output:
feat1_new: (batch_size, npoint2, mlp[-1] or mlp2[-1] or channel1+3)
TODO: Add support for skip links. Study how delta(XYZ) plays a role in feature updating.
"""
pos_t = pos.permute(0, 2, 1).contiguous()
B,C,N = pos.shape
if self.knn:
_, idx = pointutils.knn(self.nsample, pos_t, pos_t)
else:
idx, _ = query_ball_point(self.radius, self.nsample, pos_t, pos_t)
pos_grouped = pointutils.grouping_operation(pos, idx)
pos_diff = pos_grouped - pos.view(B, -1, N, 1) # [B,3,N1,S]
# x, x_knn, knn_idx, p_r = input
# N = x_knn.shape[0]
with torch.no_grad():
knn_idx_flatten = rearrange(knn_idx, 'n k -> (n k) 1')
p_r_flatten = rearrange(p_r, 'n k c -> (n k) c')
p_embed_flatten = self.linear_p(p_r_flatten)
x_knn_flatten = rearrange(x_knn, 'n k c -> (n k) c')
x_knn_flatten_shrink = self.linear(x_knn_flatten + p_embed_flatten) # nk c'
x_knn_prob_flatten_shrink = \
scatter_softmax(x_knn_flatten_shrink, knn_idx_flatten, dim=0) # (n*nsample, c')
x_v_knn_flatten = self.linear_x(x_knn_flatten) # (n*nsample, c')
x_knn_weighted_flatten = x_v_knn_flatten * x_knn_prob_flatten_shrink # (n*nsample, c')
residual = scatter_sum(x_knn_weighted_flatten, knn_idx_flatten, dim=0, dim_size=N) # (n, c')
residual = repeat(residual, 'n c -> n (repeat c)', repeat=self.share_planes)
return x + residual
'''
为了解决基于距离权重上采样带来的偏差(强假设:局部邻域的运动一致性,但是点云的稠密程度不一致,在低分辨率时容易带来较大的误差),采用了基于VFE的特征提取方法,并利用参考点的VFE与KNN近邻得到的K个点基于估计的SF在目标域和源域分别采样对应的VFE,然后计算KNN的距离差值,以及VFE_SRC和VFE_TGT,即(Delta_dist, VFE_SRC, VFE_TGT)基于CNN网络得到K个加权值,然后得到对应的高密度的点云的对应的粗略场景流信息。
'''
class UpsampleSFFeaturePropogation(nn.Module):
def __init__(self, nsample, radius, f1_channel, f2_channel, mlp, mlp2, knn = True):
super(UpsampleSFFeaturePropogation, self).__init__()
self.nsample = nsample
self.radius = radius
self.knn = knn
self.mlp1_convs = nn.ModuleList()
self.mlp2_convs = nn.ModuleList()
last_channel = f2_channel+3
for out_channel in mlp:
self.mlp1_convs.append(nn.Sequential(nn.Conv2d(last_channel, out_channel, 1, bias=False),
nn.BatchNorm2d(out_channel),
nn.ReLU(inplace=False)))
last_channel = out_channel
if len(mlp) != 0:
last_channel = mlp[-1] + f1_channel
else:
last_channel = last_channel + f1_channel
for out_channel in mlp2:
self.mlp2_convs.append(nn.Sequential(nn.Conv1d(last_channel, out_channel, 1, bias=False),
nn.BatchNorm1d(out_channel),
nn.ReLU(inplace=False)))
last_channel = out_channel
def forward(self, pos1, pos2, feats1, feats2, sparse_sf):
"""
Feature propagation from xyz2 (less points) to xyz1 (more points)
Inputs:
xyz1: (batch_size, 3, npoint1)
xyz2: (batch_size, 3, npoint2)
feat1: (batch_size, channel1, npoint1) features for xyz1 points (earlier layers, more points)
feat2: (batch_size, channel1, npoint2) features for xyz2 points
Output:
feat1_new: (batch_size, npoint2, mlp[-1] or mlp2[-1] or channel1+3)
TODO: Add support for skip links. Study how delta(XYZ) plays a role in feature updating.
"""
pos1_t = pos1.permute(0, 2, 1).contiguous()
pos2_t = pos2.permute(0, 2, 1).contiguous()
B,C,N = pos1.shape
if self.knn:
_, idx = pointutils.knn(self.nsample, pos1_t, pos2_t)
else:
idx, _ = query_ball_point(self.radius, self.nsample, pos2_t, pos1_t)
pos2_grouped = pointutils.grouping_operation(pos2, idx)
pos_diff = pos2_grouped - pos1.view(B, -1, N, 1) # [B,3,N1,S]
feat2_grouped = pointutils.grouping_operation(feats2, idx)
feat_new = torch.cat([feat2_grouped, pos_diff], dim = 1) # [B,C1+3,N1,S]
class BilinearFeedForward(nn.Module):
def __init__(self, in_planes1, in_planes2, out_planes):
super().__init__()
self.bilinear = nn.Bilinear(in_planes1, in_planes2, out_planes)
def forward(self, x):
x = x.contiguous()
x = self.bilinear(x, x)
return x
class PointMixerIntraSetLayerPaper(nn.Module):
expansion = 1
def __init__(self, in_planes, out_planes, share_planes=8, nsample=16):
super().__init__()
mid_planes = out_planes
self.out_planes = out_planes
self.share_planes = share_planes
self.nsample = nsample
self.channelMixMLPs01 = nn.Sequential( # input.shape = [N, K, C]
nn.Linear(3+in_planes, nsample),
nn.ReLU(inplace=True),
BilinearFeedForward(nsample, nsample, nsample))
self.linear_p = nn.Sequential( # input.shape = [N, K, C]
nn.Linear(3, 3),
nn.Sequential(
Rearrange('n k c -> n c k'),
nn.BatchNorm1d(3),
Rearrange('n c k -> n k c')),
nn.ReLU(inplace=True),
nn.Linear(3, out_planes))
self.shrink_p = nn.Sequential(
Rearrange('n k (a b) -> n k a b', b=nsample),
Reduce('n k a b -> n k b', 'sum', b=nsample))
self.channelMixMLPs02 = nn.Sequential( # input.shape = [N, K, C]
Rearrange('n k c -> n c k'),
nn.Conv1d(nsample+nsample, mid_planes, kernel_size=1, bias=False),
nn.BatchNorm1d(mid_planes),
nn.ReLU(inplace=True),
nn.Conv1d(mid_planes, mid_planes//share_planes, kernel_size=1, bias=False),
nn.BatchNorm1d(mid_planes//share_planes),
nn.ReLU(inplace=True),
nn.Conv1d(mid_planes//share_planes, out_planes//share_planes, kernel_size=1),
Rearrange('n c k -> n k c'))
self.channelMixMLPs03 = nn.Linear(in_planes, out_planes)
self.softmax = nn.Softmax(dim=1)
def forward(self, pxo, mask=None):
p, x, o = pxo # (n, 3), (n, c), (b)
x_knn, knn_idx = pointops.queryandgroup(
self.nsample, p, p, x, None, o, o, use_xyz=True, return_idx=True) # (n, k, 3+c)
p_r = x_knn[:, :, 0:3]
energy = self.channelMixMLPs01(x_knn) # (n, k, k)
p_embed = self.linear_p(p_r) # (n, k, out_planes)
p_embed_shrink = self.shrink_p(p_embed) # (n, k, k)
energy = torch.cat([energy, p_embed_shrink], dim=-1)
energy = self.channelMixMLPs02(energy) # (n, k, out_planes/share_planes)
w = self.softmax(energy)
x_v = self.channelMixMLPs03(x) # (n, in_planes) -> (n, k)
n = knn_idx.shape[0]; knn_idx_flatten = knn_idx.flatten()
x_v = x_v[knn_idx_flatten, :].view(n, self.nsample, -1)
n, nsample, out_planes = x_v.shape
x_knn = (x_v + p_embed).view(n, nsample, self.share_planes, out_planes//self.share_planes)
x_knn = (x_knn * w.unsqueeze(2))
x_knn = x_knn.reshape(n, nsample, out_planes)
if mask != None:
mask_flatten = mask[knn_idx, :].view(n, self.nsample, -1)
x_knn = x_knn * mask_flatten
x = x_knn.sum(1)
return (x, x_knn, knn_idx, p_r)
class PointMixerIntraSetLayerPaperv3(nn.Module):
expansion = 1
def __init__(self, in_planes, out_planes, share_planes=8, nsample=16):
super().__init__()
mid_planes = out_planes // 1
self.out_planes = out_planes
self.share_planes = share_planes
self.nsample = nsample
self.channelMixMLPs01 = nn.Sequential( # input.shape = [N*K, C]
nn.Linear(3+in_planes, nsample),
nn.ReLU(inplace=True),
BilinearFeedForward(nsample, nsample, nsample))
self.linear_p = nn.Sequential( # input.shape = [N*K, C]
nn.Linear(3, 3),
nn.BatchNorm1d(3),
nn.ReLU(inplace=True),
nn.Linear(3, out_planes))
self.shrink_p = nn.Sequential(
Rearrange('n k (a b) -> n k a b', b=nsample),
Reduce('n k a b -> (n k) b', 'sum', b=nsample))
self.channelMixMLPs02 = nn.Sequential( # input.shape = [N*K, C]
nn.Linear(nsample+nsample, mid_planes, bias=False),
nn.BatchNorm1d(mid_planes),
nn.ReLU(inplace=True),
nn.Linear(mid_planes, mid_planes//share_planes, bias=False),
nn.BatchNorm1d(mid_planes//share_planes),
nn.ReLU(inplace=True),
nn.Linear(mid_planes//share_planes, out_planes//share_planes, bias=True),
Rearrange('(n k) c -> n k c', k=nsample))
self.channelMixMLPs03 = nn.Linear(in_planes, out_planes)
self.softmax = nn.Softmax(dim=1)
def forward(self, pxo) -> torch.Tensor:
p, x, o = pxo # (n, 3), (n, c), (b)
x_knn, knn_idx = pointops.queryandgroup(
self.nsample, p, p, x, None, o, o, use_xyz=True, return_idx=True) # (n, k, 3+c)
p_r = x_knn[:, :, 0:3]
x_knn_flatten = rearrange(x_knn, 'n k c -> (n k) c')
energy_flatten = self.channelMixMLPs01(x_knn_flatten) # (n*k, k)
n = p_r.shape[0];
p_embed = self.linear_p(p_r.view(-1, 3)) # (n*k, out_planes)
p_embed = p_embed.view(n, self.nsample, -1)
p_embed_shrink_flatten = self.shrink_p(p_embed) # (n*k, k)
energy_flatten = torch.cat([energy_flatten, p_embed_shrink_flatten], dim=-1) # (n*k, 2k)
energy = self.channelMixMLPs02(energy_flatten) # (n, k, out_planes/share_planes)
w = self.softmax(energy)
x_v = self.channelMixMLPs03(x) # (n, in_planes) -> (n, k)
n = knn_idx.shape[0]; knn_idx_flatten = knn_idx.flatten()
x_v = x_v[knn_idx_flatten, :].view(n, self.nsample, -1)
n, nsample, out_planes = x_v.shape
x_knn = (x_v + p_embed).view(n, nsample, self.share_planes, out_planes//self.share_planes)
x_knn = (x_knn * w.unsqueeze(2))
x_knn = x_knn.reshape(n, nsample, out_planes)
x = x_knn.sum(1)
return (x, x_knn, knn_idx, p_r)
class PointMixerInterSetLayerGroupMLPv3(nn.Module):
def __init__(self, in_planes, share_planes, nsample=16, use_xyz=False):
super().__init__()
self.share_planes = share_planes
self.linear = nn.Linear(in_planes, in_planes//share_planes) # input.shape = [N*K, C]
self.linear_x = nn.Linear(in_planes, in_planes//share_planes) # input.shape = [N*K, C]
self.linear_p = nn.Sequential( # input.shape = [N*K, C]
nn.Linear(3, 3, bias=False),
nn.BatchNorm1d(3),
nn.ReLU(inplace=True),
nn.Linear(3, in_planes))
def forward(self, input):
x, x_knn, knn_idx, p_r = input
N = x_knn.shape[0]
with torch.no_grad():
knn_idx_flatten = rearrange(knn_idx, 'n k -> (n k) 1')
p_r_flatten = rearrange(p_r, 'n k c -> (n k) c')
p_embed_flatten = self.linear_p(p_r_flatten)
x_knn_flatten = rearrange(x_knn, 'n k c -> (n k) c')
x_knn_flatten_shrink = self.linear(x_knn_flatten + p_embed_flatten) # nk c'
x_knn_prob_flatten_shrink = \
scatter_softmax(x_knn_flatten_shrink, knn_idx_flatten, dim=0) # (n*nsample, c')
x_v_knn_flatten = self.linear_x(x_knn_flatten) # (n*nsample, c')
x_knn_weighted_flatten = x_v_knn_flatten * x_knn_prob_flatten_shrink # (n*nsample, c')
residual = scatter_sum(x_knn_weighted_flatten, knn_idx_flatten, dim=0, dim_size=N) # (n, c')
residual = repeat(residual, 'n c -> n (repeat c)', repeat=self.share_planes)
return x + residual
###########################################################################
class PointMixerBlock(nn.Module):
def __init__(self, in_planes, planes, share_planes=8, nsample=16, use_xyz=False):
super().__init__()
self.expansion = 1
# assert self.intraLayer is not None
# assert self.interLayer is not None
self.transformer2 = nn.Sequential(
PointMixerIntraSetLayerPaper(planes, planes, share_planes, nsample),
PointMixerInterSetLayerGroupMLPv3(in_planes, nsample, share_planes)
)
self.linear1 = nn.Linear(in_planes, planes, bias=False)
self.bn1 = nn.BatchNorm1d(planes)
self.bn2 = nn.BatchNorm1d(planes)
self.linear3 = nn.Linear(planes, planes*self.expansion, bias=False)
self.bn3 = nn.BatchNorm1d(planes*self.expansion)
self.relu = nn.ReLU(inplace=True)
def forward(self, pxo):
p, x, o = pxo # (n, 3), (n, c), (b)
identity = x
x = self.relu(self.bn1(self.linear1(x)))
x = self.relu(self.bn2(self.transformer2([p, x, o])))
x = self.bn3(self.linear3(x))
x = x + identity
x = self.relu(x)
return [p, x, o]
class PointMixerBlockPaperInterSetLayerGroupMLPv3(PointMixerBlock):
expansion = 1
intraLayer = PointMixerIntraSetLayerPaper
interLayer = PointMixerInterSetLayerGroupMLPv3
##############################################################################################
class SymmetricTransitionUpBlock(nn.Module):
def __init__(self, in_planes, out_planes=None, nsample=16):
super().__init__()
self.nsample = nsample
if out_planes is None:
self.linear1 = nn.Sequential(
nn.Linear(2*in_planes, in_planes),
nn.BatchNorm1d(in_planes),
nn.ReLU(inplace=True))
self.linear2 = nn.Sequential(
nn.Linear(in_planes, in_planes),
nn.ReLU(inplace=True))
else:
self.linear1 = nn.Sequential( # input.shape = [N, L]
nn.Linear(out_planes, out_planes),
nn.BatchNorm1d(out_planes),
nn.ReLU(inplace=True))
self.linear2 = nn.Sequential( # input.shape = [N, L]
nn.Linear(in_planes, out_planes),
nn.BatchNorm1d(out_planes),
nn.ReLU(inplace=True))
self.channel_shrinker = nn.Sequential( # input.shape = [N*K, L]
nn.Linear(in_planes+3, in_planes),
Rearrange('n k c -> n c k'),
nn.BatchNorm1d(in_planes),
Rearrange('n c k -> n k c'),
# nn.BatchNorm1d(in_planes),
nn.ReLU(inplace=True),
nn.Linear(in_planes, 1))
def forward(self, pxo1, pxo2=None):
if pxo2 is None:
_, x, o = pxo1 # (n, 3), (n, c), (b)
x_tmp = []
for i in range(o.shape[0]):
if i == 0:
s_i, e_i, cnt = 0, o[0], o[0]
else:
s_i, e_i, cnt = o[i-1], o[i], o[i] - o[i-1]
x_b = x[s_i:e_i, :]
x_b = torch.cat((x_b, self.linear2(x_b.sum(0, True) / cnt).repeat(cnt, 1)), 1)
x_tmp.append(x_b)
x = torch.cat(x_tmp, 0)
y = self.linear1(x) # this part is the same as TransitionUp module.
else:
p1, x1, o1 = pxo1; p2, x2, o2 = pxo2
# device = p1.device
# p2 = p2.to(device)
# x2 = x2.to(device)
# o2 = o2.to(device)
# print(device)
knn_idx = pointops.knnquery(self.nsample, p1, p2, o1, o2)[0].long()
with torch.no_grad():
knn_idx_flatten = rearrange(knn_idx, 'm k -> (m k)')
p_r = p1[knn_idx_flatten, :].view(len(p2), self.nsample, 3) - p2.unsqueeze(1)
x2_knn = x2.view(len(p2), 1, -1).repeat(1, self.nsample, 1)
x2_knn = torch.cat([p_r, x2_knn], dim=-1) # (109, 16, 259) # (m, nsample, 3+c)
with torch.no_grad():
knn_idx_flatten = knn_idx_flatten.unsqueeze(-1) # (m*nsample, 1)
# print(x2_knn_flatten.device)
x2_knn_shrink = self.channel_shrinker(x2_knn) # (m * nsample, 1)
x2_knn_flatten_shrink = rearrange(x2_knn_shrink, 'm k c -> (m k) c') # c = 3+out_planes
x2_knn_prob_flatten_shrink = scatter_softmax(x2_knn_flatten_shrink, knn_idx_flatten, dim=0)
x2_knn_prob_shrink = rearrange(x2_knn_prob_flatten_shrink, '(m k) 1 -> m k 1', k=self.nsample)
up_x2_weighted = self.linear2(x2).unsqueeze(1) * x2_knn_prob_shrink # (m, nsample, c)
up_x2_weighted_flatten = rearrange(up_x2_weighted, 'm k c -> (m k) c')
up_x2 = scatter_sum(up_x2_weighted_flatten, knn_idx_flatten, dim=0, dim_size=len(p1))
y = self.linear1(x1) + up_x2
return y
##############################################################################################
class SymmetricTransitionDownBlockPaperv3(nn.Module):
def __init__(self, in_planes, out_planes, stride=1, nsample=16):
super().__init__()
self.stride, self.nsample = stride, nsample
if stride != 1:
self.linear2 = nn.Sequential( # input.shape = [N, L]
nn.Linear(in_planes, out_planes, bias=False),
nn.BatchNorm1d(out_planes),
nn.ReLU(inplace=True))
self.channel_shrinker = nn.Sequential( # input.shape = [N*K, L]
nn.Linear(3+in_planes, in_planes, bias=False),
nn.BatchNorm1d(in_planes),
nn.ReLU(inplace=True),
nn.Linear(in_planes, 1))
else:
self.linear2 = nn.Sequential(
nn.Linear(in_planes, out_planes, bias=False),
nn.BatchNorm1d(out_planes),
nn.ReLU(inplace=True))
def forward(self, pxo):
p, x, o = pxo # (n, 3), (n, c), (b)
if self.stride != 1:
n_o, count = [o[0].item() // self.stride], o[0].item() // self.stride
for i in range(1, o.shape[0]):
count += (o[i].item() - o[i-1].item()) // self.stride
n_o.append(count)
n_o = torch.cuda.IntTensor(n_o)
idx = pointops.furthestsampling(p, o, n_o) # (m)
n_p = p[idx.long(), :] # (m, 3)
x_knn, knn_idx = pointops.queryandgroup(
self.nsample, p, n_p, x, None, o, n_o, use_xyz=True, return_idx=True) # (m, nsample, 3+c)
m, k, c = x_knn.shape
x_knn_flatten = rearrange(x_knn, 'm k c -> (m k) c')
x_knn_flatten_shrink = self.channel_shrinker(x_knn_flatten) # (m*nsample, 1)
x_knn_shrink = rearrange(x_knn_flatten_shrink, '(m k) c -> m k c', m=m, k=k)
x_knn_prob_shrink = F.softmax(x_knn_shrink, dim=1)
y = self.linear2(x) # (n, c)
with torch.no_grad():
knn_idx_flatten = rearrange(knn_idx, 'm k -> (m k)')
y_knn_flatten = y[knn_idx_flatten, :] # (m*nsample, c)
y_knn = rearrange(y_knn_flatten, '(m k) c -> m k c', m=m, k=k)
x_knn_weighted = y_knn * x_knn_prob_shrink # (m, nsample, c_out)
y = torch.sum(x_knn_weighted, dim=1).contiguous() # (m, c_out)
p, o = n_p, n_o
else:
idx = pointops.furthestsampling(p, o, o) # (m)
y = self.linear2(x) # (n, c)
return [p, y, o, idx]
'''
基于估计的场景流信息在目标域搜索对应的K个邻域信息;先根据参考点的邻域计算一个平均的相关参数,作为稀疏阈值;然后将邻域点按照不同的分辨率Voxelize,构造出不同分辨率级别的VFE特征,依次利用关联操作以及稀疏阈值选择操作,结合scatter操作concat到一起,通过进行加权或者cnn+maxpooling/GRU对应的权重信息;组合不同级别的特信息;分别输出对应的权重和用于估计遮挡信息的掩膜特征。
Method 1: 参考SAC方法构建motion featrue 的选择方法
Method 1: 参考PointMixer方法构建Cost Volume
'''
# class CostVolumeNet(nn.Module):
# def __init__(self, nsample, in_channel, mid_channel, share_channel, out_channel,
# intraLayer='PointMixerIntraSetLayer',
# interLayer='PointMixerInterSetLayer',
# transup='SymmetricTransitionUpBlock',
# transdown='TransitionDownBlock'):
# super().__init__()
# self.nsample = nsample
# self.mid_channel = mid_channel
# self.share_channel = share_channel
# self.out_channel = out_channel
# self.channelMixMLPs01 = nn.Sequential( # input.shape = [N, K, C]
# nn.Linear(3+in_channel*2, nsample),
# nn.ReLU(inplace=True),
# BilinearFeedForward(nsample, nsample, nsample))
# self.channelMixMLPs01_2 = nn.Sequential( # input.shape = [N, K, C]
# nn.Linear(3+out_channel*2, nsample),
# nn.ReLU(inplace=True),
# BilinearFeedForward(nsample, nsample, nsample))
# self.linear_p = nn.Sequential( # input.shape = [N, K, C]
# nn.Linear(3, out_channel//2),
# nn.Sequential(
# Rearrange('n k c -> n c k'),
# nn.BatchNorm1d(out_channel//2),
# Rearrange('n c k -> n k c')),
# nn.ReLU(inplace=True),
# nn.Linear(out_channel//2, out_channel))
# self.shrink_p = nn.Sequential(
# Rearrange('n k (a b) -> n k a b', b=nsample),
# Reduce('n k a b -> n k b', 'sum', b=nsample))
# self.channelMixMLPs02 = nn.Sequential( # input.shape = [N, K, C]
# Rearrange('n k c -> n c k'),
# nn.Conv1d(nsample+nsample, mid_channel, kernel_size=1, bias=False),
# nn.BatchNorm1d(mid_channel),
# nn.ReLU(inplace=True),
# nn.Conv1d(mid_channel, mid_channel//share_channel, kernel_size=1, bias=False),
# nn.BatchNorm1d(mid_channel//share_channel),
# nn.ReLU(inplace=True),
# nn.Conv1d(mid_channel//share_channel, out_channel//share_channel, kernel_size=1),
# Rearrange('n c k -> n k c'))
# self.channelMixMLPs02_2 = nn.Sequential( # input.shape = [N, K, C]
# Rearrange('n k c -> n c k'),
# nn.Conv1d(nsample+nsample, mid_channel, kernel_size=1, bias=False),
# nn.BatchNorm1d(mid_channel),
# nn.ReLU(inplace=True),
# nn.Conv1d(mid_channel, mid_channel//share_channel, kernel_size=1, bias=False),
# nn.BatchNorm1d(mid_channel//share_channel),