# (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary. """D4RT query decoder with fp32 output heads and validated source-view indices.""" from __future__ import annotations import math from collections.abc import Callable from dataclasses import dataclass import torch import torch.utils.checkpoint as cp from timm.models.layers import trunc_normal_ from torch import nn from nets.ucpe_cd50_stable.backbone import _attention_backend OUTPUT_SPLIT = (3, 2, 1, 3, 3, 1) OUTPUT_DIM = sum(OUTPUT_SPLIT) class Mlp(nn.Module): def __init__( self, in_features: int, hidden_features: int | None = None, out_features: int | None = None, act_layer: Callable[..., nn.Module] = nn.GELU, bias: bool = True, ) -> None: super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features, bias=bias) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features, bias=bias) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.fc2(self.act(self.fc1(x))) class CrossAttention(nn.Module): """Queries attend to encoder tokens. No self-attention between queries. That absence is the decoder's central efficiency property: queries are independent, so a batch of 2,048 of them costs one attention against the token set rather than a 2048x2048 self-attention. """ def __init__( self, dim: int, dim_kv: int, num_heads: int = 8, qkv_bias: bool = False ) -> None: super().__init__() self.num_heads = num_heads self.q = nn.Linear(dim, dim, bias=qkv_bias) self.kv = nn.Linear(dim_kv, 2 * dim, bias=qkv_bias) self.proj = nn.Linear(dim, dim) def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: (batch, queries, channels) = x.shape tokens = y.shape[1] head_dim = channels // self.num_heads q = self.q(x).reshape(batch, queries, self.num_heads, head_dim) kv = ( self.kv(y) .reshape(batch, tokens, 2, self.num_heads, head_dim) .permute(2, 0, 1, 3, 4) ) attended = _attention_backend(q, kv[0], kv[1]) return self.proj(attended.reshape(batch, queries, channels)) class BlockCross(nn.Module): """Cross-attention plus MLP, both pre-normed with affine-free LayerNorm.""" def __init__( self, dim: int, dim_kv: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = False, act_layer: Callable[..., nn.Module] = nn.GELU, norm_layer: Callable[..., nn.Module] = nn.LayerNorm, ) -> None: super().__init__() self.norm1 = norm_layer(dim, elementwise_affine=False) self.attn = CrossAttention(dim, dim_kv, num_heads=num_heads, qkv_bias=qkv_bias) self.norm2 = norm_layer(dim, elementwise_affine=False) self.mlp = Mlp( in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer ) def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: x = x + self.attn(self.norm1(x), y) return x + self.mlp(self.norm2(x)) class FourierEmbedding(nn.Module): """Sinusoidal embedding of a `uv` pixel coordinate, half the channels per axis.""" div_term_sin: torch.Tensor div_term_cos: torch.Tensor def __init__(self, in_channels: int = 1408, base: int = 1000) -> None: super().__init__() self.in_channels = in_channels self.base = base per_axis = in_channels // 2 self.register_buffer( "div_term_sin", base ** (torch.arange(0, per_axis, 2).float() / per_axis) ) self.register_buffer( "div_term_cos", base ** (torch.arange(1, per_axis, 2).float() / per_axis) ) def forward(self, uv: torch.Tensor) -> torch.Tensor: """Embed each axis into half the channels.""" (batch, points, _) = uv.shape u = uv[..., 0:1] v = uv[..., 1:2] u_embed = torch.stack( [torch.sin(u / self.div_term_sin), torch.cos(u / self.div_term_cos)], dim=-1 ).reshape(batch, points, -1) v_embed = torch.stack( [torch.sin(v / self.div_term_sin), torch.cos(v / self.div_term_cos)], dim=-1 ).reshape(batch, points, -1) return torch.cat([u_embed, v_embed], dim=-1) @dataclass class D4RTDecoderConfig: """`type: "d4rt_v00.D4RTDecoderConfig"`. `kv_dim` is absent: it must equal the encoder's `embed_dim`, so it arrives as a build parameter rather than as a field a config author could get wrong. """ embed_dim: int = 1024 max_time_len: int = 60 img_window_size: int = 3 depth: int = 24 num_heads: int = 16 mlp_ratio: float = 4.0 qkv_bias: bool = False cp_freq: int = 1 max_view_num: int = 3 use_v_src: bool = False use_t_cam: bool = False def build(self, kv_dim: int) -> D4RTDecoder: return D4RTDecoder( embed_dim=self.embed_dim, kv_dim=kv_dim, max_time_len=self.max_time_len, img_window_size=self.img_window_size, depth=self.depth, num_heads=self.num_heads, mlp_ratio=self.mlp_ratio, qkv_bias=self.qkv_bias, cp_freq=self.cp_freq, max_view_num=self.max_view_num, use_v_src=self.use_v_src, use_t_cam=self.use_t_cam, ) class D4RTDecoder(nn.Module): """Cross-attention decoder from query points to per-point 3D predictions.""" def __init__( self, embed_dim: int = 1024, kv_dim: int = 1024, output_dim: int = OUTPUT_DIM, max_time_len: int = 60, img_window_size: int = 3, depth: int = 24, num_heads: int = 16, mlp_ratio: float = 4.0, qkv_bias: bool = False, norm_layer: Callable[..., nn.Module] = nn.LayerNorm, cp_freq: int = 1, max_view_num: int = 3, use_v_src: bool = False, use_t_cam: bool = False, ) -> None: super().__init__() self.embed_dim = embed_dim self.max_view_num = max_view_num self.use_v_src = use_v_src self.use_t_cam = use_t_cam self.cp_freq = int(cp_freq) self.uv_embed = FourierEmbedding(in_channels=embed_dim) embedding_scale = math.sqrt(embed_dim // num_heads) self.t_src_embed = nn.Parameter( torch.randn(1, max_time_len, embed_dim) / embedding_scale ) self.t_tgt_embed = nn.Parameter( torch.randn(1, max_time_len, embed_dim) / embedding_scale ) self.t_cam_embed = ( nn.Parameter(torch.randn(1, max_time_len, embed_dim) / embedding_scale) if use_t_cam else None ) self.view_embed = ( nn.Parameter(torch.zeros(max_view_num, kv_dim)) if max_view_num > 1 else None ) self.v_src_embed = nn.Embedding(max_view_num, embed_dim) if use_v_src else None self.image_patch_embed = nn.Linear( img_window_size * img_window_size * 3, embed_dim ) self.input_mlp = Mlp( in_features=embed_dim, hidden_features=int(mlp_ratio * embed_dim), out_features=embed_dim, ) self.cross_blocks = nn.ModuleList( [ BlockCross( dim=embed_dim, dim_kv=kv_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, norm_layer=norm_layer, ) for _ in range(depth) ] ) self.norm = norm_layer(embed_dim) self.fc = nn.Linear(embed_dim, output_dim) self.apply(self._init_weights) if self.v_src_embed is not None: nn.init.normal_(self.v_src_embed.weight, std=1e-06) def _init_weights(self, module: nn.Module) -> None: if isinstance(module, nn.Linear): trunc_normal_(module.weight, std=0.02) if module.bias is not None: nn.init.constant_(module.bias, 0) elif isinstance(module, nn.LayerNorm): if module.bias is not None: nn.init.constant_(module.bias, 0) if module.weight is not None: nn.init.constant_(module.weight, 1.0) def _sample_time_embed( self, time_embed: torch.Tensor, t: torch.Tensor, batch_size: int, pts_num: int, device: torch.device, ) -> torch.Tensor: """Read a learned time table at possibly-fractional indices. `grid_sample` rather than indexing, because target times are not always integers -- a query may sit between frames, and the linear interpolation is what makes the embedding continuous in time. `padding_mode="border"` clamps out-of-range times to the end of the table rather than wrapping. """ max_time_len = time_embed.shape[1] table = time_embed.permute(0, 2, 1).unsqueeze(-1).expand(batch_size, -1, -1, -1) normalized = 2.0 * t / (max_time_len - 1) - 1.0 grid = torch.zeros(batch_size, pts_num, 1, 2, device=device, dtype=table.dtype) grid[..., 1] = normalized.squeeze(-1).unsqueeze(-1) return ( torch.nn.functional.grid_sample( table, grid, mode="bilinear", padding_mode="border", align_corners=True ) .squeeze(-1) .permute(0, 2, 1) ) def forward( self, uv: torch.Tensor, t_src: torch.Tensor, t_tgt: torch.Tensor, image_patch: torch.Tensor, y: torch.Tensor, num_views: int = 1, v_src: torch.Tensor | None = None, t_cam: torch.Tensor | None = None, ) -> tuple[torch.Tensor, ...]: """`OUTPUT_NAMES` in order, each `(B, N, D)`. See the family interface.""" (batch_size, pts_num) = uv.shape[0:2] _validate_source_views(uv, y, num_views, self.max_view_num, v_src) if self.view_embed is not None: num_tokens = y.shape[1] per_view = num_tokens // num_views view_embed = self.view_embed[:num_views] view_embed = view_embed.unsqueeze(1).expand(-1, per_view, -1) y = y + view_embed.reshape(1, num_tokens, -1) with torch.no_grad(): uv_embed = self.uv_embed(uv) decoder_input = ( self._sample_time_embed( self.t_src_embed, t_src, batch_size, pts_num, uv.device ) + self._sample_time_embed( self.t_tgt_embed, t_tgt, batch_size, pts_num, uv.device ) + self.image_patch_embed(image_patch.reshape(batch_size, pts_num, -1)) + uv_embed ) if self.t_cam_embed is not None: if t_cam is None: raise ValueError("t_cam is required when use_t_cam=True") decoder_input = decoder_input + self._sample_time_embed( self.t_cam_embed, t_cam, batch_size, pts_num, uv.device ) if self.v_src_embed is not None: if v_src is None: raise ValueError("v_src is required when use_v_src=True") view_index = v_src.squeeze(-1).long() decoder_input = decoder_input + self.v_src_embed(view_index) x = self.input_mlp(decoder_input) for index, block in enumerate(self.cross_blocks): if self.cp_freq > 0 and self.training and (index % self.cp_freq == 0): x = cp.checkpoint(block, x, y, use_reentrant=False) else: x = block(x, y) with torch.autocast(x.device.type, enabled=False): x = torch.nn.functional.linear( self.norm(x.float()), self.fc.weight.float(), self.fc.bias.float() ) (pos_3d, pos_2d, vis, disp, normal, conf) = torch.split( x, list(OUTPUT_SPLIT), dim=-1 ) normal = torch.nn.functional.normalize(normal, dim=-1) pos_2d = torch.sigmoid(pos_2d) return (pos_3d, pos_2d, vis, disp, normal, conf) def _validate_source_views( uv: torch.Tensor, tokens: torch.Tensor, num_views: int, max_view_num: int, v_src: torch.Tensor | None, ) -> None: (batch_size, pts_num) = uv.shape[:2] if not 1 <= num_views <= max_view_num or tokens.shape[1] % num_views: raise ValueError("num_views must fit the decoder and divide the token count") if v_src is not None: if v_src.shape != (batch_size, pts_num, 1): raise ValueError("v_src must have shape (B, N, 1)") if v_src.dtype not in (torch.int32, torch.int64): raise ValueError("v_src must contain integer source-view indices") if bool(((v_src < 0) | (v_src >= num_views)).any()): raise ValueError("v_src must index an encoded view")