# (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary. """VideoMAE backbone with resident positional encoding and dtype-aware attention.""" from __future__ import annotations from collections.abc import Callable from functools import partial import numpy as np import torch import torch.nn.functional as F try: from flash_attn import flash_attn_func except ImportError: flash_attn_func = None from timm.models.layers import drop_path, to_2tuple, trunc_normal_ from torch import nn GIANT_PATCH_SIZE = 14 GIANT_EMBED_DIM = 1408 GIANT_DEPTH = 40 GIANT_NUM_HEADS = 16 GIANT_MLP_RATIO = 48 / 11 def _attention_backend( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, *, dropout_p: float = 0.0, softmax_scale: float | None = None, ) -> torch.Tensor: if q.dtype != k.dtype or q.dtype != v.dtype: raise ValueError("attention query, key and value must have matching dtypes") if flash_attn_func is not None and q.is_cuda and q.dtype in (torch.float16, torch.bfloat16): return flash_attn_func( q, k, v, dropout_p=dropout_p, softmax_scale=softmax_scale ) return F.scaled_dot_product_attention( q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), dropout_p=dropout_p, scale=softmax_scale, ).transpose(1, 2) class DropPath(nn.Module): """Stochastic depth, per sample, on the residual branch.""" def __init__(self, drop_prob: float | None = None) -> None: super().__init__() self.drop_prob = drop_prob def forward(self, x: torch.Tensor) -> torch.Tensor: return drop_path(x, self.drop_prob or 0.0, self.training) def extra_repr(self) -> str: return f"p={self.drop_prob}" 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, drop: float = 0.0, ) -> 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) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.drop(self.fc2(self.act(self.fc1(x)))) class Attention(nn.Module): """Multi-head self-attention, flash or math. `use_flash_attn=False` is not just a fallback -- it is what makes any of this runnable on CPU, and therefore what makes the encoder unit-testable without a GPU. """ def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = False, qk_scale: float | None = None, attn_drop: float = 0.0, proj_drop: float = 0.0, attn_head_dim: int | None = None, use_flash_attn: bool = True, ) -> None: super().__init__() self.num_heads = num_heads head_dim = attn_head_dim if attn_head_dim is not None else dim // num_heads all_head_dim = head_dim * self.num_heads self.head_dim = head_dim self.scale = qk_scale or head_dim ** (-0.5) self.use_flash_attn = use_flash_attn self.attn_drop_rate = attn_drop self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False) self.q_bias: nn.Parameter | None self.v_bias: nn.Parameter | None if qkv_bias: self.q_bias = nn.Parameter(torch.zeros(all_head_dim)) self.v_bias = nn.Parameter(torch.zeros(all_head_dim)) else: self.q_bias = None self.v_bias = None self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(all_head_dim, dim) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x: torch.Tensor) -> torch.Tensor: (B, N, _) = x.shape qkv_bias = None (q_bias, v_bias) = (self.q_bias, self.v_bias) if q_bias is not None and v_bias is not None: qkv_bias = torch.cat( (q_bias, torch.zeros_like(v_bias, requires_grad=False), v_bias) ) qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias) if self.use_flash_attn: qkv = qkv.reshape(B, N, 3, self.num_heads, self.head_dim) (q, k, v) = (qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]) dropout_p = self.attn_drop_rate if self.training else 0.0 x = _attention_backend( q, k, v, dropout_p=dropout_p, softmax_scale=self.scale ) x = x.reshape(B, N, -1) else: qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) (q, k, v) = (qkv[0], qkv[1], qkv[2]) attn = q * self.scale @ k.transpose(-2, -1) attn = self.attn_drop(attn.softmax(dim=-1)) x = (attn @ v).transpose(1, 2).reshape(B, N, -1) return self.proj_drop(self.proj(x)) class Block(nn.Module): def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = False, qk_scale: float | None = None, drop: float = 0.0, attn_drop: float = 0.0, drop_path_rate: float = 0.0, init_values: float | None = None, act_layer: Callable[..., nn.Module] = nn.GELU, norm_layer: Callable[..., nn.Module] = nn.LayerNorm, attn_head_dim: int | None = None, use_flash_attn: bool = True, ) -> None: super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, attn_head_dim=attn_head_dim, use_flash_attn=use_flash_attn, ) self.drop_path = ( DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity() ) self.norm2 = norm_layer(dim) self.mlp = Mlp( in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, drop=drop, ) if init_values is not None and init_values > 0: self.gamma_1 = nn.Parameter(init_values * torch.ones(dim)) self.gamma_2 = nn.Parameter(init_values * torch.ones(dim)) else: (self.gamma_1, self.gamma_2) = (None, None) def forward(self, x: torch.Tensor) -> torch.Tensor: if self.gamma_1 is None: x = x + self.drop_path(self.attn(self.norm1(x))) return x + self.drop_path(self.mlp(self.norm2(x))) x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x))) return x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x))) class PatchEmbed(nn.Module): """Video to tubelet tokens, via one strided 3D convolution. Used twice per encoder: once over RGB (`in_chans=3`) and once over Pluecker rays (`in_chans=6`), with the ray tokens added to the image tokens. """ def __init__( self, img_size: int | tuple[int, int] = 224, patch_size: int = 16, in_chans: int = 3, embed_dim: int = 768, num_frames: int = 16, tubelet_size: int = 2, ) -> None: super().__init__() img_size_tuple: tuple[int, int] = to_2tuple(img_size) patch_size_tuple: tuple[int, int] = to_2tuple(patch_size) spatial_patches = ( img_size_tuple[0] // patch_size_tuple[0] * (img_size_tuple[1] // patch_size_tuple[1]) ) self.img_size = img_size_tuple self.tubelet_size = tubelet_size self.patch_size = patch_size_tuple self.num_patches = spatial_patches * (num_frames // tubelet_size) self.proj = nn.Conv3d( in_channels=in_chans, out_channels=embed_dim, kernel_size=(tubelet_size, patch_size_tuple[0], patch_size_tuple[1]), stride=(tubelet_size, patch_size_tuple[0], patch_size_tuple[1]), ) def forward(self, x: torch.Tensor) -> torch.Tensor: (_, _, _, height, width) = x.shape if height != self.img_size[0] or width != self.img_size[1]: raise ValueError( f"input {height}x{width} does not match the patch embedding's {self.img_size[0]}x{self.img_size[1]}" ) return self.proj(x).flatten(2).transpose(1, 2) def get_sinusoid_encoding_table(n_position: int, d_hid: int) -> torch.Tensor: """Fixed sinusoidal positions. Not a parameter -- see `VisionTransformer.pos_embed`.""" positions = np.arange(n_position)[:, None] hidden_dims = np.arange(d_hid)[None, :] table = positions / np.power(10000, 2 * (hidden_dims // 2) / d_hid) table[:, 0::2] = np.sin(table[:, 0::2]) table[:, 1::2] = np.cos(table[:, 1::2]) return torch.from_numpy(table).float().unsqueeze(0) class VisionTransformer(nn.Module): """The VideoMAE encoder trunk: patch embedding, positions, blocks, final norm. Deliberately has **no classifier head and no pooled forward**. D4RT reads tokens, not class logits, and it does so through `encoder_v00.get_encoder_tokens` rather than through a `forward` here -- because the token path needs to interleave gradient checkpointing and per-frame attention grouping between blocks, which a monolithic `forward` cannot express. See the module docstring for why the head is gone. """ def __init__( self, img_size: int | tuple[int, int] = 224, patch_size: int = 16, in_chans: int = 3, embed_dim: int = 768, depth: int = 12, num_heads: int = 12, mlp_ratio: float = 4.0, qkv_bias: bool = False, qk_scale: float | None = None, drop_rate: float = 0.0, attn_drop_rate: float = 0.0, drop_path_rate: float = 0.0, norm_layer: Callable[..., nn.Module] = nn.LayerNorm, init_values: float = 0.0, all_frames: int = 16, tubelet_size: int = 2, use_flash_attn: bool = True, no_pluecker_rays: bool = False, ) -> None: super().__init__() self.num_features = self.embed_dim = embed_dim self.tubelet_size = tubelet_size self.no_pluecker_rays = no_pluecker_rays self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, num_frames=all_frames, tubelet_size=tubelet_size, ) if not no_pluecker_rays: self.patch_embed_pluecker_rays = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=6, embed_dim=embed_dim, num_frames=all_frames, tubelet_size=tubelet_size, ) else: self.patch_embed_pluecker_rays = None self.register_buffer( "pos_embed", get_sinusoid_encoding_table(self.patch_embed.num_patches, embed_dim), persistent=False, ) self.pos_drop = nn.Dropout(p=drop_rate) decay = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] self.blocks = nn.ModuleList( [ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path_rate=decay[i], norm_layer=norm_layer, init_values=init_values, use_flash_attn=use_flash_attn, ) for i in range(depth) ] ) self.fc_norm = norm_layer(embed_dim) self.apply(self._init_weights) 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): nn.init.constant_(module.bias, 0) nn.init.constant_(module.weight, 1.0) def get_num_layers(self) -> int: return len(self.blocks) def vit_giant_patch14_224( img_size: int = 224, all_frames: int = 48, tubelet_size: int = 2, drop_path_rate: float = 0.0, use_flash_attn: bool = True, no_pluecker_rays: bool = False, ) -> VisionTransformer: """ViT-Giant/14, ~1B parameters. The VideoMAE v2 encoder D4RT is built on. Spelled with explicit parameters rather than `**kwargs`: densetrack's version filters kwargs against a set of twenty-four supported names and silently drops the rest, so a misspelled argument there configures nothing and says nothing. """ return VisionTransformer( img_size=img_size, patch_size=GIANT_PATCH_SIZE, embed_dim=GIANT_EMBED_DIM, depth=GIANT_DEPTH, num_heads=GIANT_NUM_HEADS, mlp_ratio=GIANT_MLP_RATIO, qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), all_frames=all_frames, tubelet_size=tubelet_size, drop_path_rate=drop_path_rate, use_flash_attn=use_flash_attn, no_pluecker_rays=no_pluecker_rays, )