Download tools/validate_repository.py from JunhaoWu7/Attack: direct link, hf CLI and curl.
- Browser
- Download file 6.97 kB
-
https://huggingface.co/JunhaoWu7/Attack/resolve/main/tools/validate_repository.py
- Command line
-
hf download hf://JunhaoWu7/Attack/tools/validate_repository.py
-
curl -L -o validate_repository.py https://huggingface.co/JunhaoWu7/Attack/resolve/main/tools/validate_repository.py
6.97 kB
| #!/usr/bin/env python3 | |
| """Validate an Attack-WAM Hugging Face artifact staging directory.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import re | |
| import sys | |
| from pathlib import Path | |
| SCHEMA_VERSION = "1.0.0" | |
| VARIANTS = { | |
| "direct_A1V0": ("direct", 1.0, 0.0), | |
| "direct_A0V1": ("direct", 0.0, 1.0), | |
| "direct_A1V1": ("direct", 1.0, 1.0), | |
| "de_proj_A1V0": ("de_proj", 1.0, 0.0), | |
| "de_proj_A0V1": ("de_proj", 0.0, 1.0), | |
| "bisect_A1V1": ("bisect", 1.0, 1.0), | |
| } | |
| DATASETS = { | |
| ("libero", "long"), | |
| ("libero", "goal"), | |
| ("libero", "object"), | |
| ("libero", "spatial"), | |
| ("robotwin", "main"), | |
| } | |
| SHA256_RE = re.compile(r"^[0-9a-f]{64}$") | |
| def digest(path: Path) -> str: | |
| value = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(1024 * 1024), b""): | |
| value.update(chunk) | |
| return value.hexdigest() | |
| def expected_metadata_path(root: Path, meta: dict) -> Path: | |
| benchmark = meta["benchmark"] | |
| suite = meta["suite"] | |
| variant = meta["variant"]["name"] | |
| regime = meta["regime"] | |
| if regime == "full": | |
| return root / "artifacts" / "full" / benchmark / suite / variant / "metadata.json" | |
| ablation = meta.get("ablation") or {} | |
| if regime == "episode_pool": | |
| limit = int(ablation["episode_pool_limit"]) | |
| return ( | |
| root / "artifacts" / "ablation" / "episode_pool" / benchmark / | |
| suite / f"top_{limit}" / variant / "metadata.json" | |
| ) | |
| if regime == "task_fraction": | |
| percent = int(ablation["task_fraction_percent"]) | |
| return ( | |
| root / "artifacts" / "ablation" / "task_fraction" / benchmark / | |
| suite / f"p{percent}" / variant / "metadata.json" | |
| ) | |
| raise ValueError(f"unsupported regime: {regime!r}") | |
| def validate_metadata(root: Path, path: Path) -> list[str]: | |
| errors: list[str] = [] | |
| try: | |
| meta = json.loads(path.read_text(encoding="utf-8")) | |
| except Exception as exc: | |
| return [f"{path}: invalid JSON: {exc}"] | |
| required = { | |
| "schema_version", "experiment_id", "status", "benchmark", "suite", | |
| "regime", "variant", "data", "model", "attack", "result", "code", | |
| "environment", "artifacts", | |
| } | |
| missing = sorted(required - set(meta)) | |
| if missing: | |
| errors.append(f"{path}: missing keys: {', '.join(missing)}") | |
| return errors | |
| if meta["schema_version"] != SCHEMA_VERSION: | |
| errors.append(f"{path}: unsupported schema_version {meta['schema_version']!r}") | |
| dataset = (meta["benchmark"], meta["suite"]) | |
| if dataset not in DATASETS: | |
| errors.append(f"{path}: invalid benchmark/suite pair {dataset!r}") | |
| variant_name = meta["variant"].get("name") | |
| if variant_name not in VARIANTS: | |
| errors.append(f"{path}: invalid variant {variant_name!r}") | |
| else: | |
| method, action_weight, video_weight = VARIANTS[variant_name] | |
| actual = ( | |
| meta["variant"].get("method"), | |
| float(meta["variant"].get("action_loss_weight", -1)), | |
| float(meta["variant"].get("video_loss_weight", -1)), | |
| ) | |
| expected = (method, action_weight, video_weight) | |
| if actual != expected: | |
| errors.append(f"{path}: variant fields {actual!r} do not match {expected!r}") | |
| try: | |
| expected_path = expected_metadata_path(root, meta).resolve() | |
| if path.resolve() != expected_path: | |
| errors.append(f"{path}: canonical location is {expected_path}") | |
| except Exception as exc: | |
| errors.append(f"{path}: cannot derive canonical path: {exc}") | |
| roles: set[str] = set() | |
| for artifact in meta.get("artifacts", []): | |
| role = artifact.get("role") | |
| roles.add(role) | |
| relative = artifact.get("path", "") | |
| artifact_path = path.parent / relative | |
| if Path(relative).is_absolute() or ".." in Path(relative).parts: | |
| errors.append(f"{path}: unsafe artifact path {relative!r}") | |
| continue | |
| if not artifact_path.is_file(): | |
| errors.append(f"{path}: missing artifact {relative!r}") | |
| continue | |
| expected_bytes = artifact.get("bytes") | |
| if expected_bytes != artifact_path.stat().st_size: | |
| errors.append( | |
| f"{path}: size mismatch for {relative}: " | |
| f"{expected_bytes} != {artifact_path.stat().st_size}" | |
| ) | |
| expected_hash = artifact.get("sha256", "") | |
| if not SHA256_RE.fullmatch(expected_hash): | |
| errors.append(f"{path}: invalid SHA-256 for {relative}") | |
| elif digest(artifact_path) != expected_hash: | |
| errors.append(f"{path}: SHA-256 mismatch for {relative}") | |
| if meta["status"] in {"complete", "complete_with_note"} and "top1" not in roles: | |
| errors.append(f"{path}: completed run does not declare a top1 artifact") | |
| return errors | |
| def main() -> int: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("root", nargs="?", default=".") | |
| parser.add_argument("--require-complete-full", action="store_true") | |
| args = parser.parse_args() | |
| root = Path(args.root).resolve() | |
| errors: list[str] = [] | |
| manifest_path = root / "manifest.json" | |
| if not manifest_path.is_file(): | |
| errors.append(f"missing {manifest_path}") | |
| manifest = {} | |
| else: | |
| try: | |
| manifest = json.loads(manifest_path.read_text(encoding="utf-8")) | |
| except Exception as exc: | |
| errors.append(f"{manifest_path}: invalid JSON: {exc}") | |
| manifest = {} | |
| if manifest and manifest.get("schema_version") != SCHEMA_VERSION: | |
| errors.append(f"{manifest_path}: schema_version must be {SCHEMA_VERSION}") | |
| metadata_paths = sorted((root / "artifacts").glob("**/metadata.json")) | |
| for path in metadata_paths: | |
| errors.extend(validate_metadata(root, path)) | |
| indexed = { | |
| item.get("metadata_path") | |
| for item in manifest.get("runs", []) | |
| if isinstance(item, dict) | |
| } | |
| discovered = {str(path.relative_to(root)) for path in metadata_paths} | |
| for path in sorted(discovered - indexed): | |
| errors.append(f"manifest does not index {path}") | |
| for path in sorted(indexed - discovered): | |
| errors.append(f"manifest indexes missing metadata {path}") | |
| if args.require_complete_full: | |
| expected = { | |
| str(Path("artifacts/full") / benchmark / suite / variant / "metadata.json") | |
| for benchmark, suite in DATASETS | |
| for variant in VARIANTS | |
| } | |
| for path in sorted(expected - discovered): | |
| errors.append(f"missing full-data run {path}") | |
| if errors: | |
| print("VALIDATION FAILED") | |
| for error in errors: | |
| print(f"- {error}") | |
| return 1 | |
| print( | |
| f"VALIDATION OK: {len(metadata_paths)} runs, " | |
| f"{len(manifest.get('runs', []))} manifest entries" | |
| ) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |