File size: 40,769 Bytes
9c890d3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 | # (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))
|