dliu1014's picture Xuweiyi's picture meta-bot's picture
Initial data commit
9c890d3
Raw History Blame Contribute Delete
8.63 kB
# (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
"""Tubelet queries attend to camera geometry from both RGB frames."""
from __future__ import annotations
import torch
import torch.nn.functional as F
from nets.ucpe_cd50_stable.ucpe import RelativeRayAttention as _SingleFrameAttention
from nets.ucpe_cd50_stable.ucpe import (
_apply_ucpe_transform,
_invert_se3,
_rope_coefficients,
_validate_camera_inputs,
)
from nets.ucpe_cd50_stable.ucpe import build_lat_up_encoding as _frame_lat_up
from nets.ucpe_cd50_stable.ucpe import (
build_relative_ray_transforms as _frame_ray_transforms,
)
def _group_frames(value: torch.Tensor, tubelet_size: int, patches: int) -> torch.Tensor:
batch = value.shape[0]
grouped = value.reshape(batch, -1, tubelet_size, patches, *value.shape[2:])
order = (0, 1, 3, 2, *range(4, grouped.ndim))
return grouped.permute(order).reshape(batch, -1, tubelet_size, *value.shape[2:])
def _ungroup_frames(value: torch.Tensor, patches: int) -> torch.Tensor:
(batch, _, frames) = value.shape[:3]
grouped = value.reshape(batch, -1, patches, frames, *value.shape[3:])
order = (0, 1, 3, 2, *range(4, grouped.ndim))
return grouped.permute(order).flatten(1, 3)
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:
(_, frames) = _validate_camera_inputs(T_world_cam, T_pix_cam)
if min(image_height, image_width, patch_size, tubelet_size) <= 0:
raise ValueError("geometry dimensions must be positive")
complete_frames = frames // tubelet_size * tubelet_size
rays = _frame_ray_transforms(
T_world_cam[:, :complete_frames],
T_pix_cam[:, :complete_frames],
image_height=image_height,
image_width=image_width,
patch_size=patch_size,
tubelet_size=1,
)
patches = image_height // patch_size * (image_width // patch_size)
return _group_frames(rays, tubelet_size, patches)
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:
(_, frames) = _validate_camera_inputs(T_world_cam, T_pix_cam)
if min(image_height, image_width, patch_size, tubelet_size) <= 0:
raise ValueError("geometry dimensions must be positive")
complete_frames = frames // tubelet_size * tubelet_size
lat_up = _frame_lat_up(
T_world_cam[:, :complete_frames],
T_pix_cam[:, :complete_frames],
world_up=world_up,
image_height=image_height,
image_width=image_width,
patch_size=patch_size,
tubelet_size=1,
)
patches = image_height // patch_size * (image_width // patch_size)
return _group_frames(lat_up, tubelet_size, patches)
class RelativeRayAttention(_SingleFrameAttention):
def _oriented_tokens(
self,
tokens: torch.Tensor,
lat_up: torch.Tensor | None,
valid: torch.Tensor | None,
) -> torch.Tensor:
if lat_up is None:
return tokens
if self.lat_up_proj is None:
raise ValueError("latitude/up requires absolute orientation")
if valid is not None:
if valid.shape != (tokens.shape[0],) or valid.dtype != torch.bool:
raise ValueError("lat_up_valid must be bool with shape [batch]")
if valid.device != tokens.device:
raise ValueError("latitude/up validity must share the token device")
lat_up = torch.where(valid[:, None, None], lat_up, 0.0)
bias = self.lat_up_proj(lat_up.to(dtype=tokens.dtype))
if valid is not None:
bias = torch.where(valid[:, None, None], bias, 0.0)
return tokens + bias
def _rope(
self, features: torch.Tensor, spatial_height: int, spatial_width: int
) -> tuple[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor, torch.Tensor]]:
frames = features.shape[2] // (spatial_height * spatial_width)
x = (
torch.arange(spatial_width, device=features.device, dtype=torch.float32)
.repeat(spatial_height)
.repeat(frames)
)
y = (
torch.arange(spatial_height, device=features.device, dtype=torch.float32)
.repeat_interleave(spatial_width)
.repeat(frames)
)
return (
_rope_coefficients(x, self.head_dim // 4),
_rope_coefficients(y, self.head_dim // 4),
)
def _attend(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
anchors: torch.Tensor,
frames: torch.Tensor,
spatial_height: int,
spatial_width: int,
) -> torch.Tensor:
query_rope = self._rope(q, spatial_height, spatial_width)
frame_rope = self._rope(k, spatial_height, spatial_width)
with torch.amp.autocast(device_type=q.device.type, enabled=False):
anchors = anchors.float()
inverse_frames = _invert_se3(frames.float())
q = _apply_ucpe_transform(q, anchors.transpose(-1, -2), *query_rope)
k = _apply_ucpe_transform(k, inverse_frames, *frame_rope)
v = _apply_ucpe_transform(v, inverse_frames, *frame_rope)
output = F.scaled_dot_product_attention(
q, k, v, dropout_p=self.dropout if self.training else 0.0
)
return _apply_ucpe_transform(output, anchors, *query_rope, inverse_rope=True)
def _validate_geometry(
self,
tokens: torch.Tensor,
ray_transforms: torch.Tensor,
spatial_height: int,
spatial_width: int,
lat_up_encoding: torch.Tensor | None,
) -> tuple[int, int, int, int]:
if tokens.ndim != 3 or tokens.shape[-1] != self.dim:
raise ValueError(f"tokens must have shape [batch, length, {self.dim}]")
(batch, length, _) = tokens.shape
if (
ray_transforms.ndim != 5
or ray_transforms.shape[:2] != (batch, length)
or ray_transforms.shape[-2:] != (4, 4)
or (ray_transforms.shape[2] <= 0)
):
raise ValueError(
"ray transforms must have shape [batch, length, frames, 4, 4]"
)
if ray_transforms.device != tokens.device:
raise ValueError("tokens and ray transforms must share the device")
patches = spatial_height * spatial_width
if min(spatial_height, spatial_width) <= 0 or length % patches != 0:
raise ValueError("token length must contain complete spatial grids")
frames_per_tubelet = ray_transforms.shape[2]
if lat_up_encoding is not None and (
lat_up_encoding.shape != (batch, length, frames_per_tubelet, 3)
or lat_up_encoding.device != tokens.device
):
raise ValueError("latitude/up must have shape [batch, length, frames, 3]")
return (batch, length, frames_per_tubelet, patches)
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:
(batch, length, frames_per_tubelet, patches) = self._validate_geometry(
tokens, ray_transforms, spatial_height, spatial_width, lat_up_encoding
)
frame_tokens = _ungroup_frames(
tokens[:, :, None].expand(-1, -1, frames_per_tubelet, -1), patches
)
query_lat_up = None if lat_up_encoding is None else lat_up_encoding[:, :, 0]
frame_lat_up = (
None
if lat_up_encoding is None
else _ungroup_frames(lat_up_encoding, patches)
)
query_tokens = self._oriented_tokens(tokens, query_lat_up, lat_up_valid)
frame_tokens = self._oriented_tokens(frame_tokens, frame_lat_up, lat_up_valid)
output = self._attend(
self._project(self.q_proj(query_tokens)),
self._project(self.k_proj(frame_tokens)),
self._project(self.v_proj(frame_tokens)),
ray_transforms[:, :, 0],
_ungroup_frames(ray_transforms, patches),
spatial_height,
spatial_width,
)
output = output.transpose(1, 2).reshape(batch, length, self.attention_dim)
return self.out_proj(output)