#!/usr/bin/env python3 """Static contract checks for the E4 spectral-audit deployment package.""" from __future__ import annotations import argparse import hashlib import json from pathlib import Path import yaml AUDIT_ROOT = Path("/nfs/ywang29/GmNet/e4_spectral_audit") LONG_LIVE_INIT = Path("/nfs/ywang29/LongLive/scripts/init_run.sh") TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml") WRAPPER = AUDIT_ROOT / "scripts" / "run_parallel_5arms.sh" GENERATOR = AUDIT_ROOT / "scripts" / "generate_deploy.py" MANIFEST = AUDIT_ROOT / "input_manifest.json" DEPLOY = Path( "/nfs/ywang29/GmNet/depoly/e4_imagenet_spectral_20260718/" "e4_matched_spectral_5arms_seed0.yaml" ) EXPECTED_TEMPLATE_SHA256 = "1c84a6a1219bbd6a68c73aa673912d8154065f020083581089b5b615fd1459a9" EXPECTED_PROTOCOL_SHA256 = "b66f0aa2f620135584483fb0057fe6fec9a55b4b501b08fd26065034a892b4a2" EXPECTED_INPUT_MANIFEST_SHA256 = "8b32da7c33f6b578dd2b5359d727afe313462be0c0040212a2640755ad2fadf7" EXPECTED_AUDIT_RUNTIME_CODE_SHA256 = "f6bd434a2ac86c772f2e23683431f3bb7ccb06f539558682a3bea6464bacebf9" EXPECTED_ALIGNMENT_TRAINING_CODE_SHA256 = "4a62bc48370247d882196cd9afc1a0f1629a5bbfd522c3f599ffaf0c1187641f" RESOURCE_KEYS = ( "gpu_type", "gpu_num", "gpu_memory", "cpu_num", "memory", "efa", "priority", "pytorchjob", "custom_node_labels", "volcano_queue", "project_name", "project_support_alias", "team", "cost_team", "cost_feature", "cost_sub_feature", "docker_image", "mount", ) def require(condition: bool, message: str) -> None: if not condition: raise RuntimeError(message) def sha256(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() def export_block(path: Path) -> str: lines = path.read_text(encoding="utf-8").splitlines() start = lines.index("export TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC=1800") end = lines.index("export LD_LIBRARY_PATH=", start) return "\n".join(lines[start : end + 1]) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--require-generated", action="store_true") args = parser.parse_args() require(sha256(TEMPLATE) == EXPECTED_TEMPLATE_SHA256, "LongLive YAML template hash changed") require(export_block(WRAPPER) == export_block(LONG_LIVE_INIT), "LongLive export block is not exact") require(sha256(MANIFEST) == EXPECTED_INPUT_MANIFEST_SHA256, "input manifest changed") manifest = json.loads(MANIFEST.read_text(encoding="utf-8")) require(manifest["protocol_id"] == "gmnet-e4-imagenet-matched-spectral-v1", "protocol ID changed") protocol_path = Path(manifest["protocol"]["path"]) require(manifest["protocol"]["sha256"] == EXPECTED_PROTOCOL_SHA256, "protocol hash registration changed") require(sha256(protocol_path) == EXPECTED_PROTOCOL_SHA256, "frozen protocol file changed") runtime = manifest["runtime"] require(runtime["torch"] == "2.9.0+cu130", "runtime must use official torch 2.9.0+cu130") require(runtime["torchvision"] == "0.24.0+cu130", "runtime must use official torchvision 0.24.0+cu130") require(runtime["gpus_requested"] == 8, "deployment must request eight GPUs") require(runtime["canonical_arms"] == 5, "deployment must run five canonical arms") require(runtime["parallel_tasks"] == 8, "deployment must run eight parallel tasks") require(runtime["canonical_batch_size"] == 256, "canonical batch must be 256") require(runtime["max_eval_samples"] == 50000, "all low-pass conditions must use 50,000 images") require(runtime["spectral_samples"] == 4096, "block spectral subset must contain 4,096 images") require(runtime["lowpass_cutoffs"] == [0.125, 0.25, 0.5, 0.75], "cutoff grid changed") require( {probe["task_id"] for probe in manifest["order_probes"]} == {"D_order1", "D_order2", "B_order1"}, "order-probe set changed", ) require({probe["gpu"] for probe in manifest["order_probes"]} == {5, 6, 7}, "probe GPU assignment changed") require(manifest["order_encoding"]["index_encoding"] == "exactly 8 unsigned little-endian bytes", "order encoding changed") require(manifest["spectral_subset"]["num_samples"] == 4096, "subset size changed") require(manifest["spectral_subset"]["expected_class_histogram"] == {"classes_with_4": 904, "classes_with_5": 96}, "subset class balance changed") require(manifest["lowpass"]["unfiltered_condition"] == "true transform bypass", "unfiltered condition is not a bypass") require({item["arm"] for item in manifest["arms"]} == {"B", "D", "S", "C", "SC"}, "arm set changed") require( manifest["code_provenance"]["audit_runtime_code_sha256"] == EXPECTED_AUDIT_RUNTIME_CODE_SHA256, "audit runtime code identity changed", ) require( manifest["code_provenance"]["alignment_training_code_sha256"] == EXPECTED_ALIGNMENT_TRAINING_CODE_SHA256, "alignment training code identity changed", ) aggregator_self_test = ( f"/tmp/gmnet_venv/bin/python {AUDIT_ROOT}/scripts/aggregate_and_validate.py --self-test" ) generator = GENERATOR.read_text(encoding="utf-8") require( 'f"/tmp/gmnet_venv/bin/python {AUDIT_ROOT}/scripts/aggregate_and_validate.py --self-test && "' in generator, "deploy generator does not register the aggregator self-test", ) require( 'f"/tmp/gmnet_venv/bin/python {AUDIT_ROOT}/scripts/static_check.py --require-generated && "' in generator, "deploy generator does not register the runtime static check", ) wrapper = WRAPPER.read_text(encoding="utf-8") required_literals = ( "readonly BATCH_SIZE=256", "readonly WORKERS_PER_ARM=8", "readonly MAX_EVAL_SAMPLES=50000", "readonly SPECTRAL_SAMPLES=4096", 'readonly LOWPASS_CUTOFFS="0.125,0.25,0.5,0.75"', 'readonly EXPECTED_INPUT_MANIFEST_SHA256="8b32da7c33f6b578dd2b5359d727afe313462be0c0040212a2640755ad2fadf7"', '--max-eval-samples "${MAX_EVAL_SAMPLES}"', '--spectral-samples "${SPECTRAL_SAMPLES}"', '--lowpass-cutoffs "${LOWPASS_CUTOFFS}"', '--order "${order}"', '--conditions "${conditions}"', '--input-manifest "${MANIFEST_PATH}"', 'export CONTAINER_IMAGE="763104351884.dkr.ecr.us-west-2.amazonaws.com/pytorch-training:2.9.0-gpu-py312-cu130-ubuntu22.04-ec2"', '--subset-manifest "${SHARED_SUBSET_MANIFEST}"', 'subset["artifact_path"]', 'subset["sha256"]', '--task-id "${task_id}"', 'if [[ "${#TASK_ROWS[@]}" != 8 ]]', 'B:0|D:1|S:2|C:3|SC:4|D_order1:5|D_order2:6|B_order1:7', '"${PYTHON}" "${AGGREGATOR}"', '--root "${WORK_ROOT}"', '--input-manifest "${MANIFEST_PATH}"', '--runner "${SPECTRAL_RUNNER}"', ) for literal in required_literals: require(literal in wrapper, f"wrapper contract missing: {literal}") require( wrapper.count('"${PYTHON}" "${AGGREGATOR}"') == 2, "wrapper must run the aggregator once and then re-open it in check-only mode", ) for literal in ( 'aggregate_and_validate_check_only.log', 'results.get("formal_complete") is True', 'results.get("order_audit_complete") is True', 'isinstance(results.get("claim_decision"), dict)', 'validation.get("status") == "passed"', '"protocol.json"', '"frozen_protocol.md"', '"input_manifest.json"', '"environment.json"', '"checkpoint_manifest.json"', '"subset_manifest.jsonl"', '"accuracy_bootstrap.csv"', '"order_probe_accuracy.csv"', '"order_probe_spectral_by_block.csv"', '"d_order_sensitivity_by_block.csv"', '"raw_amplitude_by_block.csv"', '"gate_operating_diagnostics.csv"', '"coherence_by_block.csv"', '"transfer_bootstrap_by_block.csv"', '"figures/accuracy_lowpass.svg"', '"figures/mixing_depth_profile.svg"', '"figures/spectral_stage_profile.svg"', '"figures/coherence_depth_profile.svg"', '"figures/transfer_heatmaps.svg"', '"figures/accuracy_mixing_raw.svg"', 'source_hashes.get("runner_sha256")', 'source_hashes.get("aggregator_sha256")', 'source_hashes.get("input_manifest_sha256")', 'Runner changed after aggregate check-only', 'Aggregator changed after aggregate check-only', 'Input manifest changed after aggregate check-only', 'temporary.write_text("complete\\n", encoding="ascii")', 'os.replace(temporary, root / "COMPLETE")', ): require(literal in wrapper, f"wrapper completion gate missing: {literal}") require( wrapper.index('aggregate_and_validate_check_only.log') < wrapper.index('temporary.write_text("complete\\n", encoding="ascii")') < wrapper.index('mv "${WORK_ROOT}" "${OUTPUT_ROOT}"'), "root COMPLETE must follow aggregate check-only and precede the atomic directory move", ) if args.require_generated: require(DEPLOY.is_file(), f"generated YAML missing: {DEPLOY}") source = yaml.safe_load(TEMPLATE.read_text(encoding="utf-8")) deploy = yaml.safe_load(DEPLOY.read_text(encoding="utf-8")) for key in RESOURCE_KEYS: require(deploy.get(key) == source.get(key), f"template field changed: {key}") pre_run_event = deploy["script"]["pre_run_event"] require( aggregator_self_test in pre_run_event, "deploy pre_run_event does not run the aggregator self-test", ) require( pre_run_event.index("aggregate_and_validate.py --self-test") < pre_run_event.index("stage_imagenet.sh full"), "aggregator self-test must run before ImageNet staging", ) require("launchjob" not in pre_run_event, "deploy pre_run_event must not submit launchjob") command = deploy["script"]["command"] require("run_parallel_5arms.sh" in command, "deploy command does not use the formal wrapper") require("launchjob" not in command, "generator must not submit launchjob") print("E4 spectral deployment static checks passed") if __name__ == "__main__": main()