# (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary. """Relative-ray attention adapted from UCPE and PRoPE. This file contains code adapted from: * UCPE, Copyright (c) 2026 Cheng Zhang https://github.com/chengzhag/UCPE * PRoPE, "Cameras as Relative Positional Encoding" https://arxiv.org/abs/2507.10496 Both sources are distributed under the MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import annotations import math import torch import torch.nn as nn import torch.nn.functional as F _GEOMETRY_EPS = 1e-06 _UP_PERTURBATION_RADIANS = 0.1 def _normalize(vector: torch.Tensor) -> torch.Tensor: return F.normalize(vector, dim=-1, eps=_GEOMETRY_EPS) def _invert_se3(transform: torch.Tensor) -> torch.Tensor: rotation_inv = transform[..., :3, :3].transpose(-1, -2) inverse = torch.zeros_like(transform) inverse[..., :3, :3] = rotation_inv inverse[..., :3, 3] = -torch.einsum( "...ij,...j->...i", rotation_inv, transform[..., :3, 3] ) inverse[..., 3, 3] = 1.0 return inverse def _validate_camera_inputs( T_world_cam: torch.Tensor, T_pix_cam: torch.Tensor ) -> tuple[int, int]: if T_world_cam.ndim != 4 or T_world_cam.shape[-2:] != (4, 4): raise ValueError( ( f"T_world_cam must have shape [batch, frames, 4, 4], got " f"{tuple(T_world_cam.shape)}" ) ) if T_pix_cam.ndim != 4 or T_pix_cam.shape[-2:] not in ((3, 3), (4, 4)): raise ValueError( ( f"T_pix_cam must have shape [batch, frames, 3, 3] or " f"[batch, frames, 4, 4], got {tuple(T_pix_cam.shape)}" ) ) if T_world_cam.shape[:2] != T_pix_cam.shape[:2]: raise ValueError( ( "T_world_cam and T_pix_cam must have matching batch/frame " "dimensions" ) ) if T_world_cam.device != T_pix_cam.device: raise ValueError("T_world_cam and T_pix_cam must be on the same device") return (int(T_world_cam.shape[0]), int(T_world_cam.shape[1])) def build_relative_ray_transforms( T_world_cam: torch.Tensor, T_pix_cam: torch.Tensor, *, image_height: int, image_width: int, patch_size: int, tubelet_size: int, ) -> torch.Tensor: (batch_size, num_frames) = _validate_camera_inputs(T_world_cam, T_pix_cam) if min(image_height, image_width, patch_size, tubelet_size) <= 0: raise ValueError( "image dimensions, patch_size, and tubelet_size must be positive" ) num_tubelets = num_frames // tubelet_size spatial_height = image_height // patch_size spatial_width = image_width // patch_size if num_tubelets == 0 or spatial_height == 0 or spatial_width == 0: raise ValueError( "camera sequence and image must contain at least one tubelet" ) frame_indices = ( torch.arange(num_tubelets, device=T_world_cam.device, dtype=torch.long) * tubelet_size ) with torch.amp.autocast(device_type=T_world_cam.device.type, enabled=False): return _build_relative_ray_transforms_fp32( T_world_cam, T_pix_cam, frame_indices=frame_indices, batch_size=batch_size, num_tubelets=num_tubelets, spatial_height=spatial_height, spatial_width=spatial_width, patch_size=patch_size, ) def _build_relative_ray_transforms_fp32( T_world_cam: torch.Tensor, T_pix_cam: torch.Tensor, *, frame_indices: torch.Tensor, batch_size: int, num_tubelets: int, spatial_height: int, spatial_width: int, patch_size: int, ) -> torch.Tensor: (camera_to_world, _, _, world_rays) = _build_token_ray_geometry_fp32( T_world_cam, T_pix_cam, frame_indices=frame_indices, spatial_height=spatial_height, spatial_width=spatial_width, patch_size=patch_size, ) camera_rotation = camera_to_world[..., :3, :3] camera_y = ( camera_rotation[..., :, 1] .unsqueeze(-2) .unsqueeze(-2) .expand_as(world_rays) ) ray_x = _normalize(torch.cross(camera_y, world_rays, dim=-1)) ray_y = _normalize(torch.cross(world_rays, ray_x, dim=-1)) ray_to_world_rotation = torch.stack((ray_x, ray_y, world_rays), dim=-1) camera_center = ( camera_to_world[..., :3, 3] .unsqueeze(-2) .unsqueeze(-2) .expand_as(world_rays) ) ray_to_world = torch.zeros( (batch_size, num_tubelets, spatial_height, spatial_width, 4, 4), device=T_world_cam.device, dtype=torch.float32, ) ray_to_world[..., :3, :3] = ray_to_world_rotation ray_to_world[..., :3, 3] = camera_center ray_to_world[..., 3, 3] = 1.0 world_to_ray = _invert_se3(ray_to_world) return world_to_ray.flatten(1, 3) def _build_token_ray_geometry_fp32( T_world_cam: torch.Tensor, T_pix_cam: torch.Tensor, *, frame_indices: torch.Tensor, spatial_height: int, spatial_width: int, patch_size: int, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: camera_to_world = T_world_cam.index_select(1, frame_indices).float() intrinsics = T_pix_cam.index_select(1, frame_indices)[..., :3, :3].float() patch_offset = (patch_size - 1) * 0.5 pixel_x = ( torch.arange( spatial_width, device=T_world_cam.device, dtype=torch.float32 ) * patch_size + patch_offset ) pixel_y = ( torch.arange( spatial_height, device=T_world_cam.device, dtype=torch.float32 ) * patch_size + patch_offset ) (grid_y, grid_x) = torch.meshgrid(pixel_y, pixel_x, indexing="ij") pixels = torch.stack((grid_x, grid_y, torch.ones_like(grid_x)), dim=-1) camera_rays = torch.einsum( "btij,hwj->bthwi", torch.linalg.inv(intrinsics), pixels ) camera_rays = _normalize(camera_rays) camera_rotation = camera_to_world[..., :3, :3] world_rays = _normalize( torch.einsum("btij,bthwj->bthwi", camera_rotation, camera_rays) ) return (camera_to_world, intrinsics, pixels, world_rays) def prepare_world_up( world_up: torch.Tensor | None, world_up_valid: torch.Tensor | None, *, batch_size: int, device: torch.device, ) -> tuple[torch.Tensor, torch.Tensor]: if world_up_valid is not None: if ( world_up_valid.shape != (batch_size,) or world_up_valid.dtype != torch.bool ): raise ValueError("world_up_valid must be bool with shape (B,)") if world_up_valid.device != device: raise ValueError( "world_up_valid and camera poses must be on the same device" ) if world_up is None: if world_up_valid is not None and bool(world_up_valid.any()): raise ValueError("valid gravity requires world_up") return ( torch.zeros(batch_size, 3, device=device), torch.zeros(batch_size, dtype=torch.bool, device=device), ) if world_up.shape != (batch_size, 3) or not world_up.is_floating_point(): raise ValueError("world_up must be floating point with shape (B, 3)") if world_up.device != device: raise ValueError("world_up and camera poses must be on the same device") valid = ( torch.ones(batch_size, dtype=torch.bool, device=device) if world_up_valid is None else world_up_valid ) up = torch.where(valid[:, None], world_up.float(), 0.0) norms = torch.linalg.vector_norm(up, dim=-1) invalid = valid & ( ~torch.isfinite(up).all(-1) | ~torch.isfinite(norms) | (norms <= _GEOMETRY_EPS) ) if bool(invalid.any()): raise ValueError("valid world_up directions must be finite and nonzero") return (up / norms.clamp_min(_GEOMETRY_EPS)[:, None], valid) def build_lat_up_encoding( T_world_cam: torch.Tensor, T_pix_cam: torch.Tensor, *, world_up: torch.Tensor, image_height: int, image_width: int, patch_size: int, tubelet_size: int, ) -> torch.Tensor: (batch_size, num_frames) = _validate_camera_inputs(T_world_cam, T_pix_cam) if min(image_height, image_width, patch_size, tubelet_size) <= 0: raise ValueError( "image dimensions, patch_size, and tubelet_size must be positive" ) if ( world_up.shape != (batch_size, 3) or world_up.device != T_world_cam.device ): raise ValueError("world_up must have shape (B, 3) on the camera device") if not world_up.is_floating_point() or not bool( torch.isfinite(world_up).all() ): raise ValueError("world_up must be finite floating point") num_tubelets = num_frames // tubelet_size spatial_height = image_height // patch_size spatial_width = image_width // patch_size if num_tubelets == 0 or spatial_height == 0 or spatial_width == 0: raise ValueError( "camera sequence and image must contain at least one tubelet" ) frame_indices = ( torch.arange(num_tubelets, device=T_world_cam.device, dtype=torch.long) * tubelet_size ) with torch.amp.autocast(device_type=T_world_cam.device.type, enabled=False): lat_up = _build_lat_up_encoding_fp32( T_world_cam, T_pix_cam, world_up=world_up, frame_indices=frame_indices, spatial_height=spatial_height, spatial_width=spatial_width, patch_size=patch_size, ) return lat_up.reshape( batch_size, num_tubelets * spatial_height * spatial_width, 3 ) def _build_lat_up_encoding_fp32( T_world_cam: torch.Tensor, T_pix_cam: torch.Tensor, *, world_up: torch.Tensor, frame_indices: torch.Tensor, spatial_height: int, spatial_width: int, patch_size: int, ) -> torch.Tensor: (camera_to_world, intrinsics, pixels, world_rays) = ( _build_token_ray_geometry_fp32( T_world_cam, T_pix_cam, frame_indices=frame_indices, spatial_height=spatial_height, spatial_width=spatial_width, patch_size=patch_size, ) ) up_direction = _normalize(world_up.float())[:, None, None, None, :] vertical = (world_rays * up_direction).sum(dim=-1) horizontal_norm = torch.linalg.vector_norm( torch.cross(world_rays, up_direction.expand_as(world_rays), dim=-1), dim=-1, ) latitude = torch.atan2(vertical, horizontal_norm) up = _build_up_map_fp32( world_rays, camera_to_world[..., :3, :3], intrinsics, pixels, up_direction, ) return torch.cat((latitude.unsqueeze(-1), up), dim=-1) def _build_up_map_fp32( world_rays: torch.Tensor, camera_rotation: torch.Tensor, intrinsics: torch.Tensor, pixels: torch.Tensor, world_up: torch.Tensor, ) -> torch.Tensor: world_up = world_up.expand_as(world_rays) rotation_axes = torch.cross(world_rays, world_up, dim=-1) axis_norm = torch.linalg.vector_norm(rotation_axes, dim=-1, keepdim=True) valid_axis = axis_norm > _GEOMETRY_EPS rotation_axes = rotation_axes / axis_norm.clamp_min(_GEOMETRY_EPS) cos_delta = math.cos(_UP_PERTURBATION_RADIANS) sin_delta = math.sin(_UP_PERTURBATION_RADIANS) axis_dot_ray = (rotation_axes * world_rays).sum(dim=-1, keepdim=True) rotated_world_rays = ( world_rays * cos_delta + torch.cross(rotation_axes, world_rays, dim=-1) * sin_delta + rotation_axes * axis_dot_ray * (1.0 - cos_delta) ) rotated_camera_rays = torch.einsum( "btji,bthwj->bthwi", camera_rotation, rotated_world_rays ) projected = torch.einsum( "btij,bthwj->bthwi", intrinsics, rotated_camera_rays ) depth = projected[..., 2:3] safe_depth = torch.where(depth >= 0.0, 1.0, -1.0) * depth.abs().clamp_min( _GEOMETRY_EPS ) rotated_pixels = projected[..., :2] / safe_depth pixel_offsets = rotated_pixels - pixels[..., :2] offset_norm = torch.linalg.vector_norm(pixel_offsets, dim=-1, keepdim=True) valid = valid_axis & (depth > _GEOMETRY_EPS) & (offset_norm > _GEOMETRY_EPS) normalized_offsets = pixel_offsets / offset_norm.clamp_min(_GEOMETRY_EPS) return torch.where( valid, normalized_offsets, torch.zeros_like(normalized_offsets) ) def _apply_tiled_transform( features: torch.Tensor, transform: torch.Tensor ) -> torch.Tensor: (batch_size, num_heads, sequence_length, feature_dim) = features.shape if feature_dim % 4 != 0: raise ValueError("SE(3) feature block must be divisible by 4") grouped = features.reshape( batch_size, num_heads, sequence_length, feature_dim // 4, 4 ) transformed = torch.einsum("blij,bhlpj->bhlpi", transform, grouped) return transformed.reshape_as(features) def _rope_coefficients( positions: torch.Tensor, feature_dim: int ) -> tuple[torch.Tensor, torch.Tensor]: if feature_dim % 2 != 0: raise ValueError("RoPE feature block must be even") num_frequencies = feature_dim // 2 frequencies = 100.0 ** ( -torch.arange( num_frequencies, device=positions.device, dtype=torch.float32 ) / num_frequencies ) angles = positions.float()[None, None, :, None] * frequencies return (torch.cos(angles), torch.sin(angles)) def _apply_rope( features: torch.Tensor, coefficients: tuple[torch.Tensor, torch.Tensor], *, inverse: bool = False, ) -> torch.Tensor: (cos, sin) = coefficients (first, second) = features.chunk(2, dim=-1) if inverse: return torch.cat( (cos * first - sin * second, sin * first + cos * second), dim=-1 ) return torch.cat( (cos * first + sin * second, -sin * first + cos * second), dim=-1 ) def _apply_ucpe_transform( features: torch.Tensor, se3_transform: torch.Tensor, rope_x: tuple[torch.Tensor, torch.Tensor], rope_y: tuple[torch.Tensor, torch.Tensor], *, inverse_rope: bool = False, ) -> torch.Tensor: feature_dtype = features.dtype with torch.amp.autocast(device_type=features.device.type, enabled=False): quarter_dim = features.shape[-1] // 4 (se3_features, x_features, y_features) = torch.split( features.float(), [2 * quarter_dim, quarter_dim, quarter_dim], dim=-1, ) se3_features = _apply_tiled_transform( se3_features, se3_transform.float() ) x_features = _apply_rope(x_features, rope_x, inverse=inverse_rope) y_features = _apply_rope(y_features, rope_y, inverse=inverse_rope) transformed = torch.cat((se3_features, x_features, y_features), dim=-1) return transformed.to(dtype=feature_dtype) class RelativeRayAttention(nn.Module): def __init__( self, dim: int, num_heads: int, compression: int = 8, dropout: float = 0.0, use_absolute_orientation: bool = False, ) -> None: super().__init__() if dim <= 0 or num_heads <= 0 or compression <= 0: raise ValueError("dim, num_heads, and compression must be positive") if dim % compression != 0 or num_heads % compression != 0: raise ValueError("compression must divide both dim and num_heads") if dim % num_heads != 0: raise ValueError("num_heads must divide dim") if dim // num_heads % 8 != 0: raise ValueError("attention head dimension must be divisible by 8") if not 0.0 <= dropout < 1.0: raise ValueError("dropout must be in [0, 1)") self.dim = dim self.num_heads = num_heads // compression self.head_dim = dim // num_heads self.attention_dim = dim // compression self.dropout = dropout self.q_proj = nn.Linear(dim, self.attention_dim) self.k_proj = nn.Linear(dim, self.attention_dim) self.v_proj = nn.Linear(dim, self.attention_dim) self.out_proj = nn.Linear(self.attention_dim, dim) self.lat_up_proj = ( nn.Linear(3, dim) if use_absolute_orientation else None ) nn.init.zeros_(self.out_proj.weight) nn.init.zeros_(self.out_proj.bias) def forward( self, tokens: torch.Tensor, ray_transforms: torch.Tensor, *, spatial_height: int, spatial_width: int, lat_up_encoding: torch.Tensor | None = None, lat_up_valid: torch.Tensor | None = None, ) -> torch.Tensor: if tokens.ndim != 3 or tokens.shape[-1] != self.dim: raise ValueError( ( f"tokens must have shape [batch, length, {self.dim}], got " f"{tuple(tokens.shape)}" ) ) (batch_size, sequence_length, _) = tokens.shape if ray_transforms.shape != (batch_size, sequence_length, 4, 4): raise ValueError( ( f"ray_transforms must have shape [{batch_size}, " f"{sequence_length}, 4, 4], got " f"{tuple(ray_transforms.shape)}" ) ) if ray_transforms.device != tokens.device: raise ValueError( "tokens and ray_transforms must be on the same device" ) if lat_up_encoding is not None: expected_lat_up_shape = (batch_size, sequence_length, 3) if lat_up_encoding.shape != expected_lat_up_shape: raise ValueError( ( "lat_up_encoding must have shape " f"{expected_lat_up_shape}, " f"got {tuple(lat_up_encoding.shape)}" ) ) if lat_up_encoding.device != tokens.device: raise ValueError( "tokens and lat_up_encoding must be on the same device" ) if self.lat_up_proj is None: raise ValueError( "lat_up_encoding requires use_absolute_orientation=True" ) spatial_tokens = spatial_height * spatial_width if spatial_height <= 0 or spatial_width <= 0: raise ValueError("spatial dimensions must be positive") if sequence_length % spatial_tokens != 0: raise ValueError( "token length must be divisible by the spatial token count" ) attention_tokens = tokens if lat_up_encoding is not None: assert self.lat_up_proj is not None if lat_up_valid is not None: if ( lat_up_valid.shape != (batch_size,) or lat_up_valid.dtype != torch.bool ): raise ValueError( "lat_up_valid must be bool with shape (B,)" ) if lat_up_valid.device != tokens.device: raise ValueError( "lat_up_valid and tokens must be on the same device" ) lat_up_encoding = torch.where( lat_up_valid[:, None, None], lat_up_encoding, 0.0 ) orientation_bias = self.lat_up_proj( lat_up_encoding.to(dtype=tokens.dtype) ) if lat_up_valid is not None: orientation_bias = torch.where( lat_up_valid[:, None, None], orientation_bias, 0.0 ) attention_tokens = attention_tokens + orientation_bias q = self._project(self.q_proj(attention_tokens)) k = self._project(self.k_proj(attention_tokens)) v = self._project(self.v_proj(attention_tokens)) num_frames = sequence_length // spatial_tokens x_positions = torch.arange( spatial_width, device=tokens.device, dtype=torch.float32 ).repeat(spatial_height) y_positions = torch.arange( spatial_height, device=tokens.device, dtype=torch.float32 ).repeat_interleave(spatial_width) x_positions = x_positions.repeat(num_frames) y_positions = y_positions.repeat(num_frames) rope_dim = self.head_dim // 4 with torch.amp.autocast(device_type=tokens.device.type, enabled=False): rope_x = _rope_coefficients(x_positions, rope_dim) rope_y = _rope_coefficients(y_positions, rope_dim) ray_transforms_fp32 = ray_transforms.float() inverse_ray_transforms = _invert_se3(ray_transforms_fp32) q = _apply_ucpe_transform( q, ray_transforms_fp32.transpose(-1, -2), rope_x, rope_y ) k = _apply_ucpe_transform(k, inverse_ray_transforms, rope_x, rope_y) v = _apply_ucpe_transform(v, inverse_ray_transforms, rope_x, rope_y) output = F.scaled_dot_product_attention( q, k, v, dropout_p=self.dropout if self.training else 0.0 ) output = _apply_ucpe_transform( output, ray_transforms_fp32, rope_x, rope_y, inverse_rope=True ) output = output.transpose(1, 2).reshape( batch_size, sequence_length, self.attention_dim ) return self.out_proj(output) def _project(self, projected_tokens: torch.Tensor) -> torch.Tensor: (batch_size, sequence_length, _) = projected_tokens.shape return projected_tokens.reshape( batch_size, sequence_length, self.num_heads, self.head_dim ).transpose(1, 2)