File size: 8,827 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 | """Standalone UCPE model with stable geometry and optional extent conditioning."""
from __future__ import annotations
import json
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
import numpy as np
import torch
from torch import nn
from nets.ucpe_cd50_stable.decoder import D4RTDecoder, D4RTDecoderConfig
from nets.ucpe_cd50_stable.encoder import VideoMAEEncoder, VideoMAEEncoderConfig
from nets.ucpe_cd50_stable.transition import (
UCPETransitionConfig,
restore_ucpe_transition_for_evaluation,
set_ucpe_transition_scale,
)
@dataclass(frozen=True)
class WeightLoadReport:
loaded_tensors: int
initialized_parameters: tuple[str, ...]
checkpoint_step: int | None
def _read_weights(path: str | Path) -> Mapping[str, object]:
try:
from numpy._core import multiarray
except ImportError:
from numpy.core import multiarray
allowed = [multiarray._reconstruct, np.ndarray, np.dtype, type(np.dtype(np.uint32))]
with torch.serialization.safe_globals(allowed):
return torch.load(path, map_location="cpu", weights_only=True, mmap=True)
def _flatten_weights(payload: Mapping[str, object]) -> dict[str, torch.Tensor]:
modules = payload.get("modules")
if "format_version" in payload and isinstance(modules, Mapping):
sections = {
"" if name == "__root__" else str(name): state
for name, state in modules.items()
}
elif "d4rtencoder" in payload:
sections = {
target: payload[source]
for source, target in (
("d4rtencoder", "encoder"),
("d4rtdecoder", "decoder"),
)
if source in payload
}
else:
state = payload
for key in ("model", "state_dict", "module"):
if isinstance(payload.get(key), Mapping):
state = payload[key]
break
sections = {"": state}
flat = {}
for prefix, state in sections.items():
if not isinstance(state, Mapping):
raise TypeError(f"Invalid checkpoint module {prefix!r}")
for name, tensor in state.items():
if not isinstance(tensor, torch.Tensor):
continue
parts = str(name).split(".")
while len(parts) > 1 and parts[0] in ("module", "_fsdp_wrapped_module"):
parts.pop(0)
name = ".".join(parts)
name = f"{prefix}.{name}" if prefix else name
if name in flat:
raise ValueError(f"Duplicate checkpoint tensor {name}")
flat[name] = tensor
return flat
class UCPECD50StableModel(nn.Module):
def __init__(
self,
encoder: VideoMAEEncoder,
decoder: D4RTDecoder,
transition: UCPETransitionConfig | None = None,
) -> None:
super().__init__()
self.encoder = encoder
self.decoder = decoder
self.transition = transition
if transition is not None:
transition.validate()
else:
set_ucpe_transition_scale(self, 1.0)
@classmethod
def from_config(
cls,
config_path: str | Path | None = None,
*,
variant: str = "stable",
use_flash_attn: bool = True,
) -> UCPECD50StableModel:
files = {
"stable": "model_config.json",
"gate20m": "model_config_gate20m.json",
"cap20m": "model_config_cap20m.json",
"cap20m_aspect": "model_config_cap20m.json",
"cap20m_ucpe_bias": "model_config_cap20m_ucpe_bias.json",
"ft440k": "model_config_ft440k.json",
"ft440k_aspect": "model_config_ft440k.json",
"ft440k_ucpe_bias": "model_config_ft440k_ucpe_bias.json",
"scale4d_140k": "model_config_scale4d_140k.json",
}
if variant not in files:
raise ValueError(f"Unknown UCPE model variant {variant!r}")
path = (
Path(config_path)
if config_path
else Path(__file__).with_name(files[variant])
)
config = json.loads(path.read_text())
encoder_options = dict(config["encoder"])
encoder_options["use_flash_attn"] = use_flash_attn
encoder = VideoMAEEncoderConfig(**encoder_options).build()
decoder = D4RTDecoderConfig(**config["decoder"]).build(encoder.embed_dim)
transition = config.get("ucpe_transition")
return cls(
encoder,
decoder,
None if transition is None else UCPETransitionConfig(**transition),
)
def set_global_step(self, step: int) -> None:
scale = 1.0 if self.transition is None else self.transition.scale_at(step)
set_ucpe_transition_scale(self, scale)
def set_checkpoint_step(self, step: int) -> None:
if self.transition is None:
set_ucpe_transition_scale(self, 1.0)
else:
restore_ucpe_transition_for_evaluation(self, self.transition, step)
def load_pretrained_weights(self, path: str | Path) -> WeightLoadReport:
"""Load model tensors, leaving only the new extent projection initialized."""
payload = _read_weights(path)
state = _flatten_weights(payload)
target = self.state_dict()
missing = set(target) - set(state)
allowed = (
{"encoder.extent_scale_proj.weight"}
if self.encoder.extent_scale_proj is not None
else set()
)
unexpected = set(state) - set(target)
mismatched = [
name
for name in set(state) & set(target)
if state[name].shape != target[name].shape
]
if missing - allowed or unexpected or mismatched:
raise ValueError(
f"Checkpoint mismatch: missing={sorted(missing - allowed)[:5]}, "
f"unexpected={sorted(unexpected)[:5]}, shapes={mismatched[:5]}"
)
self.load_state_dict(state, strict=False)
saved = payload.get("run_config", payload)
if (
self.transition is not None
and isinstance(saved, Mapping)
and "ucpe_transition" in saved
):
transition = saved["ucpe_transition"]
self.transition = (
None if transition is None else UCPETransitionConfig(**transition)
)
step = payload.get("global_step")
if step is not None:
self.set_checkpoint_step(int(step))
return WeightLoadReport(
len(state), tuple(sorted(missing)), None if step is None else int(step)
)
def encode(
self,
video: torch.Tensor,
T_world_cam: torch.Tensor,
T_pix_cam: torch.Tensor,
*,
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:
raise ValueError("video must have shape (B, V, 3, T, H, W)")
if aspect_ratio is None:
focal_x = T_pix_cam[..., 0, 0].abs()
focal_y = T_pix_cam[..., 1, 1].abs()
aspect_ratio = (
(focal_y / focal_x.clamp_min(torch.finfo(focal_x.dtype).eps))
.median(dim=2)
.values.unsqueeze(-1)
)
return self.encoder(
video,
T_world_cam=T_world_cam,
T_pix_cam=T_pix_cam,
aspect_ratio=aspect_ratio,
camera_condition_mask=camera_condition_mask,
world_up=world_up,
world_up_valid=world_up_valid,
).flatten(1, 2)
def forward(
self,
video: torch.Tensor,
T_world_cam: torch.Tensor,
T_pix_cam: torch.Tensor,
uv: torch.Tensor,
t_src: torch.Tensor,
t_tgt: torch.Tensor,
image_patch: torch.Tensor,
v_src: torch.Tensor,
*,
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,
) -> tuple[torch.Tensor, ...]:
tokens = self.encode(
video,
T_world_cam,
T_pix_cam,
aspect_ratio=aspect_ratio,
camera_condition_mask=camera_condition_mask,
world_up=world_up,
world_up_valid=world_up_valid,
)
return self.decoder(
uv=uv,
t_src=t_src,
t_tgt=t_tgt,
image_patch=image_patch,
y=tokens,
num_views=video.shape[1],
v_src=v_src,
t_cam=t_tgt,
)
|