forked from torch-points3d/torch-points3d
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathdense.py
492 lines (401 loc) · 18.1 KB
/
dense.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
import logging
import torch
from torch.nn import Sequential
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Conv1d
import torch_points_kernels as tp
from torch_points3d.core.base_conv.dense import *
from torch_points3d.core.common_modules.dense_modules import MLP2D
from torch_points3d.core.spatial_ops import DenseFPSSampler, DenseRadiusNeighbourFinder
from torch_points3d.utils.colors import COLORS
log = logging.getLogger(__name__)
class RSConvMapper(nn.Module):
"""[This class handles the special mechanism between the msg
and the features of RSConv]
"""
def __init__(self, down_conv_nn, use_xyz, bn=True, activation=nn.LeakyReLU(negative_slope=0.01), *args, **kwargs):
super(RSConvMapper, self).__init__()
self._down_conv_nn = down_conv_nn
self._use_xyz = use_xyz
self.nn = nn.ModuleDict()
if len(self._down_conv_nn) == 2: # First layer
self._first_layer = True
f_in, f_intermediate, f_out = self._down_conv_nn[0]
self.nn["features_nn"] = MLP2D(self._down_conv_nn[1], bn=bn, bias=False)
else:
self._first_layer = False
f_in, f_intermediate, f_out = self._down_conv_nn
self.nn["mlp_msg"] = MLP2D([f_in, f_intermediate, f_out], bn=bn, bias=False)
self.nn["norm"] = Sequential(*[nn.BatchNorm2d(f_out), activation])
self._f_out = f_out
@property
def f_out(self):
return self._f_out
def forward(self, features, msg):
"""
features -- [B, C, num_points, nsamples]
msg -- [B, 10, num_points, nsamples]
The 10 features comes from [distance: 1,
coord_origin:3,
coord_target:3,
delta_origin_target:3]
"""
# Transform msg
msg = self.nn["mlp_msg"](msg)
# If first_layer, augment features_size
if self._first_layer:
features = self.nn["features_nn"](features)
return self.nn["norm"](torch.mul(features, msg))
class SharedRSConv(nn.Module):
"""
Input shape: (B, C_in, npoint, nsample)
Output shape: (B, C_out, npoint)
"""
def __init__(self, mapper: RSConvMapper, radius):
super(SharedRSConv, self).__init__()
self._mapper = mapper
self._radius = radius
def forward(self, aggr_features, centroids):
"""
aggr_features -- [B, 3 + 3 + C, num_points, nsamples]
centroids -- [B, 3, num_points, 1]
"""
# Extract information to create message
abs_coord = aggr_features[:, :3] # absolute coordinates
delta_x = aggr_features[:, 3:6] # normalized coordinates
features = aggr_features[:, 3:]
nsample = abs_coord.shape[-1]
coord_xi = centroids.repeat(1, 1, 1, nsample) # (B, 3, npoint, nsample) centroid points
distance = torch.norm(delta_x, p=2, dim=1).unsqueeze(1) # Calculate distance
# Create message by contenating distance, origin / target coords, delta coords
h_xi_xj = torch.cat((distance, coord_xi, abs_coord, delta_x), dim=1)
return self._mapper(features, h_xi_xj)
def __repr__(self):
return "{}(radius={})".format(self.__class__.__name__, self._radius)
class RSConvSharedMSGDown(BaseDenseConvolutionDown):
def __init__(
self,
npoint=None,
radii=None,
nsample=None,
down_conv_nn=None,
channel_raising_nn=None,
bn=True,
use_xyz=True,
activation=nn.ReLU(),
**kwargs
):
assert len(radii) == len(nsample)
if len(radii) != len(down_conv_nn):
log.warn("The down_conv_nn has a different size as radii. Make sure of have SharedRSConv")
super(RSConvSharedMSGDown, self).__init__(
DenseFPSSampler(num_to_sample=npoint), DenseRadiusNeighbourFinder(radii, nsample), **kwargs
)
self.use_xyz = use_xyz
self.npoint = npoint
self.mlps = nn.ModuleList()
# https://github.com/Yochengliu/Relation-Shape-CNN/blob/6464eb8bb4efc686adec9da437112ef888e55684/utils/pointnet2_modules.py#L106
self._mapper = RSConvMapper(down_conv_nn, activation=activation, use_xyz=self.use_xyz)
self.mlp_out = Sequential(
*[
Conv1d(channel_raising_nn[0], channel_raising_nn[-1], kernel_size=1, stride=1, bias=True),
nn.BatchNorm1d(channel_raising_nn[-1]),
activation,
]
)
for i in range(len(radii)):
self.mlps.append(SharedRSConv(self._mapper, radii[i]))
def _prepare_features(self, x, pos, new_pos, idx):
new_pos_trans = pos.transpose(1, 2).contiguous()
grouped_pos_absolute = tp.grouping_operation(new_pos_trans, idx) # (B, 3, npoint, nsample)
centroids = new_pos.transpose(1, 2).unsqueeze(-1)
grouped_pos_normalized = grouped_pos_absolute - centroids
if x is not None:
grouped_features = tp.grouping_operation(x, idx)
if self.use_xyz:
new_features = torch.cat(
[grouped_pos_absolute, grouped_pos_normalized, grouped_features], dim=1
) # (B, 3 + 3 + C, npoint, nsample)
else:
new_features = grouped_features
else:
assert self.use_xyz, "Cannot have not features and not use xyz as a feature!"
new_features = torch.cat(
[grouped_pos_absolute, grouped_pos_normalized], dim=1
) # (B, 3 + 3 npoint, nsample)
return new_features, centroids
def conv(self, x, pos, new_pos, radius_idx, scale_idx):
""" Implements a Dense convolution where radius_idx represents
the indexes of the points in x and pos to be agragated into the new feature
for each point in new_pos
Arguments:
x -- Previous features [B, N, C]
pos -- Previous positions [B, N, 3]
new_pos -- Sampled positions [B, npoints, 3]
radius_idx -- Indexes to group [B, npoints, nsample]
scale_idx -- Scale index in multiscale convolutional layers
Returns:
new_x -- Features after passing trhough the MLP [B, mlp[-1], npoints]
"""
assert scale_idx < len(self.mlps)
aggr_features, centroids = self._prepare_features(x, pos, new_pos, radius_idx)
new_features = self.mlps[scale_idx](aggr_features, centroids) # (B, mlp[-1], npoint, nsample)
new_features = F.max_pool2d(new_features, kernel_size=[1, new_features.size(3)]) # (B, mlp[-1], npoint, 1)
new_features = self.mlp_out(new_features.squeeze(-1)) # (B, mlp[-1], npoint)
return new_features
def __repr__(self):
return "{}({}, shared: {} {}, {} {})".format(
self.__class__.__name__,
self.mlps.__repr__(),
COLORS.Cyan,
self.mlp_out.__repr__(),
self._mapper.__repr__(),
COLORS.END_TOKEN,
)
######################################################################
class OriginalRSConv(nn.Module):
"""
Input shape: (B, C_in, npoint, nsample)
Output shape: (B, C_out, npoint)
"""
def __init__(self, mapping=None, first_layer=False, radius=None, activation=nn.ReLU(inplace=True)):
super(OriginalRSConv, self).__init__()
self.nn = nn.ModuleList()
self._radius = radius
self.mapping_func1 = mapping[0]
self.mapping_func2 = mapping[1]
self.cr_mapping = mapping[2]
self.first_layer = first_layer
if first_layer:
self.xyz_raising = mapping[3]
self.bn_xyz_raising = nn.BatchNorm2d(self.xyz_raising.out_channels)
self.nn.append(self.bn_xyz_raising)
self.bn_mapping = nn.BatchNorm2d(self.mapping_func1.out_channels)
self.bn_rsconv = nn.BatchNorm2d(self.cr_mapping.in_channels)
self.bn_channel_raising = nn.BatchNorm1d(self.cr_mapping.out_channels)
self.nn.append(self.bn_mapping)
self.nn.append(self.bn_rsconv)
self.nn.append(self.bn_channel_raising)
self.activation = activation
def forward(self, input): # input: (B, 3 + 3 + C_in, npoint, centroid + nsample)
x = input[:, 3:, :, :] # (B, C_in, npoint, nsample+1), input features
nsample = x.size()[3]
abs_coord = input[:, 0:3, :, :] # (B, 3, npoint, nsample+1), absolute coordinates
delta_x = input[:, 3:6, :, :] # (B, 3, npoint, nsample+1), normalized coordinates
coord_xi = abs_coord[:, :, :, 0:1].repeat(1, 1, 1, nsample) # (B, 3, npoint, nsample), centroid point
h_xi_xj = torch.norm(delta_x, p=2, dim=1).unsqueeze(1)
h_xi_xj = torch.cat((h_xi_xj, coord_xi, abs_coord, delta_x), dim=1)
h_xi_xj = self.mapping_func2(self.activation(self.bn_mapping(self.mapping_func1(h_xi_xj))))
if self.first_layer:
x = self.activation(self.bn_xyz_raising(self.xyz_raising(x)))
x = F.max_pool2d(self.activation(self.bn_rsconv(torch.mul(h_xi_xj, x))), kernel_size=(1, nsample)).squeeze(
3
) # (B, C_in, npoint)
x = self.activation(self.bn_channel_raising(self.cr_mapping(x)))
return x
def __repr__(self):
return "{}({})".format(self.__class__.__name__, self.nn.__repr__())
class RSConvOriginalMSGDown(BaseDenseConvolutionDown):
def __init__(
self,
npoint=None,
radii=None,
nsample=None,
down_conv_nn=None,
channel_raising_nn=None,
bn=True,
bias=True,
use_xyz=True,
activation=nn.ReLU(),
**kwargs
):
assert len(radii) == len(nsample)
if len(radii) != len(down_conv_nn):
log.warning("The down_conv_nn has a different size as radii. Make sure of have SharedRSConv")
super(RSConvOriginalMSGDown, self).__init__(
DenseFPSSampler(num_to_sample=npoint), DenseRadiusNeighbourFinder(radii, nsample), **kwargs
)
self.use_xyz = use_xyz
self.mlps = nn.ModuleList()
self.mappings = nn.ModuleList()
self._first_layer = True if len(down_conv_nn) == 2 else False
if self._first_layer:
C_in, C_intermediate, C_out = down_conv_nn[0]
feat_in, f_out = down_conv_nn[-1]
xyz_raising = nn.Conv2d(
in_channels=feat_in, out_channels=f_out, kernel_size=(1, 1), stride=(1, 1), bias=bias,
)
nn.init.kaiming_normal_(xyz_raising.weight)
if bias:
nn.init.constant_(xyz_raising.bias, 0)
else:
C_in, C_intermediate, C_out = down_conv_nn
mapping_func1 = nn.Conv2d(
in_channels=C_in, out_channels=C_intermediate, kernel_size=(1, 1), stride=(1, 1), bias=bias,
)
mapping_func2 = nn.Conv2d(
in_channels=C_intermediate, out_channels=C_out, kernel_size=(1, 1), stride=(1, 1), bias=bias,
)
nn.init.kaiming_normal_(mapping_func1.weight)
nn.init.kaiming_normal_(mapping_func2.weight)
if bias:
nn.init.constant_(mapping_func1.bias, 0)
nn.init.constant_(mapping_func2.bias, 0)
# channel raising mapping
cr_mapping = nn.Conv1d(
in_channels=channel_raising_nn[0], out_channels=channel_raising_nn[1], kernel_size=1, stride=1, bias=bias,
)
nn.init.kaiming_normal_(cr_mapping.weight)
nn.init.constant_(cr_mapping.bias, 0)
if self._first_layer:
mapping = [mapping_func1, mapping_func2, cr_mapping, xyz_raising]
elif npoint is not None:
mapping = [mapping_func1, mapping_func2, cr_mapping]
for m in mapping:
self.mappings.append(m)
for radius in radii:
self.mlps.append(OriginalRSConv(mapping=mapping, first_layer=self._first_layer, radius=radius))
def _prepare_features(
self, xyz: torch.Tensor, new_xyz: torch.Tensor, features: torch.Tensor = None, idx: torch.Tensor = None
) -> torch.Tensor:
"""
Parameters
----------
xyz : torch.Tensor
xyz coordinates of the features (B, N, 3)
new_xyz : torch.Tensor
centriods (B, npoint, 3)
features : torch.Tensor
Descriptors of the features (B, C, N)
Returns
-------
new_features : torch.Tensor
(B, 3 + C, npoint, nsample) tensor
"""
xyz_trans = xyz.transpose(1, 2).contiguous()
grouped_xyz = tp.grouping_operation(xyz_trans, idx) # (B, 3, npoint, nsample)
raw_grouped_xyz = grouped_xyz
grouped_xyz -= new_xyz.transpose(1, 2).unsqueeze(-1)
if features is not None:
grouped_features = tp.grouping_operation(features, idx)
if self.use_xyz:
new_features = torch.cat(
[raw_grouped_xyz, grouped_xyz, grouped_features], dim=1
) # (B, 3 + 3 + C, npoint, nsample)
else:
new_features = grouped_features
else:
assert self.use_xyz, "Cannot have not features and not use xyz as a feature!"
new_features = torch.cat([raw_grouped_xyz, grouped_xyz], dim=1)
return new_features
def conv(self, x, pos, new_pos, radius_idx, scale_idx):
""" Implements a Dense convolution where radius_idx represents
the indexes of the points in x and pos to be agragated into the new feature
for each point in new_pos
Arguments:
x -- Previous features [B, N, C]
pos -- Previous positions [B, N, 3]
new_pos -- Sampled positions [B, npoints, 3]
radius_idx -- Indexes to group [B, npoints, nsample]
scale_idx -- Scale index in multiscale convolutional layers
Returns:
new_x -- Features after passing trhough the MLP [B, mlp[-1], npoints]
"""
assert scale_idx < len(self.mlps)
aggr_features = self._prepare_features(pos, new_pos, x, radius_idx)
new_features = self.mlps[scale_idx](
aggr_features
) # (B, 3 + 3 + C, npoint, nsample) -> (B, mlp[-1], npoint, nsample)
return new_features
def __repr__(self):
return "{}: {} ({}, shared: {} {} {})".format(
self.__class__.__name__,
self.nb_params,
self.mlps.__repr__(),
COLORS.Cyan,
self.mappings.__repr__(),
COLORS.END_TOKEN,
)
class RSConvMSGDown(BaseDenseConvolutionDown):
def __init__(
self,
npoint=None,
radii=None,
nsample=None,
down_conv_nn=None,
channel_raising_nn=None,
bn=True,
bias=True,
use_xyz=True,
activation=nn.ReLU(),
**kwargs
):
assert len(radii) == len(nsample)
if len(radii) != len(down_conv_nn):
log.warning("The down_conv_nn has a different size as radii. Make sure to have sharedMLP")
super(RSConvMSGDown, self).__init__(
DenseFPSSampler(num_to_sample=npoint), DenseRadiusNeighbourFinder(radii, nsample), **kwargs
)
self.use_xyz = use_xyz
self.npoint = npoint
self.mlps = nn.ModuleList()
# https://github.com/Yochengliu/Relation-Shape-CNN/blob/6464eb8bb4efc686adec9da437112ef888e55684/utils/pointnet2_modules.py#L106
self.mlp_out = Sequential(
*[
Conv1d(channel_raising_nn[0], channel_raising_nn[-1], kernel_size=1, stride=1, bias=True),
nn.BatchNorm1d(channel_raising_nn[-1]),
activation,
]
)
for i in range(len(radii)):
mapper = RSConvMapper(down_conv_nn, activation=activation, use_xyz=self.use_xyz)
self.mlps.append(SharedRSConv(mapper, radii[i]))
self._mapper = mapper
def _prepare_features(self, x, pos, new_pos, idx):
new_pos_trans = pos.transpose(1, 2).contiguous()
grouped_pos_absolute = tp.grouping_operation(new_pos_trans, idx) # (B, 3, npoint, nsample)
centroids = new_pos.transpose(1, 2).unsqueeze(-1)
grouped_pos_normalized = grouped_pos_absolute - centroids
if x is not None:
grouped_features = tp.grouping_operation(x, idx)
if self.use_xyz:
new_features = torch.cat(
[grouped_pos_absolute, grouped_pos_normalized, grouped_features], dim=1
) # (B, 3 + 3 + C, npoint, nsample)
else:
new_features = grouped_features
else:
assert self.use_xyz, "Cannot have not features and not use xyz as a feature!"
new_features = torch.cat(
[grouped_pos_absolute, grouped_pos_normalized], dim=1
) # (B, 3 + 3 npoint, nsample)
return new_features, centroids
def conv(self, x, pos, new_pos, radius_idx, scale_idx):
""" Implements a Dense convolution where radius_idx represents
the indexes of the points in x and pos to be agragated into the new feature
for each point in new_pos
Arguments:
x -- Previous features [B, N, C]
pos -- Previous positions [B, N, 3]
new_pos -- Sampled positions [B, npoints, 3]
radius_idx -- Indexes to group [B, npoints, nsample]
scale_idx -- Scale index in multiscale convolutional layers
Returns:
new_x -- Features after passing trhough the MLP [B, mlp[-1], npoints]
"""
assert scale_idx < len(self.mlps)
aggr_features, centroids = self._prepare_features(x, pos, new_pos, radius_idx)
new_features = self.mlps[scale_idx](aggr_features, centroids) # (B, mlp[-1], npoint, nsample)
new_features = F.max_pool2d(new_features, kernel_size=[1, new_features.size(3)]) # (B, mlp[-1], npoint, 1)
new_features = self.mlp_out(new_features.squeeze(-1)) # (B, mlp[-1], npoint)
return new_features
def __repr__(self):
return "{}({}, shared: {} {}, {} {})".format(
self.__class__.__name__,
self.mlps.__repr__(),
COLORS.Cyan,
self.mlp_out.__repr__(),
self._mapper.__repr__(),
COLORS.END_TOKEN,
)