File size: 3,062 Bytes
10979b5 | 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 | #!/usr/bin/env python3
"""Create or verify the immutable source manifest used by long experiments."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
from typing import Any
SCHEMA_VERSION = 1
ROOT_FILES = (
"pyproject.toml",
"requirements-runtime.txt",
"requirements-dev.txt",
)
TREE_PATTERNS = (
("gmnet", "*.py"),
("scripts", "*.py"),
("scripts", "*.sh"),
("configs", "*.yaml"),
)
def file_sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def stable_sha256(value: Any) -> str:
payload = json.dumps(
value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
).encode("utf-8")
return hashlib.sha256(payload).hexdigest()
def build_manifest(root: Path) -> dict[str, Any]:
root = root.resolve()
paths = [root / name for name in ROOT_FILES]
for directory, pattern in TREE_PATTERNS:
paths.extend((root / directory).rglob(pattern))
paths = sorted({path.resolve() for path in paths if path.is_file()})
records = [
{
"path": path.relative_to(root).as_posix(),
"size": path.stat().st_size,
"sha256": file_sha256(path),
}
for path in paths
]
manifest: dict[str, Any] = {
"schema_version": SCHEMA_VERSION,
"fingerprint_scope": "training_source_configs_and_environment_specs",
"files": records,
}
manifest["code_sha256"] = stable_sha256(manifest)
return manifest
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--root", type=Path, default=Path(__file__).resolve().parents[1]
)
action = parser.add_mutually_exclusive_group()
action.add_argument("--write", type=Path)
action.add_argument("--check", type=Path)
action.add_argument("--print", dest="print_fingerprint", action="store_true")
return parser.parse_args()
def main() -> int:
args = parse_args()
manifest = build_manifest(args.root)
if args.write is not None:
args.write.parent.mkdir(parents=True, exist_ok=True)
args.write.write_text(
json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
elif args.check is not None:
expected = json.loads(args.check.read_text(encoding="utf-8"))
if expected != manifest:
expected_hash = expected.get("code_sha256")
raise SystemExit(
"code manifest mismatch: "
f"expected {expected_hash}, computed {manifest['code_sha256']}"
)
if args.print_fingerprint or args.write is not None or args.check is not None:
print(manifest["code_sha256"])
else:
print(json.dumps(manifest, indent=2, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|