File size: 7,052 Bytes
db613b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
"""Prepare local tensor-only UniCal weights and licensed source snapshots; never upload."""

from __future__ import annotations

import argparse
import json
import shutil
import subprocess
from pathlib import Path

import torch
from prepare_release import archive_directory, write_checksums

from kitti_c2l.release import sha256

TRAINING_COMMIT = "7c16fd81e4889d6f16076b1ec5b58835d876807b"
INFERENCE_COMMIT = "eebb3b03fc049ee2c946e891512305d7a706d1d6"
HARNESS_COMMIT = "2550c6dbab40d48f64bc260f03bf5e69d5bc5452"
BEST_EPOCHS = {42: 44, 43: 33, 44: 39}


def git(repo: Path, *args: str) -> bytes:
    return subprocess.check_output(["git", "-C", str(repo), *args])


def prepare(root: Path, unical_repo: Path, experiment_root: Path, output: Path) -> Path:
    if output.exists() or output.with_name(output.name + ".tar.gz").exists():
        raise FileExistsError(f"Refusing to overwrite baseline output: {output}")
    evidence_path = root / "release/v1/assessment_results.json"
    evidence = json.loads(evidence_path.read_text())
    # The inference backport changes installation/loading only, not model/preprocessing.
    if git(
        unical_repo,
        "diff",
        TRAINING_COMMIT,
        INFERENCE_COMMIT,
        "--",
        "src/unical/models",
        "src/unical/data/preprocessor.py",
        "src/unical/utils",
    ):
        raise ValueError("Inference source differs from the audited model/preprocessor")
    sources = []
    for seed, epoch in BEST_EPOCHS.items():
        run = f"main-c2l-long50-fast256-seed{seed}"
        source = experiment_root / run / "checkpoints" / f"unical-{epoch:03d}.ckpt"
        expected = evidence["long_main_training_controls"][run]["best_checkpoint_sha256"]
        if sha256(source) != expected:
            raise ValueError(f"Original checkpoint hash mismatch: {run}")
        sources.append((seed, run, source, expected))
    # Resolve source revisions before writing a partial package.
    for revision in (TRAINING_COMMIT, INFERENCE_COMMIT, HARNESS_COMMIT):
        git(unical_repo, "rev-parse", "--verify", revision + "^{commit}")
    output.mkdir(parents=True)
    manifest = {
        "dataset_version": "1.0.0",
        "license": "CC-BY-NC-4.0",
        "upstream_notice": "Inherited MobileViT backbone components retain the Apple sample code license; see THIRD_PARTY.md",
        "training_source_commit": TRAINING_COMMIT,
        "inference_source_commit": INFERENCE_COMMIT,
        "harness_source_commit": HARNESS_COMMIT,
        "source_repository": "https://github.com/mcocheteux/unical-plus",
        "models": [],
    }
    for seed, run, source, source_hash in sources:
        # Trusted local checkpoints only. The public export is then verified with weights_only=True.
        state = torch.load(source, map_location="cpu", weights_only=False)
        exported = {
            "state_dict": {
                key: value.detach().cpu().clone() for key, value in state["state_dict"].items()
            },
            "epoch": int(state["epoch"]),
            "global_step": int(state["global_step"]),
            "training_seed": seed,
        }
        destination = output / run / "checkpoints/model.pt"
        destination.parent.mkdir(parents=True)
        torch.save(exported, destination)
        loaded = torch.load(destination, map_location="cpu", weights_only=True)
        for key, tensor in exported["state_dict"].items():
            if (
                not torch.equal(tensor, loaded["state_dict"][key])
                or not torch.isfinite(tensor).all()
            ):
                raise ValueError(f"Invalid exported weight: {run}/{key}")
        run_manifest = json.loads((source.parent.parent / "run.json").read_text())
        arguments = run_manifest["arguments"]
        clean_arguments = {
            key: value
            for key, value in arguments.items()
            if key not in {"data_dir", "raw_root", "output", "resume"}
        }
        (destination.parent.parent / "run.json").write_text(
            json.dumps(
                {
                    "arguments": clean_arguments,
                    "training_source_commit": TRAINING_COMMIT,
                    "experiment_code_commit": run_manifest["experiment_code_commit"],
                    "experiment_source_hashes": run_manifest["experiment_source_hashes"],
                },
                indent=2,
            )
            + "\n"
        )
        manifest["models"].append(
            {
                "run": run,
                "seed": seed,
                "original_checkpoint_sha256": source_hash,
                "export_path": str(destination.relative_to(output)),
                "export_sha256": sha256(destination),
                "bytes": destination.stat().st_size,
                "epoch_zero_based": exported["epoch"],
                "global_step": exported["global_step"],
            }
        )
    (output / "unical-source.tar").write_bytes(
        git(unical_repo, "archive", "--format=tar", "--prefix=unical/", INFERENCE_COMMIT)
    )
    (output / "harness-source.tar").write_bytes(
        git(
            unical_repo,
            "archive",
            "--format=tar",
            "--prefix=harness/",
            HARNESS_COMMIT,
            "experiments",
            "LICENSE",
            "uv.lock",
            "pyproject.toml",
        )
    )
    (output / "LICENSE").write_bytes(git(unical_repo, "show", INFERENCE_COMMIT + ":LICENSE"))
    (output / "README.md").write_text(
        (root / "docs/BASELINES.md")
        .read_text()
        .replace("../release/v1/assessment_results.json", "assessment_results.json")
    )
    shutil.copyfile(root / "docs/ASSESSMENT.md", output / "ASSESSMENT.md")
    shutil.copyfile(
        root / "release/v1/APPLE-MOBILEVIT-LICENSE.txt", output / "APPLE-MOBILEVIT-LICENSE.txt"
    )
    shutil.copyfile(root / "docs/THIRD_PARTY.md", output / "THIRD_PARTY.md")
    shutil.copyfile(root / "scripts/evaluate_baseline.py", output / "evaluate_baseline.py")
    shutil.copyfile(evidence_path, output / "assessment_results.json")
    manifest["source_archives"] = {
        name: sha256(output / name) for name in ("unical-source.tar", "harness-source.tar")
    }
    (output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
    write_checksums(output)
    return archive_directory(output)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
    parser.add_argument("--unical-repo", type=Path, required=True)
    parser.add_argument("--experiment-root", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    archive = prepare(
        args.root.resolve(),
        args.unical_repo.resolve(),
        args.experiment_root.resolve(),
        args.output.resolve(),
    )
    print(f"Prepared baseline archive: {archive}\nSHA-256: {sha256(archive)}")


if __name__ == "__main__":
    main()