"""Hugging Face model of the J3PA encoders.""" import math import torch from transformers import PreTrainedModel # Loading from a downloaded folder only copies the files this module imports directly, and transformers only # recognizes `from .module import name`: import every code file here. from .configuration_j3pa import J3PAConfig from .layers import VoxelSizeEmbedding from .pt_transf import PointTransformer, PointTransformerOut from .qk_layernorm_rope_triton import qk_layernorm_rope # noqa: F401 from .rope import RoPE # noqa: F401 from .rope_triton import qk_rope # noqa: F401 from .space_filling_curves_triton import space_filling_idx # noqa: F401 class J3PAModel(PreTrainedModel): """A J3PA encoder with Hugging Face loading and saving. The encoder itself is PointTransformer.""" config_class = J3PAConfig base_model_prefix = "j3pa" main_input_name = "points" # Lets model.gradient_checkpointing_enable() switch on PointTransformer.gradient_checkpointing. supports_gradient_checkpointing = True def __init__(self, config: J3PAConfig): super().__init__(config) self.encoder = PointTransformer( stage_dims=config.stage_dims, num_down_layers_per_stage=config.num_down_layers_per_stage, num_up_layers_per_stage=config.num_up_layers_per_stage, num_heads_per_stage=config.num_heads_per_stage, qk_layernorm=config.qk_layernorm, sdpa_gate=config.sdpa_gate, voxel_size_conditioning_range=config.voxel_size_conditioning_range, ) self.post_init() def _init_weights(self, module): # Loading refills buffers that are not in the weights file with uninitialized memory: recompute this one as # VoxelSizeEmbedding.__init__ does. if isinstance(module, VoxelSizeEmbedding): module._freqs.copy_(math.pi * 2 ** torch.linspace(-2, 1, module._freqs.numel(), device="cpu")) def forward(self, points, batch_idx=None, voxel_size=None) -> PointTransformerOut: """See PointTransformer.forward. points can also be a list of (N_i, 5) point clouds, without batch_idx.""" # In bfloat16 the RoPE angles are rounded and the voxel size MLP breaks. if self.encoder._init_proj[0].weight.dtype != torch.float32: raise ValueError("Keep J3PA in float32 (the default): it computes in bfloat16 internally.") if not isinstance(points, torch.Tensor): batch_idx = torch.cat([torch.full((len(p),), i, device=p.device) for i, p in enumerate(points)]) points = torch.cat(points) return self.encoder(points, batch_idx, voxel_size=voxel_size)