File size: 6,968 Bytes
7a90b8c | 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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | #!/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())
|