KITTI-C2L-Dataset / code /scripts /prepare_baselines.py
mcocheteux's picture
Release KITTI-C2L v1.0.0: documented self-contained benchmark, loader and baselines
db613b6 verified
Raw History Blame Contribute Delete
7.05 kB
"""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()