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