Feature Extraction
Transformers
Safetensors
j3pa
lidar
point-cloud
self-supervised-learning
autonomous-driving
custom_code
Instructions to use Zenseact/j3pa-tiny with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Zenseact/j3pa-tiny with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="Zenseact/j3pa-tiny", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Zenseact/j3pa-tiny", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download pt_transf.py from Zenseact/j3pa-tiny: direct link, hf CLI and curl.
- Browser
- Download file 31.6 kB
-
https://huggingface.co/Zenseact/j3pa-tiny/resolve/main/pt_transf.py
- Command line
-
hf download hf://Zenseact/j3pa-tiny/pt_transf.py
-
curl -L -o pt_transf.py https://huggingface.co/Zenseact/j3pa-tiny/resolve/main/pt_transf.py
31.6 kB
| """Encoder of J3PA. | |
| This is a stripped copy of the released training code. See the paper for details. | |
| """ | |
| import math | |
| from collections.abc import Sequence | |
| from typing import NamedTuple | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| from torch.utils.checkpoint import checkpoint | |
| from .layers import PEDynamic, VoxelSizeEmbedding, log_voxel_size_coordinate | |
| from .qk_layernorm_rope_triton import qk_layernorm_rope | |
| from .rope import RoPE | |
| from .rope_triton import qk_rope | |
| from .space_filling_curves_triton import space_filling_idx | |
| # Expected x, y, z indices for points. | |
| XYZ_SLICE = slice(1, 4) | |
| # Size of the positional encoding of the input positions. | |
| INPUT_PE_DIM = 64 | |
| # Tokens per attention group. | |
| GROUP_SIZE = 1024 | |
| # Default voxel size (meters) of the first stage. This voxel size was used for the main evaluation table in the paper. | |
| VOXEL_SIZE = 0.05 | |
| # This is used for normalizing the RoPE input coordinates, regardless of the voxel size being used. | |
| POS_NORM_VOXEL_SIZE = 0.05 | |
| class PointTransformerOut(NamedTuple): | |
| """Outputs of the encoder stages, from fine to coarse. | |
| The voxel size becomes 2x larger for each hip between stages. | |
| point_features() and voxel_features() append the features across all stages for a given point | |
| or finest stage voxel. | |
| """ | |
| # (N_s, C_s) features of the voxels of stage s. | |
| features: list[torch.Tensor] | |
| # (N_s, 3) aggregated position of each voxel. | |
| positions: list[torch.Tensor] | |
| # (N_s,) sample in the batch of each voxel of stage s. | |
| batch_indices: list[torch.Tensor] | |
| # Mapping from each stage to the previous stage (N_s-1,). This can be used to | |
| # cascade the output of each stage back to the finest stage or points. | |
| up_indices: list[torch.Tensor] | |
| def point_features(self, stages: int | Sequence[int] | None = None) -> torch.Tensor: | |
| """Features for every point, concatenated across stages. | |
| Args: | |
| stages: The stage or stages to take the features of, negative ones counted from the deepest. If None is passed | |
| all stages are aggregated. | |
| Returns: | |
| (N, D) tensor for N points with D the sum of stage-wise channel counts. | |
| """ | |
| return self._gather_stages(self.up_indices[0], stages) | |
| def voxel_features(self, stages: int | Sequence[int] | None = None) -> torch.Tensor: | |
| """Features for every voxel at the finest stage, concatenated from across stages. | |
| See point_features. | |
| """ | |
| first_stage = torch.arange(len(self.features[0]), device=self.features[0].device) | |
| return self._gather_stages(first_stage, stages) | |
| def _gather_stages(self, idx: torch.Tensor, stages: int | Sequence[int] | None) -> torch.Tensor: | |
| num_stages = len(self.features) | |
| if stages is None: | |
| stages = range(num_stages - 1, -1, -1) | |
| elif isinstance(stages, int): | |
| stages = [stages] | |
| stages = [range(num_stages)[s] for s in stages] | |
| # Aggregate the up indices into a single compound index to avoid more gathers than needed. | |
| stage_idx = [idx] | |
| for t in range(1, max(stages) + 1): | |
| stage_idx.append(self.up_indices[t][stage_idx[-1]]) | |
| out = self.features[0].new_empty(len(idx), sum(self.features[s].shape[1] for s in stages)) | |
| needs_grad = torch.is_grad_enabled() and any(self.features[s].requires_grad for s in stages) | |
| col = 0 | |
| for s in stages: | |
| dim = self.features[s].shape[1] | |
| if needs_grad: | |
| out[:, col : col + dim] = self.features[s][stage_idx[s]] | |
| else: | |
| torch.index_select(self.features[s], 0, stage_idx[s], out=out[:, col : col + dim]) | |
| col += dim | |
| return out | |
| def get_grid_idx(pt_pos: torch.Tensor, batch_idx: torch.Tensor, cell_size: float | torch.Tensor, batch_size: int): | |
| """Get the grid index of each point, from the minimum position of its sample. | |
| Args: | |
| pt_pos: (N, 3) point positions. | |
| batch_idx: (N,) batch indices. | |
| cell_size: float or (N,) per-point cell sizes. | |
| batch_size: Number of samples in the batch. | |
| Returns: | |
| (N, 3) grid indices. | |
| """ | |
| min_pos = torch.empty((batch_size, 3), device=pt_pos.device, dtype=pt_pos.dtype) | |
| # scatter_reduce_ does not broadcast, so batch_idx is expanded to 3 channels manually. | |
| min_pos.scatter_reduce_(0, batch_idx.unsqueeze(-1).expand(-1, 3), pt_pos, reduce="amin", include_self=False) | |
| if isinstance(cell_size, torch.Tensor): | |
| cell_size = cell_size.unsqueeze(-1) | |
| return torch.div(pt_pos - min_pos[batch_idx], cell_size, rounding_mode="trunc").long() | |
| def pad_and_unpad_idx(batch_indices: torch.Tensor, group_size: int, batch_size: int) -> tuple[torch.Tensor, torch.Tensor]: | |
| """Indices that pad every sample to a multiple of group_size tokens, and that remove the padding again. | |
| The last group of each sample is filled up with repeated tokens of the sample, so that every group only holds tokens | |
| of one sample. | |
| Returns: | |
| pad_idx: (M,) M >= N, the token (in an order with the tokens of each sample contiguous) of every padded position. | |
| unpad_idx: (N,) the padded position of every token. | |
| """ | |
| counts = torch.empty((batch_size,), device=batch_indices.device, dtype=batch_indices.dtype) | |
| counts.scatter_reduce_(0, batch_indices, torch.ones_like(batch_indices), reduce="sum", include_self=False) | |
| padded_counts = ((counts + group_size - 1) // group_size) * group_size | |
| pad_idx = torch.arange(padded_counts.sum(), device=batch_indices.device, dtype=batch_indices.dtype) | |
| pad_batch_indices = torch.arange(batch_size, device=batch_indices.device, dtype=batch_indices.dtype).repeat_interleave(padded_counts) | |
| pad_batch_offsets = (torch.cumsum(counts, 0) - counts)[pad_batch_indices] | |
| pad_offsets = (torch.cumsum(padded_counts, 0) - padded_counts)[pad_batch_indices] | |
| pad_idx -= pad_offsets | |
| counts_per_point = counts[pad_batch_indices] | |
| unpad_mask = pad_idx < counts_per_point | |
| last_group_start = torch.clamp(counts_per_point - group_size, min=0) | |
| pad_idx = torch.where(unpad_mask, pad_idx, last_group_start + (pad_idx % counts_per_point)) | |
| # The unpadding indices index the padded tensor and the padding indices the original one, so they are offset by | |
| # the start of each sample in the padded and in the original tensor. | |
| unpad_idx = pad_idx + pad_offsets | |
| unpad_idx = unpad_idx[unpad_mask] | |
| pad_idx += pad_batch_offsets | |
| return pad_idx, unpad_idx | |
| def batched_permute(sf_idx: torch.Tensor, batch_idx: torch.Tensor, batch_size: int) -> torch.Tensor: | |
| """For random sample-wise permutation of the space-filling curves.""" | |
| # (B, 4) a random permutation per sample -> (4, N) the row each point takes its index from. | |
| permutations = torch.argsort(torch.rand(batch_size, 4, device=sf_idx.device), dim=1) | |
| return torch.gather(sf_idx, dim=0, index=permutations[batch_idx].T) | |
| class PointSelfAttn(nn.Module): | |
| """Pre-norm transformer layer with grouped attention of tokens consecutive along a space-filling curve.""" | |
| def __init__(self, dim: int, num_heads: int, group_size: int, qk_layernorm: bool, sdpa_gate: bool, condition_voxel_size: bool): | |
| """Initialize. | |
| Args: | |
| dim, num_heads: Obvious. | |
| group_size: Tokens per attention group. | |
| qk_layernorm: LayerNorm of the queries and keys over the head dim, before RoPE. | |
| sdpa_gate: Gate the attention output elementwise with a sigmoid of a linear map of the token's normalized | |
| input, before the output projection. | |
| condition_voxel_size: Modulate the layer with the voxel size modulation of its stage plus a learned | |
| per-layer offset. | |
| """ | |
| assert dim % num_heads == 0 | |
| super().__init__() | |
| self._ln_attn = nn.LayerNorm(dim) | |
| # Per-layer offset on the stage's shared voxel size modulation (adaLN-single). Zero is unmodulated. | |
| self._adaln_vs_bias = nn.Parameter(torch.zeros(6, dim)) if condition_voxel_size else None | |
| self._pqkv = nn.Linear(dim, 3 * dim) | |
| self._q_ln = nn.LayerNorm(dim // num_heads) if qk_layernorm else None | |
| self._k_ln = nn.LayerNorm(dim // num_heads) if qk_layernorm else None | |
| self._rope = RoPE(dim=dim, pos_dim=3, max_freq=100, num_heads=num_heads) | |
| self._po = nn.Linear(dim, dim) | |
| self._sdpa_gate_lin = nn.Linear(dim, dim) if sdpa_gate else None | |
| self._num_heads = num_heads | |
| self._group_size = group_size | |
| self._ln_ffn = nn.LayerNorm(dim) | |
| self._ffn = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim)) | |
| def forward(self, pt_feat, order_idx, inv_order_idx, pad_idx, unpad_idx, pt_pos, batch_indices, voxel_size_mod=None): | |
| """ | |
| Args: | |
| pt_feat: (N, C) | |
| order_idx: (N,) the tokens in the order of the space-filling curve. | |
| inv_order_idx: (N,) the position of every token along the space-filling curve. | |
| pad_idx: (M,) M >= N, see pad_and_unpad_idx. | |
| unpad_idx: (N,) see pad_and_unpad_idx. | |
| pt_pos: (N, 3) positions in units of the normalization voxel size of the stage. | |
| batch_indices: (N,) | |
| voxel_size_mod: (B, 6, C) voxel size modulation shared by the stage, the deltas of | |
| (alpha_attn, beta_attn, gamma_attn, alpha_ffn, beta_ffn, gamma_ffn) from identity. | |
| Returns: | |
| (N, C) output features. | |
| """ | |
| assert pad_idx.shape[0] % self._group_size == 0 | |
| num_groups = pad_idx.shape[0] // self._group_size | |
| C = pt_feat.shape[1] | |
| conditioned = self._adaln_vs_bias is not None | |
| if conditioned: | |
| # In the bfloat16 of the encoder's autocast. | |
| mods = (voxel_size_mod + self._adaln_vs_bias).to(torch.bfloat16) | |
| if mods.requires_grad: | |
| # The same values as indexing, but the backward pass of indexing adds the gradients of all points of a | |
| # sample to its row one after another in bfloat16, which is slow and inaccurate. The matmul accumulates | |
| # them in float32. | |
| B = mods.shape[0] | |
| mods = (F.one_hot(batch_indices, B).to(mods.dtype) @ mods.reshape(B, -1)).view(-1, *mods.shape[1:]) | |
| # This is faster during forward pass but insanely slow backward because of thread locks. Don't use for training. | |
| else: | |
| mods = mods[batch_indices] | |
| alpha_attn, beta_attn, gamma_attn, alpha_ffn, beta_ffn, gamma_ffn = mods.unbind(1) | |
| normed_feat = self._ln_attn(pt_feat) | |
| if conditioned: | |
| # Not how AdaLNZero should be used but we trained our model like this and now it works... | |
| normed_feat = normed_feat + gamma_attn * normed_feat + beta_attn | |
| fused_pad_idx = order_idx[pad_idx] | |
| # SPDA gate values from the original input features. | |
| pt_gate = torch.sigmoid(self._sdpa_gate_lin(normed_feat)) if self._sdpa_gate_lin is not None else None | |
| qkv = self._pqkv(normed_feat)[fused_pad_idx] | |
| # K groups of G tokens: (K*G, 3C) -> (K, G, 3, H, C//H) -> 3 x (K, H, G, C//H) | |
| q, k, v = qkv.view(num_groups, self._group_size, 3, self._num_heads, C // self._num_heads).permute(2, 0, 3, 1, 4).unbind(0) | |
| if self._q_ln is not None: | |
| q, k = qk_layernorm_rope(q, k, self._q_ln, self._k_ln, self._rope, pt_pos[fused_pad_idx]) | |
| else: | |
| q, k = qk_rope(q, k, self._rope, pt_pos[fused_pad_idx]) | |
| del qkv | |
| fused_unpad_idx = unpad_idx[inv_order_idx] | |
| # (K, H, G, C//H) | |
| attn_out = F.scaled_dot_product_attention(q, k, v, is_causal=False) | |
| del q, k, v | |
| # (K, H, G, C//H) -> (K*G, C) -> (N, C) | |
| attn_out = attn_out.permute(0, 2, 1, 3).reshape(num_groups * self._group_size, C)[fused_unpad_idx] | |
| if pt_gate is not None: | |
| attn_out = attn_out * pt_gate | |
| attn_out = self._po(attn_out) | |
| feat = pt_feat + attn_out + alpha_attn * attn_out if conditioned else pt_feat + attn_out | |
| normed = self._ln_ffn(feat) | |
| if not conditioned: | |
| return feat + self._ffn(normed) | |
| ffn_out = self._ffn(normed + gamma_ffn * normed + beta_ffn) | |
| # Same AdaLNZero mess up as before, but this is how it is now. | |
| return feat + ffn_out + alpha_ffn * ffn_out | |
| class Pool(nn.Module): | |
| """Pool (stride 2) along each cell edge.""" | |
| def __init__(self, stride: int, in_dim: int, out_dim: int): | |
| super().__init__() | |
| n_bits_to_shift = math.log2(stride) | |
| assert n_bits_to_shift.is_integer() | |
| self._n_bits_to_shift = int(n_bits_to_shift) | |
| self._proj = nn.Linear(in_dim, out_dim) | |
| self._norm = nn.LayerNorm(in_dim) | |
| self._out_dim = out_dim | |
| self._activation = nn.GELU() | |
| self._stride = stride | |
| def forward(self, pt_feat, pt_pos, sf_idx, batch_idx, batch_size: int): | |
| """Pool the voxels and order the pooled ones along the pooled space-filling curves.. | |
| In train mode the four curves are shuffled for every sample, as in pretraining. | |
| Returns: | |
| * new features | |
| * new positions | |
| * new batch_idx, | |
| * new SFC indices | |
| * new order indices | |
| * new inverse order indices | |
| * new up indices | |
| """ | |
| # Shift by 1 bit for each dimension (3) to increase voxel size by factor 2 along each dimension. | |
| pooled_sf_idx = sf_idx >> self._n_bits_to_shift * 3 | |
| # Linear indices that also separate the samples of the batch. All four curves are offset, since the linear | |
| # indices also sort the pooled voxels below. Important to offset by 1. | |
| max_sf_idx = pooled_sf_idx.max() + 1 | |
| linear_idx = max_sf_idx * batch_idx + pooled_sf_idx | |
| # unique_pooled_idx (K) K <= N, up_idx (N) | |
| unique_pooled_idx, up_idx = torch.unique(linear_idx[0], sorted=False, return_inverse=True, return_counts=False) | |
| pt_feat = self._proj(self._norm(pt_feat)) | |
| out_feat = torch.zeros(unique_pooled_idx.shape[0], self._out_dim, device=pt_feat.device, dtype=pt_feat.dtype) | |
| # (N, C) -> (K, D) | |
| out_feat.scatter_reduce_(0, up_idx.unsqueeze(-1).expand(-1, out_feat.shape[-1]), pt_feat, reduce="amax", include_self=False) | |
| out_feat = self._activation(out_feat) | |
| # The positions and batch indices of the pooled voxels need no gradients, as in the training code. | |
| with torch.no_grad(): | |
| # (N, 3) -> (K, 3) | |
| out_pos = torch.empty(unique_pooled_idx.shape[0], pt_pos.shape[-1], device=pt_pos.device, dtype=pt_pos.dtype) | |
| out_pos.scatter_reduce_(0, up_idx.unsqueeze(-1).expand(-1, out_pos.shape[-1]), pt_pos, reduce="mean", include_self=False) | |
| # (N,) -> (K,) | |
| out_batch = torch.empty(unique_pooled_idx.shape[0], device=batch_idx.device, dtype=batch_idx.dtype) | |
| out_batch.scatter_reduce_(0, up_idx, batch_idx, reduce="amax", include_self=False) | |
| # The space-filling curve indices of the pooled voxels are those of the first voxel pooled into each of them. | |
| first_occurrence = torch.empty(unique_pooled_idx.shape[0], device=up_idx.device, dtype=up_idx.dtype) | |
| first_occurrence.scatter_reduce_(0, up_idx, torch.arange(up_idx.shape[0], device=up_idx.device), reduce="amin", include_self=False) | |
| pooled_sf_idx = pooled_sf_idx[..., first_occurrence] | |
| if self.training: | |
| pooled_sf_idx = batched_permute(pooled_sf_idx, out_batch, batch_size) | |
| pooled_linear_idx = max_sf_idx * out_batch + pooled_sf_idx | |
| # (4, K) The linear indices keep the samples separate and each sample in the order of the curve. | |
| order = torch.argsort(pooled_linear_idx, dim=-1) | |
| inv_order = torch.empty_like(order) | |
| inv_order.scatter_(-1, order, torch.arange(order.size(-1), device=order.device).expand_as(order)) | |
| return out_feat, out_pos, out_batch, pooled_sf_idx, order, inv_order, up_idx | |
| class UnPool(nn.Module): | |
| """Adds the projected features of the coarser stage to those of the voxels they were pooled from. | |
| Cleaner residual compared to PTv3 and derived models. | |
| """ | |
| def __init__(self, dim_lowres, dim_highres): | |
| super().__init__() | |
| # The affine norm can absorb the bias. | |
| self._proj = nn.Linear(dim_lowres, dim_highres, bias=False) | |
| self._norm = nn.LayerNorm(dim_lowres) | |
| def forward(self, feat_lowres, feat_highres, up_idx): | |
| return feat_highres + self._proj(self._norm(feat_lowres))[up_idx] | |
| class PointTransformer(nn.Module): | |
| """J3PA encoder.""" | |
| def __init__( | |
| self, | |
| stage_dims: list[int], | |
| num_down_layers_per_stage: list[int], | |
| num_up_layers_per_stage: list[int], | |
| num_heads_per_stage: list[int], | |
| qk_layernorm: bool, | |
| sdpa_gate: bool, | |
| voxel_size_conditioning_range: tuple[float, float] | None, | |
| gradient_checkpointing: bool = False, | |
| ): | |
| """Initialize. | |
| Args: | |
| stage_dims: Channels of each stage. | |
| num_down_layers_per_stage: Attention layers of each stage before its up connection, i.e. on the down path. | |
| All layers of the deepest stage are on the down path. | |
| num_up_layers_per_stage: Attention layers of each stage but the deepest after its up connection, i.e. on | |
| the up path. | |
| num_heads_per_stage: Attention heads of each stage. | |
| qk_layernorm: QK-LayerNorm in every attention layer. | |
| sdpa_gate: Gate the attention output of every attention layer, see PointSelfAttn. | |
| voxel_size_conditioning_range: For an encoder that takes the voxel size as input, the (min, max) first-stage | |
| voxel sizes in meters it was trained with. Its log voxel size, normalized to | |
| [-1, 1] over this range, is appended to the features of every input point | |
| and modulates all attention layers, through one shared modulation per stage | |
| plus a learned offset per layer (adaLN-single). None for an encoder without | |
| voxel size input. Either way the encoder runs with any voxel size. | |
| gradient_checkpointing: Whether to enable gradient checkpointing or not. Can be set later. | |
| """ | |
| num_stages = len(stage_dims) | |
| assert len(num_down_layers_per_stage) == num_stages and len(num_heads_per_stage) == num_stages | |
| assert len(num_up_layers_per_stage) == num_stages - 1, "Need the number of up layers of every stage but the deepest." | |
| super().__init__() | |
| self._stage_dims = list(stage_dims) | |
| self._num_up_layers = [*num_up_layers_per_stage, 0] | |
| # Where each stage's up layers start in _us_attn_layers. | |
| self._up_layer_starts = [sum(self._num_up_layers[:s]) for s in range(num_stages)] | |
| self._voxel_size_conditioning_range = voxel_size_conditioning_range | |
| conditioned = voxel_size_conditioning_range is not None | |
| if conditioned: | |
| # Per stage, shared by all its layers: u -> [u, sin(f*u), cos(f*u)] -> Linear(17, 64) -> GELU -> Linear(64, 6*C) | |
| # -> (B, 6, C) deltas of (alpha_attn, beta_attn, gamma_attn, alpha_ffn, beta_ffn, gamma_ffn). | |
| self._voxel_size_embed = nn.ModuleList([VoxelSizeEmbedding(6 * sd) for sd in stage_dims]) | |
| else: | |
| self._voxel_size_embed = None | |
| # The input point features, the positional encoding of the position in voxels and with conditioning the voxel | |
| # size, projected so that the norm of the first pooling does not wash out the small-scale point information. | |
| # The input points: [age in seconds, x, y, z in meters, intensity 0..255]. | |
| in_dim = 5 + INPUT_PE_DIM + int(conditioned) | |
| self._init_pe = PEDynamic(embed_dim=INPUT_PE_DIM, pos_dim=3, max_freq=1000) | |
| self._init_proj = nn.Sequential(nn.Linear(in_dim, stage_dims[0]), nn.GELU()) | |
| self._init_pool = Pool(stride=2, in_dim=stage_dims[0], out_dim=stage_dims[0]) | |
| def attn_layer(dim, num_heads): | |
| return PointSelfAttn(dim, num_heads, GROUP_SIZE, qk_layernorm=qk_layernorm, sdpa_gate=sdpa_gate, condition_voxel_size=conditioned) | |
| self._ds_attn_groups = nn.ModuleList( | |
| [ | |
| nn.ModuleList([attn_layer(sd, hd) for _ in range(nl)]) | |
| for nl, sd, hd in zip(num_down_layers_per_stage, stage_dims, num_heads_per_stage, strict=True) | |
| ] | |
| ) | |
| self._pool_layers = nn.ModuleList([Pool(stride=2, in_dim=stage_dims[i], out_dim=stage_dims[i + 1]) for i in range(num_stages - 1)]) | |
| # The up layers of all stages, shallowest first. | |
| self._us_attn_layers = nn.ModuleList( | |
| [ | |
| attn_layer(sd, hd) | |
| for sd, hd, nl in zip(stage_dims[:-1], num_heads_per_stage[:-1], num_up_layers_per_stage, strict=True) | |
| for _ in range(nl) | |
| ] | |
| ) | |
| self._unpool_layers = nn.ModuleList([UnPool(dim_lowres=stage_dims[i + 1], dim_highres=stage_dims[i]) for i in range(num_stages - 1)]) | |
| self._final_layernorms = nn.ModuleList([nn.LayerNorm(sd) for sd in stage_dims]) | |
| # Normalization voxel sizes of the positions: of the input positional encoding on the grid of the initial | |
| # embedding, and of RoPE in every stage, twice that of the previous one. | |
| self._pos_norm_voxel_size = POS_NORM_VOXEL_SIZE / self._init_pool._stride | |
| self._pos_stage_voxel_sizes = [POS_NORM_VOXEL_SIZE * 2**s for s in range(num_stages)] | |
| # Activation checkpointing of the initial embedding, every attention layer, pooling and unpooling. | |
| # Named as in Hugging Face, whose gradient_checkpointing_enable() of a wrapping model sets it. | |
| self.gradient_checkpointing = gradient_checkpointing | |
| def gradient_checkpointing_enable(self) -> None: | |
| self.gradient_checkpointing = True | |
| def gradient_checkpointing_disable(self) -> None: | |
| self.gradient_checkpointing = False | |
| def _maybe_checkpoint(self, function, *args, preserve_rng_state: bool = False): | |
| """function(*args), with activation checkpointing if it is enabled and gradients are computed.""" | |
| if self.gradient_checkpointing and torch.is_grad_enabled(): | |
| # Non-reentrant, so that the parameters of the initial embedding get gradients although none of its inputs | |
| # requires them. Where the recomputation redoes the random serialization of train mode (initial embedding and | |
| # pooling), it replays the same random numbers instead of drawing new ones, so that checkpointing leaves the | |
| # random number stream as is. | |
| return checkpoint(function, *args, use_reentrant=False, preserve_rng_state=preserve_rng_state) | |
| return function(*args) | |
| def num_stages(self) -> int: | |
| return len(self._stage_dims) | |
| def stage_dims(self) -> list[int]: | |
| return self._stage_dims | |
| def _initial_embed(self, points, batch_idx, voxel_size, voxel_size_u, batch_size): | |
| """Embed the input points, voxelize them with voxel_size, half the voxel size of the first stage, serialize them | |
| and pool them into the first stage.""" | |
| pos_s0 = points[..., XYZ_SLICE] | |
| # Raw point features and a PE of the position in voxels. | |
| feat_s0 = [points, self._init_pe(pos_s0 / self._pos_norm_voxel_size)] | |
| if self._voxel_size_conditioning_range is not None: | |
| feat_s0.append(voxel_size_u[batch_idx].to(points.dtype).view(-1, 1)) | |
| feat_s0 = torch.cat(feat_s0, dim=-1) | |
| grid_divisor = voxel_size[batch_idx] if isinstance(voxel_size, torch.Tensor) else voxel_size | |
| grid_idx = get_grid_idx(pos_s0, batch_idx, grid_divisor, batch_size=batch_size) | |
| sf_idx = space_filling_idx(grid_idx) | |
| feat_s0 = self._init_proj(feat_s0) | |
| return self._init_pool(feat_s0, pos_s0, sf_idx, batch_idx, batch_size) | |
| def forward( | |
| self, points: torch.Tensor, batch_idx: torch.Tensor | None = None, voxel_size: float | torch.Tensor | None = None | |
| ) -> PointTransformerOut: | |
| """Encode a point cloud or a batch of them. | |
| In train mode the layers of every stage take the space-filling curves in a random order and every sample's | |
| curves are shuffled at every pooling, as in pretraining. In eval mode the order is fixed. | |
| Args: | |
| points: (N, 5) float32 points of all samples, [age in seconds, x, y, z in meters, intensity 0..255], on the | |
| GPU. The age is the time from the point to the newest point of its sample (0 for a single sweep). | |
| batch_idx: (N,) int64 sample of each point, on the GPU, for a batch of B = batch_idx.max() + 1 samples. None | |
| for a single point cloud (B = 1), in that case it will be automatically generated as zeroes. | |
| voxel_size: Voxel size in meters of the first stage, a float for all samples or a (B,) tensor with one per | |
| sample. Defaults to VOXEL_SIZE. Every encoder runs with any voxel size, but the ones without a | |
| voxel size input were only trained with VOXEL_SIZE, and the others with the voxel sizes of | |
| their voxel_size_conditioning_range. | |
| Returns: | |
| The features, positions, batch indices and upsampling indices of every stage. | |
| """ | |
| assert points.is_cuda, "The encoder runs on the GPU." | |
| assert points.dim() == 2 and points.shape[-1] == 5, f"Expects (N, 5) points." | |
| # The batch size, which everything below takes from here. | |
| if batch_idx is None: | |
| batch_idx = torch.zeros(points.shape[0], device=points.device, dtype=torch.long) | |
| B = 1 | |
| else: | |
| assert batch_idx.shape == points.shape[:1] | |
| B = batch_idx.max().item() + 1 | |
| if voxel_size is None: | |
| voxel_size = VOXEL_SIZE | |
| # From here on the voxel sizes of the grid of the initial embedding, half those of the first stage, which the | |
| # training code took as input. Halving is exact, so they are those of training. | |
| stride = self._init_pool._stride | |
| if isinstance(voxel_size, torch.Tensor): | |
| assert voxel_size.shape == (B,), "Expects a float or one voxel size per sample." | |
| voxel_size = voxel_sizes = voxel_size.to(points.device, torch.float32) / stride | |
| else: | |
| # A float divides the grid as a Python float, as the default voxel size did in training and evaluation: on the | |
| # GPU this rounds differently from dividing by a tensor. | |
| voxel_size = float(voxel_size) / stride | |
| voxel_sizes = torch.full((B,), voxel_size, device=points.device, dtype=torch.float32) | |
| if self._voxel_size_conditioning_range is not None: | |
| # Scaling the voxel sizes and the range alike leaves the normalized log voxel size unchanged. It is computed | |
| # from the halved voxel sizes like in training, so that it rounds the same. | |
| voxel_size_range = tuple(v / stride for v in self._voxel_size_conditioning_range) | |
| voxel_size_u = log_voxel_size_coordinate(voxel_sizes, voxel_size_range) | |
| with torch.autocast("cuda", enabled=False): | |
| # (B, 6, C) per stage, shared by all attention layers of the stage. | |
| voxel_size_mod_stages = [embed(voxel_size_u).view(B, 6, -1) for embed in self._voxel_size_embed] | |
| else: | |
| voxel_size_u = None | |
| voxel_size_mod_stages = [None] * self.num_stages | |
| feat_stage, pos_stage, batch_idx_stage, sf_idx, order, inv_order, up_idx = self._maybe_checkpoint( | |
| self._initial_embed, points, batch_idx, voxel_size, voxel_size_u, B, preserve_rng_state=True | |
| ) | |
| pt_feats, pt_positions, batch_indices, up_idxs = [], [], [], [up_idx] | |
| orders, inv_orders, paddings, unpaddings, stage_curves = [], [], [], [], [] | |
| # Down path: the attention layers of each stage, then pooling to the next stage. | |
| for stage in range(self.num_stages): | |
| pad, unpad = pad_and_unpad_idx(batch_indices=batch_idx_stage, group_size=GROUP_SIZE, batch_size=B) | |
| # The curve of each attention layer of the stage, the down and then the up layers: the four in turn, in train | |
| # mode in a random order (a random permutation for every four layers). | |
| num_layers = len(self._ds_attn_groups[stage]) + self._num_up_layers[stage] | |
| if self.training: | |
| curves = torch.cat([torch.randperm(4) for _ in range(math.ceil(num_layers / 4))]).tolist() | |
| else: | |
| curves = [i % 4 for i in range(num_layers)] | |
| stage_curves.append(curves) | |
| pos_normed = pos_stage / self._pos_stage_voxel_sizes[stage] | |
| for i, layer in enumerate(self._ds_attn_groups[stage]): | |
| feat_stage = self._maybe_checkpoint( | |
| layer, feat_stage, order[curves[i]], inv_order[curves[i]], pad, unpad, pos_normed, batch_idx_stage, voxel_size_mod_stages[stage] | |
| ) | |
| pt_feats.append(feat_stage) | |
| pt_positions.append(pos_stage) | |
| batch_indices.append(batch_idx_stage) | |
| if stage < self.num_stages - 1: | |
| orders.append(order) | |
| inv_orders.append(inv_order) | |
| paddings.append(pad) | |
| unpaddings.append(unpad) | |
| feat_stage, pos_stage, batch_idx_stage, sf_idx, order, inv_order, up_idx = self._maybe_checkpoint( | |
| self._pool_layers[stage], feat_stage, pos_stage, sf_idx, batch_idx_stage, B, preserve_rng_state=True | |
| ) | |
| up_idxs.append(up_idx) | |
| # Up path: from the deepest stage, add the upsampled features of the coarser stage and run the up layers. | |
| for stage in reversed(range(self.num_stages - 1)): | |
| feat_stage = self._maybe_checkpoint(self._unpool_layers[stage], pt_feats[stage + 1], pt_feats[stage], up_idxs[stage + 1]) | |
| start = self._up_layer_starts[stage] | |
| up_layers = self._us_attn_layers[start : start + self._num_up_layers[stage]] | |
| pos_normed = pt_positions[stage] / self._pos_stage_voxel_sizes[stage] | |
| # The curves continue from the stage's down layers. | |
| for i, layer in enumerate(up_layers, start=len(self._ds_attn_groups[stage])): | |
| curve = stage_curves[stage][i] | |
| feat_stage = self._maybe_checkpoint( | |
| layer, | |
| feat_stage, | |
| orders[stage][curve], | |
| inv_orders[stage][curve], | |
| paddings[stage], | |
| unpaddings[stage], | |
| pos_normed, | |
| batch_indices[stage], | |
| voxel_size_mod_stages[stage], | |
| ) | |
| pt_feats[stage] = feat_stage | |
| pt_feats = [norm(feat) for norm, feat in zip(self._final_layernorms, pt_feats, strict=True)] | |
| return PointTransformerOut(pt_feats, pt_positions, batch_indices, up_idxs) |