File size: 33,762 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 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 | #!/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."""
@dataclass(frozen=True)
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
@property
def output_dir(self) -> Path:
return RUN_ROOT / self.task_id
@property
def deploy_path(self) -> Path:
return BATCH_ROOT / f"{self.task_id}.yaml"
@property
def approval_path(self) -> Path:
return APPROVAL_ROOT / f"{self.task_id}.json"
@property
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())
|