Download examples/visualizer_code/source/d4rt_scripts/export_scale4d_teacher.py from facebook/SCALE4D: direct link, hf CLI and curl.
- Browser
- Download file 4.65 kB
-
https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/d4rt_scripts/export_scale4d_teacher.py
- Command line
-
hf download hf://facebook/SCALE4D/examples/visualizer_code/source/d4rt_scripts/export_scale4d_teacher.py
-
curl -L -o export_scale4d_teacher.py https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/d4rt_scripts/export_scale4d_teacher.py
4.65 kB
| """Export the saved EMA teacher from a native SCALE4D distillation checkpoint.""" | |
| from __future__ import annotations | |
| import argparse | |
| import copy | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import torch | |
| from safetensors.torch import save_file | |
| from evaluation.ucpe_checkpoint import recorded_model_config | |
| from evaluation.ucpe_inputs import sha256_file | |
| from nets.ucpe_cd50_stable.model import _flatten_weights, _read_weights | |
| def state_digest(state: dict) -> str: | |
| digest = hashlib.sha256() | |
| for name, tensor in sorted(state.items()): | |
| tensor = tensor.detach().cpu().contiguous() | |
| digest.update( | |
| json.dumps([name, str(tensor.dtype), list(tensor.shape)]).encode() | |
| ) | |
| digest.update(tensor.reshape(-1).view(torch.uint8).numpy().tobytes()) | |
| return digest.hexdigest() | |
| def export_teacher(checkpoint: Path, output: Path, expected_source_sha256: str) -> dict: | |
| if output.exists(): | |
| raise FileExistsError(output) | |
| checksum = sha256_file(checkpoint) | |
| if checksum != expected_source_sha256: | |
| raise ValueError("Source checkpoint differs from the experiment receipt") | |
| payload = _read_weights(checkpoint) | |
| if payload.get("format_version") != 1: | |
| raise ValueError("Expected native checkpoint format 1") | |
| recorded = copy.deepcopy(payload["run_config"]) | |
| kind = recorded["trainer"]["type"] | |
| if kind != "mv_trainer_stable_ucpe_flywheel_v02.MVTrainerConfig": | |
| raise ValueError("Expected the recorded camera-distillation trainer") | |
| recorded["trainer"]["type"] = "mv_trainer_stable_ucpe_v00.MVTrainerConfig" | |
| encoder, decoder = recorded_model_config(recorded) | |
| encoder["checkpoint_path"] = "" | |
| flat = _flatten_weights(payload) | |
| teacher = {} | |
| for component in ("encoder", "fusion", "decoder"): | |
| prefix = "teacher_" + component + "." | |
| selected = { | |
| component + "." + name[len(prefix) :]: tensor | |
| for name, tensor in flat.items() | |
| if name.startswith(prefix) | |
| } | |
| student = { | |
| name: value | |
| for name, value in flat.items() | |
| if name.startswith(component + ".") | |
| } | |
| if selected.keys() != student.keys() or ( | |
| component != "fusion" and not selected | |
| ): | |
| raise ValueError("EMA teacher and student structures differ") | |
| if any( | |
| selected[name].shape != student[name].shape | |
| or selected[name].dtype != student[name].dtype | |
| for name in selected | |
| ): | |
| raise ValueError("EMA teacher tensor shapes or dtypes differ") | |
| teacher.update(selected) | |
| step = int(payload["global_step"]) | |
| updates = int(flat["ema_state.updates"].item()) | |
| decay = float(flat["ema_state.decay"].item()) | |
| if updates != step or abs(decay - 0.99999) > 1e-7: | |
| raise ValueError("Saved EMA metadata differs from the experiment") | |
| config = { | |
| "format_version": 1, | |
| "model_type": "scale4d", | |
| "checkpoint_step": step, | |
| "encoder": encoder, | |
| "decoder": decoder, | |
| "ucpe_transition": recorded.get("ucpe_transition"), | |
| "camera_condition_max_diameter_m": recorded["trainer"].get( | |
| "camera_condition_max_diameter_m" | |
| ), | |
| } | |
| digest = state_digest(teacher) | |
| output.mkdir(parents=True) | |
| save_file( | |
| {key: value.contiguous() for key, value in teacher.items()}, | |
| str(output / "model.safetensors"), | |
| metadata={ | |
| "format": "pt", | |
| "checkpoint_step": str(step), | |
| "weight_role": "ema_teacher", | |
| }, | |
| ) | |
| (output / "config.json").write_text(json.dumps(config, indent=2) + "\n") | |
| result = { | |
| "weight_role": "ema_teacher", | |
| "checkpoint_step": step, | |
| "source_checkpoint_sha256": checksum, | |
| "teacher_state_sha256": digest, | |
| "ema_updates": updates, | |
| "ema_decay": decay, | |
| "tensor_count": len(teacher), | |
| "weights_sha256": sha256_file(output / "model.safetensors"), | |
| } | |
| (output / "teacher.json").write_text(json.dumps(result, indent=2) + "\n") | |
| return result | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--checkpoint", type=Path, required=True) | |
| parser.add_argument("--output", type=Path, required=True) | |
| parser.add_argument("--expected-source-sha256", required=True) | |
| args = parser.parse_args() | |
| print( | |
| json.dumps( | |
| export_teacher(args.checkpoint, args.output, args.expected_source_sha256), | |
| indent=2, | |
| ), | |
| flush=True, | |
| ) | |
| if __name__ == "__main__": | |
| main() | |