File size: 4,195 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 | """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"),
)
|