Download examples/visualizer_code/source/nets/ucpe_cd50_stable/model.py from facebook/SCALE4D: direct link, hf CLI and curl.
- Browser
- Download file 8.83 kB
-
https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/nets/ucpe_cd50_stable/model.py
- Command line
-
hf download hf://facebook/SCALE4D/examples/visualizer_code/source/nets/ucpe_cd50_stable/model.py
-
curl -L -o model.py https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/nets/ucpe_cd50_stable/model.py
8.83 kB
| """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, | |
| ) | |
| 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) | |
| 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, | |
| ) | |