File size: 17,887 Bytes
12c2325 | 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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | #!/usr/bin/env python3
"""Fail-closed validation for the E4 matched spectral audit inputs."""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
from pathlib import Path
from typing import Any
import numpy as np
EXPECTED_ARMS = {"B", "D", "S", "C", "SC"}
EXPECTED_PROTOCOL_ID = "gmnet-e4-imagenet-matched-spectral-v1"
EXPECTED_INPUT_MANIFEST_SHA256 = "8b32da7c33f6b578dd2b5359d727afe313462be0c0040212a2640755ad2fadf7"
EXPECTED_PROTOCOL_SHA256 = "b66f0aa2f620135584483fb0057fe6fec9a55b4b501b08fd26065034a892b4a2"
EXPECTED_AUDIT_RUNTIME_CODE_SHA256 = "f6bd434a2ac86c772f2e23683431f3bb7ccb06f539558682a3bea6464bacebf9"
EXPECTED_ALIGNMENT_TRAINING_CODE_SHA256 = "4a62bc48370247d882196cd9afc1a0f1629a5bbfd522c3f599ffaf0c1187641f"
EXPECTED_AUDIT_RUNTIME_MANIFEST_SHA256 = "e354339142ffc72e669234a9f297113a64e5294ce8ff37dd658e62f723f0b239"
EXPECTED_ALIGNMENT_TRAINING_MANIFEST_SHA256 = "fa1a6ba00c82619dbd51b9af61489a34326b635978d83ef948584e45f93cddbc"
EXPECTED_TORCH = "2.9.0+cu130"
EXPECTED_TORCHVISION = "0.24.0+cu130"
EXPECTED_SCHEMA = "352cb771eaf4123fb9364dfd25d0151f9c2e6fa5493b989759091819f8981c99"
EXPECTED_PERMUTATION = "0219d0a289ae2e3c2bde90568af4b05d23ca629522f1b19b6a1d09473d87fb8b"
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def require(condition: bool, message: str) -> None:
if not condition:
raise RuntimeError(message)
def read_json(path: Path) -> dict[str, Any]:
require(path.is_file(), f"missing JSON file: {path}")
value = json.loads(path.read_text(encoding="utf-8"))
require(isinstance(value, dict), f"expected a JSON object: {path}")
return value
def verify_artifact(path: Path, expected: str, label: str) -> str:
require(path.is_file(), f"missing {label}: {path}")
actual = sha256(path)
require(actual == expected, f"{label} hash mismatch: expected {expected}, got {actual}")
return actual
def verify_arm(arm: dict[str, Any]) -> dict[str, Any]:
name = str(arm["arm"])
run_dir = Path(arm["run_dir"])
require(run_dir.is_dir(), f"{name}: run directory missing: {run_dir}")
require((run_dir / "official_eval" / "COMPLETE").is_file(), f"{name}: official COMPLETE missing")
checkpoint = Path(arm["checkpoint"])
checkpoint_hash = verify_artifact(
checkpoint, str(arm["checkpoint_sha256"]), f"{name} checkpoint"
)
verify_artifact(
Path(arm["config_source"]),
str(arm["config_source_sha256"]),
f"{name} config source",
)
results_path = Path(arm["official_results"])
verify_artifact(
results_path,
str(arm["official_results_sha256"]),
f"{name} official results",
)
checks_path = Path(arm["official_checks"])
verify_artifact(
checks_path,
str(arm["official_checks_sha256"]),
f"{name} official checks",
)
per_sample_path = Path(arm["official_per_sample"])
verify_artifact(
per_sample_path,
str(arm["official_per_sample_sha256"]),
f"{name} official per-sample evidence",
)
results = read_json(results_path)
checks = read_json(checks_path)
require(checks.get("status") == "passed", f"{name}: official checks did not pass")
require(results.get("status") == "complete", f"{name}: official result is incomplete")
require(results.get("partial_evaluation") is False, f"{name}: official result is partial")
require(results.get("checkpoint_epoch") == 299, f"{name}: checkpoint is not fixed-last epoch 299")
require(results.get("training_epochs") == 300, f"{name}: expected 300 training epochs")
require(results.get("training_completion", {}).get("training_complete") is True, f"{name}: training incomplete")
require(results.get("training_completion", {}).get("world_size") == 8, f"{name}: training world size is not 8")
require(results.get("metrics", {}).get("samples") == 50000, f"{name}: expected 50,000 official samples")
require(results.get("hashes", {}).get("checkpoint_sha256") == checkpoint_hash, f"{name}: certificate checkpoint hash mismatch")
require(results.get("topology", {}).get("model_state_schema_sha256") == EXPECTED_SCHEMA, f"{name}: model state schema mismatch")
require(results.get("topology", {}).get("parameter_count") == 7791544, f"{name}: parameter count mismatch")
require(results.get("topology", {}).get("state_tensor_count") == 365, f"{name}: state tensor count mismatch")
require(results.get("gate_intervention", {}).get("mode") == arm["gate_intervention"], f"{name}: intervention mismatch")
require(
abs(float(results["metrics"]["top1"]) - float(arm["official_top1"])) < 1e-12,
f"{name}: official Top-1 mismatch",
)
require(
abs(float(results["metrics"]["top5"]) - float(arm["official_top5"])) < 1e-12,
f"{name}: official Top-5 mismatch",
)
require(round(float(results["metrics"]["top1"]) * 500) == arm["official_top1_correct"], f"{name}: official Top-1 count mismatch")
require(round(float(results["metrics"]["top5"]) * 500) == arm["official_top5_correct"], f"{name}: official Top-5 count mismatch")
with np.load(per_sample_path, allow_pickle=False) as per_sample:
require(
set(per_sample.files)
== {"sample_index", "target", "prediction", "confidence", "correct", "top5_correct", "nll"},
f"{name}: official per-sample schema mismatch",
)
require(
all(per_sample[field].shape == (50000,) for field in per_sample.files),
f"{name}: official per-sample shapes mismatch",
)
require(
np.array_equal(per_sample["sample_index"], np.arange(50000, dtype=np.int64)),
f"{name}: official per-sample index is not canonical",
)
require(int(per_sample["correct"].sum()) == arm["official_top1_correct"], f"{name}: per-sample Top-1 count mismatch")
require(int(per_sample["top5_correct"].sum()) == arm["official_top5_correct"], f"{name}: per-sample Top-5 count mismatch")
permutation = results.get("gate_intervention", {}).get("permutation_manifest_sha256")
if name in {"C", "SC"}:
require(permutation == EXPECTED_PERMUTATION, f"{name}: frozen channel permutation mismatch")
if name == "D":
require(
results.get("gate_intervention", {}).get("batch_derangement_manifest_sha256"),
"D: missing official batch-derangement mapping manifest",
)
return {
"arm": name,
"checkpoint_sha256": checkpoint_hash,
"official_top1": results["metrics"]["top1"],
"permutation_manifest_sha256": permutation,
"status": "passed",
}
def verify_runtime() -> dict[str, Any]:
import torch
import torchvision
require(torch.__version__ == EXPECTED_TORCH, f"expected torch {EXPECTED_TORCH}, got {torch.__version__}")
require(torchvision.__version__ == EXPECTED_TORCHVISION, f"expected torchvision {EXPECTED_TORCHVISION}, got {torchvision.__version__}")
require(torch.cuda.is_available(), "CUDA is unavailable")
require(torch.cuda.device_count() == 8, f"expected exactly 8 visible GPUs, got {torch.cuda.device_count()}")
return {
"python": sys.version.split()[0],
"torch": torch.__version__,
"torchvision": torchvision.__version__,
"cuda_devices": torch.cuda.device_count(),
}
def verify_equivalence(path: Path, manifest: dict[str, Any]) -> dict[str, Any]:
evidence = read_json(path)
require(evidence.get("status") == "passed", "source-equivalence audit did not pass")
require(evidence.get("runtime", {}).get("torch") == EXPECTED_TORCH, "source-equivalence audit did not run under torch 2.9")
provenance = manifest["code_provenance"]
require(evidence.get("old_source", {}).get("sha256") == provenance["alignment_source_gmnet_sha256"], "source-equivalence old source mismatch")
require(evidence.get("new_source", {}).get("sha256") == provenance["audit_runtime_gmnet_sha256"], "source-equivalence current source mismatch")
arms = evidence.get("arms", [])
require({arm.get("arm") for arm in arms} == {"B", "S", "C"}, "source-equivalence arm set mismatch")
for arm in arms:
name = arm["arm"]
for field in (
"forward_bitwise_equal",
"input_gradient_bitwise_equal",
"parameter_gradients_bitwise_equal",
):
require(arm.get(field) is True, f"source-equivalence {name} failed {field}")
require(all(float(value) == 0.0 for value in arm.get("maximum_abs", {}).values()), f"source-equivalence {name} has nonzero error")
require(arm.get("parameter_count") == 7791544, f"source-equivalence {name} parameter count mismatch")
require(arm.get("state_tensor_count") == 365, f"source-equivalence {name} state count mismatch")
stop = evidence.get("explicit_stop_gradient_semantics", {})
require(stop.get("stop_gradient_matches_detached_formula") is True, "stop-gradient formula audit failed")
require(stop.get("baseline_matches_full_formula") is True, "baseline gradient formula audit failed")
return {"path": str(path), "sha256": sha256(path), "status": "passed"}
def verify_frozen_subset(manifest: dict[str, Any]) -> tuple[list[dict[str, Any]], dict[str, Any]]:
registration = manifest["spectral_subset"]
path = Path(registration["artifact_path"])
digest = verify_artifact(path, registration["sha256"], "frozen spectral subset")
rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line]
require(len(rows) == registration["num_samples"] == 4096, "frozen spectral subset row count mismatch")
indices = [row.get("canonical_index") for row in rows]
require(len(set(indices)) == 4096, "frozen spectral subset indices are not unique")
counts: dict[int, int] = {}
for row in rows:
require(
set(row)
== {"canonical_index", "relative_path", "class_id", "selection_sha256", "within_class_rank", "selection_kind"},
"frozen spectral subset row schema mismatch",
)
class_id = int(row["class_id"])
counts[class_id] = counts.get(class_id, 0) + 1
expected_hash = hashlib.sha256(
b"gmnet-e4-spectral-v1\0" + row["relative_path"].encode("utf-8")
).hexdigest()
require(row["selection_sha256"] == expected_hash, "frozen spectral subset selection hash mismatch")
rank = row["within_class_rank"]
require(rank in range(1, 6), "frozen spectral subset rank is outside 1..5")
require(
row["selection_kind"] == ("base_four" if rank <= 4 else "extra_fifth"),
"frozen spectral subset kind/rank mismatch",
)
require(set(counts) == set(range(1000)), "frozen spectral subset does not cover all classes")
histogram = {count: list(counts.values()).count(count) for count in set(counts.values())}
require(histogram == {4: 904, 5: 96}, f"frozen spectral subset class balance mismatch: {histogram}")
return rows, {"path": str(path), "sha256": digest, "rows": len(rows), "class_histogram": histogram}
def verify_data_root(path: Path, manifest: dict[str, Any]) -> dict[str, Any]:
from gmnet.data import imagefolder_split_fingerprint
from torchvision import datasets
expected = Path(manifest["dataset"]["runtime_root"])
require(path.resolve() == expected, f"data root must be {expected}, got {path.resolve()}")
ready_path = path / ".READY"
require(ready_path.is_file(), f"staged ImageNet marker missing: {ready_path}")
require((path / "train").is_dir(), f"ImageNet train directory missing: {path}")
require((path / "val").is_dir(), f"ImageNet val directory missing: {path}")
data = manifest["dataset"]
ready = read_json(ready_path)
require(ready.get("status") == "ready", "ImageNet .READY status is not ready")
require(ready.get("source") == data["source_archive_uri"], "ImageNet .READY source URI mismatch")
require(ready.get("archive_bytes") == data["expected_archive_bytes"], "ImageNet archive byte count mismatch")
val_root = path / "val"
imagefolder = datasets.ImageFolder(val_root)
require(len(imagefolder) == data["expected_val_samples"], "ImageNet validation count mismatch")
require(len(imagefolder.classes) == 1000, "ImageNet class count mismatch")
class_hash = hashlib.sha256(
json.dumps(
imagefolder.class_to_idx,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=True,
).encode("utf-8")
).hexdigest()
require(class_hash == data["class_to_idx_sha256"], "ImageNet class mapping hash mismatch")
fingerprint = imagefolder_split_fingerprint(imagefolder, val_root)
require(
fingerprint["sample_index_sha256"] == data["val_sample_index_sha256"],
"ImageNet canonical validation order hash mismatch",
)
require(
fingerprint["sampled_content_sha256"] == data["val_sampled_content_sha256"],
"ImageNet sampled validation content hash mismatch",
)
require(
fingerprint["sampled_content_samples"] == data["val_sampled_content_samples"],
"ImageNet sampled validation content count mismatch",
)
subset_rows, subset_summary = verify_frozen_subset(manifest)
samples = [
(Path(sample_path).relative_to(val_root).as_posix(), int(class_id))
for sample_path, class_id in imagefolder.samples
]
for row in subset_rows:
index = int(row["canonical_index"])
require(0 <= index < len(samples), "frozen subset canonical index is out of range")
require(
samples[index] == (row["relative_path"], int(row["class_id"])),
"frozen subset receiver identity differs from canonical ImageFolder order",
)
return {
"data_root": str(path),
"status": "ready",
"class_to_idx_sha256": class_hash,
"frozen_subset": subset_summary,
**fingerprint,
}
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--runner", type=Path)
parser.add_argument("--runner-sha256")
parser.add_argument("--runtime", action="store_true")
parser.add_argument("--data-root", type=Path)
parser.add_argument("--equivalence", type=Path)
args = parser.parse_args()
verify_artifact(
args.manifest,
EXPECTED_INPUT_MANIFEST_SHA256,
"frozen input manifest",
)
manifest = read_json(args.manifest)
require(manifest.get("schema_version") == 1, "unsupported manifest schema")
require(manifest.get("protocol_id") == EXPECTED_PROTOCOL_ID, "protocol ID changed")
protocol = manifest["protocol"]
require(
protocol.get("sha256") == EXPECTED_PROTOCOL_SHA256,
"registered protocol SHA changed",
)
verify_artifact(Path(protocol["path"]), protocol["sha256"], "frozen protocol")
provenance = manifest["code_provenance"]
expected_provenance = {
"audit_runtime_code_sha256": EXPECTED_AUDIT_RUNTIME_CODE_SHA256,
"alignment_training_code_sha256": EXPECTED_ALIGNMENT_TRAINING_CODE_SHA256,
"audit_runtime_manifest_sha256": EXPECTED_AUDIT_RUNTIME_MANIFEST_SHA256,
"alignment_training_manifest_sha256": EXPECTED_ALIGNMENT_TRAINING_MANIFEST_SHA256,
}
require(
all(provenance.get(key) == value for key, value in expected_provenance.items()),
"frozen training-code provenance changed",
)
for prefix in ("audit_runtime", "alignment_training"):
path = Path(provenance[f"{prefix}_manifest"])
verify_artifact(path, provenance[f"{prefix}_manifest_sha256"], f"{prefix} code manifest")
code_manifest = read_json(path)
require(
code_manifest.get("code_sha256") == provenance[f"{prefix}_code_sha256"],
f"{prefix} code SHA does not match its manifest",
)
verify_artifact(
Path(provenance["alignment_source_snapshot_manifest"]),
provenance["alignment_source_snapshot_manifest_sha256"],
"alignment source snapshot manifest",
)
arms = manifest.get("arms")
require(isinstance(arms, list) and len(arms) == 5, "manifest must contain five arms")
names = [str(arm.get("arm")) for arm in arms]
require(set(names) == EXPECTED_ARMS and len(names) == len(set(names)), f"invalid arms: {names}")
verified_arms = [verify_arm(arm) for arm in arms]
permutations = {
arm["permutation_manifest_sha256"]
for arm in verified_arms
if arm["arm"] in {"C", "SC"}
}
require(permutations == {EXPECTED_PERMUTATION}, "C and SC permutation manifests differ")
summary: dict[str, Any] = {
"protocol_id": manifest["protocol_id"],
"manifest_sha256": sha256(args.manifest),
"arms": verified_arms,
}
_, summary["frozen_subset"] = verify_frozen_subset(manifest)
if args.runner is not None:
require(args.runner_sha256 is not None, "--runner-sha256 is required with --runner")
summary["runner"] = {
"path": str(args.runner),
"sha256": verify_artifact(args.runner, args.runner_sha256, "spectral runner"),
}
if args.runtime:
summary["runtime"] = verify_runtime()
if args.data_root is not None:
summary["data"] = verify_data_root(args.data_root, manifest)
if args.equivalence is not None:
summary["source_equivalence"] = verify_equivalence(args.equivalence, manifest)
summary["status"] = "passed"
print(json.dumps(summary, indent=2, sort_keys=True))
if __name__ == "__main__":
main()
|