"""Load SCALE4D inference weights from a local export or Hugging Face.""" from __future__ import annotations import json from pathlib import Path from huggingface_hub import snapshot_download from safetensors.torch import load_file from evaluation.ucpe_checkpoint import ( CheckpointInfo, load_checkpoint, recorded_model_config, ) from nets.ucpe_cd50_stable.model import ( UCPECD50StableModel, _flatten_weights, _read_weights, ) HF_REPO_ID = "facebook/SCALE4D" HF_REVISION = "069f22ba021e3c23c7e4831ff4385927978eac63" CONFIG_PATH = Path(__file__).parent / "ucpe_cd50_stable/model_config_scale4d_140k.json" def _config(path: Path) -> dict: config = json.loads(path.read_text()) if config.get("format_version") != 1 or config.get("model_type") != "scale4d": raise ValueError("Expected a SCALE4D inference config, format version 1") if config["encoder"]["load_pretrained"]: raise ValueError( "SCALE4D inference requires every model weight in the checkpoint" ) return config def _check_recorded_config(recorded: dict, config: dict) -> None: encoder, decoder = recorded_model_config(recorded) encoder["checkpoint_path"] = "" expected_encoder = dict(config["encoder"]) expected_encoder["checkpoint_path"] = "" encoder.pop("use_flash_attn", None) expected_encoder.pop("use_flash_attn", None) if ( encoder != expected_encoder or decoder != config["decoder"] or recorded.get("ucpe_transition") != config.get("ucpe_transition") or recorded["trainer"].get("camera_condition_max_diameter_m") != config.get("camera_condition_max_diameter_m") ): raise ValueError( "The supplied config differs from the native checkpoint config" ) def load_model( checkpoint: str | Path = HF_REPO_ID, *, revision: str | None = None, config_path: str | Path | None = None, use_flash_attn: bool = True, ) -> tuple[UCPECD50StableModel, CheckpointInfo]: path = Path(checkpoint).expanduser() explicit_config = None if config_path is None else Path(config_path).expanduser() if not path.exists(): if ( path.suffix in (".pt", ".pth", ".safetensors") or path.is_absolute() or str(checkpoint).startswith((".", "~", "manifold://")) ): raise FileNotFoundError(path) path = Path( snapshot_download( repo_id=str(checkpoint), revision=revision or (HF_REVISION if str(checkpoint) == HF_REPO_ID else None), allow_patterns=["config.json", "model.safetensors"], ) ) if path.is_dir(): path = path / "model.safetensors" if path.suffix == ".safetensors": payload = {} state = load_file(str(path)) else: payload = _read_weights(path) if isinstance(payload.get("run_config"), dict): if explicit_config is not None: _check_recorded_config(payload["run_config"], _config(explicit_config)) del payload return load_checkpoint(path, use_flash_attn=use_flash_attn) if "format_version" in payload: raise ValueError( "Native WDM checkpoints must contain their recorded run_config" ) state = _flatten_weights(payload) sidecar = path.parent / "config.json" selected_config = explicit_config or (sidecar if sidecar.is_file() else CONFIG_PATH) config = _config(selected_config) model = UCPECD50StableModel.from_config( selected_config, use_flash_attn=use_flash_attn ) model.load_state_dict(state, strict=True) step = int(payload.get("global_step", config["checkpoint_step"])) model.set_checkpoint_step(step) model.eval() return model, CheckpointInfo( step=step, loaded_tensors=len(state), encoder={**config["encoder"], "use_flash_attn": use_flash_attn}, decoder=dict(config["decoder"]), camera_condition_max_diameter_m=config.get("camera_condition_max_diameter_m"), ucpe_transition=config.get("ucpe_transition"), )