openpoints 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- openpoints/__init__.py +3 -0
- openpoints/cpp/__init__.py +6 -0
- openpoints/cpp/chamfer_dist/__init__.py +110 -0
- openpoints/cpp/chamfer_dist/setup.py +19 -0
- openpoints/cpp/chamfer_dist/test.py +34 -0
- openpoints/cpp/emd/__init__.py +3 -0
- openpoints/cpp/emd/emd.py +88 -0
- openpoints/cpp/emd/setup.py +27 -0
- openpoints/cpp/emd/test_emd_loss.py +45 -0
- openpoints/cpp/pointnet2_batch/__init__.py +24 -0
- openpoints/cpp/pointnet2_batch/setup.py +23 -0
- openpoints/cpp/pointops/__init__.py +0 -0
- openpoints/cpp/pointops/functions/__init__.py +0 -0
- openpoints/cpp/pointops/functions/pointops.py +314 -0
- openpoints/cpp/pointops/setup.py +37 -0
- openpoints/cpp/pointops/src/__init__.py +0 -0
- openpoints/dataset/__init__.py +10 -0
- openpoints/dataset/atom3d/__init__.py +1 -0
- openpoints/dataset/atom3d/psr.py +38 -0
- openpoints/dataset/build.py +98 -0
- openpoints/dataset/data_util.py +192 -0
- openpoints/dataset/datalist.py +67 -0
- openpoints/dataset/dataset_base.py +96 -0
- openpoints/dataset/graph_dataset/__init__.py +3 -0
- openpoints/dataset/graph_dataset/graph_dataset.py +93 -0
- openpoints/dataset/graph_dataset/stack_with_pad.py +91 -0
- openpoints/dataset/graph_dataset/structural_dataset.py +73 -0
- openpoints/dataset/graph_dataset/svd_encodings_dataset.py +110 -0
- openpoints/dataset/grid_sample.py +21 -0
- openpoints/dataset/matterport3d/__init__.py +1 -0
- openpoints/dataset/matterport3d/category_mapping.tsv +1660 -0
- openpoints/dataset/matterport3d/matterport3d.py +210 -0
- openpoints/dataset/matterport3d/matterport3d_dataprocessing.py +105 -0
- openpoints/dataset/modelnet/__init__.py +3 -0
- openpoints/dataset/modelnet/modelnet40_normal_resampled_loader.py +124 -0
- openpoints/dataset/modelnet/modelnet40_ply_2048_loader.py +160 -0
- openpoints/dataset/molhiv/__init__.py +1 -0
- openpoints/dataset/molhiv/data.py +59 -0
- openpoints/dataset/molpcba/__init__.py +1 -0
- openpoints/dataset/molpcba/data.py +59 -0
- openpoints/dataset/parsers/__init__.py +1 -0
- openpoints/dataset/parsers/class_map.py +19 -0
- openpoints/dataset/parsers/constants.py +1 -0
- openpoints/dataset/parsers/parser.py +17 -0
- openpoints/dataset/parsers/parser_factory.py +29 -0
- openpoints/dataset/parsers/parser_image_folder.py +69 -0
- openpoints/dataset/parsers/parser_image_in_tar.py +222 -0
- openpoints/dataset/parsers/parser_image_tar.py +72 -0
- openpoints/dataset/parsers/parser_tfds.py +297 -0
- openpoints/dataset/pcqm4m/__init__.py +1 -0
- openpoints/dataset/pcqm4m/data.py +62 -0
- openpoints/dataset/pcqm4mv2/__init__.py +1 -0
- openpoints/dataset/pcqm4mv2/data.py +87 -0
- openpoints/dataset/s3dis/__init__.py +2 -0
- openpoints/dataset/s3dis/s3dis.py +156 -0
- openpoints/dataset/s3dis/s3dis_block.py +96 -0
- openpoints/dataset/s3dis/s3dis_sphere.py +349 -0
- openpoints/dataset/scannetv2/__init__.py +1 -0
- openpoints/dataset/scannetv2/scannet.py +176 -0
- openpoints/dataset/scanobjectnn/__init__.py +3 -0
- openpoints/dataset/scanobjectnn/scanobjectnn.py +110 -0
- openpoints/dataset/semantic_kitti/__init__.py +1 -0
- openpoints/dataset/semantic_kitti/helper_tool.py +286 -0
- openpoints/dataset/semantic_kitti/label_mapping.yaml +211 -0
- openpoints/dataset/semantic_kitti/semantickitti.py +229 -0
- openpoints/dataset/semantic_kitti/utils/meta/anno_paths.txt +272 -0
- openpoints/dataset/semantic_kitti/utils/meta/class_names.txt +13 -0
- openpoints/dataset/semantic_kitti/utils/semantic-kitti.yaml +211 -0
- openpoints/dataset/shapenet/__init__.py +1 -0
- openpoints/dataset/shapenet/shapenet55.py +76 -0
- openpoints/dataset/shapenet/shapenetpart.py +121 -0
- openpoints/dataset/shapenetpart/__init__.py +1 -0
- openpoints/dataset/shapenetpart/shapenet55.py +75 -0
- openpoints/dataset/shapenetpart/shapenetpart.py +388 -0
- openpoints/dataset/vis2d.py +17 -0
- openpoints/dataset/vis3d.py +153 -0
- openpoints/loss/__init__.py +3 -0
- openpoints/loss/build.py +281 -0
- openpoints/loss/cross_entropy.py +38 -0
- openpoints/loss/distill_loss.py +76 -0
- openpoints/models/__init__.py +10 -0
- openpoints/models/backbone/Stratified_transformer.py +558 -0
- openpoints/models/backbone/__init__.py +11 -0
- openpoints/models/backbone/baafnet.py +527 -0
- openpoints/models/backbone/ball_dgcnn.py +123 -0
- openpoints/models/backbone/curvenet.py +793 -0
- openpoints/models/backbone/debug_invvit.py +114 -0
- openpoints/models/backbone/deepgcn.py +143 -0
- openpoints/models/backbone/dgcnn.py +119 -0
- openpoints/models/backbone/graphvit3d.py +134 -0
- openpoints/models/backbone/grouppointnet.py +100 -0
- openpoints/models/backbone/pct.py +163 -0
- openpoints/models/backbone/pointmlp.py +417 -0
- openpoints/models/backbone/pointnet.py +199 -0
- openpoints/models/backbone/pointnetv2.py +511 -0
- openpoints/models/backbone/pointnext.py +663 -0
- openpoints/models/backbone/pointnextPyG.py +555 -0
- openpoints/models/backbone/pointtransformer.py +293 -0
- openpoints/models/backbone/pointvector.py +853 -0
- openpoints/models/backbone/pointvit.py +392 -0
- openpoints/models/backbone/pointvit_inv.py +942 -0
- openpoints/models/backbone/pointvit_inv_old.py +784 -0
- openpoints/models/backbone/randlenet.py +318 -0
- openpoints/models/backbone/resnet.py +342 -0
- openpoints/models/backbone/simpleview.py +153 -0
- openpoints/models/backbone/simpleview_util.py +292 -0
- openpoints/models/build.py +13 -0
- openpoints/models/classification/__init__.py +5 -0
- openpoints/models/classification/cls_base.py +136 -0
- openpoints/models/classification/point_bert.py +154 -0
- openpoints/models/layers/__init__.py +14 -0
- openpoints/models/layers/activation.py +57 -0
- openpoints/models/layers/attention.py +103 -0
- openpoints/models/layers/conv.py +167 -0
- openpoints/models/layers/drop.py +164 -0
- openpoints/models/layers/graph_conv.py +122 -0
- openpoints/models/layers/group.py +415 -0
- openpoints/models/layers/group_embed.py +286 -0
- openpoints/models/layers/helpers.py +43 -0
- openpoints/models/layers/kmeans.py +119 -0
- openpoints/models/layers/knn.py +110 -0
- openpoints/models/layers/local_aggregation.py +286 -0
- openpoints/models/layers/mlp.py +129 -0
- openpoints/models/layers/norm.py +106 -0
- openpoints/models/layers/padding.py +56 -0
- openpoints/models/layers/patch_embed.py +37 -0
- openpoints/models/layers/registry.py +168 -0
- openpoints/models/layers/subsample.py +185 -0
- openpoints/models/layers/upsampling.py +106 -0
- openpoints/models/layers/weight_init.py +89 -0
- openpoints/models/reconstruction/__init__.py +8 -0
- openpoints/models/reconstruction/base_recontruct.py +216 -0
- openpoints/models/reconstruction/maskedpoint.py +116 -0
- openpoints/models/reconstruction/maskedpointgroup.py +168 -0
- openpoints/models/reconstruction/maskedpointvit.py +253 -0
- openpoints/models/reconstruction/nodeshuffle.py +11 -0
- openpoints/models/registry.py +149 -0
- openpoints/models/segmentation/__init__.py +6 -0
- openpoints/models/segmentation/base_seg.py +278 -0
- openpoints/models/segmentation/vit_seg.py +126 -0
- openpoints/optim/__init__.py +15 -0
- openpoints/optim/adabelief.py +201 -0
- openpoints/optim/adafactor.py +167 -0
- openpoints/optim/adahessian.py +156 -0
- openpoints/optim/adamp.py +105 -0
- openpoints/optim/adamw.py +122 -0
- openpoints/optim/lamb.py +192 -0
- openpoints/optim/lars.py +135 -0
- openpoints/optim/lookahead.py +61 -0
- openpoints/optim/madgrad.py +184 -0
- openpoints/optim/nadam.py +92 -0
- openpoints/optim/nvnovograd.py +120 -0
- openpoints/optim/optim_factory.py +306 -0
- openpoints/optim/radam.py +89 -0
- openpoints/optim/rmsprop_tf.py +139 -0
- openpoints/optim/sgdp.py +70 -0
- openpoints/scheduler/__init__.py +8 -0
- openpoints/scheduler/cosine_lr.py +124 -0
- openpoints/scheduler/multistep_lr.py +65 -0
- openpoints/scheduler/plateau_lr.py +113 -0
- openpoints/scheduler/poly_lr.py +116 -0
- openpoints/scheduler/scheduler.py +110 -0
- openpoints/scheduler/scheduler_factory.py +118 -0
- openpoints/scheduler/step_lr.py +65 -0
- openpoints/scheduler/tanh_lr.py +117 -0
- openpoints/transforms/__init__.py +7 -0
- openpoints/transforms/point_transform_cpu.py +332 -0
- openpoints/transforms/point_transformer_gpu.py +764 -0
- openpoints/transforms/transforms_factory.py +60 -0
- openpoints/utils/__init__.py +8 -0
- openpoints/utils/ckpt_util.py +438 -0
- openpoints/utils/config.py +113 -0
- openpoints/utils/dist_utils.py +54 -0
- openpoints/utils/logger.py +170 -0
- openpoints/utils/metrics.py +311 -0
- openpoints/utils/random.py +16 -0
- openpoints/utils/registry.py +294 -0
- openpoints/utils/str2bool.py +11 -0
- openpoints/utils/wandb.py +88 -0
- openpoints-0.1.0.dist-info/METADATA +150 -0
- openpoints-0.1.0.dist-info/RECORD +184 -0
- openpoints-0.1.0.dist-info/WHEEL +5 -0
- openpoints-0.1.0.dist-info/licenses/LICENSE +21 -0
- openpoints-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
|
|
2
|
+
import inspect
|
|
3
|
+
import warnings
|
|
4
|
+
from functools import partial
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Registry:
|
|
8
|
+
"""A registry to map strings to classes.
|
|
9
|
+
Args:
|
|
10
|
+
name (str): Registry name.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, name):
|
|
14
|
+
self._name = name
|
|
15
|
+
self._module_dict = dict()
|
|
16
|
+
|
|
17
|
+
def __len__(self):
|
|
18
|
+
return len(self._module_dict)
|
|
19
|
+
|
|
20
|
+
def __contains__(self, key):
|
|
21
|
+
return self.get(key) is not None
|
|
22
|
+
|
|
23
|
+
def __repr__(self):
|
|
24
|
+
format_str = self.__class__.__name__ + \
|
|
25
|
+
f'(name={self._name}, ' \
|
|
26
|
+
f'items={self._module_dict})'
|
|
27
|
+
return format_str
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def name(self):
|
|
31
|
+
return self._name
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def module_dict(self):
|
|
35
|
+
return self._module_dict
|
|
36
|
+
|
|
37
|
+
def get(self, key):
|
|
38
|
+
"""Get the registry record.
|
|
39
|
+
Args:
|
|
40
|
+
key (str): The class name in string format.
|
|
41
|
+
Returns:
|
|
42
|
+
class: The corresponding class.
|
|
43
|
+
"""
|
|
44
|
+
return self._module_dict.get(key, None)
|
|
45
|
+
|
|
46
|
+
def _register_module(self, module_class, module_name=None, force=False):
|
|
47
|
+
if not inspect.isclass(module_class):
|
|
48
|
+
raise TypeError('module must be a class, '
|
|
49
|
+
f'but got {type(module_class)}')
|
|
50
|
+
|
|
51
|
+
if module_name is None:
|
|
52
|
+
module_name = module_class.__name__
|
|
53
|
+
if not force and module_name in self._module_dict:
|
|
54
|
+
raise KeyError(f'{module_name} is already registered '
|
|
55
|
+
f'in {self.name}')
|
|
56
|
+
self._module_dict[module_name] = module_class
|
|
57
|
+
|
|
58
|
+
def deprecated_register_module(self, cls=None, force=False):
|
|
59
|
+
warnings.warn(
|
|
60
|
+
'The old API of register_module(module, force=False) '
|
|
61
|
+
'is deprecated and will be removed, please use the new API '
|
|
62
|
+
'register_module(name=None, force=False, module=None) instead.')
|
|
63
|
+
if cls is None:
|
|
64
|
+
return partial(self.deprecated_register_module, force=force)
|
|
65
|
+
self._register_module(cls, force=force)
|
|
66
|
+
return cls
|
|
67
|
+
|
|
68
|
+
def register_module(self, name=None, force=False, module=None):
|
|
69
|
+
"""Register a module.
|
|
70
|
+
A record will be added to `self._module_dict`, whose key is the class
|
|
71
|
+
name or the specified name, and value is the class itself.
|
|
72
|
+
It can be used as a decorator or a normal function.
|
|
73
|
+
Example:
|
|
74
|
+
>>> backbones = Registry('backbone')
|
|
75
|
+
>>> @backbones.register_module()
|
|
76
|
+
>>> class ResNet:
|
|
77
|
+
>>> pass
|
|
78
|
+
>>> backbones = Registry('backbone')
|
|
79
|
+
>>> @backbones.register_module(name='mnet')
|
|
80
|
+
>>> class MobileNet:
|
|
81
|
+
>>> pass
|
|
82
|
+
>>> backbones = Registry('backbone')
|
|
83
|
+
>>> class ResNet:
|
|
84
|
+
>>> pass
|
|
85
|
+
>>> backbones.register_module(ResNet)
|
|
86
|
+
Args:
|
|
87
|
+
name (str | None): The module name to be registered. If not
|
|
88
|
+
specified, the class name will be used.
|
|
89
|
+
force (bool, optional): Whether to override an existing class with
|
|
90
|
+
the same name. Default: False.
|
|
91
|
+
module (type): Module class to be registered.
|
|
92
|
+
"""
|
|
93
|
+
if not isinstance(force, bool):
|
|
94
|
+
raise TypeError(f'force must be a boolean, but got {type(force)}')
|
|
95
|
+
# NOTE: This is a walkaround to be compatible with the old api,
|
|
96
|
+
# while it may introduce unexpected bugs.
|
|
97
|
+
if isinstance(name, type):
|
|
98
|
+
return self.deprecated_register_module(name, force=force)
|
|
99
|
+
|
|
100
|
+
# use it as a normal method: x.register_module(module=SomeClass)
|
|
101
|
+
if module is not None:
|
|
102
|
+
self._register_module(
|
|
103
|
+
module_class=module, module_name=name, force=force)
|
|
104
|
+
return module
|
|
105
|
+
|
|
106
|
+
# raise the error ahead of time
|
|
107
|
+
if not (name is None or isinstance(name, str)):
|
|
108
|
+
raise TypeError(f'name must be a str, but got {type(name)}')
|
|
109
|
+
|
|
110
|
+
# use it as a decorator: @x.register_module()
|
|
111
|
+
def _register(cls):
|
|
112
|
+
self._register_module(
|
|
113
|
+
module_class=cls, module_name=name, force=force)
|
|
114
|
+
return cls
|
|
115
|
+
|
|
116
|
+
return _register
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def build_from_cfg(cfg, registry, default_args=None):
|
|
120
|
+
"""Build a module from config dict.
|
|
121
|
+
Args:
|
|
122
|
+
cfg (dict): Config dict. It should at least contain the key "type".
|
|
123
|
+
registry (:obj:`Registry`): The registry to search the type from.
|
|
124
|
+
default_args (dict, optional): Default initialization arguments.
|
|
125
|
+
Returns:
|
|
126
|
+
object: The constructed object.
|
|
127
|
+
"""
|
|
128
|
+
if not isinstance(cfg, dict):
|
|
129
|
+
raise TypeError(f'cfg must be a dict, but got {type(cfg)}')
|
|
130
|
+
if 'type' not in cfg:
|
|
131
|
+
if default_args is None or 'type' not in default_args:
|
|
132
|
+
raise KeyError(
|
|
133
|
+
'`cfg` or `default_args` must contain the key "type", '
|
|
134
|
+
f'but got {cfg}\n{default_args}')
|
|
135
|
+
if not isinstance(registry, Registry):
|
|
136
|
+
raise TypeError('registry must be an mmcv.Registry object, '
|
|
137
|
+
f'but got {type(registry)}')
|
|
138
|
+
if not (isinstance(default_args, dict) or default_args is None):
|
|
139
|
+
raise TypeError('default_args must be a dict or None, '
|
|
140
|
+
f'but got {type(default_args)}')
|
|
141
|
+
|
|
142
|
+
args = cfg.copy()
|
|
143
|
+
|
|
144
|
+
if default_args is not None:
|
|
145
|
+
for name, value in default_args.items():
|
|
146
|
+
args.setdefault(name, value)
|
|
147
|
+
|
|
148
|
+
obj_type = args.pop('type') # pop the type out, then leave the args for the class.
|
|
149
|
+
if isinstance(obj_type, str):
|
|
150
|
+
obj_cls = registry.get(obj_type)
|
|
151
|
+
if obj_cls is None:
|
|
152
|
+
raise KeyError(
|
|
153
|
+
f'{obj_type} is not in the {registry.name} registry. '
|
|
154
|
+
f'obj_type should be one of {list(registry._module_dict.keys())}. '
|
|
155
|
+
f'Check if any typo and make sure the capitalization is the same. ')
|
|
156
|
+
elif inspect.isclass(obj_type):
|
|
157
|
+
obj_cls = obj_type
|
|
158
|
+
else:
|
|
159
|
+
raise TypeError(
|
|
160
|
+
f'type must be a str or valid type, but got {type(obj_type)}')
|
|
161
|
+
|
|
162
|
+
return obj_cls(**args)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
NORM_LAYERS = Registry('norm layer')
|
|
166
|
+
ACTIVATION_LAYERS = Registry('activation layer')
|
|
167
|
+
CONV_LAYERS = Registry('conv layer')
|
|
168
|
+
DROPOUT_LAYERS = Registry('dropout layer')
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
# subsample layer for 3d processing.
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
import torch.nn as nn
|
|
6
|
+
from torch.autograd import Function
|
|
7
|
+
import math
|
|
8
|
+
from openpoints.cpp.pointnet2_batch import pointnet2_cuda
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class BaseSampler(ABC):
|
|
12
|
+
"""If num_to_sample is provided, sample exactly
|
|
13
|
+
num_to_sample points. Otherwise sample floor(pos[0] * ratio) points
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(self, ratio=None, num_to_sample=None, subsampling_param=None):
|
|
17
|
+
if num_to_sample is not None:
|
|
18
|
+
if (ratio is not None) or (subsampling_param is not None):
|
|
19
|
+
raise ValueError(
|
|
20
|
+
"Can only specify ratio or num_to_sample or subsampling_param, not several !")
|
|
21
|
+
self._num_to_sample = num_to_sample
|
|
22
|
+
|
|
23
|
+
elif ratio is not None:
|
|
24
|
+
self._ratio = ratio
|
|
25
|
+
|
|
26
|
+
elif subsampling_param is not None:
|
|
27
|
+
self._subsampling_param = subsampling_param
|
|
28
|
+
|
|
29
|
+
else:
|
|
30
|
+
raise Exception(
|
|
31
|
+
'At least ["ratio, num_to_sample, subsampling_param"] should be defined')
|
|
32
|
+
|
|
33
|
+
def __call__(self, xyz):
|
|
34
|
+
return self.sample(xyz)
|
|
35
|
+
|
|
36
|
+
def _get_num_to_sample(self, npoints) -> int:
|
|
37
|
+
if hasattr(self, "_num_to_sample"):
|
|
38
|
+
return self._num_to_sample
|
|
39
|
+
else:
|
|
40
|
+
return math.floor(npoints * self._ratio)
|
|
41
|
+
|
|
42
|
+
def _get_ratio_to_sample(self, batch_size) -> float:
|
|
43
|
+
if hasattr(self, "_ratio"):
|
|
44
|
+
return self._ratio
|
|
45
|
+
else:
|
|
46
|
+
return self._num_to_sample / float(batch_size)
|
|
47
|
+
|
|
48
|
+
@abstractmethod
|
|
49
|
+
def sample(self, xyz, feature=None, batch=None):
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class RandomSample(BaseSampler):
|
|
54
|
+
"""Random Sample for dense data
|
|
55
|
+
Arguments:
|
|
56
|
+
xyz -- [B, N, 3]
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def sample(self, xyz, **kwargs):
|
|
60
|
+
if len(xyz.shape) != 3:
|
|
61
|
+
raise ValueError(" Expects the xyz tensor to be of dimension 3")
|
|
62
|
+
B, N, _ = xyz.shape
|
|
63
|
+
idx = torch.randint(
|
|
64
|
+
0, N, (B, self._get_num_to_sample(N)), device=xyz.device)
|
|
65
|
+
sampled_xyz = torch.gather(xyz, 1, idx.unsqueeze(-1).expand(-1, -1, 3))
|
|
66
|
+
# sampled_feature = torch.gather(feature, 2, idx.unsqueeze(1).repeat(1, C, 1))
|
|
67
|
+
return sampled_xyz, idx
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def random_sample(xyz, npoint):
|
|
71
|
+
B, N, _ = xyz.shape
|
|
72
|
+
idx = torch.randint(0, N, (B, npoint), device=xyz.device)
|
|
73
|
+
return idx
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class FurthestPointSampling(Function):
|
|
77
|
+
@staticmethod
|
|
78
|
+
def forward(ctx, xyz: torch.Tensor, npoint: int) -> torch.Tensor:
|
|
79
|
+
"""
|
|
80
|
+
Uses iterative furthest point sampling to select a set of npoint features that have the largest
|
|
81
|
+
minimum distance
|
|
82
|
+
:param ctx:
|
|
83
|
+
:param xyz: (B, N, 3) where N > npoint
|
|
84
|
+
:param npoint: int, number of features in the sampled set
|
|
85
|
+
:return:
|
|
86
|
+
output: (B, npoint) tensor containing the set (idx)
|
|
87
|
+
"""
|
|
88
|
+
assert xyz.is_contiguous()
|
|
89
|
+
|
|
90
|
+
B, N, _ = xyz.size()
|
|
91
|
+
# output = torch.cuda.IntTensor(B, npoint, device=xyz.device)
|
|
92
|
+
# temp = torch.cuda.FloatTensor(B, N, device=xyz.device).fill_(1e10)
|
|
93
|
+
output = torch.cuda.IntTensor(B, npoint)
|
|
94
|
+
temp = torch.cuda.FloatTensor(B, N).fill_(1e10)
|
|
95
|
+
|
|
96
|
+
pointnet2_cuda.furthest_point_sampling_wrapper(
|
|
97
|
+
B, N, npoint, xyz, temp, output)
|
|
98
|
+
return output
|
|
99
|
+
|
|
100
|
+
@staticmethod
|
|
101
|
+
def backward(xyz, a=None):
|
|
102
|
+
return None, None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
furthest_point_sample = FurthestPointSampling.apply
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class GatherOperation(Function):
|
|
109
|
+
@staticmethod
|
|
110
|
+
def forward(ctx, features: torch.Tensor, idx: torch.Tensor) -> torch.Tensor:
|
|
111
|
+
"""
|
|
112
|
+
:param ctx:
|
|
113
|
+
:param features: (B, C, N)
|
|
114
|
+
:param idx: (B, npoint) index tensor of the features to gather
|
|
115
|
+
:return:
|
|
116
|
+
output: (B, C, npoint)
|
|
117
|
+
"""
|
|
118
|
+
assert features.is_contiguous()
|
|
119
|
+
assert idx.is_contiguous()
|
|
120
|
+
|
|
121
|
+
B, npoint = idx.size()
|
|
122
|
+
_, C, N = features.size()
|
|
123
|
+
output = torch.cuda.FloatTensor(B, C, npoint, device=features.device)
|
|
124
|
+
|
|
125
|
+
pointnet2_cuda.gather_points_wrapper(
|
|
126
|
+
B, C, N, npoint, features, idx, output)
|
|
127
|
+
|
|
128
|
+
ctx.for_backwards = (idx, C, N)
|
|
129
|
+
return output
|
|
130
|
+
|
|
131
|
+
@staticmethod
|
|
132
|
+
def backward(ctx, grad_out):
|
|
133
|
+
idx, C, N = ctx.for_backwards
|
|
134
|
+
B, npoint = idx.size()
|
|
135
|
+
|
|
136
|
+
grad_features = torch.zeros(
|
|
137
|
+
[B, C, N], dtype=torch.float, device=grad_out.device, requires_grad=True)
|
|
138
|
+
grad_out_data = grad_out.data.contiguous()
|
|
139
|
+
pointnet2_cuda.gather_points_grad_wrapper(
|
|
140
|
+
B, C, N, npoint, grad_out_data, idx, grad_features.data)
|
|
141
|
+
return grad_features, None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
gather_operation = GatherOperation.apply
|
|
145
|
+
# mark: torch gather is even faster. sampled_xyz = torch.gather(points, 1, idx.unsqueeze(-1).expand(-1, -1, 3))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def fps(data, number):
|
|
149
|
+
'''
|
|
150
|
+
data B N C
|
|
151
|
+
number int
|
|
152
|
+
'''
|
|
153
|
+
fps_idx = furthest_point_sample(data[:, :, :3].contiguous(), number)
|
|
154
|
+
fps_data = torch.gather(
|
|
155
|
+
data, 1, fps_idx.unsqueeze(-1).long().expand(-1, -1, data.shape[-1]))
|
|
156
|
+
return fps_data
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
if __name__ == '__main__':
|
|
160
|
+
import time
|
|
161
|
+
|
|
162
|
+
B, C, N = 2, 3, 10000
|
|
163
|
+
K = 16
|
|
164
|
+
device = 'cuda'
|
|
165
|
+
points = torch.randn([B, N, 3], device=device, dtype=torch.float)
|
|
166
|
+
print(points.shape, '\n', points)
|
|
167
|
+
|
|
168
|
+
nsample = 4096
|
|
169
|
+
idx = furthest_point_sample(points, nsample)
|
|
170
|
+
|
|
171
|
+
st = time.time()
|
|
172
|
+
for _ in range(100):
|
|
173
|
+
query1 = torch.gather(
|
|
174
|
+
points, 1, idx.long().unsqueeze(-1).expand(-1, -1, 3))
|
|
175
|
+
print(time.time() - st)
|
|
176
|
+
print(query1.shape)
|
|
177
|
+
|
|
178
|
+
st = time.time()
|
|
179
|
+
for _ in range(100):
|
|
180
|
+
query2 = gather_operation(points.transpose(
|
|
181
|
+
1, 2).contiguous(), idx).transpose(1, 2).contiguous()
|
|
182
|
+
print(time.time() - st)
|
|
183
|
+
print(query2.shape)
|
|
184
|
+
|
|
185
|
+
print(torch.allclose(query1, query2))
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
from typing import List, Tuple
|
|
2
|
+
from torch.autograd import Function
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
import torch.nn as nn
|
|
6
|
+
|
|
7
|
+
from openpoints.cpp.pointnet2_batch import pointnet2_cuda
|
|
8
|
+
from openpoints.models.layers import create_convblock1d
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ThreeNN(Function):
|
|
12
|
+
|
|
13
|
+
@staticmethod
|
|
14
|
+
def forward(ctx, unknown: torch.Tensor, known: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
15
|
+
"""
|
|
16
|
+
Find the three nearest neighbors of unknown in known
|
|
17
|
+
:param ctx:
|
|
18
|
+
:param unknown: (B, N, 3)
|
|
19
|
+
:param known: (B, M, 3)
|
|
20
|
+
:return:
|
|
21
|
+
dist: (B, N, 3) l2 distance to the three nearest neighbors
|
|
22
|
+
idx: (B, N, 3) index of 3 nearest neighbors
|
|
23
|
+
"""
|
|
24
|
+
assert unknown.is_contiguous()
|
|
25
|
+
assert known.is_contiguous()
|
|
26
|
+
|
|
27
|
+
B, N, _ = unknown.size()
|
|
28
|
+
m = known.size(1)
|
|
29
|
+
dist2 = torch.cuda.FloatTensor(B, N, 3)
|
|
30
|
+
idx = torch.cuda.IntTensor(B, N, 3)
|
|
31
|
+
|
|
32
|
+
pointnet2_cuda.three_nn_wrapper(B, N, m, unknown, known, dist2, idx)
|
|
33
|
+
return torch.sqrt(dist2), idx
|
|
34
|
+
|
|
35
|
+
@staticmethod
|
|
36
|
+
def backward(ctx, a=None, b=None):
|
|
37
|
+
return None, None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
three_nn = ThreeNN.apply
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class ThreeInterpolate(Function):
|
|
44
|
+
|
|
45
|
+
@staticmethod
|
|
46
|
+
@torch.cuda.amp.custom_fwd(cast_inputs=torch.float32)
|
|
47
|
+
def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
|
|
48
|
+
"""
|
|
49
|
+
Performs weight linear interpolation on 3 features
|
|
50
|
+
:param ctx:
|
|
51
|
+
:param features: (B, C, M) Features descriptors to be interpolated from
|
|
52
|
+
:param idx: (B, n, 3) three nearest neighbors of the target features in features
|
|
53
|
+
:param weight: (B, n, 3) weights
|
|
54
|
+
:return:
|
|
55
|
+
output: (B, C, N) tensor of the interpolated features
|
|
56
|
+
"""
|
|
57
|
+
assert features.is_contiguous()
|
|
58
|
+
assert idx.is_contiguous()
|
|
59
|
+
assert weight.is_contiguous()
|
|
60
|
+
|
|
61
|
+
B, c, m = features.size()
|
|
62
|
+
n = idx.size(1)
|
|
63
|
+
ctx.three_interpolate_for_backward = (idx, weight, m)
|
|
64
|
+
output = torch.cuda.FloatTensor(B, c, n)
|
|
65
|
+
|
|
66
|
+
pointnet2_cuda.three_interpolate_wrapper(B, c, m, n, features, idx, weight, output)
|
|
67
|
+
return output
|
|
68
|
+
|
|
69
|
+
@staticmethod
|
|
70
|
+
def backward(ctx, grad_out: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
71
|
+
"""
|
|
72
|
+
:param ctx:
|
|
73
|
+
:param grad_out: (B, C, N) tensor with gradients of outputs
|
|
74
|
+
:return:
|
|
75
|
+
grad_features: (B, C, M) tensor with gradients of features
|
|
76
|
+
None:
|
|
77
|
+
None:
|
|
78
|
+
"""
|
|
79
|
+
idx, weight, m = ctx.three_interpolate_for_backward
|
|
80
|
+
B, c, n = grad_out.size()
|
|
81
|
+
|
|
82
|
+
grad_features = torch.zeros([B, c, m], device='cuda', requires_grad=True)
|
|
83
|
+
grad_out_data = grad_out.data.contiguous()
|
|
84
|
+
|
|
85
|
+
pointnet2_cuda.three_interpolate_grad_wrapper(B, c, n, m, grad_out_data, idx, weight, grad_features.data)
|
|
86
|
+
return grad_features, None, None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
three_interpolate = ThreeInterpolate.apply
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def three_interpolation(unknown_xyz, known_xyz, know_feat):
|
|
93
|
+
"""
|
|
94
|
+
input: known_xyz: (m, 3), unknown_xyz: (n, 3), feat: (m, c), offset: (b), new_offset: (b)
|
|
95
|
+
output: (n, c)
|
|
96
|
+
"""
|
|
97
|
+
dist, idx = three_nn(unknown_xyz, known_xyz)
|
|
98
|
+
dist_recip = 1.0 / (dist + 1e-8)
|
|
99
|
+
norm = torch.sum(dist_recip, dim=2, keepdim=True)
|
|
100
|
+
weight = dist_recip / norm
|
|
101
|
+
interpolated_feats = three_interpolate(know_feat, idx, weight)
|
|
102
|
+
return interpolated_feats
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
if __name__ == "__main__":
|
|
106
|
+
pass
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import math
|
|
3
|
+
import warnings
|
|
4
|
+
|
|
5
|
+
from torch.nn.init import _calculate_fan_in_and_fan_out
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _no_grad_trunc_normal_(tensor, mean, std, a, b):
|
|
9
|
+
# Cut & paste from PyTorch official master until it's in a few official releases - RW
|
|
10
|
+
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
|
|
11
|
+
def norm_cdf(x):
|
|
12
|
+
# Computes standard normal cumulative distribution function
|
|
13
|
+
return (1. + math.erf(x / math.sqrt(2.))) / 2.
|
|
14
|
+
|
|
15
|
+
if (mean < a - 2 * std) or (mean > b + 2 * std):
|
|
16
|
+
warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
|
|
17
|
+
"The distribution of values may be incorrect.",
|
|
18
|
+
stacklevel=2)
|
|
19
|
+
|
|
20
|
+
with torch.no_grad():
|
|
21
|
+
# Values are generated by using a truncated uniform distribution and
|
|
22
|
+
# then using the inverse CDF for the normal distribution.
|
|
23
|
+
# Get upper and lower cdf values
|
|
24
|
+
l = norm_cdf((a - mean) / std)
|
|
25
|
+
u = norm_cdf((b - mean) / std)
|
|
26
|
+
|
|
27
|
+
# Uniformly fill tensor with values from [l, u], then translate to
|
|
28
|
+
# [2l-1, 2u-1].
|
|
29
|
+
tensor.uniform_(2 * l - 1, 2 * u - 1)
|
|
30
|
+
|
|
31
|
+
# Use inverse cdf transform for normal distribution to get truncated
|
|
32
|
+
# standard normal
|
|
33
|
+
tensor.erfinv_()
|
|
34
|
+
|
|
35
|
+
# Transform to proper mean, std
|
|
36
|
+
tensor.mul_(std * math.sqrt(2.))
|
|
37
|
+
tensor.add_(mean)
|
|
38
|
+
|
|
39
|
+
# Clamp to ensure it's in the proper range
|
|
40
|
+
tensor.clamp_(min=a, max=b)
|
|
41
|
+
return tensor
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
|
|
45
|
+
# type: (Tensor, float, float, float, float) -> Tensor
|
|
46
|
+
r"""Fills the input Tensor with values drawn from a truncated
|
|
47
|
+
normal distribution. The values are effectively drawn from the
|
|
48
|
+
normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
|
|
49
|
+
with values outside :math:`[a, b]` redrawn until they are within
|
|
50
|
+
the bounds. The method used for generating the random values works
|
|
51
|
+
best when :math:`a \leq \text{mean} \leq b`.
|
|
52
|
+
Args:
|
|
53
|
+
tensor: an n-dimensional `torch.Tensor`
|
|
54
|
+
mean: the mean of the normal distribution
|
|
55
|
+
std: the standard deviation of the normal distribution
|
|
56
|
+
a: the minimum cutoff value
|
|
57
|
+
b: the maximum cutoff value
|
|
58
|
+
Examples:
|
|
59
|
+
>>> w = torch.empty(3, 5)
|
|
60
|
+
>>> nn.init.trunc_normal_(w)
|
|
61
|
+
"""
|
|
62
|
+
return _no_grad_trunc_normal_(tensor, mean, std, a, b)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def variance_scaling_(tensor, scale=1.0, mode='fan_in', distribution='normal'):
|
|
66
|
+
fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
|
|
67
|
+
if mode == 'fan_in':
|
|
68
|
+
denom = fan_in
|
|
69
|
+
elif mode == 'fan_out':
|
|
70
|
+
denom = fan_out
|
|
71
|
+
elif mode == 'fan_avg':
|
|
72
|
+
denom = (fan_in + fan_out) / 2
|
|
73
|
+
|
|
74
|
+
variance = scale / denom
|
|
75
|
+
|
|
76
|
+
if distribution == "truncated_normal":
|
|
77
|
+
# constant is stddev of standard normal truncated to (-2, 2)
|
|
78
|
+
trunc_normal_(tensor, std=math.sqrt(variance) / .87962566103423978)
|
|
79
|
+
elif distribution == "normal":
|
|
80
|
+
tensor.normal_(std=math.sqrt(variance))
|
|
81
|
+
elif distribution == "uniform":
|
|
82
|
+
bound = math.sqrt(3 * variance)
|
|
83
|
+
tensor.uniform_(-bound, bound)
|
|
84
|
+
else:
|
|
85
|
+
raise ValueError(f"invalid distribution {distribution}")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def lecun_normal_(tensor):
|
|
89
|
+
variance_scaling_(tensor, mode='fan_in', distribution='truncated_normal')
|