# (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary. """Multiview VideoMAE with UCPE and features from blocks 10, 20, 30, and 40.""" from __future__ import annotations import copy import logging from collections.abc import Sequence from dataclasses import dataclass from typing import Any, ClassVar, cast import torch import torch.nn as nn import torch.utils.checkpoint as cp from nets.ucpe_cd50.backbone import ( VisionTransformer, trunc_normal_, vit_giant_patch14_224, ) from nets.ucpe_cd50.ucpe import prepare_world_up from nets.ucpe_cd50.ucpe_transition import ( RelativeRayAttention, build_lat_up_encoding, build_relative_ray_transforms, ) logger: logging.Logger = logging.getLogger(__name__) DEFAULT_CHECKPOINT_PATH = "" TUBELET_SIZE = 2 NUM_FRAMES = 48 IMG_SIZE = 224 VIDEOMAE_FEATURE_LAYERS = (10, 20, 30, 40) DENSETRACK_CLASSIFIER_NUM_CLASSES = 710 DENSETRACK_ENCODER_SECTION = "d4rtencoder" ATTENTION_GLOBAL = "global" ATTENTION_ALTERNATING_FRAME_GLOBAL = "alternating_frame_global" ATTENTION_PATTERNS = (ATTENTION_GLOBAL, ATTENTION_ALTERNATING_FRAME_GLOBAL) CAMERA_ENCODING_PLUECKER = "pluecker" CAMERA_ENCODING_NONE = "none" CAMERA_ENCODING_UCPE_RELATIVE = "ucpe_relative" CAMERA_ENCODINGS = ( CAMERA_ENCODING_PLUECKER, CAMERA_ENCODING_NONE, CAMERA_ENCODING_UCPE_RELATIVE, ) def apply_densetrack_classifier_head_rng_compatibility( enabled: bool, *, embed_dim: int ) -> None: if not enabled: return compatibility_head = nn.Linear( embed_dim, DENSETRACK_CLASSIFIER_NUM_CLASSES, device="cpu" ) trunc_normal_(compatibility_head.weight, std=0.02) if compatibility_head.bias is not None: nn.init.constant_(compatibility_head.bias, 0) def _read_checkpoint(checkpoint_path: str) -> dict[str, object]: checkpoint = torch.load( checkpoint_path, map_location="cpu", weights_only=True ) if DENSETRACK_ENCODER_SECTION in checkpoint: return _strip_prefix(checkpoint[DENSETRACK_ENCODER_SECTION], "model.") for key in ("model", "module"): if key in checkpoint: return checkpoint[key] return checkpoint def _strip_prefix(state: dict[str, object], prefix: str) -> dict[str, object]: return { key[len(prefix) :]: value for (key, value) in state.items() if key.startswith(prefix) } def _drop_classifier_keys(checkpoint: dict[str, object]) -> list[str]: prefixes = ["head."] if any((k.startswith("fc_norm.") for k in checkpoint)): prefixes.append("norm.") dropped = [k for k in checkpoint if k.startswith(tuple(prefixes))] for key in dropped: del checkpoint[key] return dropped _EXPECTED_MISSING_PREFIXES: tuple[str, ...] = ("patch_embed_pluecker_rays.",) def load_encoder_weights( model: nn.Module, checkpoint_path: str, strict: bool = False, *, allow_missing: bool = False, ) -> nn.Module: checkpoint = _read_checkpoint(checkpoint_path) if any((k.startswith("encoder.") for k in checkpoint)): rewritten: dict[str, object] = {} for key, value in checkpoint.items(): if not key.startswith("encoder."): continue name = key[len("encoder.") :] if name.startswith("norm."): name = "fc_" + name rewritten[name] = value checkpoint = rewritten logger.info( "extracted %d encoder keys from a pretrain checkpoint", len(checkpoint), ) dropped = _drop_classifier_keys(checkpoint) if dropped: logger.info( "dropped %d classifier key(s); wdm's backbone has no head", len(dropped), ) (missing, unexpected) = model.load_state_dict(checkpoint, strict=strict) if len(missing) == len(model.state_dict()): raise RuntimeError( ( f"no encoder weights loaded from {checkpoint_path}: none of " f"the {len(checkpoint)} key(s) in it matched any of the " f"{len(model.state_dict())} the model expects. The first " f"few offered were {sorted(checkpoint)[:5]}, and the model " f"wants {sorted(model.state_dict())[:5]}. This is a layout " f"the loader does not recognize, not a partial load -- see " f"`_read_checkpoint` for the three it handles." ) ) unexplained = [ key for key in missing if not key.startswith(_EXPECTED_MISSING_PREFIXES) ] if unexplained and (not allow_missing): raise RuntimeError( ( f"{len(unexplained)} of {len(model.state_dict())} encoder " f"parameter(s) absent from {checkpoint_path}: " f"{sorted(unexplained)[:5]}. Those would keep their random " f"initialization while the config says `load_pretrained: " f"true`, and nothing downstream would say so. Pass " f"`allow_missing=True` if this checkpoint legitimately " f"predates them, or add them to " f"`_EXPECTED_MISSING_PREFIXES` if every pretrained " f"checkpoint is expected to lack them." ) ) if missing: logger.info( "%d encoder key(s) absent and trained from scratch: %s...", len(missing), sorted(missing)[:3], ) if unexpected: logger.warning("unexpected encoder keys: %s...", unexpected[:5]) return model def _gate_pluecker_ray_tokens( ray_tokens: torch.Tensor, pluecker_ray_mask: torch.Tensor | None ) -> torch.Tensor: if pluecker_ray_mask is None: return ray_tokens batch_size = ray_tokens.shape[0] if pluecker_ray_mask.shape != (batch_size,): raise ValueError( ( f"pluecker_ray_mask must have shape ({batch_size},), got " f"{tuple(pluecker_ray_mask.shape)}" ) ) scale = pluecker_ray_mask.to( device=ray_tokens.device, dtype=ray_tokens.dtype ) return ray_tokens * scale.reshape(batch_size, 1, 1) @dataclass class VideoMAEEncoderConfig: ucpe_transition_supported: ClassVar[bool] = True ucpe_tubelet_size: ClassVar[int] = TUBELET_SIZE ucpe_camera_frame_offsets: ClassVar[tuple[int, ...]] = tuple( range(TUBELET_SIZE) ) checkpoint_path: str = DEFAULT_CHECKPOINT_PATH load_pretrained: bool = True freeze_encoder: bool = True all_frames: int = NUM_FRAMES img_size: int = IMG_SIZE drop_path_rate: float = 0.0 camera_encoding: str = CAMERA_ENCODING_PLUECKER ucpe_attention_compression: int = 8 ucpe_attention_interval: int = 1 ucpe_absolute_lat_up: bool = False use_aspect_ratio_token: bool = False use_flash_attn: bool = True use_checkpoint: bool = False checkpoint_every: int = 1 attention_pattern: str = ATTENTION_GLOBAL mv_interleave: bool = False same_time_view_attention_interval: int = 2 mv_use_view_embed: bool = True max_view_num: int = 3 densetrack_classifier_head_rng_compat: bool = False def build(self) -> VideoMAEEncoder: if self.camera_encoding not in CAMERA_ENCODINGS: raise ValueError( ( f"unknown camera_encoding {self.camera_encoding!r}; " f"expected one of {CAMERA_ENCODINGS}" ) ) model = vit_giant_patch14_224( img_size=self.img_size, all_frames=self.all_frames, tubelet_size=TUBELET_SIZE, drop_path_rate=self.drop_path_rate, use_flash_attn=self.use_flash_attn, no_pluecker_rays=self.camera_encoding != CAMERA_ENCODING_PLUECKER, ) apply_densetrack_classifier_head_rng_compatibility( self.densetrack_classifier_head_rng_compat, embed_dim=model.embed_dim, ) if self.load_pretrained: load_encoder_weights(model, self.checkpoint_path) else: logger.info("skipping pretrained encoder weights (random init)") return VideoMAEEncoder( model, freeze_encoder=self.freeze_encoder, camera_encoding=self.camera_encoding, ucpe_attention_compression=self.ucpe_attention_compression, ucpe_attention_interval=self.ucpe_attention_interval, ucpe_absolute_lat_up=self.ucpe_absolute_lat_up, use_aspect_ratio_token=self.use_aspect_ratio_token, use_checkpoint=self.use_checkpoint, checkpoint_every=self.checkpoint_every, attention_pattern=self.attention_pattern, all_frames=self.all_frames, mv_interleave=self.mv_interleave, same_time_view_attention_interval=( self.same_time_view_attention_interval ), mv_use_view_embed=self.mv_use_view_embed, max_view_num=self.max_view_num, ) def _collect_multilayer_feature( features: list[torch.Tensor], block_number: int, tokens: torch.Tensor, aspect_tokens: torch.Tensor | None = None, ) -> None: if block_number not in VIDEOMAE_FEATURE_LAYERS: return if tokens.ndim == 5: tokens = tokens.flatten(2, 3) if aspect_tokens is not None: tokens = torch.cat((tokens, aspect_tokens), dim=-2) features.append(tokens) def _fuse_multilayer_features( model: nn.Module, features: Sequence[torch.Tensor], projection: nn.Linear ) -> torch.Tensor: if len(features) != len(VIDEOMAE_FEATURE_LAYERS): raise ValueError( "multilayer features require outputs from blocks 10/20/30/40" ) model_any: Any = model norm = ( model_any.fc_norm if model_any.fc_norm is not None else model_any.norm ) return projection( torch.cat([norm(feature) for feature in features], dim=-1) ) def _gate_ucpe_residual( residual: torch.Tensor, camera_condition_mask: torch.Tensor | None ) -> torch.Tensor: if camera_condition_mask is None: return residual batch_size = residual.shape[0] if camera_condition_mask.shape != (batch_size,): raise ValueError( ( f"camera_condition_mask must have shape {(batch_size,)}, " f"got {tuple(camera_condition_mask.shape)}" ) ) return residual * camera_condition_mask.to( device=residual.device, dtype=residual.dtype ).reshape(batch_size, 1, 1) class UCPEAttentionBranch(RelativeRayAttention): def __init__( self, source_block: nn.Module, *, compression: int, use_absolute_orientation: bool, ) -> None: source: Any = source_block dim = int(source.norm1.normalized_shape[0]) super().__init__( dim=dim, num_heads=int(source.attn.num_heads), compression=compression, use_absolute_orientation=use_absolute_orientation, ) self.norm = copy.deepcopy(source.norm1) self.drop_path = copy.deepcopy(source.drop_path) self.layer_scale = ( None if source.gamma_1 is None else nn.Parameter(source.gamma_1.detach().clone()) ) 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, camera_condition_mask: torch.Tensor | None = None, ) -> torch.Tensor: delta = super().forward( self.norm(tokens), ray_transforms, spatial_height=spatial_height, spatial_width=spatial_width, lat_up_encoding=lat_up_encoding, lat_up_valid=lat_up_valid, ) if self.layer_scale is not None: delta = self.layer_scale.to(dtype=delta.dtype) * delta delta = self.drop_path(delta) return _gate_ucpe_residual(delta, camera_condition_mask) def _run_block_with_ucpe( tokens: torch.Tensor, block: nn.Module, branch: UCPEAttentionBranch, ray_transforms: torch.Tensor, lat_up_encoding: torch.Tensor | None, spatial_height: int, spatial_width: int, camera_condition_mask: torch.Tensor | None, lat_up_valid: torch.Tensor | None, ) -> torch.Tensor: block_any: Any = block patch_token_count = ray_transforms.shape[1] ucpe_residual = branch( tokens[:, :patch_token_count], ray_transforms, spatial_height=spatial_height, spatial_width=spatial_width, lat_up_encoding=lat_up_encoding, lat_up_valid=lat_up_valid, camera_condition_mask=camera_condition_mask, ) if tokens.shape[1] > patch_token_count: ucpe_residual = torch.cat( (ucpe_residual, torch.zeros_like(tokens[:, patch_token_count:])), dim=1, ) attention_residual = block_any.attn(block_any.norm1(tokens)) if block_any.gamma_1 is None: tokens = ( tokens + block_any.drop_path(attention_residual) + ucpe_residual ) return tokens + block_any.drop_path( block_any.mlp(block_any.norm2(tokens)) ) tokens = ( tokens + block_any.drop_path(block_any.gamma_1 * attention_residual) + ucpe_residual ) return tokens + block_any.drop_path( block_any.gamma_2 * block_any.mlp(block_any.norm2(tokens)) ) class SameTimeViewAttentionBranch(nn.Module): def __init__(self, source_block: nn.Module) -> None: super().__init__() source: Any = source_block self.norm = copy.deepcopy(source.norm1) self.attn = copy.deepcopy(source.attn) self.drop_path = copy.deepcopy(source.drop_path) self.gate = nn.Parameter(torch.zeros_like(source.norm1.weight)) self.initialize_from_block(source_block) def initialize_from_block(self, source_block: nn.Module) -> None: source: Any = source_block self.norm.load_state_dict(source.norm1.state_dict(), strict=True) self.attn.load_state_dict(source.attn.state_dict(), strict=True) nn.init.zeros_(self.gate) def forward(self, tokens: torch.Tensor) -> torch.Tensor: delta = self.drop_path(self.attn(self.norm(tokens))) return self.gate.to(dtype=delta.dtype) * delta @dataclass(frozen=True) class _UCPEInputs: rays: torch.Tensor lat_up: torch.Tensor | None spatial_height: int spatial_width: int condition_mask: torch.Tensor | None lat_up_valid: torch.Tensor | None class VideoMAEEncoder(nn.Module): def __init__( self, model: VisionTransformer, freeze_encoder: bool = True, camera_encoding: str = CAMERA_ENCODING_PLUECKER, ucpe_attention_compression: int = 8, ucpe_attention_interval: int = 1, ucpe_absolute_lat_up: bool = False, use_aspect_ratio_token: bool = False, use_checkpoint: bool = False, checkpoint_every: int = 1, attention_pattern: str = ATTENTION_GLOBAL, all_frames: int = NUM_FRAMES, mv_interleave: bool = False, same_time_view_attention_interval: int = 2, mv_use_view_embed: bool = True, max_view_num: int = 3, ) -> None: super().__init__() if len(model.blocks) != VIDEOMAE_FEATURE_LAYERS[-1]: raise ValueError("multilayer features require 40-block VideoMAE") if attention_pattern not in ATTENTION_PATTERNS: raise ValueError( ( f"unknown attention_pattern {attention_pattern!r}; " f"expected one of {ATTENTION_PATTERNS}" ) ) if camera_encoding not in CAMERA_ENCODINGS: raise ValueError( ( f"unknown camera_encoding {camera_encoding!r}; " f"expected one of {CAMERA_ENCODINGS}" ) ) if camera_encoding == CAMERA_ENCODING_UCPE_RELATIVE: if attention_pattern != ATTENTION_GLOBAL: raise ValueError( ( "camera_encoding='ucpe_relative' requires " "attention_pattern='global'" ) ) elif ucpe_absolute_lat_up: raise ValueError( "ucpe_absolute_lat_up requires camera_encoding='ucpe_relative'" ) self.model = model self.num_frames = all_frames self.use_checkpoint = use_checkpoint self.checkpoint_every = checkpoint_every self.camera_encoding = camera_encoding self.no_pluecker_rays = camera_encoding != CAMERA_ENCODING_PLUECKER self.ucpe_absolute_lat_up = ucpe_absolute_lat_up self.attention_pattern = attention_pattern self.embed_dim = model.embed_dim self.num_patches = model.patch_embed.num_patches self.tubelet_size = model.patch_embed.tubelet_size self.patch_size = model.patch_embed.patch_size[0] self.use_aspect_ratio_token = use_aspect_ratio_token self.aspect_ratio_proj: nn.Module | None = None if use_aspect_ratio_token: embed_dim = self.embed_dim self.aspect_ratio_proj = nn.Sequential( nn.Linear(1, embed_dim), nn.GELU(), nn.Linear(embed_dim, embed_dim), ) self.mv_interleave = mv_interleave self.same_time_view_attention_interval = 0 self.mv_view_embed: nn.Parameter | None = None self.videomae_mv_view_branches: nn.ModuleList = nn.ModuleList() if mv_interleave: self._configure_multiview_interleave( interval=same_time_view_attention_interval, use_view_embed=mv_use_view_embed, max_view_num=max_view_num, ) self.ucpe_attention_interval = 0 self.ucpe_attention_branches: nn.ModuleList = nn.ModuleList() self.ucpe_cross_view_attention_branches: nn.ModuleList = nn.ModuleList() if camera_encoding == CAMERA_ENCODING_UCPE_RELATIVE: self._configure_ucpe_attention( interval=ucpe_attention_interval, compression=ucpe_attention_compression, ) if freeze_encoder: for parameter in self.model.parameters(): parameter.requires_grad = False self.model.eval() projection_width = self.embed_dim self.multilayer_projection = nn.Linear( len(VIDEOMAE_FEATURE_LAYERS) * projection_width, projection_width, bias=False, ) with torch.no_grad(): self.multilayer_projection.weight.zero_() identity = torch.eye( self.embed_dim, device=self.multilayer_projection.weight.device, dtype=self.multilayer_projection.weight.dtype, ) self.multilayer_projection.weight[:, -self.embed_dim :].copy_( identity ) def _configure_ucpe_attention( self, interval: int, compression: int ) -> None: if interval <= 0: raise ValueError( f"ucpe_attention_interval must be positive, got {interval}" ) depth = len(self.model.blocks) if depth % interval != 0: raise ValueError( ( f"block depth {depth} is not divisible by " f"ucpe_attention_interval={interval}" ) ) self.ucpe_attention_interval = interval self.ucpe_attention_branches = nn.ModuleList( ( UCPEAttentionBranch( self.model.blocks[index], compression=compression, use_absolute_orientation=self.ucpe_absolute_lat_up, ) for index in range(interval - 1, depth, interval) ) ) if self.mv_interleave: cross_interval = self.same_time_view_attention_interval self.ucpe_cross_view_attention_branches = nn.ModuleList( ( UCPEAttentionBranch( self.model.blocks[index], compression=compression, use_absolute_orientation=self.ucpe_absolute_lat_up, ) for index in range( cross_interval - 1, depth, cross_interval ) ) ) def _build_ucpe_geometry( self, T_world_cam: torch.Tensor, T_pix_cam: torch.Tensor, height: int, width: int, world_up: torch.Tensor | None, ) -> tuple[torch.Tensor, torch.Tensor | None]: if T_world_cam.ndim != 5 or T_world_cam.shape[-2:] != (4, 4): raise ValueError( ( f"expected T_world_cam (B, V, T, 4, 4), got " f"{tuple(T_world_cam.shape)}" ) ) if T_pix_cam.ndim != 5: raise ValueError( ( f"expected T_pix_cam (B, V, T, k, k), got " f"{tuple(T_pix_cam.shape)}" ) ) if T_pix_cam.shape[:3] != T_world_cam.shape[:3]: raise ValueError( ( f"T_world_cam and T_pix_cam must agree on (B, V, T); got " f"{tuple(T_world_cam.shape[:3])} and " f"{tuple(T_pix_cam.shape[:3])}" ) ) (batch, views) = T_world_cam.shape[:2] flat_world = T_world_cam.reshape(batch * views, *T_world_cam.shape[2:]) flat_pix = T_pix_cam.reshape(batch * views, *T_pix_cam.shape[2:]) geometry = { "image_height": height, "image_width": width, "patch_size": self.patch_size, "tubelet_size": self.tubelet_size, } rays = build_relative_ray_transforms(flat_world, flat_pix, **geometry) tokens = rays.shape[1] tokens_per_slot = height // self.patch_size * (width // self.patch_size) rays = rays.reshape( batch, views, tokens // tokens_per_slot, tokens_per_slot, self.tubelet_size, 4, 4, ) lat_up = None if self.ucpe_absolute_lat_up: assert world_up is not None lat_up = build_lat_up_encoding( flat_world, flat_pix, world_up=world_up.repeat_interleave(views, dim=0), **geometry, ).reshape( batch, views, tokens // tokens_per_slot, tokens_per_slot, self.tubelet_size, 3, ) return (rays, lat_up) def _project_aspect_tokens( self, aspect_ratio: torch.Tensor | None, batch: int, views: int, dtype: torch.dtype, device: torch.device, ) -> torch.Tensor | None: if self.aspect_ratio_proj is None: return None if aspect_ratio is None: raise ValueError( "aspect_ratio is required when use_aspect_ratio_token=True" ) aspect_ratio = aspect_ratio.to(device=device, dtype=dtype) if aspect_ratio.ndim == 2: aspect_ratio = aspect_ratio.unsqueeze(-1) if aspect_ratio.shape != (batch, views, 1): raise ValueError( ( f"expected aspect_ratio {(batch, views, 1)}, got " f"{tuple(aspect_ratio.shape)}" ) ) projected = self.aspect_ratio_proj( aspect_ratio.reshape(batch * views, 1) ) return projected.reshape(batch, views, 1, self.embed_dim) def _configure_multiview_interleave( self, interval: int, use_view_embed: bool, max_view_num: int ) -> None: if interval <= 0: raise ValueError( ( f"same_time_view_attention_interval must be positive, got " f"{interval}" ) ) if max_view_num <= 0: raise ValueError( f"max_view_num must be positive, got {max_view_num}" ) depth = len(self.model.blocks) if depth % interval != 0: raise ValueError( ( f"block depth {depth} is not divisible by " f"same_time_view_attention_interval={interval}" ) ) self.same_time_view_attention_interval = interval self.videomae_mv_view_branches = nn.ModuleList( ( SameTimeViewAttentionBranch(self.model.blocks[index]) for index in range(interval - 1, depth, interval) ) ) if use_view_embed: self.mv_view_embed = nn.Parameter( torch.zeros(max_view_num, self.embed_dim) ) def _embed( self, video: torch.Tensor, pluecker_rays: torch.Tensor | None, pluecker_ray_mask: torch.Tensor | None, ) -> torch.Tensor: batch_size = video.size(0) x = self.model.patch_embed(video) ray_embed = self.model.patch_embed_pluecker_rays if ( not self.no_pluecker_rays and pluecker_rays is not None and (ray_embed is not None) ): ray_tokens = ray_embed(pluecker_rays) x = x + _gate_pluecker_ray_tokens(ray_tokens, pluecker_ray_mask) if self.model.pos_embed is not None: positions = self.model.pos_embed[:, : x.shape[1]] x = ( x + positions.expand(batch_size, -1, -1) .type_as(x) .to(x.device) .detach() ) return self.model.pos_drop(x) def _run_block(self, block_index: int, x: torch.Tensor) -> torch.Tensor: block = cast(nn.Module, self.model.blocks[block_index]) if ( self.use_checkpoint and self.training and (self.checkpoint_every > 0) and (block_index % self.checkpoint_every == 0) ): return cp.checkpoint(block, x, use_reentrant=False) return block(x) def get_encoder_tokens( self, video: torch.Tensor, pluecker_rays: torch.Tensor | None = None, pluecker_ray_mask: torch.Tensor | None = None, ) -> torch.Tensor: x = self._embed(video, pluecker_rays, pluecker_ray_mask) (_, _, frames, height, width) = video.shape (patch_height, patch_width) = self.model.patch_embed.patch_size temporal_tokens = frames // self.model.patch_embed.tubelet_size spatial_tokens = height // patch_height * (width // patch_width) expected = temporal_tokens * spatial_tokens if x.shape[1] != expected: raise ValueError( ( f"expected {expected} tokens from {temporal_tokens} " f"temporal bins x {spatial_tokens} spatial tokens, got " f"{x.shape[1]}" ) ) intermediate_features: list[torch.Tensor] = [] frame_local = ( self.attention_pattern == ATTENTION_ALTERNATING_FRAME_GLOBAL ) for index in range(len(self.model.blocks)): if frame_local and index % 2 == 0: x = self._run_frame_local( index, x, temporal_tokens, spatial_tokens ) else: x = self._run_block(index, x) _collect_multilayer_feature(intermediate_features, index + 1, x) return _fuse_multilayer_features( self.model, intermediate_features, self.multilayer_projection ) def _run_frame_local( self, block_index: int, x: torch.Tensor, temporal_tokens: int, spatial_tokens: int, ) -> torch.Tensor: (batch_size, tokens, channels) = x.shape if tokens != temporal_tokens * spatial_tokens: raise ValueError( ( f"frame-local attention expected " f"{temporal_tokens * spatial_tokens} tokens, got {tokens}" ) ) folded = x.reshape( batch_size * temporal_tokens, spatial_tokens, channels ) folded = self._run_block(block_index, folded) return folded.reshape(batch_size, tokens, channels) def _run_frame_local_multiview_block( self, block_index: int, x: torch.Tensor ) -> torch.Tensor: (b, v, t, p, c) = x.shape folded = self._run_block(block_index, x.reshape(b * v * t, p, c)) return folded.reshape(b, v, t, p, c) def _run_global_per_view_block( self, block_index: int, x: torch.Tensor, aspect_tokens: torch.Tensor | None, ucpe: _UCPEInputs | None, ) -> tuple[torch.Tensor, torch.Tensor | None]: (b, v, t, p, c) = x.shape folded = x.reshape(b * v, t * p, c) if aspect_tokens is not None: folded = torch.cat( (folded, aspect_tokens.reshape(b * v, 1, c)), dim=1 ) use_ucpe = ( ucpe is not None and self.ucpe_attention_interval > 0 and ((block_index + 1) % self.ucpe_attention_interval == 0) ) if use_ucpe: assert ucpe is not None branch_index = (block_index + 1) // self.ucpe_attention_interval - 1 branch = cast( UCPEAttentionBranch, self.ucpe_attention_branches[branch_index] ) rays = ucpe.rays.reshape(b * v, t * p, self.tubelet_size, 4, 4) lat_up = ( None if ucpe.lat_up is None else ucpe.lat_up.reshape(b * v, t * p, self.tubelet_size, 3) ) mask = ( None if ucpe.condition_mask is None else ucpe.condition_mask.repeat_interleave(v) ) lat_up_valid = ( None if ucpe.lat_up_valid is None else ucpe.lat_up_valid.repeat_interleave(v) ) def run(tokens: torch.Tensor) -> torch.Tensor: return _run_block_with_ucpe( tokens, self.model.blocks[block_index], branch, rays, lat_up, ucpe.spatial_height, ucpe.spatial_width, mask, lat_up_valid, ) if self._recompute(block_index): folded = cp.checkpoint(run, folded, use_reentrant=False) else: folded = run(folded) else: folded = self._run_block(block_index, folded) if aspect_tokens is None: return (folded.reshape(b, v, t, p, c), None) return ( folded[:, :-1].reshape(b, v, t, p, c), folded[:, -1:].reshape(b, v, 1, c), ) def _recompute(self, index: int) -> bool: return ( self.use_checkpoint and self.training and (self.checkpoint_every > 0) and (index % self.checkpoint_every == 0) ) def _run_same_time_view_branch( self, branch_index: int, x: torch.Tensor, ucpe: _UCPEInputs | None ) -> torch.Tensor: (b, v, t, p, c) = x.shape packed = x.permute(0, 2, 1, 3, 4).reshape(b * t, v * p, c) branch = self.videomae_mv_view_branches[branch_index] if self._recompute(branch_index): delta = cp.checkpoint(branch, packed, use_reentrant=False) else: delta = branch(packed) if ( ucpe is not None and len(self.ucpe_cross_view_attention_branches) > 0 ): ucpe_branch = cast( UCPEAttentionBranch, self.ucpe_cross_view_attention_branches[branch_index], ) rays = ucpe.rays.permute(0, 2, 1, 3, 4, 5, 6).reshape( b * t, v * p, self.tubelet_size, 4, 4 ) lat_up = ( None if ucpe.lat_up is None else ucpe.lat_up.permute(0, 2, 1, 3, 4, 5).reshape( b * t, v * p, self.tubelet_size, 3 ) ) mask = ( None if ucpe.condition_mask is None else ucpe.condition_mask.repeat_interleave(t) ) lat_up_valid = ( None if ucpe.lat_up_valid is None else ucpe.lat_up_valid.repeat_interleave(t) ) def run_ucpe(tokens: torch.Tensor) -> torch.Tensor: return ucpe_branch( tokens, rays, spatial_height=ucpe.spatial_height, spatial_width=ucpe.spatial_width, lat_up_encoding=lat_up, lat_up_valid=lat_up_valid, camera_condition_mask=mask, ) if self._recompute(branch_index): delta = delta + cp.checkpoint( run_ucpe, packed, use_reentrant=False ) else: delta = delta + run_ucpe(packed) delta = delta.reshape(b, t, v, p, c).permute(0, 2, 1, 3, 4) return x + delta def get_multiview_encoder_tokens( self, video: torch.Tensor, pluecker_rays: torch.Tensor | None = None, pluecker_ray_mask: torch.Tensor | None = None, T_world_cam: torch.Tensor | None = None, T_pix_cam: torch.Tensor | None = None, aspect_ratio: torch.Tensor | None = None, camera_condition_mask: torch.Tensor | None = None, world_up: torch.Tensor | None = None, world_up_valid: torch.Tensor | None = None, ) -> torch.Tensor: if not self.mv_interleave: raise ValueError("mv_interleave is not enabled on this encoder") if video.ndim != 6: raise ValueError( f"expected (B, V, C, T, H, W), got shape {tuple(video.shape)}" ) (batch_size, num_views, _, _, height, width) = video.shape view_embed = self.mv_view_embed if view_embed is not None and num_views > view_embed.shape[0]: raise ValueError( ( f"num_views={num_views} exceeds " f"max_view_num={view_embed.shape[0]}" ) ) per_view = [ self._embed( video[:, view_index], None if pluecker_rays is None else pluecker_rays[:, view_index], pluecker_ray_mask, ) for view_index in range(num_views) ] x = torch.stack(per_view, dim=1) (_, _, tokens, channels) = x.shape patches_wide = width // self.patch_size patches_high = height // self.patch_size tokens_per_slot = patches_high * patches_wide if tokens % tokens_per_slot != 0: raise ValueError( ( f"token count {tokens} is not divisible by " f"{tokens_per_slot} tokens per temporal slot" ) ) temporal_slots = tokens // tokens_per_slot x = x.reshape( batch_size, num_views, temporal_slots, tokens_per_slot, channels ) aspect_tokens = self._project_aspect_tokens( aspect_ratio, batch_size, num_views, x.dtype, x.device ) if view_embed is not None: slots = view_embed[:num_views].to(device=x.device, dtype=x.dtype) x = x + slots.reshape(1, num_views, 1, 1, channels) if aspect_tokens is not None: aspect_tokens = aspect_tokens + slots.reshape( 1, num_views, 1, channels ) ucpe = None if self.camera_encoding == CAMERA_ENCODING_UCPE_RELATIVE: if T_world_cam is None or T_pix_cam is None: raise ValueError( ( "camera_encoding='ucpe_relative' requires " "T_world_cam and T_pix_cam" ) ) lat_up_valid = None if self.ucpe_absolute_lat_up: (world_up, lat_up_valid) = prepare_world_up( world_up, world_up_valid, batch_size=batch_size, device=video.device, ) (rays, lat_up) = self._build_ucpe_geometry( T_world_cam, T_pix_cam, height, width, world_up ) ucpe = _UCPEInputs( rays=rays, lat_up=lat_up, spatial_height=patches_high, spatial_width=patches_wide, condition_mask=camera_condition_mask, lat_up_valid=lat_up_valid, ) intermediate_features: list[torch.Tensor] = [] frame_local = ( self.attention_pattern == ATTENTION_ALTERNATING_FRAME_GLOBAL ) interval = self.same_time_view_attention_interval for block_index in range(len(self.model.blocks)): if frame_local and block_index % 2 == 0: x = self._run_frame_local_multiview_block(block_index, x) else: (x, aspect_tokens) = self._run_global_per_view_block( block_index, x, aspect_tokens, ucpe ) if (block_index + 1) % interval == 0: x = self._run_same_time_view_branch( block_index // interval, x, ucpe ) _collect_multilayer_feature( intermediate_features, block_index + 1, x, aspect_tokens ) x = _fuse_multilayer_features( self.model, intermediate_features, self.multilayer_projection ) return x def forward( self, video: torch.Tensor, pluecker_rays: torch.Tensor | None = None, pluecker_ray_mask: torch.Tensor | None = None, T_world_cam: torch.Tensor | None = None, T_pix_cam: torch.Tensor | None = None, aspect_ratio: torch.Tensor | None = None, camera_condition_mask: torch.Tensor | None = None, world_up: torch.Tensor | None = None, world_up_valid: torch.Tensor | None = None, ) -> torch.Tensor: if video.ndim == 6: return self.get_multiview_encoder_tokens( video, pluecker_rays, pluecker_ray_mask, T_world_cam, T_pix_cam, aspect_ratio, camera_condition_mask, world_up, world_up_valid, ) if self.mv_interleave: tokens = self.get_multiview_encoder_tokens( video.unsqueeze(1), None if pluecker_rays is None else pluecker_rays.unsqueeze(1), pluecker_ray_mask, None if T_world_cam is None else T_world_cam.unsqueeze(1), None if T_pix_cam is None else T_pix_cam.unsqueeze(1), None if aspect_ratio is None else aspect_ratio.unsqueeze(1), camera_condition_mask, world_up, world_up_valid, ) return tokens.squeeze(1) if self.camera_encoding == CAMERA_ENCODING_UCPE_RELATIVE: raise ValueError( ( "camera_encoding='ucpe_relative' requires " "mv_interleave=True; the UCPE branches are built alongside " "the interleaved blocks" ) ) return self.get_encoder_tokens(video, pluecker_rays, pluecker_ray_mask) @staticmethod def get_normalization() -> tuple[tuple[float, float, float], ...]: return ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))