Elffuss BraidHub

kikocis/SpatialLM public

main · 32.8 KiBRawPermalink
1"""
2Point Transformer - V3 Mode2 - Sonata
3Pointcept detached version
4
5Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
6"""
7
8# Copyright (c) Meta Platforms, Inc. and affiliates.
9#
10# Licensed under the Apache License, Version 2.0 (the "License");
11# you may not use this file except in compliance with the License.
12# You may obtain a copy of the License at
13#
14# http://www.apache.org/licenses/LICENSE-2.0
15#
16# Unless required by applicable law or agreed to in writing, software
17# distributed under the License is distributed on an "AS IS" BASIS,
18# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19# See the License for the specific language governing permissions and
20# limitations under the License.
21
22import sys
23from collections import OrderedDict
24
25from huggingface_hub import PyTorchModelHubMixin
26from addict import Dict
27import torch
28import torch.nn as nn
29import spconv.pytorch as spconv
30import torch_scatter
31from timm.layers import DropPath
32
33try:
34 import flash_attn
35except ImportError:
36 flash_attn = None
37
38from .serialization import encode
39
40
41@torch.inference_mode()
42def offset2bincount(offset):
43 return torch.diff(
44 offset, prepend=torch.tensor([0], device=offset.device, dtype=torch.long)
45 )
46
47
48@torch.inference_mode()
49def offset2batch(offset):
50 bincount = offset2bincount(offset)
51 return torch.arange(
52 len(bincount), device=offset.device, dtype=torch.long
53 ).repeat_interleave(bincount)
54
55
56@torch.inference_mode()
57def batch2offset(batch):
58 return torch.cumsum(batch.bincount(), dim=0).long()
59
60
61class Point(Dict):
62 """
63 Point Structure of Pointcept
64
65 A Point (point cloud) in Pointcept is a dictionary that contains various properties of
66 a batched point cloud. The property with the following names have a specific definition
67 as follows:
68
69 - "coord": original coordinate of point cloud;
70 - "grid_coord": grid coordinate for specific grid size (related to GridSampling);
71 Point also support the following optional attributes:
72 - "offset": if not exist, initialized as batch size is 1;
73 - "batch": if not exist, initialized as batch size is 1;
74 - "feat": feature of point cloud, default input of model;
75 - "grid_size": Grid size of point cloud (related to GridSampling);
76 (related to Serialization)
77 - "serialized_depth": depth of serialization, 2 ** depth * grid_size describe the maximum of point cloud range;
78 - "serialized_code": a list of serialization codes;
79 - "serialized_order": a list of serialization order determined by code;
80 - "serialized_inverse": a list of inverse mapping determined by code;
81 (related to Sparsify: SpConv)
82 - "sparse_shape": Sparse shape for Sparse Conv Tensor;
83 - "sparse_conv_feat": SparseConvTensor init with information provide by Point;
84 """
85
86 def __init__(self, *args, **kwargs):
87 super().__init__(*args, **kwargs)
88 # If one of "offset" or "batch" do not exist, generate by the existing one
89 if "batch" not in self.keys() and "offset" in self.keys():
90 self["batch"] = offset2batch(self.offset)
91 elif "offset" not in self.keys() and "batch" in self.keys():
92 self["offset"] = batch2offset(self.batch)
93
94 def serialization(self, order="z", depth=None, shuffle_orders=False):
95 """
96 Point Cloud Serialization
97
98 relay on ["grid_coord" or "coord" + "grid_size", "batch", "feat"]
99 """
100 self["order"] = order
101 assert "batch" in self.keys()
102 if "grid_coord" not in self.keys():
103 # if you don't want to operate GridSampling in data augmentation,
104 # please add the following augmentation into your pipeline:
105 # dict(type="Copy", keys_dict={"grid_size": 0.01}),
106 # (adjust `grid_size` to what your want)
107 assert {"grid_size", "coord"}.issubset(self.keys())
108
109 self["grid_coord"] = torch.div(
110 self.coord - self.coord.min(0)[0], self.grid_size, rounding_mode="trunc"
111 ).int()
112
113 if depth is None:
114 # Adaptive measure the depth of serialization cube (length = 2 ^ depth)
115 depth = int(self.grid_coord.max() + 1).bit_length()
116 self["serialized_depth"] = depth
117 # Maximum bit length for serialization code is 63 (int64)
118 assert depth * 3 + len(self.offset).bit_length() <= 63
119 # Here we follow OCNN and set the depth limitation to 16 (48bit) for the point position.
120 # Although depth is limited to less than 16, we can encode a 655.36^3 (2^16 * 0.01) meter^3
121 # cube with a grid size of 0.01 meter. We consider it is enough for the current stage.
122 # We can unlock the limitation by optimizing the z-order encoding function if necessary.
123 assert depth <= 16
124
125 # The serialization codes are arranged as following structures:
126 # [Order1 ([n]),
127 # Order2 ([n]),
128 # ...
129 # OrderN ([n])] (k, n)
130 code = [
131 encode(self.grid_coord, self.batch, depth, order=order_) for order_ in order
132 ]
133 code = torch.stack(code)
134 order = torch.argsort(code)
135 inverse = torch.zeros_like(order).scatter_(
136 dim=1,
137 index=order,
138 src=torch.arange(0, code.shape[1], device=order.device).repeat(
139 code.shape[0], 1
140 ),
141 )
142
143 if shuffle_orders:
144 perm = torch.randperm(code.shape[0])
145 code = code[perm]
146 order = order[perm]
147 inverse = inverse[perm]
148
149 self["serialized_code"] = code
150 self["serialized_order"] = order
151 self["serialized_inverse"] = inverse
152
153 def sparsify(self, pad=96):
154 """
155 Point Cloud Serialization
156
157 Point cloud is sparse, here we use "sparsify" to specifically refer to
158 preparing "spconv.SparseConvTensor" for SpConv.
159
160 relay on ["grid_coord" or "coord" + "grid_size", "batch", "feat"]
161
162 pad: padding sparse for sparse shape.
163 """
164 assert {"feat", "batch"}.issubset(self.keys())
165 if "grid_coord" not in self.keys():
166 # if you don't want to operate GridSampling in data augmentation,
167 # please add the following augmentation into your pipeline:
168 # dict(type="Copy", keys_dict={"grid_size": 0.01}),
169 # (adjust `grid_size` to what your want)
170 assert {"grid_size", "coord"}.issubset(self.keys())
171 self["grid_coord"] = torch.div(
172 self.coord - self.coord.min(0)[0], self.grid_size, rounding_mode="trunc"
173 ).int()
174 if "sparse_shape" in self.keys():
175 sparse_shape = self.sparse_shape
176 else:
177 sparse_shape = torch.add(
178 torch.max(self.grid_coord, dim=0).values, pad
179 ).tolist()
180 sparse_conv_feat = spconv.SparseConvTensor(
181 features=self.feat,
182 indices=torch.cat(
183 [self.batch.unsqueeze(-1).int(), self.grid_coord.int()], dim=1
184 ).contiguous(),
185 spatial_shape=sparse_shape,
186 batch_size=self.batch[-1].tolist() + 1,
187 )
188 self["sparse_shape"] = sparse_shape
189 self["sparse_conv_feat"] = sparse_conv_feat
190
191
192class PointModule(nn.Module):
193 r"""PointModule
194 placeholder, all module subclass from this will take Point in PointSequential.
195 """
196
197 def __init__(self, *args, **kwargs):
198 super().__init__(*args, **kwargs)
199
200
201class PointSequential(PointModule):
202 r"""A sequential container.
203 Modules will be added to it in the order they are passed in the constructor.
204 Alternatively, an ordered dict of modules can also be passed in.
205 """
206
207 def __init__(self, *args, **kwargs):
208 super().__init__()
209 if len(args) == 1 and isinstance(args[0], OrderedDict):
210 for key, module in args[0].items():
211 self.add_module(key, module)
212 else:
213 for idx, module in enumerate(args):
214 self.add_module(str(idx), module)
215 for name, module in kwargs.items():
216 if sys.version_info < (3, 6):
217 raise ValueError("kwargs only supported in py36+")
218 if name in self._modules:
219 raise ValueError("name exists.")
220 self.add_module(name, module)
221
222 def __getitem__(self, idx):
223 if not (-len(self) <= idx < len(self)):
224 raise IndexError("index {} is out of range".format(idx))
225 if idx < 0:
226 idx += len(self)
227 it = iter(self._modules.values())
228 for i in range(idx):
229 next(it)
230 return next(it)
231
232 def __len__(self):
233 return len(self._modules)
234
235 def add(self, module, name=None):
236 if name is None:
237 name = str(len(self._modules))
238 if name in self._modules:
239 raise KeyError("name exists")
240 self.add_module(name, module)
241
242 def forward(self, input):
243 for k, module in self._modules.items():
244 # Point module
245 if isinstance(module, PointModule):
246 input = module(input)
247 # Spconv module
248 elif spconv.modules.is_spconv_module(module):
249 if isinstance(input, Point):
250 input.sparse_conv_feat = module(input.sparse_conv_feat)
251 input.feat = input.sparse_conv_feat.features
252 else:
253 input = module(input)
254 # PyTorch module
255 else:
256 if isinstance(input, Point):
257 input.feat = module(input.feat)
258 if "sparse_conv_feat" in input.keys():
259 input.sparse_conv_feat = input.sparse_conv_feat.replace_feature(
260 input.feat
261 )
262 elif isinstance(input, spconv.SparseConvTensor):
263 if input.indices.shape[0] != 0:
264 input = input.replace_feature(module(input.features))
265 else:
266 input = module(input)
267 return input
268
269
270class LayerScale(nn.Module):
271 def __init__(
272 self,
273 dim: int,
274 init_values: float = 1e-5,
275 inplace: bool = False,
276 ) -> None:
277 super().__init__()
278 self.inplace = inplace
279 self.gamma = nn.Parameter(init_values * torch.ones(dim))
280
281 def forward(self, x: torch.Tensor) -> torch.Tensor:
282 return x.mul_(self.gamma) if self.inplace else x * self.gamma
283
284
285class RPE(torch.nn.Module):
286 def __init__(self, patch_size, num_heads):
287 super().__init__()
288 self.patch_size = patch_size
289 self.num_heads = num_heads
290 self.pos_bnd = int((4 * patch_size) ** (1 / 3) * 2)
291 self.rpe_num = 2 * self.pos_bnd + 1
292 self.rpe_table = torch.nn.Parameter(torch.zeros(3 * self.rpe_num, num_heads))
293 torch.nn.init.trunc_normal_(self.rpe_table, std=0.02)
294
295 def forward(self, coord):
296 idx = (
297 coord.clamp(-self.pos_bnd, self.pos_bnd) # clamp into bnd
298 + self.pos_bnd # relative position to positive index
299 + torch.arange(3, device=coord.device) * self.rpe_num # x, y, z stride
300 )
301 out = self.rpe_table.index_select(0, idx.reshape(-1))
302 out = out.view(idx.shape + (-1,)).sum(3)
303 out = out.permute(0, 3, 1, 2) # (N, K, K, H) -> (N, H, K, K)
304 return out
305
306
307class SerializedAttention(PointModule):
308 def __init__(
309 self,
310 channels,
311 num_heads,
312 patch_size,
313 qkv_bias=True,
314 qk_scale=None,
315 attn_drop=0.0,
316 proj_drop=0.0,
317 order_index=0,
318 enable_rpe=False,
319 enable_flash=True,
320 upcast_attention=True,
321 upcast_softmax=True,
322 ):
323 super().__init__()
324 assert channels % num_heads == 0
325 self.channels = channels
326 self.num_heads = num_heads
327 self.scale = qk_scale or (channels // num_heads) ** -0.5
328 self.order_index = order_index
329 self.upcast_attention = upcast_attention
330 self.upcast_softmax = upcast_softmax
331 self.enable_rpe = enable_rpe
332 self.enable_flash = enable_flash
333 if enable_flash:
334 assert (
335 enable_rpe is False
336 ), "Set enable_rpe to False when enable Flash Attention"
337 assert (
338 upcast_attention is False
339 ), "Set upcast_attention to False when enable Flash Attention"
340 assert (
341 upcast_softmax is False
342 ), "Set upcast_softmax to False when enable Flash Attention"
343 assert flash_attn is not None, "Make sure flash_attn is installed."
344 self.patch_size = patch_size
345 self.attn_drop = attn_drop
346 else:
347 # when disable flash attention, we still don't want to use mask
348 # consequently, patch size will auto set to the
349 # min number of patch_size_max and number of points
350 self.patch_size_max = patch_size
351 self.patch_size = 0
352 self.attn_drop = torch.nn.Dropout(attn_drop)
353
354 self.qkv = torch.nn.Linear(channels, channels * 3, bias=qkv_bias)
355 self.proj = torch.nn.Linear(channels, channels)
356 self.proj_drop = torch.nn.Dropout(proj_drop)
357 self.softmax = torch.nn.Softmax(dim=-1)
358 self.rpe = RPE(patch_size, num_heads) if self.enable_rpe else None
359
360 @torch.no_grad()
361 def get_rel_pos(self, point, order):
362 K = self.patch_size
363 rel_pos_key = f"rel_pos_{self.order_index}"
364 if rel_pos_key not in point.keys():
365 grid_coord = point.grid_coord[order]
366 grid_coord = grid_coord.reshape(-1, K, 3)
367 point[rel_pos_key] = grid_coord.unsqueeze(2) - grid_coord.unsqueeze(1)
368 return point[rel_pos_key]
369
370 @torch.no_grad()
371 def get_padding_and_inverse(self, point):
372 pad_key = "pad"
373 unpad_key = "unpad"
374 cu_seqlens_key = "cu_seqlens_key"
375 if (
376 pad_key not in point.keys()
377 or unpad_key not in point.keys()
378 or cu_seqlens_key not in point.keys()
379 ):
380 offset = point.offset
381 bincount = offset2bincount(offset)
382 bincount_pad = (
383 torch.div(
384 bincount + self.patch_size - 1,
385 self.patch_size,
386 rounding_mode="trunc",
387 )
388 * self.patch_size
389 )
390 # only pad point when num of points larger than patch_size
391 mask_pad = bincount > self.patch_size
392 bincount_pad = ~mask_pad * bincount + mask_pad * bincount_pad
393 _offset = nn.functional.pad(offset, (1, 0))
394 _offset_pad = nn.functional.pad(torch.cumsum(bincount_pad, dim=0), (1, 0))
395 pad = torch.arange(_offset_pad[-1], device=offset.device)
396 unpad = torch.arange(_offset[-1], device=offset.device)
397 cu_seqlens = []
398 for i in range(len(offset)):
399 unpad[_offset[i] : _offset[i + 1]] += _offset_pad[i] - _offset[i]
400 if bincount[i] != bincount_pad[i]:
401 pad[
402 _offset_pad[i + 1]
403 - self.patch_size
404 + (bincount[i] % self.patch_size) : _offset_pad[i + 1]
405 ] = pad[
406 _offset_pad[i + 1]
407 - 2 * self.patch_size
408 + (bincount[i] % self.patch_size) : _offset_pad[i + 1]
409 - self.patch_size
410 ]
411 pad[_offset_pad[i] : _offset_pad[i + 1]] -= _offset_pad[i] - _offset[i]
412 cu_seqlens.append(
413 torch.arange(
414 _offset_pad[i],
415 _offset_pad[i + 1],
416 step=self.patch_size,
417 dtype=torch.int32,
418 device=offset.device,
419 )
420 )
421 point[pad_key] = pad
422 point[unpad_key] = unpad
423 point[cu_seqlens_key] = nn.functional.pad(
424 torch.concat(cu_seqlens), (0, 1), value=_offset_pad[-1]
425 )
426 return point[pad_key], point[unpad_key], point[cu_seqlens_key]
427
428 def forward(self, point):
429 if not self.enable_flash:
430 self.patch_size = min(
431 offset2bincount(point.offset).min().tolist(), self.patch_size_max
432 )
433
434 H = self.num_heads
435 K = self.patch_size
436 C = self.channels
437
438 pad, unpad, cu_seqlens = self.get_padding_and_inverse(point)
439
440 order = point.serialized_order[self.order_index][pad]
441 inverse = unpad[point.serialized_inverse[self.order_index]]
442
443 # padding and reshape feat and batch for serialized point patch
444 qkv = self.qkv(point.feat)[order]
445
446 if not self.enable_flash:
447 # encode and reshape qkv: (N', K, 3, H, C') => (3, N', H, K, C')
448 q, k, v = (
449 qkv.reshape(-1, K, 3, H, C // H).permute(2, 0, 3, 1, 4).unbind(dim=0)
450 )
451 # attn
452 if self.upcast_attention:
453 q = q.float()
454 k = k.float()
455 attn = (q * self.scale) @ k.transpose(-2, -1) # (N', H, K, K)
456 if self.enable_rpe:
457 attn = attn + self.rpe(self.get_rel_pos(point, order))
458 if self.upcast_softmax:
459 attn = attn.float()
460 attn = self.softmax(attn)
461 attn = self.attn_drop(attn).to(qkv.dtype)
462 feat = (attn @ v).transpose(1, 2).reshape(-1, C)
463 else:
464 feat = flash_attn.flash_attn_varlen_qkvpacked_func(
465 qkv.half().reshape(-1, 3, H, C // H),
466 cu_seqlens,
467 max_seqlen=self.patch_size,
468 dropout_p=self.attn_drop if self.training else 0,
469 softmax_scale=self.scale,
470 ).reshape(-1, C)
471 feat = feat.to(qkv.dtype)
472 feat = feat[inverse]
473
474 # ffn
475 feat = self.proj(feat)
476 feat = self.proj_drop(feat)
477 point.feat = feat
478 return point
479
480
481class MLP(nn.Module):
482 def __init__(
483 self,
484 in_channels,
485 hidden_channels=None,
486 out_channels=None,
487 act_layer=nn.GELU,
488 drop=0.0,
489 ):
490 super().__init__()
491 out_channels = out_channels or in_channels
492 hidden_channels = hidden_channels or in_channels
493 self.fc1 = nn.Linear(in_channels, hidden_channels)
494 self.act = act_layer()
495 self.fc2 = nn.Linear(hidden_channels, out_channels)
496 self.drop = nn.Dropout(drop)
497
498 def forward(self, x):
499 x = self.fc1(x)
500 x = self.act(x)
501 x = self.drop(x)
502 x = self.fc2(x)
503 x = self.drop(x)
504 return x
505
506
507class Block(PointModule):
508 def __init__(
509 self,
510 channels,
511 num_heads,
512 patch_size=48,
513 mlp_ratio=4.0,
514 qkv_bias=True,
515 qk_scale=None,
516 attn_drop=0.0,
517 proj_drop=0.0,
518 drop_path=0.0,
519 layer_scale=None,
520 norm_layer=nn.LayerNorm,
521 act_layer=nn.GELU,
522 pre_norm=True,
523 order_index=0,
524 cpe_indice_key=None,
525 enable_rpe=False,
526 enable_flash=True,
527 upcast_attention=True,
528 upcast_softmax=True,
529 ):
530 super().__init__()
531 self.channels = channels
532 self.pre_norm = pre_norm
533
534 self.cpe = PointSequential(
535 spconv.SubMConv3d(
536 channels,
537 channels,
538 kernel_size=3,
539 bias=True,
540 indice_key=cpe_indice_key,
541 ),
542 nn.Linear(channels, channels),
543 norm_layer(channels),
544 )
545
546 self.norm1 = PointSequential(norm_layer(channels))
547 self.ls1 = PointSequential(
548 LayerScale(channels, init_values=layer_scale)
549 if layer_scale is not None
550 else nn.Identity()
551 )
552 self.attn = SerializedAttention(
553 channels=channels,
554 patch_size=patch_size,
555 num_heads=num_heads,
556 qkv_bias=qkv_bias,
557 qk_scale=qk_scale,
558 attn_drop=attn_drop,
559 proj_drop=proj_drop,
560 order_index=order_index,
561 enable_rpe=enable_rpe,
562 enable_flash=enable_flash,
563 upcast_attention=upcast_attention,
564 upcast_softmax=upcast_softmax,
565 )
566 self.norm2 = PointSequential(norm_layer(channels))
567 self.ls2 = PointSequential(
568 LayerScale(channels, init_values=layer_scale)
569 if layer_scale is not None
570 else nn.Identity()
571 )
572 self.mlp = PointSequential(
573 MLP(
574 in_channels=channels,
575 hidden_channels=int(channels * mlp_ratio),
576 out_channels=channels,
577 act_layer=act_layer,
578 drop=proj_drop,
579 )
580 )
581 self.drop_path = PointSequential(
582 DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
583 )
584
585 def forward(self, point: Point):
586 shortcut = point.feat
587 point = self.cpe(point)
588 point.feat = shortcut + point.feat
589 shortcut = point.feat
590 if self.pre_norm:
591 point = self.norm1(point)
592 point = self.drop_path(self.ls1(self.attn(point)))
593 point.feat = shortcut + point.feat
594 if not self.pre_norm:
595 point = self.norm1(point)
596
597 shortcut = point.feat
598 if self.pre_norm:
599 point = self.norm2(point)
600 point = self.drop_path(self.ls2(self.mlp(point)))
601 point.feat = shortcut + point.feat
602 if not self.pre_norm:
603 point = self.norm2(point)
604 point.sparse_conv_feat = point.sparse_conv_feat.replace_feature(point.feat)
605 return point
606
607
608class GridPooling(PointModule):
609 def __init__(
610 self,
611 in_channels,
612 out_channels,
613 stride=2,
614 norm_layer=None,
615 act_layer=None,
616 reduce="max",
617 shuffle_orders=True,
618 traceable=True, # record parent and cluster
619 ):
620 super().__init__()
621 self.in_channels = in_channels
622 self.out_channels = out_channels
623
624 self.stride = stride
625 assert reduce in ["sum", "mean", "min", "max"]
626 self.reduce = reduce
627 self.shuffle_orders = shuffle_orders
628 self.traceable = traceable
629
630 self.proj = nn.Linear(in_channels, out_channels)
631 if norm_layer is not None:
632 self.norm = PointSequential(norm_layer(out_channels))
633 if act_layer is not None:
634 self.act = PointSequential(act_layer())
635
636 def forward(self, point: Point):
637 if "grid_coord" in point.keys():
638 grid_coord = point.grid_coord
639 elif {"coord", "grid_size"}.issubset(point.keys()):
640 grid_coord = torch.div(
641 point.coord - point.coord.min(0)[0],
642 point.grid_size,
643 rounding_mode="trunc",
644 ).int()
645 else:
646 raise AssertionError(
647 "[gird_coord] or [coord, grid_size] should be include in the Point"
648 )
649 grid_coord = torch.div(grid_coord, self.stride, rounding_mode="trunc")
650 grid_coord = grid_coord | point.batch.view(-1, 1) << 48
651 grid_coord, cluster, counts = torch.unique(
652 grid_coord,
653 sorted=True,
654 return_inverse=True,
655 return_counts=True,
656 dim=0,
657 )
658 grid_coord = grid_coord & ((1 << 48) - 1)
659 # indices of point sorted by cluster, for torch_scatter.segment_csr
660 _, indices = torch.sort(cluster)
661 # index pointer for sorted point, for torch_scatter.segment_csr
662 idx_ptr = torch.cat([counts.new_zeros(1), torch.cumsum(counts, dim=0)])
663 # head_indices of each cluster, for reduce attr e.g. code, batch
664 head_indices = indices[idx_ptr[:-1]]
665 point_dict = Dict(
666 feat=torch_scatter.segment_csr(
667 self.proj(point.feat)[indices], idx_ptr, reduce=self.reduce
668 ),
669 coord=torch_scatter.segment_csr(
670 point.coord[indices], idx_ptr, reduce="mean"
671 ),
672 grid_coord=grid_coord,
673 batch=point.batch[head_indices],
674 )
675 if "origin_coord" in point.keys():
676 point_dict["origin_coord"] = torch_scatter.segment_csr(
677 point.origin_coord[indices], idx_ptr, reduce="mean"
678 )
679 if "condition" in point.keys():
680 point_dict["condition"] = point.condition
681 if "context" in point.keys():
682 point_dict["context"] = point.context
683 if "name" in point.keys():
684 point_dict["name"] = point.name
685 if "split" in point.keys():
686 point_dict["split"] = point.split
687 if "color" in point.keys():
688 point_dict["color"] = torch_scatter.segment_csr(
689 point.color[indices], idx_ptr, reduce="mean"
690 )
691 if "grid_size" in point.keys():
692 point_dict["grid_size"] = point.grid_size * self.stride
693
694 if self.traceable:
695 point_dict["pooling_inverse"] = cluster
696 point_dict["pooling_parent"] = point
697 order = point.order
698 point = Point(point_dict)
699 if self.norm is not None:
700 point = self.norm(point)
701 if self.act is not None:
702 point = self.act(point)
703 point.serialization(order=order, shuffle_orders=self.shuffle_orders)
704 point.sparsify()
705 return point
706
707
708class GridUnpooling(PointModule):
709 def __init__(
710 self,
711 in_channels,
712 skip_channels,
713 out_channels,
714 norm_layer=None,
715 act_layer=None,
716 traceable=False, # record parent and cluster
717 ):
718 super().__init__()
719 self.proj = PointSequential(nn.Linear(in_channels, out_channels))
720 self.proj_skip = PointSequential(nn.Linear(skip_channels, out_channels))
721
722 if norm_layer is not None:
723 self.proj.add(norm_layer(out_channels))
724 self.proj_skip.add(norm_layer(out_channels))
725
726 if act_layer is not None:
727 self.proj.add(act_layer())
728 self.proj_skip.add(act_layer())
729
730 self.traceable = traceable
731
732 def forward(self, point):
733 assert "pooling_parent" in point.keys()
734 assert "pooling_inverse" in point.keys()
735 parent = point.pop("pooling_parent")
736 inverse = point.pooling_inverse
737 feat = point.feat
738
739 parent = self.proj_skip(parent)
740 parent.feat = parent.feat + self.proj(point).feat[inverse]
741 parent.sparse_conv_feat = parent.sparse_conv_feat.replace_feature(parent.feat)
742
743 if self.traceable:
744 point.feat = feat
745 parent["unpooling_parent"] = point
746 return parent
747
748
749class Embedding(PointModule):
750 def __init__(
751 self,
752 in_channels,
753 embed_channels,
754 norm_layer=None,
755 act_layer=None,
756 mask_token=False,
757 ):
758 super().__init__()
759 self.in_channels = in_channels
760 self.embed_channels = embed_channels
761
762 self.stem = PointSequential(linear=nn.Linear(in_channels, embed_channels))
763 if norm_layer is not None:
764 self.stem.add(norm_layer(embed_channels), name="norm")
765 if act_layer is not None:
766 self.stem.add(act_layer(), name="act")
767
768 # BUG Parameters which did not receive grad for rank 0: point_backbone.embedding.mask_token
769 # if mask_token:
770 # self.mask_token = nn.Parameter(torch.zeros(1, embed_channels))
771 # else:
772 # self.mask_token = None
773
774 def forward(self, point: Point):
775 point = self.stem(point)
776 # if "mask" in point.keys():
777 # point.feat = torch.where(
778 # point.mask.unsqueeze(-1),
779 # self.mask_token.to(point.feat.dtype),
780 # point.feat,
781 # )
782 return point
783
784
785def fourier_encode_vector(vec, num_bands=10, sample_rate=60):
786 """Fourier encode a vector.
787
788 Args:
789 vec: [N, D] torch.FloatTensor.
790 num_bands: int.
791 sample_rate: int.
792
793 Returns:
794 [N, (2 * num_bands + 1) * D] torch.FloatTensor.
795 """
796 n, d = vec.shape
797 samples = torch.linspace(1, sample_rate / 2, num_bands).to(vec.device) * torch.pi
798 sines = torch.sin(samples[None, :, None] * vec[:, None, :])
799 cosines = torch.cos(samples[None, :, None] * vec[:, None, :])
800
801 encoding = torch.stack([sines, cosines], dim=2).reshape(n, 2 * num_bands, d)
802 encoding = torch.cat([vec[:, None, :], encoding], dim=1)
803 return encoding.flatten(1)
804
805
806class Sonata(PointModule, PyTorchModelHubMixin):
807 def __init__(
808 self,
809 in_channels=6,
810 order=("z", "z-trans"),
811 stride=(2, 2, 2, 2),
812 enc_depths=(3, 3, 3, 12, 3),
813 enc_channels=(48, 96, 192, 384, 512),
814 enc_num_head=(3, 6, 12, 24, 32),
815 enc_patch_size=(1024, 1024, 1024, 1024, 1024),
816 mlp_ratio=4,
817 qkv_bias=True,
818 qk_scale=None,
819 attn_drop=0.0,
820 proj_drop=0.0,
821 drop_path=0.3,
822 layer_scale=None,
823 pre_norm=True,
824 shuffle_orders=True,
825 enable_rpe=False,
826 enable_flash=True,
827 upcast_attention=False,
828 upcast_softmax=False,
829 mask_token=False,
830 enc_mode=True,
831 enable_fourier_encode=False,
832 num_bins=1280,
833 ):
834 super().__init__()
835 self.num_stages = len(enc_depths)
836 self.order = [order] if isinstance(order, str) else order
837 self.enc_mode = enc_mode
838 self.shuffle_orders = shuffle_orders
839
840 assert self.num_stages == len(stride) + 1
841 assert self.num_stages == len(enc_depths)
842 assert self.num_stages == len(enc_channels)
843 assert self.num_stages == len(enc_num_head)
844 assert self.num_stages == len(enc_patch_size)
845
846 # normalization layer
847 ln_layer = nn.LayerNorm
848 # activation layers
849 act_layer = nn.GELU
850
851 self.embedding = Embedding(
852 in_channels=in_channels,
853 embed_channels=enc_channels[0],
854 norm_layer=ln_layer,
855 act_layer=act_layer,
856 mask_token=mask_token,
857 )
858
859 # encoder
860 enc_drop_path = [
861 x.item() for x in torch.linspace(0, drop_path, sum(enc_depths))
862 ]
863 self.enc = PointSequential()
864 for s in range(self.num_stages):
865 enc_drop_path_ = enc_drop_path[
866 sum(enc_depths[:s]) : sum(enc_depths[: s + 1])
867 ]
868 enc = PointSequential()
869 if s > 0:
870 enc.add(
871 GridPooling(
872 in_channels=enc_channels[s - 1],
873 out_channels=enc_channels[s],
874 stride=stride[s - 1],
875 norm_layer=ln_layer,
876 act_layer=act_layer,
877 ),
878 name="down",
879 )
880 for i in range(enc_depths[s]):
881 enc.add(
882 Block(
883 channels=enc_channels[s],
884 num_heads=enc_num_head[s],
885 patch_size=enc_patch_size[s],
886 mlp_ratio=mlp_ratio,
887 qkv_bias=qkv_bias,
888 qk_scale=qk_scale,
889 attn_drop=attn_drop,
890 proj_drop=proj_drop,
891 drop_path=enc_drop_path_[i],
892 layer_scale=layer_scale,
893 norm_layer=ln_layer,
894 act_layer=act_layer,
895 pre_norm=pre_norm,
896 order_index=i % len(self.order),
897 cpe_indice_key=f"stage{s}",
898 enable_rpe=enable_rpe,
899 enable_flash=enable_flash,
900 upcast_attention=upcast_attention,
901 upcast_softmax=upcast_softmax,
902 ),
903 name=f"block{i}",
904 )
905 if len(enc) != 0:
906 self.enc.add(module=enc, name=f"enc{s}")
907
908 # fourier encode positional embedding inaddition to Sonata
909 self.enable_fourier_encode = enable_fourier_encode
910 downconvs = len(enc_channels) - 1
911 res_reduction = 2**downconvs # voxel resolution reduction
912 self.reduced_grid_size = int(num_bins / res_reduction)
913 self.input_proj = (
914 nn.Linear(enc_channels[-1] + 63, enc_channels[-1])
915 if self.enable_fourier_encode
916 else None
917 ) # 63 for fourier encoding
918
919 def forward(self, data_dict):
920 point = Point(data_dict)
921 point = self.embedding(point)
922
923 point.serialization(order=self.order, shuffle_orders=self.shuffle_orders)
924 point.sparsify()
925
926 point = self.enc(point)
927 context = point["sparse_conv_feat"].features
928
929 if self.enable_fourier_encode:
930 coords = point["grid_coord"]
931 coords_normalised = coords / (self.reduced_grid_size - 1)
932 encoded_coords = fourier_encode_vector(coords_normalised)
933
934 context = torch.cat([context, encoded_coords], dim=-1)
935 context = self.input_proj(context)
936
937 return context