Download gmnet/code/journal_exp/scripts/generate_e4_alignment_deploy.py from YFanwang/Backup: direct link, hf CLI and curl.
- Browser
- Download file 33.8 kB
-
https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/scripts/generate_e4_alignment_deploy.py
- Command line
-
hf download hf://datasets/YFanwang/Backup/gmnet/code/journal_exp/scripts/generate_e4_alignment_deploy.py
-
curl -L -o generate_e4_alignment_deploy.py https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/scripts/generate_e4_alignment_deploy.py
33.8 kB
| #!/usr/bin/env python3 | |
| """Generate and fail-closed validate the matched E4 ImageNet launch batch.""" | |
| from __future__ import annotations | |
| import argparse | |
| import copy | |
| import hashlib | |
| import json | |
| import math | |
| import re | |
| import sys | |
| from dataclasses import asdict, dataclass | |
| from pathlib import Path | |
| from typing import Any | |
| import yaml | |
| SCRIPT_PATH = Path(__file__).resolve() | |
| JOURNAL_ROOT = SCRIPT_PATH.parents[1] | |
| GMNET_ROOT = JOURNAL_ROOT.parent | |
| PROTOCOL_PATH = JOURNAL_ROOT / "configs/e4_alignment_protocol.yaml" | |
| BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml") | |
| BATCH_ROOT = GMNET_ROOT / "depoly/e4_alignment_20260716" | |
| RUN_ROOT = GMNET_ROOT / "runs/e4_alignment" | |
| CODE_MANIFEST_RELATIVE_PATH = "configs/code_manifests/e4_alignment_20260716.json" | |
| SMOKE_EVIDENCE_PATH = BATCH_ROOT / "smoke_evidence.json" | |
| APPROVAL_ROOT = BATCH_ROOT / "approvals" | |
| BASELINE_CONFIG_PATH = JOURNAL_ROOT / "configs/e0_baseline/imagenet_gmnet_s3.yaml" | |
| GENERATED_HEADER = ( | |
| "# Generated by journal_exp/scripts/generate_e4_alignment_deploy.py; " | |
| "do not edit.\n" | |
| ) | |
| TASK_IDS = ( | |
| "e4a_s3_stop_gradient_seed0", | |
| "e4a_s3_channel_derangement_seed0", | |
| ) | |
| INTERVENTIONS = ("stop_gradient", "channel_derangement") | |
| SHA256_PATTERN = re.compile(r"[0-9a-f]{64}") | |
| RESOURCE_KEYS = ( | |
| "gpu_type", | |
| "gpu_num", | |
| "gpu_memory", | |
| "cpu_num", | |
| "memory", | |
| "efa", | |
| "priority", | |
| "pytorchjob", | |
| "custom_node_labels", | |
| "volcano_queue", | |
| ) | |
| PROJECT_KEYS = ( | |
| "project_name", | |
| "project_support_alias", | |
| "team", | |
| "cost_team", | |
| "cost_feature", | |
| "cost_sub_feature", | |
| "docker_image", | |
| "mount", | |
| ) | |
| class ApprovalError(RuntimeError): | |
| """Raised when the E4 launch guard intentionally denies a task.""" | |
| class E4Task: | |
| task_id: str | |
| experiment: str | |
| model: str | |
| gate: str | |
| gate_intervention: str | |
| gate_intervention_seed: int | |
| seed: int | |
| config_path: str | |
| role: str | |
| status: str | |
| contrast: str | |
| question: str | |
| def output_dir(self) -> Path: | |
| return RUN_ROOT / self.task_id | |
| def deploy_path(self) -> Path: | |
| return BATCH_ROOT / f"{self.task_id}.yaml" | |
| def approval_path(self) -> Path: | |
| return APPROVAL_ROOT / f"{self.task_id}.json" | |
| def job_name(self) -> str: | |
| return "gmnet-" + self.task_id.replace("_", "-") | |
| def file_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 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 require_sha256(value: Any, location: str) -> str: | |
| if not isinstance(value, str) or SHA256_PATTERN.fullmatch(value) is None: | |
| raise ValueError(f"invalid SHA-256 at {location}: {value!r}") | |
| return value | |
| def load_yaml(path: Path) -> dict[str, Any]: | |
| if not path.is_file(): | |
| raise FileNotFoundError(path) | |
| loaded = yaml.safe_load(path.read_text(encoding="utf-8")) | |
| if not isinstance(loaded, dict): | |
| raise ValueError(f"expected a YAML mapping: {path}") | |
| return loaded | |
| def load_json(path: Path) -> dict[str, Any]: | |
| if not path.is_file(): | |
| raise FileNotFoundError(path) | |
| loaded = json.loads(path.read_text(encoding="utf-8")) | |
| if not isinstance(loaded, dict): | |
| raise ValueError(f"expected a JSON object: {path}") | |
| return loaded | |
| def load_protocol() -> dict[str, Any]: | |
| return load_yaml(PROTOCOL_PATH) | |
| def load_resolved_config(path: Path) -> dict[str, Any]: | |
| if str(JOURNAL_ROOT) not in sys.path: | |
| sys.path.insert(0, str(JOURNAL_ROOT)) | |
| from gmnet.config import load_config | |
| return load_config(path) | |
| def require_value(config: dict[str, Any], dotted_key: str, expected: Any) -> None: | |
| value: Any = config | |
| for part in dotted_key.split("."): | |
| if not isinstance(value, dict) or part not in value: | |
| raise ValueError(f"missing config value {dotted_key}") | |
| value = value[part] | |
| if value != expected: | |
| raise ValueError( | |
| f"config mismatch for {dotted_key}: {value!r}, expected {expected!r}" | |
| ) | |
| def _assert_exact_config_delta(task: E4Task, config: dict[str, Any]) -> None: | |
| baseline = load_resolved_config(BASELINE_CONFIG_PATH) | |
| expected = copy.deepcopy(baseline) | |
| expected["experiment_id"] = ( | |
| "E4-ImageNet-S3-stop-gradient" | |
| if task.gate_intervention == "stop_gradient" | |
| else "E4-ImageNet-S3-channel-derangement" | |
| ) | |
| expected["protocol_id"] = "e4-imagenet-matched-alignment-v1" | |
| expected["model"]["gate_intervention"] = task.gate_intervention | |
| expected["model"]["gate_intervention_seed"] = task.gate_intervention_seed | |
| if config != expected: | |
| raise ValueError( | |
| f"{task.task_id} must differ from the paper S3 baseline only in " | |
| "experiment/protocol identity and the registered gate intervention" | |
| ) | |
| source = load_yaml(JOURNAL_ROOT / task.config_path) | |
| expected_source_keys = {"base", "experiment_id", "protocol_id", "model"} | |
| if set(source) != expected_source_keys: | |
| raise ValueError(f"unexpected source config keys for {task.task_id}") | |
| if source["base"] != "../e0_baseline/imagenet_gmnet_s3.yaml": | |
| raise ValueError(f"{task.task_id} must inherit the paper S3 baseline") | |
| if source["model"] != { | |
| "gate_intervention": task.gate_intervention, | |
| "gate_intervention_seed": task.gate_intervention_seed, | |
| }: | |
| raise ValueError(f"unexpected model overrides for {task.task_id}") | |
| def validate_task_config( | |
| protocol: dict[str, Any], task: E4Task, config: dict[str, Any] | |
| ) -> None: | |
| invariants = { | |
| "recipe_id": "paper-supplementary-table8-v1", | |
| "protocol_id": "e4-imagenet-matched-alignment-v1", | |
| "model.variant": "s3", | |
| "model.num_classes": 1000, | |
| "model.gate_type": "relu6_self", | |
| "model.gate_intervention": task.gate_intervention, | |
| "model.gate_intervention_seed": task.gate_intervention_seed, | |
| "model.drop_path_rate": 0.02, | |
| "model.f12_bn": False, | |
| "model.projection_bn": True, | |
| "model.second_dw_bn": False, | |
| "data.dataset": "imagenet", | |
| "data.num_classes": 1000, | |
| "data.expected_train_samples": protocol["data"]["expected_train_samples"], | |
| "data.expected_val_samples": protocol["data"]["expected_val_samples"], | |
| "data.expected_manifest_sha256": protocol["data"]["canonical_manifest_sha256"], | |
| "train.epochs": 300, | |
| "train.eval_interval": 300, | |
| "train.fail_on_nonfinite": True, | |
| "train.strict_resume": True, | |
| "train.official_validation_policy": "final_epoch_only", | |
| "train.save_best_checkpoint": False, | |
| } | |
| for key, expected in invariants.items(): | |
| require_value(config, key, expected) | |
| patterns = config.get("optimizer", {}).get("no_weight_decay_patterns") | |
| if not isinstance(patterns, list) or "raw_clip" not in patterns: | |
| raise ValueError(f"{task.task_id} must retain paper optimizer exclusions") | |
| _assert_exact_config_delta(task, config) | |
| def build_tasks(protocol: dict[str, Any] | None = None) -> list[E4Task]: | |
| protocol = load_protocol() if protocol is None else protocol | |
| records = protocol.get("tasks") | |
| if not isinstance(records, list): | |
| raise ValueError("E4 alignment protocol tasks must be a list") | |
| tasks: list[E4Task] = [] | |
| for record in records: | |
| if not isinstance(record, dict): | |
| raise ValueError("each E4 task must be a mapping") | |
| tasks.append( | |
| E4Task( | |
| task_id=str(record["task_id"]), | |
| experiment=str(record["experiment"]), | |
| model=str(record["model"]), | |
| gate=str(record["gate"]), | |
| gate_intervention=str(record["gate_intervention"]), | |
| gate_intervention_seed=int(record["gate_intervention_seed"]), | |
| seed=int(record["seed"]), | |
| config_path=str(record["config_path"]), | |
| role=str(record["role"]), | |
| status=str(record["status"]), | |
| contrast=str(record["contrast"]), | |
| question=str(record["question"]), | |
| ) | |
| ) | |
| validate_protocol(protocol, tasks) | |
| return tasks | |
| def validate_protocol(protocol: dict[str, Any], tasks: list[E4Task]) -> None: | |
| if protocol.get("schema_version") != 1: | |
| raise ValueError("E4 alignment protocol schema_version must be 1") | |
| if protocol.get("protocol_id") != "imagenet-e4-alignment-single-seed-20260716": | |
| raise ValueError("unexpected E4 alignment protocol_id") | |
| if Path(str(protocol.get("run_root"))) != RUN_ROOT: | |
| raise ValueError(f"E4 run_root must be {RUN_ROOT}") | |
| if Path(str(protocol.get("deploy_root"))) != BATCH_ROOT: | |
| raise ValueError(f"E4 deploy_root must be {BATCH_ROOT}") | |
| if protocol.get("code_manifest_path") != CODE_MANIFEST_RELATIVE_PATH: | |
| raise ValueError("unexpected E4 code manifest path") | |
| if Path(str(protocol.get("smoke_evidence_path"))) != SMOKE_EVIDENCE_PATH: | |
| raise ValueError("unexpected E4 smoke evidence path") | |
| if tuple(task.task_id for task in tasks) != TASK_IDS: | |
| raise ValueError("E4 task matrix or ordering drifted") | |
| if tuple(task.gate_intervention for task in tasks) != INTERVENTIONS: | |
| raise ValueError("E4 intervention matrix or ordering drifted") | |
| if len({task.task_id for task in tasks}) != len(tasks): | |
| raise ValueError("duplicate E4 task IDs") | |
| data = protocol.get("data", {}) | |
| data_expected = { | |
| "runtime_root": "/tmp/gmnet_data/imagenet-1k", | |
| "source_archive_uri": ( | |
| "s3://snap-research-cv-code/ywang29/datasets/imagenet-1k/" "imagenet-1k.tar" | |
| ), | |
| "expected_archive_bytes": 161381969920, | |
| "canonical_manifest_sha256": ( | |
| "bb70bc9f530db6bb24f70e648624b35281bfbc76a57775d589a2e0209dd98661" | |
| ), | |
| "expected_train_samples": 1281167, | |
| "expected_val_samples": 50000, | |
| } | |
| for key, expected in data_expected.items(): | |
| if data.get(key) != expected: | |
| raise ValueError(f"E4 data registration drifted: {key}") | |
| for key in ( | |
| "train_sample_index_sha256", | |
| "val_sample_index_sha256", | |
| "train_sampled_content_sha256", | |
| "val_sampled_content_sha256", | |
| ): | |
| require_sha256(data.get(key), f"protocol.data.{key}") | |
| policy = protocol.get("policy", {}) | |
| policy_expected = { | |
| "seed": 0, | |
| "seed_replication_in_scope": False, | |
| "model_variant": "s3", | |
| "baseline_recipe": "paper-supplementary-table8-v1", | |
| "baseline_top1": 78.746, | |
| "intervention_seed": 41041, | |
| "block_seed_stride": 10007, | |
| "gpus_per_job": 8, | |
| "epochs": 300, | |
| "eta_class": "greater_than_12h", | |
| "checkpoint_policy": "fixed_last", | |
| "resume": "auto", | |
| "post_eval": "strict_official", | |
| "approval_marker_required_for_every_task": True, | |
| "approval_requires_8gpu_strict_resume_smoke": True, | |
| "output_lock": "nonblocking_flock", | |
| "launchjob_submitted_by_generator": False, | |
| } | |
| for key, expected in policy_expected.items(): | |
| if policy.get(key) != expected: | |
| raise ValueError(f"E4 policy drifted: {key}") | |
| if protocol.get("relationship_to_prior_work", "").startswith("Post-hoc") is False: | |
| raise ValueError("E4 relationship to prior work must remain post-hoc") | |
| if not protocol.get("known_before_registration"): | |
| raise ValueError("E4 known-results registration is missing") | |
| restrictions = protocol.get("claim_restrictions") | |
| if not isinstance(restrictions, list) or len(restrictions) < 4: | |
| raise ValueError("E4 claim restrictions are incomplete") | |
| for task in tasks: | |
| exact = { | |
| "experiment": "E4", | |
| "model": "s3", | |
| "gate": "relu6_self", | |
| "gate_intervention_seed": 41041, | |
| "seed": 0, | |
| "role": "matched_alignment_retraining", | |
| "status": "ready_after_smoke", | |
| } | |
| for field, expected in exact.items(): | |
| if getattr(task, field) != expected: | |
| raise ValueError(f"E4 task drifted: {task.task_id}/{field}") | |
| if not task.contrast or not task.question: | |
| raise ValueError(f"E4 task rationale is incomplete: {task.task_id}") | |
| config_path = JOURNAL_ROOT / task.config_path | |
| validate_task_config(protocol, task, load_resolved_config(config_path)) | |
| def normalized_training_semantics(config: dict[str, Any]) -> dict[str, Any]: | |
| normalized = copy.deepcopy(config) | |
| normalized.pop("runtime", None) | |
| normalized.pop("experiment_id", None) | |
| protocol = normalized.get("protocol") | |
| if isinstance(protocol, dict): | |
| protocol.pop("code_sha256", None) | |
| if not protocol: | |
| normalized.pop("protocol") | |
| return normalized | |
| def read_code_manifest() -> dict[str, Any]: | |
| manifest = load_json(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH) | |
| if manifest.get("schema_version") != 1: | |
| raise ValueError("E4 code manifest schema_version must be 1") | |
| require_sha256(manifest.get("code_sha256"), "code_manifest.code_sha256") | |
| files = manifest.get("files") | |
| if not isinstance(files, list) or not files: | |
| raise ValueError("E4 code manifest files are missing") | |
| paths = {item.get("path") for item in files if isinstance(item, dict)} | |
| required_paths = { | |
| "configs/e4_alignment_protocol.yaml", | |
| "configs/e4_alignment/imagenet_gmnet_s3_stop_gradient.yaml", | |
| "configs/e4_alignment/imagenet_gmnet_s3_channel_derangement.yaml", | |
| "configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml", | |
| "configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml", | |
| "scripts/audit_e4_alignment_smoke.py", | |
| "scripts/generate_e4_alignment_deploy.py", | |
| "scripts/run_e4_alignment.sh", | |
| } | |
| missing = sorted(required_paths - paths) | |
| if missing: | |
| raise ValueError(f"E4 code manifest scope is incomplete: {missing}") | |
| return manifest | |
| def verify_code_manifest() -> tuple[str, str]: | |
| if str(JOURNAL_ROOT) not in sys.path: | |
| sys.path.insert(0, str(JOURNAL_ROOT)) | |
| from scripts.code_fingerprint import build_manifest | |
| path = JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH | |
| expected = read_code_manifest() | |
| actual = build_manifest(JOURNAL_ROOT) | |
| if actual != expected: | |
| raise ValueError( | |
| "E4 code manifest mismatch: " | |
| f"expected {expected.get('code_sha256')}, " | |
| f"computed {actual.get('code_sha256')}" | |
| ) | |
| return str(expected["code_sha256"]), file_sha256(path) | |
| def verify_historical_baseline(protocol: dict[str, Any]) -> None: | |
| record = protocol.get("historical_baseline") | |
| if not isinstance(record, dict): | |
| raise ValueError("historical baseline registration is missing") | |
| required_registration = { | |
| "evidence_id": "legacy_relu6_s3_seed0", | |
| "acceptance": "accepted_historical_seed0_alias", | |
| "code_provenance": "retrospective_unverified", | |
| "run_dir": "/nfs/ywang29/GmNet/runs/e0_s3_seed0", | |
| "target_config": "configs/e0_baseline/imagenet_gmnet_s3.yaml", | |
| } | |
| for key, expected in required_registration.items(): | |
| if record.get(key) != expected: | |
| raise ValueError(f"historical baseline registration drifted: {key}") | |
| require_sha256( | |
| record.get("semantic_projection_sha256"), | |
| "historical_baseline.semantic_projection_sha256", | |
| ) | |
| run_dir = Path(record["run_dir"]) | |
| expected_files = record.get("expected") | |
| if not isinstance(expected_files, dict) or not expected_files: | |
| raise ValueError("historical baseline hashes are missing") | |
| for relative, expected_sha in expected_files.items(): | |
| require_sha256(expected_sha, f"historical_baseline.expected.{relative}") | |
| path = run_dir / relative | |
| if not path.is_file(): | |
| raise FileNotFoundError(f"missing historical baseline artifact: {path}") | |
| actual_sha = file_sha256(path) | |
| if actual_sha != expected_sha: | |
| raise ValueError( | |
| f"historical baseline hash mismatch for {relative}: {actual_sha}" | |
| ) | |
| official = record.get("official", {}) | |
| checks = load_json(run_dir / "official_eval/checks.json") | |
| results = load_json(run_dir / "official_eval/results.json") | |
| manifest = load_json(run_dir / "data_manifest.json") | |
| if checks.get("status") != "passed": | |
| raise ValueError("historical baseline official checks did not pass") | |
| if checks.get("checkpoint_sha256") != expected_files["checkpoint_last.pt"]: | |
| raise ValueError("historical baseline checkpoint identity drifted") | |
| if checks.get("artifacts_sha256") != official.get("artifacts_sha256"): | |
| raise ValueError("historical baseline artifact identity drifted") | |
| if results.get("status") != "complete" or results.get("partial_evaluation"): | |
| raise ValueError("historical baseline evaluation is incomplete") | |
| scalar_expected = { | |
| "run_name": "e0_s3_seed0", | |
| "seed": 0, | |
| "gate_type": "relu6_self", | |
| "checkpoint_epoch": 299, | |
| "training_epochs": 300, | |
| } | |
| for key, expected in scalar_expected.items(): | |
| if results.get(key) != expected: | |
| raise ValueError(f"historical baseline result drifted: {key}") | |
| if not math.isclose( | |
| float(results.get("metrics", {}).get("top1", float("nan"))), | |
| float(official.get("top1", float("nan"))), | |
| rel_tol=0.0, | |
| abs_tol=1e-9, | |
| ): | |
| raise ValueError("historical baseline Top-1 drifted") | |
| if results.get("metrics", {}).get("samples") != 50000: | |
| raise ValueError("historical baseline evaluated sample count drifted") | |
| hashes = results.get("hashes", {}) | |
| if hashes.get("config_sha256") != official.get("checkpoint_config_sha256"): | |
| raise ValueError("historical baseline checkpoint config identity drifted") | |
| if ( | |
| hashes.get("checkpoint_data_manifest_sha256") | |
| != protocol["data"]["canonical_manifest_sha256"] | |
| ): | |
| raise ValueError("historical baseline checkpoint data identity drifted") | |
| topology = results.get("topology", {}) | |
| for key in ("parameter_count", "state_tensor_count", "model_state_schema_sha256"): | |
| if topology.get(key) != official.get(key): | |
| raise ValueError(f"historical baseline topology drifted: {key}") | |
| completion_expected = { | |
| "epoch_complete": True, | |
| "expected_global_step": 187500, | |
| "expected_steps_per_epoch": 625, | |
| "global_step": 187500, | |
| "steps_in_epoch": 625, | |
| "training_complete": True, | |
| "world_size": 8, | |
| } | |
| completion = results.get("training_completion", {}) | |
| for key, expected in completion_expected.items(): | |
| if completion.get(key) != expected: | |
| raise ValueError(f"historical training completion drifted: {key}") | |
| data = protocol["data"] | |
| data_expected = { | |
| "manifest_sha256": data["canonical_manifest_sha256"], | |
| "num_classes": 1000, | |
| "samples": { | |
| "train": data["expected_train_samples"], | |
| "val": data["expected_val_samples"], | |
| }, | |
| "sample_index_sha256": { | |
| "train": data["train_sample_index_sha256"], | |
| "val": data["val_sample_index_sha256"], | |
| }, | |
| "sampled_content_sha256": { | |
| "train": data["train_sampled_content_sha256"], | |
| "val": data["val_sampled_content_sha256"], | |
| }, | |
| } | |
| for key, expected in data_expected.items(): | |
| if manifest.get(key) != expected: | |
| raise ValueError(f"historical data manifest drifted: {key}") | |
| resolved = load_yaml(run_dir / "config_resolved.yaml") | |
| target = load_resolved_config(JOURNAL_ROOT / record["target_config"]) | |
| legacy_semantics = normalized_training_semantics(resolved) | |
| target_semantics = normalized_training_semantics(target) | |
| if legacy_semantics != target_semantics: | |
| raise ValueError("historical/current baseline config semantics differ") | |
| if stable_sha256(legacy_semantics) != record["semantic_projection_sha256"]: | |
| raise ValueError("historical baseline semantic projection drifted") | |
| def verify_smoke_evidence( | |
| protocol: dict[str, Any], | |
| tasks: list[E4Task], | |
| code_sha256: str, | |
| manifest_sha256: str, | |
| ) -> tuple[dict[str, Any], str]: | |
| evidence = load_json(SMOKE_EVIDENCE_PATH) | |
| required = { | |
| "schema_version": 1, | |
| "protocol_id": protocol["protocol_id"], | |
| "status": "passed", | |
| "code_sha256": code_sha256, | |
| "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH, | |
| "code_manifest_sha256": manifest_sha256, | |
| "world_size": 8, | |
| "strict_resume": True, | |
| } | |
| for key, expected in required.items(): | |
| if evidence.get(key) != expected: | |
| raise ApprovalError(f"E4 smoke evidence field drifted: {key}") | |
| smoke_tasks = evidence.get("tasks") | |
| if not isinstance(smoke_tasks, dict) or set(smoke_tasks) != set(TASK_IDS): | |
| raise ApprovalError("E4 smoke evidence task matrix or ordering drifted") | |
| for task in tasks: | |
| record = smoke_tasks.get(task.task_id) | |
| if not isinstance(record, dict): | |
| raise ApprovalError(f"missing E4 smoke task: {task.task_id}") | |
| task_required = { | |
| "gate_intervention": task.gate_intervention, | |
| "gate_intervention_seed": task.gate_intervention_seed, | |
| "resume_verified": True, | |
| "training_complete": True, | |
| } | |
| for key, expected in task_required.items(): | |
| if record.get(key) != expected: | |
| raise ApprovalError(f"E4 smoke evidence drifted: {task.task_id}/{key}") | |
| first = require_sha256( | |
| record.get("checkpoint_epoch0_sha256"), | |
| f"smoke.tasks.{task.task_id}.checkpoint_epoch0_sha256", | |
| ) | |
| final = require_sha256( | |
| record.get("checkpoint_last_sha256"), | |
| f"smoke.tasks.{task.task_id}.checkpoint_last_sha256", | |
| ) | |
| if first == final: | |
| raise ApprovalError( | |
| f"E4 smoke resume did not advance checkpoint: {task.task_id}" | |
| ) | |
| return evidence, file_sha256(SMOKE_EVIDENCE_PATH) | |
| def load_base_invariants() -> dict[str, Any]: | |
| source = load_yaml(BASE_TEMPLATE) | |
| required = (*RESOURCE_KEYS, *PROJECT_KEYS) | |
| missing = [key for key in required if key not in source] | |
| if missing: | |
| raise ValueError(f"base launch template missing: {', '.join(missing)}") | |
| if source.get("gpu_num") != "8" or source.get("gpu_type") != "nvidia-tesla-a100": | |
| raise ValueError("base launch template must request eight A100 GPUs") | |
| mounts = source.get("mount") | |
| if not isinstance(mounts, list): | |
| raise ValueError("base launch template mounts are invalid") | |
| mount_paths = {item.get("mount_path") for item in mounts if isinstance(item, dict)} | |
| if "/nfs" not in mount_paths or "/s3-code" not in mount_paths: | |
| raise ValueError("base launch template is missing required NFS/S3 mounts") | |
| return {key: copy.deepcopy(source[key]) for key in required} | |
| def _deny_completed_output(task: E4Task) -> None: | |
| checks_path = task.output_dir / "official_eval/checks.json" | |
| if not checks_path.is_file(): | |
| return | |
| try: | |
| checks = load_json(checks_path) | |
| except (json.JSONDecodeError, ValueError): | |
| return | |
| if checks.get("status") == "passed": | |
| raise ApprovalError( | |
| f"E4 guard denied {task.task_id}: output already passed official evaluation" | |
| ) | |
| def approval_payload( | |
| protocol: dict[str, Any], | |
| task: E4Task, | |
| code_sha256: str, | |
| manifest_sha256: str, | |
| smoke: dict[str, Any], | |
| smoke_sha256: str, | |
| ) -> dict[str, Any]: | |
| smoke_task = smoke["tasks"][task.task_id] | |
| return { | |
| "schema_version": 1, | |
| "protocol_id": protocol["protocol_id"], | |
| "task_id": task.task_id, | |
| "status": "approved", | |
| "approval_basis": "passed_8gpu_strict_resume_smoke", | |
| "config_path": task.config_path, | |
| "output_dir": str(task.output_dir), | |
| "gate_intervention": task.gate_intervention, | |
| "gate_intervention_seed": task.gate_intervention_seed, | |
| "code_sha256": code_sha256, | |
| "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH, | |
| "code_manifest_sha256": manifest_sha256, | |
| "smoke_evidence_path": str(SMOKE_EVIDENCE_PATH), | |
| "smoke_evidence_sha256": smoke_sha256, | |
| "smoke_checkpoint_last_sha256": smoke_task["checkpoint_last_sha256"], | |
| } | |
| def verify_approval( | |
| protocol: dict[str, Any], | |
| task: E4Task, | |
| code_sha256: str, | |
| manifest_sha256: str, | |
| smoke: dict[str, Any], | |
| smoke_sha256: str, | |
| ) -> None: | |
| if not task.approval_path.is_file(): | |
| raise ApprovalError( | |
| f"E4 guard denied {task.task_id}: missing {task.approval_path}" | |
| ) | |
| marker = load_json(task.approval_path) | |
| expected = approval_payload( | |
| protocol, | |
| task, | |
| code_sha256, | |
| manifest_sha256, | |
| smoke, | |
| smoke_sha256, | |
| ) | |
| if marker != expected: | |
| drifted = sorted( | |
| key | |
| for key in set(marker) | set(expected) | |
| if marker.get(key) != expected.get(key) | |
| ) | |
| raise ApprovalError( | |
| f"E4 guard denied {task.task_id}: approval drifted ({','.join(drifted)})" | |
| ) | |
| def verify_task(task_id: str, require_approval: bool) -> None: | |
| protocol = load_protocol() | |
| tasks = build_tasks(protocol) | |
| task = next((item for item in tasks if item.task_id == task_id), None) | |
| if task is None: | |
| raise ValueError(f"unknown E4 alignment task: {task_id}") | |
| code_sha256, manifest_sha256 = verify_code_manifest() | |
| verify_historical_baseline(protocol) | |
| smoke, smoke_sha256 = verify_smoke_evidence( | |
| protocol, tasks, code_sha256, manifest_sha256 | |
| ) | |
| _deny_completed_output(task) | |
| if require_approval: | |
| verify_approval( | |
| protocol, | |
| task, | |
| code_sha256, | |
| manifest_sha256, | |
| smoke, | |
| smoke_sha256, | |
| ) | |
| print( | |
| f"Verified E4 alignment task {task.task_id}: code={code_sha256}, " | |
| f"smoke={smoke_sha256}, baseline={protocol['historical_baseline']['evidence_id']}" | |
| ) | |
| def build_launch_document( | |
| protocol: dict[str, Any], task: E4Task, invariants: dict[str, Any] | |
| ) -> dict[str, Any]: | |
| verify = ( | |
| "/tmp/gmnet_venv/bin/python " | |
| "scripts/generate_e4_alignment_deploy.py " | |
| f"--verify-task {task.task_id} --require-approval" | |
| ) | |
| pre_run = ( | |
| f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && " | |
| "INSTALL_DEV=0 bash ./scripts/setup_env.sh && " | |
| f"{verify} && " | |
| "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full && " | |
| f"{verify}" | |
| ) | |
| assignments = " ".join( | |
| ( | |
| f"RUN_NAME={task.task_id}", | |
| f"CONFIG_PATH={task.config_path}", | |
| f"DATA_ROOT={protocol['data']['runtime_root']}", | |
| f"OUTPUT_DIR={task.output_dir}", | |
| f"SEED={task.seed}", | |
| "NPROC_PER_NODE=8", | |
| "RESUME=auto", | |
| "POST_EVAL=1", | |
| f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}", | |
| ) | |
| ) | |
| command = ( | |
| f"cd {JOURNAL_ROOT} && {verify} && {assignments} " | |
| "bash scripts/run_e4_alignment.sh" | |
| ) | |
| document: dict[str, Any] = { | |
| key: copy.deepcopy(invariants[key]) for key in RESOURCE_KEYS | |
| } | |
| document["script"] = { | |
| "pre_run_event": pre_run, | |
| "command": command, | |
| "jobs": [{"name": task.job_name}], | |
| } | |
| document.update({key: copy.deepcopy(invariants[key]) for key in PROJECT_KEYS}) | |
| return document | |
| def dump_yaml(value: Any) -> str: | |
| return GENERATED_HEADER + yaml.safe_dump( | |
| value, | |
| sort_keys=False, | |
| default_flow_style=False, | |
| width=1_000_000, | |
| ) | |
| def build_batch_manifest( | |
| protocol: dict[str, Any], | |
| tasks: list[E4Task], | |
| code_sha256: str, | |
| manifest_sha256: str, | |
| smoke_sha256: str, | |
| ) -> dict[str, Any]: | |
| records = [] | |
| for task in tasks: | |
| record = asdict(task) | |
| record.update( | |
| { | |
| "deploy_path": str(task.deploy_path), | |
| "approval_path": str(task.approval_path), | |
| "output_dir": str(task.output_dir), | |
| "job_name": task.job_name, | |
| "eta_class": ">12h", | |
| } | |
| ) | |
| records.append(record) | |
| return { | |
| "schema_version": 1, | |
| "protocol_id": protocol["protocol_id"], | |
| "protocol_source": str(PROTOCOL_PATH), | |
| "protocol_sha256": file_sha256(PROTOCOL_PATH), | |
| "generated_by": str(SCRIPT_PATH), | |
| "source_template": str(BASE_TEMPLATE), | |
| "source_template_sha256": file_sha256(BASE_TEMPLATE), | |
| "code_manifest_path": CODE_MANIFEST_RELATIVE_PATH, | |
| "code_manifest_sha256": manifest_sha256, | |
| "code_sha256": code_sha256, | |
| "smoke_evidence_path": str(SMOKE_EVIDENCE_PATH), | |
| "smoke_evidence_sha256": smoke_sha256, | |
| "historical_baseline": copy.deepcopy(protocol["historical_baseline"]), | |
| "relationship_to_prior_work": protocol["relationship_to_prior_work"], | |
| "known_before_registration": copy.deepcopy( | |
| protocol["known_before_registration"] | |
| ), | |
| "claim_restrictions": copy.deepcopy(protocol["claim_restrictions"]), | |
| "policy": copy.deepcopy(protocol["policy"]), | |
| "data": copy.deepcopy(protocol["data"]), | |
| "run_root": str(RUN_ROOT), | |
| "summary": { | |
| "task_count": len(tasks), | |
| "approved_count": len(tasks), | |
| "seed_count": 1, | |
| }, | |
| "tasks": records, | |
| } | |
| def expected_files() -> dict[Path, str]: | |
| protocol = load_protocol() | |
| tasks = build_tasks(protocol) | |
| code_sha256, manifest_sha256 = verify_code_manifest() | |
| verify_historical_baseline(protocol) | |
| smoke, smoke_sha256 = verify_smoke_evidence( | |
| protocol, tasks, code_sha256, manifest_sha256 | |
| ) | |
| invariants = load_base_invariants() | |
| files = { | |
| task.deploy_path: dump_yaml(build_launch_document(protocol, task, invariants)) | |
| for task in tasks | |
| } | |
| files[BATCH_ROOT / "batch_manifest.json"] = ( | |
| json.dumps( | |
| build_batch_manifest( | |
| protocol, tasks, code_sha256, manifest_sha256, smoke_sha256 | |
| ), | |
| indent=2, | |
| sort_keys=True, | |
| ) | |
| + "\n" | |
| ) | |
| for task in tasks: | |
| files[task.approval_path] = ( | |
| json.dumps( | |
| approval_payload( | |
| protocol, | |
| task, | |
| code_sha256, | |
| manifest_sha256, | |
| smoke, | |
| smoke_sha256, | |
| ), | |
| indent=2, | |
| sort_keys=True, | |
| ) | |
| + "\n" | |
| ) | |
| return files | |
| def write_files(files: dict[Path, str]) -> None: | |
| for path, content in files.items(): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| if path.is_file() and path.read_text(encoding="utf-8") == content: | |
| continue | |
| temporary = path.with_name(f".{path.name}.tmp") | |
| temporary.write_text(content, encoding="utf-8") | |
| temporary.replace(path) | |
| expected = set(files) | |
| for path in BATCH_ROOT.glob("*.yaml"): | |
| if path in expected: | |
| continue | |
| if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER): | |
| path.unlink() | |
| def check_files(files: dict[Path, str]) -> list[str]: | |
| errors = [] | |
| for path, expected in files.items(): | |
| if not path.is_file(): | |
| errors.append(f"missing: {path}") | |
| elif path.read_text(encoding="utf-8") != expected: | |
| errors.append(f"stale: {path}") | |
| for path in BATCH_ROOT.glob("*.yaml"): | |
| if path in files: | |
| continue | |
| if path.read_text(encoding="utf-8").startswith(GENERATED_HEADER): | |
| errors.append(f"stale generated file: {path}") | |
| return errors | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| action = parser.add_mutually_exclusive_group() | |
| action.add_argument("--check", action="store_true") | |
| action.add_argument("--verify-task") | |
| parser.add_argument("--require-approval", action="store_true") | |
| return parser.parse_args() | |
| def main() -> int: | |
| args = parse_args() | |
| try: | |
| if args.verify_task: | |
| verify_task(args.verify_task, args.require_approval) | |
| return 0 | |
| files = expected_files() | |
| tasks = build_tasks() | |
| if args.check: | |
| errors = check_files(files) | |
| if errors: | |
| print("\n".join(errors), file=sys.stderr) | |
| return 1 | |
| print( | |
| f"Validated {len(tasks)} E4 launch YAMLs, batch manifest, " | |
| "approvals, code, smoke, and historical baseline" | |
| ) | |
| return 0 | |
| write_files(files) | |
| print( | |
| f"Generated {len(tasks)} E4 launch YAMLs under {BATCH_ROOT}; " | |
| "no launchjob was submitted" | |
| ) | |
| return 0 | |
| except ApprovalError as error: | |
| print(str(error), file=sys.stderr) | |
| return 64 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |