Download examples/visualizer_code/source/nets/ucpe_cd50_stable/encoder.py from facebook/SCALE4D: direct link, hf CLI and curl.
- Browser
- Download file 50.5 kB
-
https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/nets/ucpe_cd50_stable/encoder.py
- Command line
-
hf download hf://facebook/SCALE4D/examples/visualizer_code/source/nets/ucpe_cd50_stable/encoder.py
-
curl -L -o encoder.py https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/nets/ucpe_cd50_stable/encoder.py
50.5 kB
# (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
"""UCPE with validated, locally centered cameras and optional metric extent conditioning."""
from __future__ import annotations
import copy
import logging
import math
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any, ClassVar, cast
import torch
import torch.utils.checkpoint as cp
from torch import nn
from nets.ucpe_cd50.encoder import load_encoder_weights
from nets.ucpe_cd50_stable.backbone import (
VisionTransformer,
trunc_normal_,
vit_giant_patch14_224,
)
from nets.ucpe_cd50_stable.geometry import (
camera_diameter,
center_camera_translations,
center_world_to_ray_transforms,
sanitize_camera_inputs,
)
from nets.ucpe_cd50_stable.ucpe import prepare_world_up
from nets.ucpe_cd50_stable.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,
)
EXTENT_SCALE_INJECTIONS = ("aspect", "ucpe_bias")
def _validate_extent_policy(
diameter: float | None,
scale_token: bool,
aspect_token: bool,
gate: float | None = None,
injection: str = "aspect",
) -> None:
if injection not in EXTENT_SCALE_INJECTIONS:
raise ValueError(f"unknown extent scale injection {injection!r}")
if injection == "ucpe_bias" and not scale_token:
raise ValueError("UCPE scale bias requires the extent scale projection")
for name, value in (
("max_camera_diameter_m", diameter),
("camera_condition_max_diameter_m", gate),
):
if value is not None and (not math.isfinite(value) or value <= 0):
raise ValueError(f"{name} must be positive and finite")
if scale_token and (diameter is None or not aspect_token):
raise ValueError(
"extent scale token requires a diameter cap and an aspect token"
)
def apply_densetrack_classifier_head_rng_compatibility(
enabled: bool, *, embed_dim: int
) -> None:
"""Advance CPU RNG as DenseTrack's discarded VideoMAE classifier head did."""
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 _gate_pluecker_ray_tokens(
ray_tokens: torch.Tensor, pluecker_ray_mask: torch.Tensor | None
) -> torch.Tensor:
"""Zero the ray contribution for masked samples.
The mask multiplies the *embedded tokens*, not the input rays, so a masked sample gets
exactly the image-only embedding rather than the embedding of a zero ray map -- which
would differ by the convolution's bias.
"""
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 {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:
"""`type: "videomae_transition_ucpe_v00.VideoMAEEncoderConfig"` in `encoders_v02`.
Resolution is scoped to the family package of the field's declared type, so a config
reaching this class did so through `mv_trainer_v03`. Which encoder *member* a recipe
names is config; which *interface* it gets is code.
"""
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
max_camera_diameter_m: float | None = None
camera_condition_max_diameter_m: float | None = None
use_extent_scale_token: bool = False
selective_ucpe_rows: bool = False
densetrack_classifier_head_rng_compat: bool = False
extent_scale_injection: str = "aspect"
def build(self) -> VideoMAEEncoder:
_validate_extent_policy(
self.max_camera_diameter_m,
self.use_extent_scale_token,
self.use_aspect_ratio_token,
self.camera_condition_max_diameter_m,
self.extent_scale_injection,
)
if self.camera_condition_max_diameter_m is not None and (
not math.isfinite(self.camera_condition_max_diameter_m)
or self.camera_condition_max_diameter_m <= 0
):
raise ValueError("camera condition diameter must be positive and finite")
if self.camera_encoding not in CAMERA_ENCODINGS:
raise ValueError(
f"unknown camera_encoding {self.camera_encoding!r}; 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,
max_camera_diameter_m=self.max_camera_diameter_m,
camera_condition_max_diameter_m=self.camera_condition_max_diameter_m,
use_extent_scale_token=self.use_extent_scale_token,
extent_scale_injection=self.extent_scale_injection,
selective_ucpe_rows=self.selective_ucpe_rows,
)
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:
"""Drop a sample's camera conditioning without dropping the sample.
Mirrors `_gate_pluecker_ray_tokens`: the RGB path keeps its full gradient, so a masked
sample still trains everything except the camera residual. That is what lets one
checkpoint serve both camera-on and camera-off evaluation.
"""
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,)}, 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):
"""A UCPE residual running in parallel with one pretrained attention layer.
Cloned from the block it accompanies -- its own `norm1`, `drop_path` and `gamma_1` --
so it is a complete pre-norm residual block rather than a bare attention op, and its
parameters are independent of the RGB path it runs beside. `out_proj` stays zero, which
is inherited from `RelativeRayAttention` and is the only zero-init here.
"""
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,
active_rows: torch.Tensor | None = None,
scale_bias: torch.Tensor | None = None,
) -> torch.Tensor:
if scale_bias is not None and scale_bias.shape != (
tokens.shape[0],
tokens.shape[-1],
):
raise ValueError("scale bias must have shape (B, C)")
if self.training and getattr(self.drop_path, "drop_prob", 0.0) > 0:
active_rows = None
if active_rows is not None:
if active_rows.numel() == 0:
zero = tokens.new_zeros(())
for parameter in self.parameters():
if parameter.requires_grad:
zero = zero + parameter.reshape(-1)[0] * 0
if scale_bias is not None:
zero = zero + scale_bias.sum() * 0
return tokens * 0 + zero.to(tokens.dtype)
delta = self._residual(
tokens.index_select(0, active_rows),
ray_transforms.index_select(0, active_rows),
spatial_height,
spatial_width,
None
if lat_up_encoding is None
else lat_up_encoding.index_select(0, active_rows),
None
if lat_up_valid is None
else lat_up_valid.index_select(0, active_rows),
None if scale_bias is None else scale_bias.index_select(0, active_rows),
)
return torch.zeros_like(tokens).index_copy(0, active_rows, delta)
return _gate_ucpe_residual(
self._residual(
tokens,
ray_transforms,
spatial_height,
spatial_width,
lat_up_encoding,
lat_up_valid,
scale_bias,
),
camera_condition_mask,
)
def _residual(
self,
tokens: torch.Tensor,
ray_transforms: torch.Tensor,
spatial_height: int,
spatial_width: int,
lat_up_encoding: torch.Tensor | None,
lat_up_valid: torch.Tensor | None,
scale_bias: torch.Tensor | None = None,
) -> torch.Tensor:
normalized = self.norm(tokens)
if scale_bias is not None:
with torch.autocast(tokens.device.type, enabled=False):
normalized = normalized.float() + scale_bias.float()[:, None, :]
delta = super().forward(
normalized,
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 delta
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,
active_rows: torch.Tensor | None,
scale_bias: torch.Tensor | None = None,
) -> torch.Tensor:
"""One VideoMAE block with the UCPE residual added *in parallel* with its attention.
The block's forward is re-implemented rather than called, because the UCPE delta has to
join the residual stream alongside the attention output and before the MLP -- a wrapper
around `block(...)` could only add it afterwards, which is a different architecture.
Tokens past `ray_transforms`'s length are extras with no pixel location -- today only the
aspect-ratio token. They get a zero UCPE residual rather than being dropped, so the
block still sees them in attention.
"""
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,
active_rows=active_rows,
scale_bias=scale_bias,
)
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):
"""Cross-view attention at one timestep, as a gated residual on the per-view stream.
Cloned from the block it sits after, so it starts as a second copy of attention that
block already learned -- a better starting point than random, and the reason the clone
is a `deepcopy` rather than a fresh module.
**The gate starts at zero**, so at initialization the branch contributes exactly
nothing and the encoder computes what the single-view encoder computes. That is what
makes this warm-startable from a single-view checkpoint: the multi-view model begins
as the model it was initialized from, and learns to use the views rather than having
to first recover from randomly scrambled ones. Same reasoning as the fusion neck's
`residual_scale_init`.
"""
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:
"""Everything the UCPE branches need, bundled so it threads as one argument.
Internal to this module: a dataclass rather than five parallel parameters because they
are always passed together and are meaningless apart.
"""
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
per_view_rows: torch.Tensor | None
cross_view_rows: torch.Tensor | None
scale_bias: torch.Tensor | None = None
class VideoMAEEncoder(nn.Module):
"""VideoMAE tokens for a decoder to cross-attend to.
`forward(video, pluecker_rays, pluecker_ray_mask)` returns `(B, L, C)`, or `(B, V, L, C)`
when `mv_interleave` is on and the video arrives with a view axis.
"""
requires_fp32_camera_inputs = True
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,
max_camera_diameter_m: float | None = None,
camera_condition_max_diameter_m: float | None = None,
use_extent_scale_token: bool = False,
selective_ucpe_rows: bool = False,
extent_scale_injection: str = "aspect",
) -> None:
super().__init__()
_validate_extent_policy(
max_camera_diameter_m,
use_extent_scale_token,
use_aspect_ratio_token,
camera_condition_max_diameter_m,
extent_scale_injection,
)
if (
extent_scale_injection == "ucpe_bias"
and camera_encoding != CAMERA_ENCODING_UCPE_RELATIVE
):
raise ValueError("UCPE scale bias requires relative UCPE camera encoding")
self.max_camera_diameter_m = max_camera_diameter_m
self.camera_condition_max_diameter_m = camera_condition_max_diameter_m
self.freeze_encoder = freeze_encoder
self.selective_ucpe_rows = selective_ucpe_rows
self.extent_scale_injection = extent_scale_injection
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}; expected one of {ATTENTION_PATTERNS}"
)
if camera_encoding not in CAMERA_ENCODINGS:
raise ValueError(
f"unknown camera_encoding {camera_encoding!r}; 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.extent_scale_proj: nn.Linear | None = None
if use_extent_scale_token:
self.extent_scale_proj = nn.Linear(1, self.embed_dim, bias=False)
nn.init.zeros_(self.extent_scale_proj.weight)
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 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 train(self, mode: bool = True) -> VideoMAEEncoder:
super().train(mode)
if self.freeze_encoder:
self.model.eval()
return self
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]:
"""Build per-view geometry with one camera-frame axis inside each tubelet."""
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 {tuple(T_world_cam.shape)}"
)
if T_pix_cam.ndim != 5:
raise ValueError(
f"expected T_pix_cam (B, V, T, k, k), got {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 {tuple(T_world_cam.shape[:3])} and {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 {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 {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 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:
"""Patch-embed RGB and rays, add positions."""
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 = cast(torch.Tensor, 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:
"""Single-view tokens."""
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} temporal bins x {spatial_tokens} spatial tokens, got {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:
"""Run one block with attention confined within each temporal tubelet.
Folding the temporal axis into the batch is what restricts attention: the block is
unchanged and keeps its pretrained weights, only the grouping of tokens it sees
differs.
"""
(batch_size, tokens, channels) = x.shape
if tokens != temporal_tokens * spatial_tokens:
raise ValueError(
f"frame-local attention expected {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:
"""One block, attention confined to one view's one frame."""
(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]:
"""One block, attention over a whole view's clip but never across views.
The aspect token rides along here and only here: it participates in per-view global
attention, and is carried untouched through frame-local and cross-view attention,
which are both organised by a spatial grid it has no place in.
"""
(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)
rays = center_world_to_ray_transforms(rays)
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,
ucpe.per_view_rows,
None
if ucpe.scale_bias is None
else ucpe.scale_bias.repeat_interleave(v, dim=0),
)
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:
"""Add the gated cross-view delta for one timestep's tokens.
Views are packed into the token axis so one attention call sees every view at that
timestep. The result is *added*, not substituted -- the per-view stream survives,
which is what lets the gate start closed.
Under UCPE a second delta from `ucpe_cross_view_attention_branches` is summed into
the same residual, so the cross-view step is camera-conditioned too.
"""
(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
)
rays = center_world_to_ray_transforms(rays)
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,
active_rows=ucpe.cross_view_rows,
scale_bias=None
if ucpe.scale_bias is None
else ucpe.scale_bias.repeat_interleave(t, dim=0),
)
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:
"""Interleaved multi-view tokens, cross-view attention at full depth.
Every block runs per-view, exactly as it would single-view; a gated cross-view
branch is added after every `same_time_view_attention_interval` blocks. Unlike
`encoders_v00/videomae_v00`, no block is replaced and no prefix of the network is
excluded, so views can inform each other from the first block rather than only the
last few. Under `camera_encoding='ucpe_relative'` both the per-view and the
cross-view step additionally see relative camera pose.
"""
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 max_view_num={view_embed.shape[0]}"
)
log_scale = None
if self.camera_encoding == CAMERA_ENCODING_UCPE_RELATIVE:
if T_world_cam is None or T_pix_cam is None:
raise ValueError("UCPE requires camera poses and intrinsics")
(T_world_cam, T_pix_cam, aspect_ratio) = sanitize_camera_inputs(
T_world_cam, T_pix_cam, aspect_ratio, camera_condition_mask
)
T_world_cam = center_camera_translations(T_world_cam)
if self.camera_condition_max_diameter_m is not None:
diameter = camera_diameter(T_world_cam)
keep = torch.isfinite(diameter) & (
diameter <= self.camera_condition_max_diameter_m
)
camera_condition_mask = (
keep
if camera_condition_mask is None
else camera_condition_mask & keep
)
(T_world_cam, T_pix_cam, aspect_ratio) = sanitize_camera_inputs(
T_world_cam, T_pix_cam, aspect_ratio, camera_condition_mask
)
if self.max_camera_diameter_m is not None:
diameter = camera_diameter(T_world_cam)
if not bool(torch.isfinite(diameter).all()):
raise ValueError("camera diameter must be finite")
scale = (diameter / self.max_camera_diameter_m).clamp_min(1)
T_world_cam = T_world_cam.clone()
T_world_cam[..., :3, 3] /= scale[:, None, None, None]
log_scale = scale.log()
if camera_condition_mask is not None:
log_scale = log_scale * camera_condition_mask.to(log_scale)
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 {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
)
scale_bias = None
if self.extent_scale_proj is not None:
assert log_scale is not None and aspect_tokens is not None
with torch.autocast(x.device.type, enabled=False):
scale_embedding = torch.nn.functional.linear(
log_scale[:, None].float(), self.extent_scale_proj.weight.float()
)
if self.extent_scale_injection == "aspect":
aspect_tokens = aspect_tokens + scale_embedding[:, None, None].to(
x.dtype
)
else:
scale_bias = scale_embedding
aspect_tokens = aspect_tokens + scale_embedding.sum().to(x.dtype) * 0
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 and (
self.training
or camera_condition_mask is None
or bool(camera_condition_mask.any())
):
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
)
per_view_rows = cross_view_rows = None
if self.selective_ucpe_rows and camera_condition_mask is not None:
active = camera_condition_mask.nonzero(as_tuple=True)[0]
if active.numel() < batch_size:
per_view_rows = (
active[:, None] * num_views
+ torch.arange(num_views, device=active.device)
).flatten()
cross_view_rows = (
active[:, None] * temporal_slots
+ torch.arange(temporal_slots, device=active.device)
).flatten()
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,
per_view_rows=per_view_rows,
cross_view_rows=cross_view_rows,
scale_bias=scale_bias,
)
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], ...]:
"""ImageNet statistics, which is what the pretrained backbone expects.
Worth keeping reachable: a port that fed the encoder unnormalized images and still
matched a synthetic-input harness at 1e-6 is the cautionary tale behind the
equivalence gates' "real batches only" rule.
"""
return ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
# (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
"""UCPE with validated, locally centered cameras and optional metric extent conditioning."""
from __future__ import annotations
import copy
import logging
import math
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any, ClassVar, cast
import torch
import torch.utils.checkpoint as cp
from torch import nn
from nets.ucpe_cd50.encoder import load_encoder_weights
from nets.ucpe_cd50_stable.backbone import (
VisionTransformer,
trunc_normal_,
vit_giant_patch14_224,
)
from nets.ucpe_cd50_stable.geometry import (
camera_diameter,
center_camera_translations,
center_world_to_ray_transforms,
sanitize_camera_inputs,
)
from nets.ucpe_cd50_stable.ucpe import prepare_world_up
from nets.ucpe_cd50_stable.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,
)
EXTENT_SCALE_INJECTIONS = ("aspect", "ucpe_bias")
def _validate_extent_policy(
diameter: float | None,
scale_token: bool,
aspect_token: bool,
gate: float | None = None,
injection: str = "aspect",
) -> None:
if injection not in EXTENT_SCALE_INJECTIONS:
raise ValueError(f"unknown extent scale injection {injection!r}")
if injection == "ucpe_bias" and not scale_token:
raise ValueError("UCPE scale bias requires the extent scale projection")
for name, value in (
("max_camera_diameter_m", diameter),
("camera_condition_max_diameter_m", gate),
):
if value is not None and (not math.isfinite(value) or value <= 0):
raise ValueError(f"{name} must be positive and finite")
if scale_token and (diameter is None or not aspect_token):
raise ValueError(
"extent scale token requires a diameter cap and an aspect token"
)
def apply_densetrack_classifier_head_rng_compatibility(
enabled: bool, *, embed_dim: int
) -> None:
"""Advance CPU RNG as DenseTrack's discarded VideoMAE classifier head did."""
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 _gate_pluecker_ray_tokens(
ray_tokens: torch.Tensor, pluecker_ray_mask: torch.Tensor | None
) -> torch.Tensor:
"""Zero the ray contribution for masked samples.