paunas commited on
Commit
8b003e4
·
verified ·
1 Parent(s): e405c40

Upload model

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "J3PAModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_j3pa.J3PAConfig",
7
+ "AutoModel": "modeling_j3pa.J3PAModel"
8
+ },
9
+ "dtype": "float32",
10
+ "model_type": "j3pa",
11
+ "num_down_layers_per_stage": [
12
+ 2,
13
+ 2,
14
+ 2,
15
+ 2,
16
+ 4
17
+ ],
18
+ "num_heads_per_stage": [
19
+ 2,
20
+ 4,
21
+ 6,
22
+ 8,
23
+ 8
24
+ ],
25
+ "num_up_layers_per_stage": [
26
+ 2,
27
+ 2,
28
+ 2,
29
+ 2
30
+ ],
31
+ "qk_layernorm": false,
32
+ "sdpa_gate": false,
33
+ "stage_dims": [
34
+ 64,
35
+ 128,
36
+ 192,
37
+ 256,
38
+ 256
39
+ ],
40
+ "transformers_version": "5.8.0",
41
+ "voxel_size_conditioning_range": [
42
+ 0.04,
43
+ 0.2
44
+ ]
45
+ }
configuration_j3pa.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hugging Face configuration of the J3PA encoders."""
2
+
3
+ from transformers import PretrainedConfig
4
+
5
+
6
+ class J3PAConfig(PretrainedConfig):
7
+ """Architecture of a J3PA encoder, see PointTransformer. Defaults are J3PA-Large's; each repo's config.json sets all
8
+ fields."""
9
+
10
+ model_type = "j3pa"
11
+
12
+ def __init__(
13
+ self,
14
+ stage_dims=(128, 192, 256, 512, 1024),
15
+ num_down_layers_per_stage=(4, 4, 4, 10, 6),
16
+ num_up_layers_per_stage=(2, 2, 2, 2),
17
+ num_heads_per_stage=(2, 3, 4, 8, 16),
18
+ qk_layernorm=False,
19
+ sdpa_gate=True,
20
+ voxel_size_conditioning_range=(0.04, 0.2),
21
+ **kwargs,
22
+ ):
23
+ self.stage_dims = list(stage_dims)
24
+ self.num_down_layers_per_stage = list(num_down_layers_per_stage)
25
+ self.num_up_layers_per_stage = list(num_up_layers_per_stage)
26
+ self.num_heads_per_stage = list(num_heads_per_stage)
27
+ self.qk_layernorm = qk_layernorm
28
+ self.sdpa_gate = sdpa_gate
29
+ r = voxel_size_conditioning_range
30
+ self.voxel_size_conditioning_range = None if r is None else list(r)
31
+ super().__init__(**kwargs)
layers.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) Copyright 2026 Zenseact AB
2
+ """Embeddings of the encoder inputs: the positional encoding of the points and the voxel size embedding."""
3
+
4
+ import math
5
+
6
+ import torch
7
+ from torch import nn
8
+
9
+
10
+ class PEDynamic(nn.Module):
11
+ """Sinusoidal positional encoding of Attention Is All You Need (https://arxiv.org/abs/1706.03762), computed for
12
+ arbitrary positions."""
13
+
14
+ def __init__(self, embed_dim: int, pos_dim: int, max_freq: float):
15
+ """Initialize.
16
+
17
+ Args:
18
+ embed_dim: Dimensionality of the positional encoding.
19
+ pos_dim: Dimensionality of the positions to encode.
20
+ max_freq: Maximum frequency value.
21
+ """
22
+ super().__init__()
23
+ # Too many encodings are computed if the dimensionalities do not line up, and cut off in forward.
24
+ dim_offset = embed_dim % (pos_dim * 2)
25
+ self._embed_dim = embed_dim
26
+ axis_dim = math.ceil((embed_dim + dim_offset) / pos_dim)
27
+ fqs = torch.arange(axis_dim // 2, dtype=torch.float)
28
+ fqs = torch.exp(-2 * (fqs / axis_dim) * math.log(max_freq))
29
+ self.register_buffer("_fqs", fqs.unsqueeze(0))
30
+
31
+ def forward(self, pos: torch.Tensor) -> torch.Tensor:
32
+ """(..., pos_dim) positions -> (..., embed_dim) positional encodings."""
33
+ pe = pos.unsqueeze(-1) * self._fqs # (..., N, 1) * (1, D/N/2) -> (..., N, D/N/2)
34
+ pe = pe.flatten(start_dim=-2, end_dim=-1) # (..., N, D/N/2) -> (..., D/2)
35
+ pe = torch.cat([torch.sin(pe), torch.cos(pe)], dim=-1) # (..., D)
36
+ # Cutting off after the concatenation only drops cosines, of different axes.
37
+ return pe[..., : self._embed_dim]
38
+
39
+
40
+ def log_voxel_size_coordinate(voxel_size: torch.Tensor, voxel_size_range: tuple[float, float]) -> torch.Tensor:
41
+ """log2 voxel size mapped linearly so that the training range of voxel sizes spans [-1, 1]."""
42
+ low, high = math.log2(voxel_size_range[0]), math.log2(voxel_size_range[1])
43
+ return (voxel_size.float().log2() - (low + high) / 2) / ((high - low) / 2)
44
+
45
+
46
+ class VoxelSizeEmbedding(nn.Module):
47
+ """Fourier features of the normalised log voxel size (see log_voxel_size_coordinate) followed by a small MLP."""
48
+
49
+ def __init__(self, out_dim: int, num_freqs: int = 8, hidden_dim: int = 64):
50
+ super().__init__()
51
+ # 0.25*pi .. 2*pi: at most two periods over [-1, 1], so the embedding stays smooth in the voxel size. Not in
52
+ # the checkpoints, and computed on the CPU as in training so that the values are the same.
53
+ freqs = math.pi * 2 ** torch.linspace(-2, 1, num_freqs, device="cpu")
54
+ self.register_buffer("_freqs", freqs, persistent=False)
55
+ self._mlp = nn.Sequential(nn.Linear(2 * num_freqs + 1, hidden_dim), nn.GELU(), nn.Linear(hidden_dim, out_dim))
56
+
57
+ def forward(self, u: torch.Tensor) -> torch.Tensor:
58
+ """(B,) normalised log voxel sizes -> (B, out_dim)."""
59
+ u = u.float().unsqueeze(-1)
60
+ phase = u * self._freqs
61
+ return self._mlp(torch.cat([u, phase.sin(), phase.cos()], dim=-1))
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43c72b0a34a8d4697facb9453fb2f0b0096118cd0c2325761e7aded0a9e9e253
3
+ size 39207396
modeling_j3pa.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hugging Face model of the J3PA encoders."""
2
+
3
+ import math
4
+
5
+ import torch
6
+ from transformers import PreTrainedModel
7
+
8
+ # Loading from a downloaded folder only copies the files this module imports directly, and transformers only
9
+ # recognizes `from .module import name`: import every code file here.
10
+ from .configuration_j3pa import J3PAConfig
11
+ from .layers import VoxelSizeEmbedding
12
+ from .pt_transf import PointTransformer, PointTransformerOut
13
+ from .qk_layernorm_rope_triton import qk_layernorm_rope # noqa: F401
14
+ from .rope import RoPE # noqa: F401
15
+ from .rope_triton import qk_rope # noqa: F401
16
+ from .space_filling_curves_triton import space_filling_idx # noqa: F401
17
+
18
+
19
+ class J3PAModel(PreTrainedModel):
20
+ """A J3PA encoder with Hugging Face loading and saving. The encoder itself is PointTransformer."""
21
+
22
+ config_class = J3PAConfig
23
+ base_model_prefix = "j3pa"
24
+ main_input_name = "points"
25
+ # Lets model.gradient_checkpointing_enable() switch on PointTransformer.gradient_checkpointing.
26
+ supports_gradient_checkpointing = True
27
+
28
+ def __init__(self, config: J3PAConfig):
29
+ super().__init__(config)
30
+ self.encoder = PointTransformer(
31
+ stage_dims=config.stage_dims,
32
+ num_down_layers_per_stage=config.num_down_layers_per_stage,
33
+ num_up_layers_per_stage=config.num_up_layers_per_stage,
34
+ num_heads_per_stage=config.num_heads_per_stage,
35
+ qk_layernorm=config.qk_layernorm,
36
+ sdpa_gate=config.sdpa_gate,
37
+ voxel_size_conditioning_range=config.voxel_size_conditioning_range,
38
+ )
39
+ self.post_init()
40
+
41
+ def _init_weights(self, module):
42
+ # Loading refills buffers that are not in the weights file with uninitialized memory: recompute this one as
43
+ # VoxelSizeEmbedding.__init__ does.
44
+ if isinstance(module, VoxelSizeEmbedding):
45
+ module._freqs.copy_(math.pi * 2 ** torch.linspace(-2, 1, module._freqs.numel(), device="cpu"))
46
+
47
+ def forward(self, points, batch_idx=None, voxel_size=None) -> PointTransformerOut:
48
+ """See PointTransformer.forward. points can also be a list of (N_i, 5) point clouds, without batch_idx."""
49
+ # In bfloat16 the RoPE angles are rounded and the voxel size MLP breaks.
50
+ if self.encoder._init_proj[0].weight.dtype != torch.float32:
51
+ raise ValueError("Keep J3PA in float32 (the default): it computes in bfloat16 internally.")
52
+ if not isinstance(points, torch.Tensor):
53
+ batch_idx = torch.cat([torch.full((len(p),), i, device=p.device) for i, p in enumerate(points)])
54
+ points = torch.cat(points)
55
+ return self.encoder(points, batch_idx, voxel_size=voxel_size)
pt_transf.py ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Encoder of J3PA.
2
+
3
+ This is a stripped copy of the released training code. See the paper for details.
4
+ """
5
+
6
+ import math
7
+ from collections.abc import Sequence
8
+ from typing import NamedTuple
9
+
10
+ import torch
11
+ from torch import nn
12
+ from torch.nn import functional as F
13
+ from torch.utils.checkpoint import checkpoint
14
+
15
+ from .layers import PEDynamic, VoxelSizeEmbedding, log_voxel_size_coordinate
16
+ from .qk_layernorm_rope_triton import qk_layernorm_rope
17
+ from .rope import RoPE
18
+ from .rope_triton import qk_rope
19
+ from .space_filling_curves_triton import space_filling_idx
20
+
21
+ # Expected x, y, z indices for points.
22
+ XYZ_SLICE = slice(1, 4)
23
+ # Size of the positional encoding of the input positions.
24
+ INPUT_PE_DIM = 64
25
+ # Tokens per attention group.
26
+ GROUP_SIZE = 1024
27
+ # Default voxel size (meters) of the first stage. This voxel size was used for the main evaluation table in the paper.
28
+ VOXEL_SIZE = 0.05
29
+ # This is used for normalizing the RoPE input coordinates, regardless of the voxel size being used.
30
+ POS_NORM_VOXEL_SIZE = 0.05
31
+
32
+
33
+ class PointTransformerOut(NamedTuple):
34
+ """Outputs of the encoder stages, from fine to coarse.
35
+
36
+ The voxel size becomes 2x larger for each hip between stages.
37
+
38
+ point_features() and voxel_features() append the features across all stages for a given point
39
+ or finest stage voxel.
40
+ """
41
+
42
+ # (N_s, C_s) features of the voxels of stage s.
43
+ features: list[torch.Tensor]
44
+ # (N_s, 3) aggregated position of each voxel.
45
+ positions: list[torch.Tensor]
46
+ # (N_s,) sample in the batch of each voxel of stage s.
47
+ batch_indices: list[torch.Tensor]
48
+ # Mapping from each stage to the previous stage (N_s-1,). This can be used to
49
+ # cascade the output of each stage back to the finest stage or points.
50
+ up_indices: list[torch.Tensor]
51
+
52
+ def point_features(self, stages: int | Sequence[int] | None = None) -> torch.Tensor:
53
+ """Features for every point, concatenated across stages.
54
+
55
+ Args:
56
+ stages: The stage or stages to take the features of, negative ones counted from the deepest. If None is passed
57
+ all stages are aggregated.
58
+
59
+ Returns:
60
+ (N, D) tensor for N points with D the sum of stage-wise channel counts.
61
+ """
62
+ return self._gather_stages(self.up_indices[0], stages)
63
+
64
+ def voxel_features(self, stages: int | Sequence[int] | None = None) -> torch.Tensor:
65
+ """Features for every voxel at the finest stage, concatenated from across stages.
66
+
67
+ See point_features.
68
+ """
69
+ first_stage = torch.arange(len(self.features[0]), device=self.features[0].device)
70
+ return self._gather_stages(first_stage, stages)
71
+
72
+ def _gather_stages(self, idx: torch.Tensor, stages: int | Sequence[int] | None) -> torch.Tensor:
73
+ num_stages = len(self.features)
74
+ if stages is None:
75
+ stages = range(num_stages - 1, -1, -1)
76
+ elif isinstance(stages, int):
77
+ stages = [stages]
78
+ stages = [range(num_stages)[s] for s in stages]
79
+
80
+ # Aggregate the up indices into a single compound index to avoid more gathers than needed.
81
+ stage_idx = [idx]
82
+ for t in range(1, max(stages) + 1):
83
+ stage_idx.append(self.up_indices[t][stage_idx[-1]])
84
+
85
+ out = self.features[0].new_empty(len(idx), sum(self.features[s].shape[1] for s in stages))
86
+ needs_grad = torch.is_grad_enabled() and any(self.features[s].requires_grad for s in stages)
87
+ col = 0
88
+ for s in stages:
89
+ dim = self.features[s].shape[1]
90
+ if needs_grad:
91
+ out[:, col : col + dim] = self.features[s][stage_idx[s]]
92
+ else:
93
+ torch.index_select(self.features[s], 0, stage_idx[s], out=out[:, col : col + dim])
94
+ col += dim
95
+ return out
96
+
97
+
98
+ def get_grid_idx(pt_pos: torch.Tensor, batch_idx: torch.Tensor, cell_size: float | torch.Tensor, batch_size: int):
99
+ """Get the grid index of each point, from the minimum position of its sample.
100
+
101
+ Args:
102
+ pt_pos: (N, 3) point positions.
103
+ batch_idx: (N,) batch indices.
104
+ cell_size: float or (N,) per-point cell sizes.
105
+ batch_size: Number of samples in the batch.
106
+
107
+ Returns:
108
+ (N, 3) grid indices.
109
+ """
110
+ min_pos = torch.empty((batch_size, 3), device=pt_pos.device, dtype=pt_pos.dtype)
111
+ # scatter_reduce_ does not broadcast, so batch_idx is expanded to 3 channels manually.
112
+ min_pos.scatter_reduce_(0, batch_idx.unsqueeze(-1).expand(-1, 3), pt_pos, reduce="amin", include_self=False)
113
+ if isinstance(cell_size, torch.Tensor):
114
+ cell_size = cell_size.unsqueeze(-1)
115
+ return torch.div(pt_pos - min_pos[batch_idx], cell_size, rounding_mode="trunc").long()
116
+
117
+
118
+ def pad_and_unpad_idx(batch_indices: torch.Tensor, group_size: int, batch_size: int) -> tuple[torch.Tensor, torch.Tensor]:
119
+ """Indices that pad every sample to a multiple of group_size tokens, and that remove the padding again.
120
+
121
+ The last group of each sample is filled up with repeated tokens of the sample, so that every group only holds tokens
122
+ of one sample.
123
+
124
+ Returns:
125
+ pad_idx: (M,) M >= N, the token (in an order with the tokens of each sample contiguous) of every padded position.
126
+ unpad_idx: (N,) the padded position of every token.
127
+ """
128
+ counts = torch.empty((batch_size,), device=batch_indices.device, dtype=batch_indices.dtype)
129
+ counts.scatter_reduce_(0, batch_indices, torch.ones_like(batch_indices), reduce="sum", include_self=False)
130
+ padded_counts = ((counts + group_size - 1) // group_size) * group_size
131
+
132
+ pad_idx = torch.arange(padded_counts.sum(), device=batch_indices.device, dtype=batch_indices.dtype)
133
+
134
+ pad_batch_indices = torch.arange(batch_size, device=batch_indices.device, dtype=batch_indices.dtype).repeat_interleave(padded_counts)
135
+ pad_batch_offsets = (torch.cumsum(counts, 0) - counts)[pad_batch_indices]
136
+ pad_offsets = (torch.cumsum(padded_counts, 0) - padded_counts)[pad_batch_indices]
137
+ pad_idx -= pad_offsets
138
+
139
+ counts_per_point = counts[pad_batch_indices]
140
+ unpad_mask = pad_idx < counts_per_point
141
+ last_group_start = torch.clamp(counts_per_point - group_size, min=0)
142
+
143
+ pad_idx = torch.where(unpad_mask, pad_idx, last_group_start + (pad_idx % counts_per_point))
144
+
145
+ # The unpadding indices index the padded tensor and the padding indices the original one, so they are offset by
146
+ # the start of each sample in the padded and in the original tensor.
147
+ unpad_idx = pad_idx + pad_offsets
148
+ unpad_idx = unpad_idx[unpad_mask]
149
+ pad_idx += pad_batch_offsets
150
+ return pad_idx, unpad_idx
151
+
152
+
153
+ def batched_permute(sf_idx: torch.Tensor, batch_idx: torch.Tensor, batch_size: int) -> torch.Tensor:
154
+ """For random sample-wise permutation of the space-filling curves."""
155
+ # (B, 4) a random permutation per sample -> (4, N) the row each point takes its index from.
156
+ permutations = torch.argsort(torch.rand(batch_size, 4, device=sf_idx.device), dim=1)
157
+ return torch.gather(sf_idx, dim=0, index=permutations[batch_idx].T)
158
+
159
+
160
+ class PointSelfAttn(nn.Module):
161
+ """Pre-norm transformer layer with grouped attention of tokens consecutive along a space-filling curve."""
162
+ def __init__(self, dim: int, num_heads: int, group_size: int, qk_layernorm: bool, sdpa_gate: bool, condition_voxel_size: bool):
163
+ """Initialize.
164
+
165
+ Args:
166
+ dim, num_heads: Obvious.
167
+ group_size: Tokens per attention group.
168
+ qk_layernorm: LayerNorm of the queries and keys over the head dim, before RoPE.
169
+ sdpa_gate: Gate the attention output elementwise with a sigmoid of a linear map of the token's normalized
170
+ input, before the output projection.
171
+ condition_voxel_size: Modulate the layer with the voxel size modulation of its stage plus a learned
172
+ per-layer offset.
173
+ """
174
+ assert dim % num_heads == 0
175
+ super().__init__()
176
+ self._ln_attn = nn.LayerNorm(dim)
177
+ # Per-layer offset on the stage's shared voxel size modulation (adaLN-single). Zero is unmodulated.
178
+ self._adaln_vs_bias = nn.Parameter(torch.zeros(6, dim)) if condition_voxel_size else None
179
+ self._pqkv = nn.Linear(dim, 3 * dim)
180
+ self._q_ln = nn.LayerNorm(dim // num_heads) if qk_layernorm else None
181
+ self._k_ln = nn.LayerNorm(dim // num_heads) if qk_layernorm else None
182
+ self._rope = RoPE(dim=dim, pos_dim=3, max_freq=100, num_heads=num_heads)
183
+ self._po = nn.Linear(dim, dim)
184
+ self._sdpa_gate_lin = nn.Linear(dim, dim) if sdpa_gate else None
185
+ self._num_heads = num_heads
186
+ self._group_size = group_size
187
+ self._ln_ffn = nn.LayerNorm(dim)
188
+ self._ffn = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim))
189
+
190
+ def forward(self, pt_feat, order_idx, inv_order_idx, pad_idx, unpad_idx, pt_pos, batch_indices, voxel_size_mod=None):
191
+ """
192
+ Args:
193
+ pt_feat: (N, C)
194
+ order_idx: (N,) the tokens in the order of the space-filling curve.
195
+ inv_order_idx: (N,) the position of every token along the space-filling curve.
196
+ pad_idx: (M,) M >= N, see pad_and_unpad_idx.
197
+ unpad_idx: (N,) see pad_and_unpad_idx.
198
+ pt_pos: (N, 3) positions in units of the normalization voxel size of the stage.
199
+ batch_indices: (N,)
200
+ voxel_size_mod: (B, 6, C) voxel size modulation shared by the stage, the deltas of
201
+ (alpha_attn, beta_attn, gamma_attn, alpha_ffn, beta_ffn, gamma_ffn) from identity.
202
+
203
+ Returns:
204
+ (N, C) output features.
205
+ """
206
+ assert pad_idx.shape[0] % self._group_size == 0
207
+ num_groups = pad_idx.shape[0] // self._group_size
208
+ C = pt_feat.shape[1]
209
+ conditioned = self._adaln_vs_bias is not None
210
+ if conditioned:
211
+ # In the bfloat16 of the encoder's autocast.
212
+ mods = (voxel_size_mod + self._adaln_vs_bias).to(torch.bfloat16)
213
+ if mods.requires_grad:
214
+ # The same values as indexing, but the backward pass of indexing adds the gradients of all points of a
215
+ # sample to its row one after another in bfloat16, which is slow and inaccurate. The matmul accumulates
216
+ # them in float32.
217
+ B = mods.shape[0]
218
+ mods = (F.one_hot(batch_indices, B).to(mods.dtype) @ mods.reshape(B, -1)).view(-1, *mods.shape[1:])
219
+ # This is faster during forward pass but insanely slow backward because of thread locks. Don't use for training.
220
+ else:
221
+ mods = mods[batch_indices]
222
+ alpha_attn, beta_attn, gamma_attn, alpha_ffn, beta_ffn, gamma_ffn = mods.unbind(1)
223
+
224
+ normed_feat = self._ln_attn(pt_feat)
225
+ if conditioned:
226
+ # Not how AdaLNZero should be used but we trained our model like this and now it works...
227
+ normed_feat = normed_feat + gamma_attn * normed_feat + beta_attn
228
+
229
+ fused_pad_idx = order_idx[pad_idx]
230
+
231
+ # SPDA gate values from the original input features.
232
+ pt_gate = torch.sigmoid(self._sdpa_gate_lin(normed_feat)) if self._sdpa_gate_lin is not None else None
233
+
234
+ qkv = self._pqkv(normed_feat)[fused_pad_idx]
235
+ # K groups of G tokens: (K*G, 3C) -> (K, G, 3, H, C//H) -> 3 x (K, H, G, C//H)
236
+ 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)
237
+ if self._q_ln is not None:
238
+ q, k = qk_layernorm_rope(q, k, self._q_ln, self._k_ln, self._rope, pt_pos[fused_pad_idx])
239
+ else:
240
+ q, k = qk_rope(q, k, self._rope, pt_pos[fused_pad_idx])
241
+ del qkv
242
+
243
+ fused_unpad_idx = unpad_idx[inv_order_idx]
244
+ # (K, H, G, C//H)
245
+ attn_out = F.scaled_dot_product_attention(q, k, v, is_causal=False)
246
+ del q, k, v
247
+ # (K, H, G, C//H) -> (K*G, C) -> (N, C)
248
+ attn_out = attn_out.permute(0, 2, 1, 3).reshape(num_groups * self._group_size, C)[fused_unpad_idx]
249
+ if pt_gate is not None:
250
+ attn_out = attn_out * pt_gate
251
+ attn_out = self._po(attn_out)
252
+ feat = pt_feat + attn_out + alpha_attn * attn_out if conditioned else pt_feat + attn_out
253
+
254
+ normed = self._ln_ffn(feat)
255
+ if not conditioned:
256
+ return feat + self._ffn(normed)
257
+ ffn_out = self._ffn(normed + gamma_ffn * normed + beta_ffn)
258
+
259
+ # Same AdaLNZero mess up as before, but this is how it is now.
260
+ return feat + ffn_out + alpha_ffn * ffn_out
261
+
262
+
263
+ class Pool(nn.Module):
264
+ """Pool (stride 2) along each cell edge."""
265
+ def __init__(self, stride: int, in_dim: int, out_dim: int):
266
+ super().__init__()
267
+ n_bits_to_shift = math.log2(stride)
268
+ assert n_bits_to_shift.is_integer()
269
+ self._n_bits_to_shift = int(n_bits_to_shift)
270
+ self._proj = nn.Linear(in_dim, out_dim)
271
+ self._norm = nn.LayerNorm(in_dim)
272
+ self._out_dim = out_dim
273
+ self._activation = nn.GELU()
274
+ self._stride = stride
275
+
276
+ def forward(self, pt_feat, pt_pos, sf_idx, batch_idx, batch_size: int):
277
+ """Pool the voxels and order the pooled ones along the pooled space-filling curves..
278
+
279
+ In train mode the four curves are shuffled for every sample, as in pretraining.
280
+
281
+ Returns:
282
+ * new features
283
+ * new positions
284
+ * new batch_idx,
285
+ * new SFC indices
286
+ * new order indices
287
+ * new inverse order indices
288
+ * new up indices
289
+ """
290
+ # Shift by 1 bit for each dimension (3) to increase voxel size by factor 2 along each dimension.
291
+ pooled_sf_idx = sf_idx >> self._n_bits_to_shift * 3
292
+
293
+ # Linear indices that also separate the samples of the batch. All four curves are offset, since the linear
294
+ # indices also sort the pooled voxels below. Important to offset by 1.
295
+ max_sf_idx = pooled_sf_idx.max() + 1
296
+ linear_idx = max_sf_idx * batch_idx + pooled_sf_idx
297
+
298
+ # unique_pooled_idx (K) K <= N, up_idx (N)
299
+ unique_pooled_idx, up_idx = torch.unique(linear_idx[0], sorted=False, return_inverse=True, return_counts=False)
300
+
301
+ pt_feat = self._proj(self._norm(pt_feat))
302
+ out_feat = torch.zeros(unique_pooled_idx.shape[0], self._out_dim, device=pt_feat.device, dtype=pt_feat.dtype)
303
+ # (N, C) -> (K, D)
304
+ out_feat.scatter_reduce_(0, up_idx.unsqueeze(-1).expand(-1, out_feat.shape[-1]), pt_feat, reduce="amax", include_self=False)
305
+ out_feat = self._activation(out_feat)
306
+
307
+ # The positions and batch indices of the pooled voxels need no gradients, as in the training code.
308
+ with torch.no_grad():
309
+ # (N, 3) -> (K, 3)
310
+ out_pos = torch.empty(unique_pooled_idx.shape[0], pt_pos.shape[-1], device=pt_pos.device, dtype=pt_pos.dtype)
311
+ out_pos.scatter_reduce_(0, up_idx.unsqueeze(-1).expand(-1, out_pos.shape[-1]), pt_pos, reduce="mean", include_self=False)
312
+
313
+ # (N,) -> (K,)
314
+ out_batch = torch.empty(unique_pooled_idx.shape[0], device=batch_idx.device, dtype=batch_idx.dtype)
315
+ out_batch.scatter_reduce_(0, up_idx, batch_idx, reduce="amax", include_self=False)
316
+
317
+ # The space-filling curve indices of the pooled voxels are those of the first voxel pooled into each of them.
318
+ first_occurrence = torch.empty(unique_pooled_idx.shape[0], device=up_idx.device, dtype=up_idx.dtype)
319
+ first_occurrence.scatter_reduce_(0, up_idx, torch.arange(up_idx.shape[0], device=up_idx.device), reduce="amin", include_self=False)
320
+ pooled_sf_idx = pooled_sf_idx[..., first_occurrence]
321
+ if self.training:
322
+ pooled_sf_idx = batched_permute(pooled_sf_idx, out_batch, batch_size)
323
+ pooled_linear_idx = max_sf_idx * out_batch + pooled_sf_idx
324
+
325
+ # (4, K) The linear indices keep the samples separate and each sample in the order of the curve.
326
+ order = torch.argsort(pooled_linear_idx, dim=-1)
327
+ inv_order = torch.empty_like(order)
328
+ inv_order.scatter_(-1, order, torch.arange(order.size(-1), device=order.device).expand_as(order))
329
+
330
+ return out_feat, out_pos, out_batch, pooled_sf_idx, order, inv_order, up_idx
331
+
332
+
333
+ class UnPool(nn.Module):
334
+ """Adds the projected features of the coarser stage to those of the voxels they were pooled from.
335
+
336
+ Cleaner residual compared to PTv3 and derived models.
337
+ """
338
+ def __init__(self, dim_lowres, dim_highres):
339
+ super().__init__()
340
+ # The affine norm can absorb the bias.
341
+ self._proj = nn.Linear(dim_lowres, dim_highres, bias=False)
342
+ self._norm = nn.LayerNorm(dim_lowres)
343
+
344
+ def forward(self, feat_lowres, feat_highres, up_idx):
345
+ return feat_highres + self._proj(self._norm(feat_lowres))[up_idx]
346
+
347
+
348
+ class PointTransformer(nn.Module):
349
+ """J3PA encoder."""
350
+ def __init__(
351
+ self,
352
+ stage_dims: list[int],
353
+ num_down_layers_per_stage: list[int],
354
+ num_up_layers_per_stage: list[int],
355
+ num_heads_per_stage: list[int],
356
+ qk_layernorm: bool,
357
+ sdpa_gate: bool,
358
+ voxel_size_conditioning_range: tuple[float, float] | None,
359
+ gradient_checkpointing: bool = False,
360
+ ):
361
+ """Initialize.
362
+
363
+ Args:
364
+ stage_dims: Channels of each stage.
365
+ num_down_layers_per_stage: Attention layers of each stage before its up connection, i.e. on the down path.
366
+ All layers of the deepest stage are on the down path.
367
+ num_up_layers_per_stage: Attention layers of each stage but the deepest after its up connection, i.e. on
368
+ the up path.
369
+ num_heads_per_stage: Attention heads of each stage.
370
+ qk_layernorm: QK-LayerNorm in every attention layer.
371
+ sdpa_gate: Gate the attention output of every attention layer, see PointSelfAttn.
372
+ voxel_size_conditioning_range: For an encoder that takes the voxel size as input, the (min, max) first-stage
373
+ voxel sizes in meters it was trained with. Its log voxel size, normalized to
374
+ [-1, 1] over this range, is appended to the features of every input point
375
+ and modulates all attention layers, through one shared modulation per stage
376
+ plus a learned offset per layer (adaLN-single). None for an encoder without
377
+ voxel size input. Either way the encoder runs with any voxel size.
378
+ gradient_checkpointing: Whether to enable gradient checkpointing or not. Can be set later.
379
+ """
380
+ num_stages = len(stage_dims)
381
+ assert len(num_down_layers_per_stage) == num_stages and len(num_heads_per_stage) == num_stages
382
+ assert len(num_up_layers_per_stage) == num_stages - 1, "Need the number of up layers of every stage but the deepest."
383
+ super().__init__()
384
+ self._stage_dims = list(stage_dims)
385
+ self._num_up_layers = [*num_up_layers_per_stage, 0]
386
+ # Where each stage's up layers start in _us_attn_layers.
387
+ self._up_layer_starts = [sum(self._num_up_layers[:s]) for s in range(num_stages)]
388
+ self._voxel_size_conditioning_range = voxel_size_conditioning_range
389
+ conditioned = voxel_size_conditioning_range is not None
390
+
391
+ if conditioned:
392
+ # Per stage, shared by all its layers: u -> [u, sin(f*u), cos(f*u)] -> Linear(17, 64) -> GELU -> Linear(64, 6*C)
393
+ # -> (B, 6, C) deltas of (alpha_attn, beta_attn, gamma_attn, alpha_ffn, beta_ffn, gamma_ffn).
394
+ self._voxel_size_embed = nn.ModuleList([VoxelSizeEmbedding(6 * sd) for sd in stage_dims])
395
+ else:
396
+ self._voxel_size_embed = None
397
+
398
+ # The input point features, the positional encoding of the position in voxels and with conditioning the voxel
399
+ # size, projected so that the norm of the first pooling does not wash out the small-scale point information.
400
+ # The input points: [age in seconds, x, y, z in meters, intensity 0..255].
401
+ in_dim = 5 + INPUT_PE_DIM + int(conditioned)
402
+ self._init_pe = PEDynamic(embed_dim=INPUT_PE_DIM, pos_dim=3, max_freq=1000)
403
+ self._init_proj = nn.Sequential(nn.Linear(in_dim, stage_dims[0]), nn.GELU())
404
+ self._init_pool = Pool(stride=2, in_dim=stage_dims[0], out_dim=stage_dims[0])
405
+
406
+ def attn_layer(dim, num_heads):
407
+ return PointSelfAttn(dim, num_heads, GROUP_SIZE, qk_layernorm=qk_layernorm, sdpa_gate=sdpa_gate, condition_voxel_size=conditioned)
408
+
409
+ self._ds_attn_groups = nn.ModuleList(
410
+ [
411
+ nn.ModuleList([attn_layer(sd, hd) for _ in range(nl)])
412
+ for nl, sd, hd in zip(num_down_layers_per_stage, stage_dims, num_heads_per_stage, strict=True)
413
+ ]
414
+ )
415
+ 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)])
416
+ # The up layers of all stages, shallowest first.
417
+ self._us_attn_layers = nn.ModuleList(
418
+ [
419
+ attn_layer(sd, hd)
420
+ for sd, hd, nl in zip(stage_dims[:-1], num_heads_per_stage[:-1], num_up_layers_per_stage, strict=True)
421
+ for _ in range(nl)
422
+ ]
423
+ )
424
+ self._unpool_layers = nn.ModuleList([UnPool(dim_lowres=stage_dims[i + 1], dim_highres=stage_dims[i]) for i in range(num_stages - 1)])
425
+ self._final_layernorms = nn.ModuleList([nn.LayerNorm(sd) for sd in stage_dims])
426
+
427
+ # Normalization voxel sizes of the positions: of the input positional encoding on the grid of the initial
428
+ # embedding, and of RoPE in every stage, twice that of the previous one.
429
+ self._pos_norm_voxel_size = POS_NORM_VOXEL_SIZE / self._init_pool._stride
430
+ self._pos_stage_voxel_sizes = [POS_NORM_VOXEL_SIZE * 2**s for s in range(num_stages)]
431
+
432
+ # Activation checkpointing of the initial embedding, every attention layer, pooling and unpooling.
433
+ # Named as in Hugging Face, whose gradient_checkpointing_enable() of a wrapping model sets it.
434
+ self.gradient_checkpointing = gradient_checkpointing
435
+
436
+ def gradient_checkpointing_enable(self) -> None:
437
+ self.gradient_checkpointing = True
438
+
439
+ def gradient_checkpointing_disable(self) -> None:
440
+ self.gradient_checkpointing = False
441
+
442
+ def _maybe_checkpoint(self, function, *args, preserve_rng_state: bool = False):
443
+ """function(*args), with activation checkpointing if it is enabled and gradients are computed."""
444
+ if self.gradient_checkpointing and torch.is_grad_enabled():
445
+ # Non-reentrant, so that the parameters of the initial embedding get gradients although none of its inputs
446
+ # requires them. Where the recomputation redoes the random serialization of train mode (initial embedding and
447
+ # pooling), it replays the same random numbers instead of drawing new ones, so that checkpointing leaves the
448
+ # random number stream as is.
449
+ return checkpoint(function, *args, use_reentrant=False, preserve_rng_state=preserve_rng_state)
450
+ return function(*args)
451
+
452
+ @property
453
+ def num_stages(self) -> int:
454
+ return len(self._stage_dims)
455
+
456
+ @property
457
+ def stage_dims(self) -> list[int]:
458
+ return self._stage_dims
459
+
460
+ def _initial_embed(self, points, batch_idx, voxel_size, voxel_size_u, batch_size):
461
+ """Embed the input points, voxelize them with voxel_size, half the voxel size of the first stage, serialize them
462
+ and pool them into the first stage."""
463
+ pos_s0 = points[..., XYZ_SLICE]
464
+ # Raw point features and a PE of the position in voxels.
465
+ feat_s0 = [points, self._init_pe(pos_s0 / self._pos_norm_voxel_size)]
466
+ if self._voxel_size_conditioning_range is not None:
467
+ feat_s0.append(voxel_size_u[batch_idx].to(points.dtype).view(-1, 1))
468
+ feat_s0 = torch.cat(feat_s0, dim=-1)
469
+
470
+ grid_divisor = voxel_size[batch_idx] if isinstance(voxel_size, torch.Tensor) else voxel_size
471
+ grid_idx = get_grid_idx(pos_s0, batch_idx, grid_divisor, batch_size=batch_size)
472
+ sf_idx = space_filling_idx(grid_idx)
473
+ feat_s0 = self._init_proj(feat_s0)
474
+ return self._init_pool(feat_s0, pos_s0, sf_idx, batch_idx, batch_size)
475
+
476
+ @torch.autocast("cuda", dtype=torch.bfloat16, cache_enabled=False)
477
+ def forward(
478
+ self, points: torch.Tensor, batch_idx: torch.Tensor | None = None, voxel_size: float | torch.Tensor | None = None
479
+ ) -> PointTransformerOut:
480
+ """Encode a point cloud or a batch of them.
481
+
482
+ In train mode the layers of every stage take the space-filling curves in a random order and every sample's
483
+ curves are shuffled at every pooling, as in pretraining. In eval mode the order is fixed.
484
+
485
+ Args:
486
+ points: (N, 5) float32 points of all samples, [age in seconds, x, y, z in meters, intensity 0..255], on the
487
+ GPU. The age is the time from the point to the newest point of its sample (0 for a single sweep).
488
+ batch_idx: (N,) int64 sample of each point, on the GPU, for a batch of B = batch_idx.max() + 1 samples. None
489
+ for a single point cloud (B = 1), in that case it will be automatically generated as zeroes.
490
+ voxel_size: Voxel size in meters of the first stage, a float for all samples or a (B,) tensor with one per
491
+ sample. Defaults to VOXEL_SIZE. Every encoder runs with any voxel size, but the ones without a
492
+ voxel size input were only trained with VOXEL_SIZE, and the others with the voxel sizes of
493
+ their voxel_size_conditioning_range.
494
+
495
+ Returns:
496
+ The features, positions, batch indices and upsampling indices of every stage.
497
+ """
498
+ assert points.is_cuda, "The encoder runs on the GPU."
499
+ assert points.dim() == 2 and points.shape[-1] == 5, f"Expects (N, 5) points."
500
+ # The batch size, which everything below takes from here.
501
+ if batch_idx is None:
502
+ batch_idx = torch.zeros(points.shape[0], device=points.device, dtype=torch.long)
503
+ B = 1
504
+ else:
505
+ assert batch_idx.shape == points.shape[:1]
506
+ B = batch_idx.max().item() + 1
507
+ if voxel_size is None:
508
+ voxel_size = VOXEL_SIZE
509
+ # From here on the voxel sizes of the grid of the initial embedding, half those of the first stage, which the
510
+ # training code took as input. Halving is exact, so they are those of training.
511
+ stride = self._init_pool._stride
512
+ if isinstance(voxel_size, torch.Tensor):
513
+ assert voxel_size.shape == (B,), "Expects a float or one voxel size per sample."
514
+ voxel_size = voxel_sizes = voxel_size.to(points.device, torch.float32) / stride
515
+ else:
516
+ # A float divides the grid as a Python float, as the default voxel size did in training and evaluation: on the
517
+ # GPU this rounds differently from dividing by a tensor.
518
+ voxel_size = float(voxel_size) / stride
519
+ voxel_sizes = torch.full((B,), voxel_size, device=points.device, dtype=torch.float32)
520
+
521
+ if self._voxel_size_conditioning_range is not None:
522
+ # Scaling the voxel sizes and the range alike leaves the normalized log voxel size unchanged. It is computed
523
+ # from the halved voxel sizes like in training, so that it rounds the same.
524
+ voxel_size_range = tuple(v / stride for v in self._voxel_size_conditioning_range)
525
+ voxel_size_u = log_voxel_size_coordinate(voxel_sizes, voxel_size_range)
526
+ with torch.autocast("cuda", enabled=False):
527
+ # (B, 6, C) per stage, shared by all attention layers of the stage.
528
+ voxel_size_mod_stages = [embed(voxel_size_u).view(B, 6, -1) for embed in self._voxel_size_embed]
529
+ else:
530
+ voxel_size_u = None
531
+ voxel_size_mod_stages = [None] * self.num_stages
532
+
533
+ feat_stage, pos_stage, batch_idx_stage, sf_idx, order, inv_order, up_idx = self._maybe_checkpoint(
534
+ self._initial_embed, points, batch_idx, voxel_size, voxel_size_u, B, preserve_rng_state=True
535
+ )
536
+ pt_feats, pt_positions, batch_indices, up_idxs = [], [], [], [up_idx]
537
+ orders, inv_orders, paddings, unpaddings, stage_curves = [], [], [], [], []
538
+
539
+ # Down path: the attention layers of each stage, then pooling to the next stage.
540
+ for stage in range(self.num_stages):
541
+ pad, unpad = pad_and_unpad_idx(batch_indices=batch_idx_stage, group_size=GROUP_SIZE, batch_size=B)
542
+ # The curve of each attention layer of the stage, the down and then the up layers: the four in turn, in train
543
+ # mode in a random order (a random permutation for every four layers).
544
+ num_layers = len(self._ds_attn_groups[stage]) + self._num_up_layers[stage]
545
+ if self.training:
546
+ curves = torch.cat([torch.randperm(4) for _ in range(math.ceil(num_layers / 4))]).tolist()
547
+ else:
548
+ curves = [i % 4 for i in range(num_layers)]
549
+ stage_curves.append(curves)
550
+ pos_normed = pos_stage / self._pos_stage_voxel_sizes[stage]
551
+ for i, layer in enumerate(self._ds_attn_groups[stage]):
552
+ feat_stage = self._maybe_checkpoint(
553
+ layer, feat_stage, order[curves[i]], inv_order[curves[i]], pad, unpad, pos_normed, batch_idx_stage, voxel_size_mod_stages[stage]
554
+ )
555
+
556
+ pt_feats.append(feat_stage)
557
+ pt_positions.append(pos_stage)
558
+ batch_indices.append(batch_idx_stage)
559
+
560
+ if stage < self.num_stages - 1:
561
+ orders.append(order)
562
+ inv_orders.append(inv_order)
563
+ paddings.append(pad)
564
+ unpaddings.append(unpad)
565
+ feat_stage, pos_stage, batch_idx_stage, sf_idx, order, inv_order, up_idx = self._maybe_checkpoint(
566
+ self._pool_layers[stage], feat_stage, pos_stage, sf_idx, batch_idx_stage, B, preserve_rng_state=True
567
+ )
568
+ up_idxs.append(up_idx)
569
+
570
+ # Up path: from the deepest stage, add the upsampled features of the coarser stage and run the up layers.
571
+ for stage in reversed(range(self.num_stages - 1)):
572
+ feat_stage = self._maybe_checkpoint(self._unpool_layers[stage], pt_feats[stage + 1], pt_feats[stage], up_idxs[stage + 1])
573
+ start = self._up_layer_starts[stage]
574
+ up_layers = self._us_attn_layers[start : start + self._num_up_layers[stage]]
575
+ pos_normed = pt_positions[stage] / self._pos_stage_voxel_sizes[stage]
576
+ # The curves continue from the stage's down layers.
577
+ for i, layer in enumerate(up_layers, start=len(self._ds_attn_groups[stage])):
578
+ curve = stage_curves[stage][i]
579
+ feat_stage = self._maybe_checkpoint(
580
+ layer,
581
+ feat_stage,
582
+ orders[stage][curve],
583
+ inv_orders[stage][curve],
584
+ paddings[stage],
585
+ unpaddings[stage],
586
+ pos_normed,
587
+ batch_indices[stage],
588
+ voxel_size_mod_stages[stage],
589
+ )
590
+ pt_feats[stage] = feat_stage
591
+
592
+ pt_feats = [norm(feat) for norm, feat in zip(self._final_layernorms, pt_feats, strict=True)]
593
+ return PointTransformerOut(pt_feats, pt_positions, batch_indices, up_idxs)
qk_layernorm_rope_triton.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """QK-LayerNorm and RoPE of the attention layers fused into one Triton kernel, with a fused backward kernel.
2
+
3
+ QK Layernorm when applied naively on our point transformer (J3PA-1B) is stupidly slow and copies a bunch of stuff. It makes the
4
+ training like 30% slower... Models smaller than J3PA-1B only use the RoPE kernel, which is less essential and could be written
5
+ as pytorch code.
6
+
7
+ What it computes
8
+ q and k each go through a LayerNorm over the head dim (QK-LayerNorm) and are then rotated by RoPE:
9
+
10
+ u = LayerNorm(x) per row: one head of one token, head_dim values
11
+ y[2i] = cos(a_i) * u[2i] - sin(a_i) * u[2i+1] every channel pair (2i, 2i+1) is rotated by its angle a_i
12
+ y[2i+1] = sin(a_i) * u[2i] + cos(a_i) * u[2i+1]
13
+ a_i = frequency_i * position[axis_i] the frequency and position axis (x, y or z) of the pair, as
14
+ in RoPE, and the position of the row's token
15
+
16
+ q and k are read once, the angles are computed in registers, once per channel pair and shared by q and k, and y is
17
+ written once. Only when gradients are needed does the forward pass also write the LayerNorm statistics of every
18
+ row, from which the backward pass recomputes the normalized input. The backward pass recomputes the angles as well
19
+ instead of keeping cos and sin.
20
+
21
+ Everything is computed in float32, with float32 angles, and rounded once to the input dtype at the end.
22
+
23
+ Tiles
24
+ q and k have shape (groups, heads, group_size, head_dim), see PointSelfAttn, and are strided views of the QKV
25
+ projection whose last dim is contiguous. A tile is BLOCK_TOKENS consecutive tokens of one head of one attention
26
+ group: every row of a tile has the same head, so the RoPE frequencies are one vector per tile, not one per row.
27
+ Rows are numbered as in a contiguous tensor of that shape, row = (group * heads + head) * group_size + token, which
28
+ is also the layout of the outputs.
29
+ """
30
+
31
+ import functools
32
+
33
+ import torch
34
+ import triton
35
+ import triton.language as tl
36
+ from torch import nn
37
+
38
+ from .rope import RoPE
39
+
40
+ # Elements of a tile per tensor (TILE // head_dim tokens) and warps per program. On an A100 these were the fastest for
41
+ # head_dim 64; other values within a factor of two are within a few percent.
42
+ _FORWARD_TILE = 2048
43
+ _BACKWARD_TILE = 2048
44
+ _FORWARD_NUM_WARPS = 4
45
+ _BACKWARD_NUM_WARPS = 8
46
+ # Backward programs per streaming multiprocessor. Each one loops over several tiles and adds up the gradients of the
47
+ # LayerNorm weights and biases in registers, so that only one partial sum per program is written.
48
+ _BACKWARD_PROGRAMS_PER_SM = 2
49
+
50
+
51
+ @triton.jit
52
+ def _token_offsets(group, head, tokens, stride_group, stride_head, stride_token):
53
+ """Offset (in elements) of the first value of each token's row of one head, in a tensor with these strides. In int64:
54
+ in large batches the offsets into the QKV projection exceed 2**31."""
55
+ return group.to(tl.int64) * stride_group + head.to(tl.int64) * stride_head + tokens.to(tl.int64) * stride_token
56
+
57
+
58
+ @triton.jit
59
+ def _rope_cos_sin(
60
+ group,
61
+ head,
62
+ tokens,
63
+ token_mask,
64
+ group_size,
65
+ pos_ptr, # (groups * group_size, 3) position of every token.
66
+ angles_ptr,
67
+ angle_idx_ptr,
68
+ pos_idx_ptr, # The RoPE module's buffers.
69
+ D: tl.constexpr,
70
+ BLOCK_PAIRS: tl.constexpr, # BLOCK_D // 2
71
+ ):
72
+ """cos and sin of the RoPE angle of every (token, channel pair) of a tile: two (BLOCK_TOKENS, BLOCK_PAIRS) tensors."""
73
+ # RoPE gives every channel of the full feature (heads * head_dim channels) an angle index into its frequencies and a
74
+ # position axis (0, 1, 2 for x, y, z). Both channels of a pair share them, so look them up for the first channel of
75
+ # every pair of the tile's head.
76
+ pairs = tl.arange(0, BLOCK_PAIRS)
77
+ pair_mask = pairs < D // 2
78
+ channel = head * D + 2 * pairs
79
+ frequency = tl.load(angles_ptr + tl.load(angle_idx_ptr + channel, mask=pair_mask, other=0), mask=pair_mask, other=0.0)
80
+ axis = tl.load(pos_idx_ptr + channel, mask=pair_mask, other=0)
81
+
82
+ # The (x, y, z) position of every token, and per pair the coordinate of its axis. Positions are given in the padded
83
+ # token order of the attention groups: token t of group g is position g * group_size + t.
84
+ point = (group.to(tl.int64) * group_size + tokens) * 3
85
+ x = tl.load(pos_ptr + point, mask=token_mask, other=0.0)
86
+ y = tl.load(pos_ptr + point + 1, mask=token_mask, other=0.0)
87
+ z = tl.load(pos_ptr + point + 2, mask=token_mask, other=0.0)
88
+ position = tl.where(axis[None, :] == 0, x[:, None], tl.where(axis[None, :] == 1, y[:, None], z[:, None]))
89
+
90
+ # The float32 product of frequency and position. tl.cos and tl.sin give the same values as torch.cos and torch.sin
91
+ # (the accurate CUDA functions, not the fast approximations).
92
+ angle = frequency[None, :] * position
93
+ return tl.cos(angle), tl.sin(angle)
94
+
95
+
96
+ @triton.jit
97
+ def _forward_one(
98
+ x_ptr,
99
+ y_ptr,
100
+ weight_ptr,
101
+ bias_ptr,
102
+ mean_ptr,
103
+ rstd_ptr,
104
+ x_offsets,
105
+ rows,
106
+ token_mask,
107
+ cos,
108
+ sin,
109
+ eps,
110
+ D: tl.constexpr,
111
+ BLOCK_D: tl.constexpr,
112
+ BLOCK_TOKENS: tl.constexpr,
113
+ SAVE_STATS: tl.constexpr,
114
+ ):
115
+ """LayerNorm and RoPE of one tile of q or of k."""
116
+ cols = tl.arange(0, BLOCK_D)
117
+ col_mask = cols < D # A head_dim that is not a power of two leaves columns of the block unused.
118
+ mask = token_mask[:, None] & col_mask[None, :]
119
+
120
+ # The LayerNorm, with its output u kept in float32 registers.
121
+ x = tl.load(x_ptr + x_offsets[:, None] + cols[None, :], mask=mask, other=0.0).to(tl.float32)
122
+ mean = tl.sum(x, axis=1) / D
123
+ x_centered = tl.where(mask, x - mean[:, None], 0.0)
124
+ rstd = tl.rsqrt(tl.sum(x_centered * x_centered, axis=1) / D + eps)
125
+ weight = tl.load(weight_ptr + cols, mask=col_mask, other=0.0).to(tl.float32)
126
+ bias = tl.load(bias_ptr + cols, mask=col_mask, other=0.0).to(tl.float32)
127
+ u = x_centered * rstd[:, None] * weight[None, :] + bias[None, :]
128
+
129
+ # RoPE: split every row into the first and the second channel of its pairs, (BLOCK_TOKENS, BLOCK_D) ->
130
+ # 2 x (BLOCK_TOKENS, BLOCK_D // 2), rotate every pair by its angle and put the channels back in their places.
131
+ u_first, u_second = tl.split(tl.reshape(u, (BLOCK_TOKENS, BLOCK_D // 2, 2)))
132
+ y = tl.interleave(cos * u_first - sin * u_second, sin * u_first + cos * u_second)
133
+
134
+ # Round once to the output dtype. The output is contiguous: row r starts at r * D.
135
+ tl.store(y_ptr + rows.to(tl.int64)[:, None] * D + cols[None, :], y.to(y_ptr.dtype.element_ty), mask=mask)
136
+ if SAVE_STATS:
137
+ # The backward pass recomputes the normalized input from x and these two statistics.
138
+ tl.store(mean_ptr + rows, mean, mask=token_mask)
139
+ tl.store(rstd_ptr + rows, rstd, mask=token_mask)
140
+
141
+
142
+ @triton.jit
143
+ def _forward_kernel(
144
+ q_ptr, k_ptr, q_out_ptr, k_out_ptr,
145
+ q_weight_ptr, q_bias_ptr, k_weight_ptr, k_bias_ptr,
146
+ q_mean_ptr, q_rstd_ptr, k_mean_ptr, k_rstd_ptr, # Written if SAVE_STATS: LayerNorm statistics of every row.
147
+ pos_ptr, angles_ptr, angle_idx_ptr, pos_idx_ptr,
148
+ stride_group, stride_head, stride_token, # Strides of q and of k, which are the same (views of the QKV projection).
149
+ num_heads, group_size, q_eps, k_eps,
150
+ D: tl.constexpr, # head_dim, the size normalised over.
151
+ BLOCK_D: tl.constexpr, # D rounded up to a power of two, as Triton's block sizes must be.
152
+ BLOCK_TOKENS: tl.constexpr, # Tokens per tile.
153
+ SAVE_STATS: tl.constexpr, # Write the statistics the backward pass needs.
154
+ ):
155
+ # Program (group * num_heads + head, block) handles the tokens [block * BLOCK_TOKENS, (block + 1) * BLOCK_TOKENS)
156
+ # of that head of that attention group, in q and in k.
157
+ group_head = tl.program_id(0)
158
+ group = group_head // num_heads
159
+ head = group_head % num_heads
160
+ tokens = tl.program_id(1) * BLOCK_TOKENS + tl.arange(0, BLOCK_TOKENS)
161
+ token_mask = tokens < group_size # The last tile of a group may run past its last token.
162
+ rows = group_head * group_size + tokens
163
+
164
+ # The angles depend only on the head and the token, so q and k share them.
165
+ cos, sin = _rope_cos_sin(group, head, tokens, token_mask, group_size, pos_ptr, angles_ptr, angle_idx_ptr, pos_idx_ptr,
166
+ D, BLOCK_D // 2)
167
+
168
+ x_offsets = _token_offsets(group, head, tokens, stride_group, stride_head, stride_token)
169
+ _forward_one(q_ptr, q_out_ptr, q_weight_ptr, q_bias_ptr, q_mean_ptr, q_rstd_ptr, x_offsets, rows, token_mask, cos, sin,
170
+ q_eps, D, BLOCK_D, BLOCK_TOKENS, SAVE_STATS)
171
+ _forward_one(k_ptr, k_out_ptr, k_weight_ptr, k_bias_ptr, k_mean_ptr, k_rstd_ptr, x_offsets, rows, token_mask, cos, sin,
172
+ k_eps, D, BLOCK_D, BLOCK_TOKENS, SAVE_STATS)
173
+
174
+
175
+ @triton.jit
176
+ def _backward_one(
177
+ x_ptr, dy_ptr, dx_ptr, weight_ptr, mean_ptr, rstd_ptr,
178
+ x_offsets, dy_offsets, rows, token_mask, cos, sin,
179
+ D: tl.constexpr, BLOCK_D: tl.constexpr, BLOCK_TOKENS: tl.constexpr,
180
+ ):
181
+ """Gradient of the input of one tile of q or of k.
182
+
183
+ Return:
184
+ Tile's contributions to the gradients of the LayerNorm weight and bias (not yet summed over the rows).
185
+ """
186
+ cols = tl.arange(0, BLOCK_D)
187
+ col_mask = cols < D
188
+ mask = token_mask[:, None] & col_mask[None, :]
189
+ x = tl.load(x_ptr + x_offsets[:, None] + cols[None, :], mask=mask, other=0.0).to(tl.float32)
190
+ dy = tl.load(dy_ptr + dy_offsets[:, None] + cols[None, :], mask=mask, other=0.0).to(tl.float32)
191
+ mean = tl.load(mean_ptr + rows, mask=token_mask, other=0.0)
192
+ rstd = tl.load(rstd_ptr + rows, mask=token_mask, other=0.0)
193
+ weight = tl.load(weight_ptr + cols, mask=col_mask, other=0.0).to(tl.float32)
194
+
195
+ # RoPE backward. A rotation is undone by the opposite rotation, so the gradient of u is the gradient of y rotated
196
+ # back by -a: du[2i] = cos * dy[2i] + sin * dy[2i+1] and du[2i+1] = cos * dy[2i+1] - sin * dy[2i].
197
+ dy_first, dy_second = tl.split(tl.reshape(dy, (BLOCK_TOKENS, BLOCK_D // 2, 2)))
198
+ du = tl.interleave(cos * dy_first + sin * dy_second, cos * dy_second - sin * dy_first)
199
+
200
+ # The LayerNorm backward with du as the output gradient: recompute the normalized input x_hat, then
201
+ # dx = (g - mean(g) - x_hat * mean(g * x_hat)) / std with g = du * weight and means over the row.
202
+ x_hat = tl.where(mask, (x - mean[:, None]) * rstd[:, None], 0.0)
203
+ g = du * weight[None, :]
204
+ mean_g = tl.sum(g, axis=1) / D
205
+ mean_g_x_hat = tl.sum(g * x_hat, axis=1) / D
206
+ dx = (g - mean_g[:, None] - x_hat * mean_g_x_hat[:, None]) * rstd[:, None]
207
+ tl.store(dx_ptr + rows.to(tl.int64)[:, None] * D + cols[None, :], dx.to(dx_ptr.dtype.element_ty), mask=mask)
208
+
209
+ # The weight gradient is the sum over the rows of du * x_hat, the bias gradient that of du.
210
+ return du * x_hat, du
211
+
212
+
213
+ @triton.jit
214
+ def _backward_kernel(
215
+ q_ptr, k_ptr, # The inputs of the forward pass.
216
+ q_out_grad_ptr, k_out_grad_ptr, # Gradients of the outputs, coming from the attention.
217
+ q_grad_ptr, k_grad_ptr, # Written: gradients of q and k.
218
+ q_weight_ptr, k_weight_ptr, q_mean_ptr, q_rstd_ptr, k_mean_ptr, k_rstd_ptr,
219
+ pos_ptr, angles_ptr, angle_idx_ptr, pos_idx_ptr,
220
+ q_dweight_ptr, q_dbias_ptr, k_dweight_ptr, k_dbias_ptr, # Written: (num_programs, D) partial sums per program.
221
+ x_stride_group, x_stride_head, x_stride_token, # Strides of q and of k.
222
+ dy_stride_group, dy_stride_head, dy_stride_token, # Strides of both output gradients (also the same).
223
+ num_heads, group_size, num_tiles, token_blocks,
224
+ D: tl.constexpr, BLOCK_D: tl.constexpr, BLOCK_TOKENS: tl.constexpr,
225
+ ):
226
+ # Program p handles the tiles p, p + num_programs, p + 2 * num_programs, ... of q and of k, and adds up the weight
227
+ # and bias gradients of its rows in registers. Tile t is token block t % token_blocks of head t // token_blocks
228
+ # (counting over all groups).
229
+ q_dweight = tl.zeros((BLOCK_TOKENS, BLOCK_D), dtype=tl.float32)
230
+ q_dbias = tl.zeros((BLOCK_TOKENS, BLOCK_D), dtype=tl.float32)
231
+ k_dweight = tl.zeros((BLOCK_TOKENS, BLOCK_D), dtype=tl.float32)
232
+ k_dbias = tl.zeros((BLOCK_TOKENS, BLOCK_D), dtype=tl.float32)
233
+
234
+ for tile in range(tl.program_id(0), num_tiles, tl.num_programs(0)):
235
+ group_head = tile // token_blocks
236
+ group = group_head // num_heads
237
+ head = group_head % num_heads
238
+ tokens = (tile % token_blocks) * BLOCK_TOKENS + tl.arange(0, BLOCK_TOKENS)
239
+ token_mask = tokens < group_size
240
+ rows = group_head * group_size + tokens
241
+
242
+ # Recompute the angles, shared by q and k, instead of keeping cos and sin from the forward pass.
243
+ cos, sin = _rope_cos_sin(group, head, tokens, token_mask, group_size, pos_ptr, angles_ptr, angle_idx_ptr,
244
+ pos_idx_ptr, D, BLOCK_D // 2)
245
+
246
+ x_offsets = _token_offsets(group, head, tokens, x_stride_group, x_stride_head, x_stride_token)
247
+ dy_offsets = _token_offsets(group, head, tokens, dy_stride_group, dy_stride_head, dy_stride_token)
248
+ dweight, dbias = _backward_one(q_ptr, q_out_grad_ptr, q_grad_ptr, q_weight_ptr, q_mean_ptr, q_rstd_ptr, x_offsets,
249
+ dy_offsets, rows, token_mask, cos, sin, D, BLOCK_D, BLOCK_TOKENS)
250
+ q_dweight += dweight
251
+ q_dbias += dbias
252
+ dweight, dbias = _backward_one(k_ptr, k_out_grad_ptr, k_grad_ptr, k_weight_ptr, k_mean_ptr, k_rstd_ptr, x_offsets,
253
+ dy_offsets, rows, token_mask, cos, sin, D, BLOCK_D, BLOCK_TOKENS)
254
+ k_dweight += dweight
255
+ k_dbias += dbias
256
+
257
+ # Sum over the rows of the tile, and write this program's partial sums.
258
+ cols = tl.arange(0, BLOCK_D)
259
+ col_mask = cols < D
260
+ partial = tl.program_id(0) * D + cols
261
+ tl.store(q_dweight_ptr + partial, tl.sum(q_dweight, axis=0), mask=col_mask)
262
+ tl.store(q_dbias_ptr + partial, tl.sum(q_dbias, axis=0), mask=col_mask)
263
+ tl.store(k_dweight_ptr + partial, tl.sum(k_dweight, axis=0), mask=col_mask)
264
+ tl.store(k_dbias_ptr + partial, tl.sum(k_dbias, axis=0), mask=col_mask)
265
+
266
+
267
+ def _block_sizes(head_dim: int, tile: int) -> tuple[int, int]:
268
+ """Block size of the head dim (a power of two) and the number of tokens of a tile with about `tile` elements."""
269
+ block_d = triton.next_power_of_2(head_dim)
270
+ return block_d, max(1, tile // block_d)
271
+
272
+
273
+ @functools.cache
274
+ def _num_sms(device_index: int) -> int:
275
+ return torch.cuda.get_device_properties(device_index).multi_processor_count
276
+
277
+
278
+ def _forward(q, k, q_weight, q_bias, k_weight, k_bias, pos, angles, angle_idx, pos_idx, q_eps, k_eps, stats=None):
279
+ """The outputs of the forward kernel, and with `stats` (4, groups, heads, group_size) the LayerNorm statistics."""
280
+ num_groups, num_heads, group_size, head_dim = q.shape
281
+ block_d, block_tokens = _block_sizes(head_dim, _FORWARD_TILE)
282
+ # Contiguous outputs, as the attention takes them.
283
+ q_out = torch.empty(q.shape, dtype=q.dtype, device=q.device)
284
+ k_out = torch.empty_like(q_out)
285
+ # Without statistics the kernel never writes them, so any pointer will do.
286
+ stats_ptrs = (q_out,) * 4 if stats is None else stats
287
+ _forward_kernel[(num_groups * num_heads, triton.cdiv(group_size, block_tokens))](
288
+ q, k, q_out, k_out,
289
+ q_weight, q_bias, k_weight, k_bias,
290
+ *stats_ptrs,
291
+ pos, angles, angle_idx, pos_idx,
292
+ *q.stride()[:3],
293
+ num_heads, group_size, q_eps, k_eps,
294
+ D=head_dim, BLOCK_D=block_d, BLOCK_TOKENS=block_tokens, SAVE_STATS=stats is not None, num_warps=_FORWARD_NUM_WARPS,
295
+ )
296
+ return q_out, k_out
297
+
298
+
299
+ class _QKLayerNormRoPE(torch.autograd.Function):
300
+ @staticmethod
301
+ def forward(ctx, q, k, q_weight, q_bias, k_weight, k_bias, pos, angles, angle_idx, pos_idx, q_eps: float, k_eps: float):
302
+ # LayerNorm statistics of every row: q mean, q 1 / std, k mean, k 1 / std.
303
+ stats = torch.empty((4, *q.shape[:-1]), dtype=torch.float32, device=q.device)
304
+ q_out, k_out = _forward(q, k, q_weight, q_bias, k_weight, k_bias, pos, angles, angle_idx, pos_idx, q_eps, k_eps, stats)
305
+ ctx.save_for_backward(q, k, q_weight, k_weight, stats, pos, angles, angle_idx, pos_idx)
306
+ return q_out, k_out
307
+
308
+ @staticmethod
309
+ def backward(ctx, q_out_grad, k_out_grad):
310
+ q, k, q_weight, k_weight, stats, pos, angles, angle_idx, pos_idx = ctx.saved_tensors
311
+ # The kernel reads both output gradients with one set of strides and every row as head_dim contiguous values.
312
+ # The attention backward hands them over like that; anything else is copied first.
313
+ if q_out_grad.stride() != k_out_grad.stride() or q_out_grad.stride(-1) != 1:
314
+ q_out_grad, k_out_grad = q_out_grad.contiguous(), k_out_grad.contiguous()
315
+ num_groups, num_heads, group_size, head_dim = q.shape
316
+ block_d, block_tokens = _block_sizes(head_dim, _BACKWARD_TILE)
317
+ token_blocks = triton.cdiv(group_size, block_tokens)
318
+ num_tiles = num_groups * num_heads * token_blocks
319
+ num_programs = min(num_tiles, _BACKWARD_PROGRAMS_PER_SM * _num_sms(q.device.index))
320
+ q_grad = torch.empty(q.shape, dtype=q.dtype, device=q.device)
321
+ k_grad = torch.empty_like(q_grad)
322
+ # Every program's partial sums of the q weight, q bias, k weight and k bias gradients.
323
+ partials = torch.empty((4, num_programs, head_dim), dtype=torch.float32, device=q.device)
324
+ _backward_kernel[(num_programs,)](
325
+ q, k, q_out_grad, k_out_grad, q_grad, k_grad,
326
+ q_weight, k_weight, *stats,
327
+ pos, angles, angle_idx, pos_idx,
328
+ *partials,
329
+ *q.stride()[:3],
330
+ *q_out_grad.stride()[:3],
331
+ num_heads, group_size, num_tiles, token_blocks,
332
+ D=head_dim, BLOCK_D=block_d, BLOCK_TOKENS=block_tokens, num_warps=_BACKWARD_NUM_WARPS,
333
+ )
334
+ # Add up the partial sums of the programs (in a fixed order, so deterministically).
335
+ q_dweight, q_dbias, k_dweight, k_dbias = partials.sum(1).to(q_weight.dtype)
336
+ # One gradient per input of forward. The positions have none, as RoPE has no learnable parameters, and neither
337
+ # do the RoPE buffers and the eps.
338
+ return q_grad, k_grad, q_dweight, q_dbias, k_dweight, k_dbias, None, None, None, None, None, None
339
+
340
+
341
+ def qk_layernorm_rope(
342
+ q: torch.Tensor, k: torch.Tensor, q_ln: nn.LayerNorm, k_ln: nn.LayerNorm, rope: RoPE, pos: torch.Tensor
343
+ ) -> tuple[torch.Tensor, torch.Tensor]:
344
+ """QK-LayerNorm followed by RoPE of the queries and keys in a point transformer attention layer.
345
+
346
+ The setup is explicitly optimized for the point transformer with grouped self attention and 4 axis tensors.
347
+ Do not use elsewhere.
348
+
349
+ Args:
350
+ q, k: (groups, heads, group_size, head_dim) views of the QKV projection. See PointSelfAttn.
351
+ q_ln, k_ln: The pytorch LayerNorm modules used for QK-LayerNorm.
352
+ rope: The RoPE module that cached indices and a lookup table.
353
+ pos: (groups * group_size, 3) position of every token in the padded order of the attention groups.
354
+
355
+ Returns:
356
+ q and k, contiguous, in their dtype.
357
+ """
358
+ assert q.dim() == 4 and q.shape == k.shape and q.dtype == k.dtype, "Expects q and k layout used in PointSelfAttn."
359
+ num_groups, num_heads, group_size, head_dim = q.shape
360
+ assert head_dim % 2 == 0, "RoPE makes no sense if channels aren't multiples of 2. You should probably not have odd channels anyway."
361
+ assert rope._pos_dim == 3 and rope._dim == num_heads * head_dim, "RoPE module or input is borked."
362
+ assert pos.shape == (num_groups * group_size, 3), "Expects one (x, y, z) position per token."
363
+ # The kernels read q and k with one set of strides and every row as head_dim contiguous values.
364
+ if q.stride() != k.stride() or q.stride(-1) != 1:
365
+ q, k = q.contiguous(), k.contiguous()
366
+ # RoPE multiplies its float32 frequencies with the positions in float32.
367
+ pos = pos.float().contiguous()
368
+ args = (q, k, q_ln.weight, q_ln.bias, k_ln.weight, k_ln.bias, pos, rope._angles, rope._angle_idx, rope._pos_idx, q_ln.eps, k_ln.eps)
369
+ if torch.is_grad_enabled() and any(t.requires_grad for t in args[:6]):
370
+ return _QKLayerNormRoPE.apply(*args)
371
+ # Without gradients (inference) skip the autograd bookkeeping and the statistics for the backward pass.
372
+ return _forward(*args)
rope.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) Copyright 2026 Zenseact AB
2
+ """Rotary Positional Embeddings (RoPE) of the encoder's attention layers.
3
+
4
+ Generic N-dimensional extension of the RoFormer paper https://arxiv.org/abs/2104.09864. We only build the angles and
5
+ lookup tables for interleaving here and do not provide any forward pass. The provided Triton kernels take care of that.
6
+ """
7
+
8
+ import math
9
+
10
+ import torch
11
+ from torch import nn
12
+
13
+
14
+ class RoPE(nn.Module):
15
+ """Per-head RoPE: the channel pairs of every head rotate with angles of the x, y and z positions in turn."""
16
+
17
+ def __init__(self, dim: int, pos_dim: int, max_freq: float, num_heads: int):
18
+ """Initialize.
19
+
20
+ Args:
21
+ dim: Channels of all heads together. The channels of each head are rotated in pairs.
22
+ pos_dim: Dimensionality of the positions.
23
+ max_freq: Maximum frequency for producing angles.
24
+ num_heads: Number of attention heads.
25
+ """
26
+ assert dim % 2 == 0
27
+ super().__init__()
28
+ self._pos_dim = pos_dim
29
+ self._dim = dim
30
+
31
+ dh = dim // num_heads
32
+ angles_per_axis = int(math.ceil(dh / (2 * pos_dim)) * num_heads)
33
+ angles = max_freq ** (-2 * torch.arange(angles_per_axis) / (dim / pos_dim))
34
+
35
+ head_idx = torch.arange(dim) // dh
36
+ pair_idx = (torch.arange(dim) % dh) // 2
37
+ angle_idx = (pair_idx // pos_dim) * num_heads + head_idx
38
+ pos_idx = (pair_idx + head_idx) % pos_dim
39
+
40
+ # Persistent, so they are loaded from the checkpoints: computed on other hardware they coulc differ from what the model was trained on.
41
+ # Probably doesn't matter, but why risk it...
42
+ self.register_buffer("_angles", angles)
43
+ self.register_buffer("_angle_idx", angle_idx)
44
+ self.register_buffer("_pos_idx", pos_idx)
rope_triton.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RoPE of the queries and keys of the attention layers in one Triton kernel, with its backward pass.
2
+
3
+ Used by the attention layers without QK-LayerNorm (J3PA-Large, Small and Tiny). The layers with it use the kernel of
4
+ qk_layernorm_rope_triton.py, which also fuses the LayerNorm.
5
+
6
+ What it computes
7
+ The RoPE of q and of k:
8
+
9
+ y[2i] = cos(a_i) * x[2i] - sin(a_i) * x[2i+1] every channel pair (2i, 2i+1) is rotated by its angle a_i
10
+ y[2i+1] = sin(a_i) * x[2i] + cos(a_i) * x[2i+1]
11
+ a_i = frequency_i * position[axis_i]
12
+
13
+ q and k are read once from the strided views of the QKV projection, the angles are computed in registers once per
14
+ channel pair and shared by q and k, and both outputs are written once. The backward pass is the same kernel rotating
15
+ the output gradients back by -a_i, so only the positions are kept for it.
16
+
17
+ Numerics
18
+ As in qk_layernorm_rope_triton.py: float32 angles, cos and sin, the rotation in float32 and a single rounding to the
19
+ input dtype.
20
+
21
+ Tiles
22
+ Those of qk_layernorm_rope_triton.py: BLOCK_TOKENS consecutive tokens of one head of one attention group, rows
23
+ numbered as in a contiguous (groups, heads, group_size, head_dim) tensor, which is also the layout of the outputs.
24
+ """
25
+
26
+ import torch
27
+ import triton
28
+ import triton.language as tl
29
+
30
+ from .qk_layernorm_rope_triton import _block_sizes, _rope_cos_sin, _token_offsets
31
+ from .rope import RoPE
32
+
33
+ # Elements of a tile per tensor (TILE // head_dim tokens) and warps per program, the fastest on an A100 for head_dim 32
34
+ # and 64 in the stage shapes of the J3PA encoders.
35
+ _TILE = 2048
36
+ _NUM_WARPS = 4
37
+
38
+
39
+ @triton.jit
40
+ def _rotate_one(
41
+ x_ptr, y_ptr, x_offsets, rows, token_mask, cos, sin,
42
+ D: tl.constexpr, BLOCK_D: tl.constexpr, BLOCK_TOKENS: tl.constexpr,
43
+ ):
44
+ """Rotate every channel pair of one tile of q or of k by its angle and write the tile contiguously."""
45
+ cols = tl.arange(0, BLOCK_D)
46
+ mask = token_mask[:, None] & (cols < D)[None, :]
47
+ x = tl.load(x_ptr + x_offsets[:, None] + cols[None, :], mask=mask, other=0.0).to(tl.float32)
48
+ # (BLOCK_TOKENS, BLOCK_D) -> 2 x (BLOCK_TOKENS, BLOCK_D // 2): the first and the second channel of every pair.
49
+ x_first, x_second = tl.split(tl.reshape(x, (BLOCK_TOKENS, BLOCK_D // 2, 2)))
50
+ y = tl.interleave(cos * x_first - sin * x_second, sin * x_first + cos * x_second)
51
+ tl.store(y_ptr + rows.to(tl.int64)[:, None] * D + cols[None, :], y.to(y_ptr.dtype.element_ty), mask=mask)
52
+
53
+
54
+ @triton.jit
55
+ def _qk_rope_kernel(
56
+ q_ptr, k_ptr, q_out_ptr, k_out_ptr,
57
+ pos_ptr, angles_ptr, angle_idx_ptr, pos_idx_ptr,
58
+ stride_group, stride_head, stride_token, # Strides of q and of k, which are the same.
59
+ num_heads, group_size,
60
+ D: tl.constexpr, # head_dim.
61
+ BLOCK_D: tl.constexpr, # D rounded up to a power of two, as Triton's block sizes must be.
62
+ BLOCK_TOKENS: tl.constexpr, # Tokens per tile.
63
+ INVERSE: tl.constexpr, # Rotate by -a instead of a, which is the backward pass.
64
+ ):
65
+ # Program (group * num_heads + head, block) handles the tokens [block * BLOCK_TOKENS, (block + 1) * BLOCK_TOKENS)
66
+ # of that head of that attention group, in q and in k.
67
+ group_head = tl.program_id(0)
68
+ group = group_head // num_heads
69
+ head = group_head % num_heads
70
+ tokens = tl.program_id(1) * BLOCK_TOKENS + tl.arange(0, BLOCK_TOKENS)
71
+ token_mask = tokens < group_size # The last tile of a group may run past its last token.
72
+ rows = group_head * group_size + tokens
73
+
74
+ # The angles depend only on the head and the token, so q and k share them.
75
+ cos, sin = _rope_cos_sin(group, head, tokens, token_mask, group_size, pos_ptr, angles_ptr, angle_idx_ptr, pos_idx_ptr,
76
+ D, BLOCK_D // 2)
77
+ if INVERSE:
78
+ sin = -sin
79
+
80
+ x_offsets = _token_offsets(group, head, tokens, stride_group, stride_head, stride_token)
81
+ _rotate_one(q_ptr, q_out_ptr, x_offsets, rows, token_mask, cos, sin, D, BLOCK_D, BLOCK_TOKENS)
82
+ _rotate_one(k_ptr, k_out_ptr, x_offsets, rows, token_mask, cos, sin, D, BLOCK_D, BLOCK_TOKENS)
83
+
84
+
85
+ def _rotate(q, k, pos, angles, angle_idx, pos_idx, inverse: bool) -> tuple[torch.Tensor, torch.Tensor]:
86
+ """Rotate q and k, (groups, heads, group_size, head_dim), into new contiguous tensors of their dtype."""
87
+ # The kernel reads q and k with one set of strides and every row as head_dim contiguous values.
88
+ if q.stride() != k.stride() or q.stride(-1) != 1:
89
+ q, k = q.contiguous(), k.contiguous()
90
+ num_groups, num_heads, group_size, head_dim = q.shape
91
+ block_d, block_tokens = _block_sizes(head_dim, _TILE)
92
+ q_out = torch.empty(q.shape, dtype=q.dtype, device=q.device)
93
+ k_out = torch.empty_like(q_out)
94
+ _qk_rope_kernel[(num_groups * num_heads, triton.cdiv(group_size, block_tokens))](
95
+ q, k, q_out, k_out,
96
+ pos, angles, angle_idx, pos_idx,
97
+ *q.stride()[:3],
98
+ num_heads, group_size,
99
+ D=head_dim, BLOCK_D=block_d, BLOCK_TOKENS=block_tokens, INVERSE=inverse, num_warps=_NUM_WARPS,
100
+ )
101
+ return q_out, k_out
102
+
103
+
104
+ class _QKRoPE(torch.autograd.Function):
105
+ @staticmethod
106
+ def forward(ctx, q, k, pos, angles, angle_idx, pos_idx):
107
+ ctx.save_for_backward(pos, angles, angle_idx, pos_idx)
108
+ return _rotate(q, k, pos, angles, angle_idx, pos_idx, inverse=False)
109
+
110
+ @staticmethod
111
+ def backward(ctx, q_out_grad, k_out_grad):
112
+ # A rotation is undone by the opposite rotation, so the input gradients are the output gradients rotated back.
113
+ q_grad, k_grad = _rotate(q_out_grad, k_out_grad, *ctx.saved_tensors, inverse=True)
114
+ # The positions have no gradient, as RoPE has no learnable parameters, and neither do the buffers.
115
+ return q_grad, k_grad, None, None, None, None
116
+
117
+
118
+ def qk_rope(q: torch.Tensor, k: torch.Tensor, rope: RoPE, pos: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
119
+ """RoPE of the queries and keys of an attention layer.
120
+
121
+ Args:
122
+ q, k: (groups, heads, group_size, head_dim) views of the QKV projection.
123
+ rope: RoPE module that contains the stored angles and lookup tables.
124
+ pos: (groups * group_size, 3) position of every token in the padded order of the attention groups.
125
+
126
+ Returns:
127
+ q and k, contiguous, in their dtype.
128
+ """
129
+ assert q.dim() == 4 and q.shape == k.shape and q.dtype == k.dtype, "This module is designed for the memory layours in PointSelfAttn."
130
+ num_groups, num_heads, group_size, head_dim = q.shape
131
+ assert head_dim % 2 == 0, "RoPE rotates channel pairs. Wild to not have channel widths multiples of 2..."
132
+ assert rope._pos_dim == 3 and rope._dim == num_heads * head_dim, "RoPE module borked?"
133
+ assert pos.shape == (num_groups * group_size, 3), "Expects 3D coordinates."
134
+ # RoPE multiplies its float32 frequencies with the positions in float32.
135
+ pos = pos.float().contiguous()
136
+ args = (q, k, pos, rope._angles, rope._angle_idx, rope._pos_idx)
137
+ if torch.is_grad_enabled() and (q.requires_grad or k.requires_grad):
138
+ return _QKRoPE.apply(*args)
139
+ # Without gradients (inference) skip the autograd bookkeeping.
140
+ return _rotate(*args, inverse=False)
space_filling_curves_triton.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The four space-filling curve codes of the voxels in one Triton kernel.
2
+
3
+ It's faster to compute them at once in a single kernel call rather than computing each of them separately for and then
4
+ concatenating.
5
+ """
6
+
7
+ import torch
8
+ import triton
9
+ import triton.language as tl
10
+
11
+ _BLOCK = 256
12
+ # 3 x 21 bits fill the 63 bits of a torch int64.
13
+ _MAX_BITS = 21
14
+
15
+
16
+ @triton.jit
17
+ def _interleave_two_zero_bits(v):
18
+ """111 -> 001001001
19
+
20
+ This is basically the whole work for the Z-order curve and is also useful for the Hilbert curve.
21
+ """
22
+ v = (v | (v << 32)) & 0x1F00000000FFFF
23
+ v = (v | (v << 16)) & 0x1F0000FF0000FF
24
+ v = (v | (v << 8)) & 0x100F00F00F00F00F
25
+ v = (v | (v << 4)) & 0x10C30C30C30C30C3
26
+ v = (v | (v << 2)) & 0x1249249249249249
27
+ return v
28
+
29
+
30
+ @triton.jit
31
+ def _hilbert_idx(x, y, z, num_bits):
32
+ """Do the stuff from Skilling's 2004 paper. It works, but its not intuitive..."""
33
+ for b in range(num_bits - 1):
34
+ bit_mask = 1 << (num_bits - b - 1)
35
+ lower_mask = bit_mask - 1
36
+ # x: invert the lower bits of x where its bit is on (its swap with itself does nothing).
37
+ x = tl.where((x & bit_mask) != 0, x ^ lower_mask, x)
38
+ # y and z: where the bit of the axis is on invert the lower bits of x, else swap them with the axis's.
39
+ on = (y & bit_mask) != 0
40
+ swap = (x ^ y) & lower_mask
41
+ x = tl.where(on, x ^ lower_mask, x ^ swap)
42
+ y = tl.where(on, y, y ^ swap)
43
+ on = (z & bit_mask) != 0
44
+ swap = (x ^ z) & lower_mask
45
+ x = tl.where(on, x ^ lower_mask, x ^ swap)
46
+ z = tl.where(on, z, z ^ swap)
47
+ # Bit b of the axes goes to bits 3 * b + 2 (x), 3 * b + 1 (y) and 3 * b (z): the z-order interleaving of
48
+ # (z, y, x).
49
+ hilbert_idx = (_interleave_two_zero_bits(x) << 2) | (_interleave_two_zero_bits(y) << 1) | _interleave_two_zero_bits(z)
50
+ # Gray hilbert_idx to binary.
51
+ hilbert_idx ^= hilbert_idx >> 1
52
+ hilbert_idx ^= hilbert_idx >> 2
53
+ hilbert_idx ^= hilbert_idx >> 4
54
+ hilbert_idx ^= hilbert_idx >> 8
55
+ hilbert_idx ^= hilbert_idx >> 16
56
+ hilbert_idx ^= hilbert_idx >> 32
57
+ return hilbert_idx
58
+
59
+
60
+ # Not specialized on the sizes, so that it compiles once rather than for every new class of them.
61
+ @triton.jit(do_not_specialize=["num_cells", "num_bits"])
62
+ def _sfc_kernel(grid_ptr, out_ptr, num_cells, num_bits, BLOCK: tl.constexpr):
63
+ cells = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
64
+ mask = cells < num_cells
65
+ x = tl.load(grid_ptr + cells * 3, mask=mask, other=0).to(tl.int64)
66
+ y = tl.load(grid_ptr + cells * 3 + 1, mask=mask, other=0).to(tl.int64)
67
+ z = tl.load(grid_ptr + cells * 3 + 2, mask=mask, other=0).to(tl.int64)
68
+ # Z-order: bit b of the axes goes to bits 3 * b (x), 3 * b + 1 (y) and 3 * b + 2 (z), as in jezpa/zorder.py.
69
+ x_spread, y_spread, z_spread = _interleave_two_zero_bits(x), _interleave_two_zero_bits(y), _interleave_two_zero_bits(z)
70
+ # The rows of the output: Hilbert, Z-order, transposed Hilbert and transposed Z-order codes.
71
+ row = num_cells.to(tl.int64)
72
+ tl.store(out_ptr + cells, _hilbert_idx(x, y, z, num_bits), mask=mask)
73
+ tl.store(out_ptr + row + cells, x_spread | (y_spread << 1) | (z_spread << 2), mask=mask)
74
+ tl.store(out_ptr + 2 * row + cells, _hilbert_idx(y, x, z, num_bits), mask=mask)
75
+ tl.store(out_ptr + 3 * row + cells, y_spread | (x_spread << 1) | (z_spread << 2), mask=mask)
76
+
77
+
78
+ def space_filling_idx(grid_idx: torch.Tensor) -> torch.Tensor:
79
+ """Compute space-filling curve indices along 2 variants of the Hilbert curve and 2 variants of the Z-order curve.
80
+
81
+ Args:
82
+ grid_idx: (N, 3)
83
+
84
+ Returns:
85
+ (4, N) int64 Hilbert and Z-order codes of (x, y, z), and Hilbert and Z-order codes of (y, x, z).
86
+ """
87
+ assert grid_idx.is_cuda and grid_idx.dim() == 2 and grid_idx.shape[1] == 3, f"Expects (N, 3) cells on the GPU, got {tuple(grid_idx.shape)}."
88
+ assert not grid_idx.is_floating_point()
89
+ # All cells share the bit depth of the largest coordinate, which the codes depend on. As in PTv3: one bit depth for
90
+ # the whole batch is simpler than one per sample.
91
+ num_bits = grid_idx.max().item().bit_length()
92
+ assert num_bits <= _MAX_BITS, f"The int64 codes hold at most {_MAX_BITS} bits per axis, got {num_bits}."
93
+ grid_idx = grid_idx.contiguous()
94
+ num_cells = grid_idx.shape[0]
95
+ out = torch.empty(4, num_cells, dtype=torch.int64, device=grid_idx.device)
96
+ _sfc_kernel[(triton.cdiv(num_cells, _BLOCK),)](grid_idx, out, num_cells, num_bits, BLOCK=_BLOCK)
97
+ return out