Download gmnet/code/journal_exp/scripts/generate_single_seed_followup.py from YFanwang/Backup: direct link, hf CLI and curl.
- Browser
- Download file 29.3 kB
-
https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/scripts/generate_single_seed_followup.py
- Command line
-
hf download hf://datasets/YFanwang/Backup/gmnet/code/journal_exp/scripts/generate_single_seed_followup.py
-
curl -L -o generate_single_seed_followup.py https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/scripts/generate_single_seed_followup.py
29.3 kB
| #!/usr/bin/env python3 | |
| """Generate and fail-closed validate the single-seed ImageNet follow-up batch.""" | |
| from __future__ import annotations | |
| import argparse | |
| import copy | |
| import hashlib | |
| import json | |
| import math | |
| import sys | |
| from dataclasses import asdict, dataclass | |
| from datetime import datetime, timezone | |
| 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/single_seed_followup_protocol.yaml" | |
| BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml") | |
| BATCH_ROOT = GMNET_ROOT / "depoly/single_seed_followup_20260715" | |
| RUN_ROOT = GMNET_ROOT / "runs/single_seed_followup" | |
| CODE_MANIFEST_RELATIVE_PATH = "configs/imagenet_v2_code_manifest.json" | |
| GENERATED_HEADER = ( | |
| "# Generated by journal_exp/scripts/generate_single_seed_followup.py; " | |
| "do not edit.\n" | |
| ) | |
| APPROVAL_ROOT = BATCH_ROOT / "approvals" | |
| TASK_IDS = ( | |
| "ssfu_e3_s3_no_gate_seed0", | |
| "ssfu_e3_s3_relu6_only_seed0", | |
| "ssfu_e3_s3_smooth_fixed_c6_seed0", | |
| "ssfu_e0_s3_release_paperbn_seed0", | |
| ) | |
| 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 a launch is intentionally denied by the batch protocol.""" | |
| class FollowupTask: | |
| task_id: str | |
| experiment: str | |
| model: str | |
| gate: str | |
| seed: int | |
| config_path: str | |
| role: str | |
| status: str | |
| submission_allowed: bool | |
| evidence: tuple[str, ...] | |
| contrast: str | |
| question: str | |
| trigger: dict[str, Any] | None = None | |
| 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 load_yaml(path: Path) -> dict[str, Any]: | |
| 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_protocol() -> dict[str, Any]: | |
| return load_yaml(PROTOCOL_PATH) | |
| def build_tasks(protocol: dict[str, Any] | None = None) -> list[FollowupTask]: | |
| protocol = load_protocol() if protocol is None else protocol | |
| records = protocol.get("tasks") | |
| if not isinstance(records, list): | |
| raise ValueError("follow-up protocol tasks must be a list") | |
| tasks = [ | |
| FollowupTask( | |
| task_id=str(record["task_id"]), | |
| experiment=str(record["experiment"]), | |
| model=str(record["model"]), | |
| gate=str(record["gate"]), | |
| seed=int(record["seed"]), | |
| config_path=str(record["config_path"]), | |
| role=str(record["role"]), | |
| status=str(record["status"]), | |
| submission_allowed=bool(record["submission_allowed"]), | |
| evidence=tuple(record.get("evidence", [])), | |
| contrast=str(record["contrast"]), | |
| question=str(record["question"]), | |
| trigger=copy.deepcopy(record.get("trigger")), | |
| ) | |
| for record in records | |
| ] | |
| validate_protocol(protocol, tasks) | |
| return tasks | |
| 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 validate_task_config( | |
| protocol: dict[str, Any], task: FollowupTask, config: dict[str, Any] | |
| ) -> None: | |
| release_audit = task.role == "conditional_recipe_audit" | |
| expected_gate = ( | |
| "smooth_clipped_self" | |
| if task.gate == "smooth_clipped_self_fixed_c6" | |
| else task.gate | |
| ) | |
| common = { | |
| "model.variant": task.model, | |
| "model.gate_type": expected_gate, | |
| "model.num_classes": 1000, | |
| "model.f12_bn": False, | |
| "model.projection_bn": True, | |
| "model.second_dw_bn": False, | |
| "data.dataset": "imagenet", | |
| "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.fail_on_nonfinite": True, | |
| "train.strict_resume": True, | |
| "train.official_validation_policy": "final_epoch_only", | |
| "train.save_best_checkpoint": False, | |
| } | |
| for key, expected in common.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 exclude raw_clip from weight decay") | |
| if release_audit: | |
| require_value(config, "recipe_id", "release-readme-legacy-audit-only") | |
| require_value(config, "model.drop_path_rate", 0.0) | |
| require_value(config, "train.epochs", 310) | |
| require_value(config, "train.eval_interval", 310) | |
| else: | |
| require_value(config, "recipe_id", "paper-supplementary-table8-v1") | |
| require_value(config, "model.drop_path_rate", 0.02) | |
| require_value(config, "train.epochs", 300) | |
| require_value(config, "train.eval_interval", 300) | |
| if task.gate == "smooth_clipped_self_fixed_c6": | |
| require_value(config, "model.smooth_clip_init", 6.0) | |
| require_value(config, "model.smooth_clip_beta", 10.0) | |
| require_value(config, "model.smooth_clip_per_channel", False) | |
| require_value(config, "model.smooth_clip_trainable", False) | |
| def validate_protocol(protocol: dict[str, Any], tasks: list[FollowupTask]) -> None: | |
| if protocol.get("schema_version") != 1: | |
| raise ValueError("follow-up protocol schema_version must be 1") | |
| if protocol.get("protocol_id") != "imagenet-single-seed-followup-20260715": | |
| raise ValueError("unexpected follow-up protocol_id") | |
| if Path(str(protocol.get("run_root"))) != RUN_ROOT: | |
| raise ValueError(f"follow-up run_root must be {RUN_ROOT}") | |
| if Path(str(protocol.get("deploy_root"))) != BATCH_ROOT: | |
| raise ValueError(f"follow-up deploy_root must be {BATCH_ROOT}") | |
| if protocol.get("code_manifest_path") != CODE_MANIFEST_RELATIVE_PATH: | |
| raise ValueError("unexpected follow-up code manifest path") | |
| if tuple(task.task_id for task in tasks) != TASK_IDS: | |
| raise ValueError("follow-up task matrix or ordering drifted") | |
| if len(set(TASK_IDS)) != len(TASK_IDS): | |
| raise ValueError("duplicate follow-up task IDs") | |
| parent = protocol["parent_protocol"] | |
| parent_path = JOURNAL_ROOT / str(parent["path"]) | |
| if file_sha256(parent_path) != parent["sha256"]: | |
| raise ValueError("parent ImageNet-v2 protocol hash drifted") | |
| resume = protocol["historical_resume_manifest"] | |
| if file_sha256(Path(str(resume["path"]))) != resume["sha256"]: | |
| raise ValueError("historical resume manifest hash drifted") | |
| evidence_ids = set(protocol.get("legacy_evidence", {})) | |
| ready = [] | |
| for task in tasks: | |
| if task.seed != 0: | |
| raise ValueError(f"non-seed0 task is outside this batch: {task.task_id}") | |
| if task.status not in {"ready", "conditional"}: | |
| raise ValueError(f"invalid task status: {task.task_id}") | |
| if task.submission_allowed != (task.status == "ready"): | |
| raise ValueError(f"task status/permission mismatch: {task.task_id}") | |
| if not task.evidence or not set(task.evidence).issubset(evidence_ids): | |
| raise ValueError(f"missing or unknown evidence for {task.task_id}") | |
| if task.status == "conditional" and task.trigger is None: | |
| raise ValueError(f"conditional task lacks trigger: {task.task_id}") | |
| if task.status == "ready": | |
| ready.append(task.task_id) | |
| config_path = JOURNAL_ROOT / task.config_path | |
| if not config_path.is_file(): | |
| raise FileNotFoundError(config_path) | |
| validate_task_config(protocol, task, load_resolved_config(config_path)) | |
| if ready != list(TASK_IDS[:3]): | |
| raise ValueError("only the three mechanism tasks may be initially ready") | |
| 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 _assert_finite(value: Any, location: str) -> None: | |
| if isinstance(value, float) and not math.isfinite(value): | |
| raise ValueError(f"non-finite value at {location}") | |
| if isinstance(value, dict): | |
| for key, child in value.items(): | |
| _assert_finite(child, f"{location}.{key}") | |
| elif isinstance(value, list): | |
| for index, child in enumerate(value): | |
| _assert_finite(child, f"{location}[{index}]") | |
| def verify_evidence(protocol: dict[str, Any], evidence_id: str) -> None: | |
| record = protocol["legacy_evidence"][evidence_id] | |
| if record.get("acceptance") != "accepted_historical_seed0_alias": | |
| raise ValueError(f"invalid evidence acceptance: {evidence_id}") | |
| if record.get("code_provenance") != "retrospective_unverified": | |
| raise ValueError(f"legacy provenance must remain unverified: {evidence_id}") | |
| run_dir = Path(str(record["run_dir"])) | |
| for relative, expected_sha in record["expected"].items(): | |
| path = run_dir / relative | |
| if not path.is_file(): | |
| raise FileNotFoundError(f"missing evidence file: {path}") | |
| actual_sha = file_sha256(path) | |
| if actual_sha != expected_sha: | |
| raise ValueError( | |
| f"evidence hash mismatch for {evidence_id}/{relative}: {actual_sha}" | |
| ) | |
| expected = record["expected"] | |
| official = record["official"] | |
| checks = json.loads( | |
| (run_dir / "official_eval/checks.json").read_text(encoding="utf-8") | |
| ) | |
| results = json.loads( | |
| (run_dir / "official_eval/results.json").read_text(encoding="utf-8") | |
| ) | |
| manifest = json.loads((run_dir / "data_manifest.json").read_text(encoding="utf-8")) | |
| if checks.get("status") != "passed": | |
| raise ValueError(f"official check did not pass: {evidence_id}") | |
| if checks.get("checkpoint_sha256") != expected["checkpoint_last.pt"]: | |
| raise ValueError(f"official checkpoint identity mismatch: {evidence_id}") | |
| if checks.get("artifacts_sha256") != official["artifacts_sha256"]: | |
| raise ValueError(f"official artifact identity mismatch: {evidence_id}") | |
| if results.get("status") != "complete" or results.get("partial_evaluation"): | |
| raise ValueError(f"official evaluation is not complete: {evidence_id}") | |
| if results.get("run_name") != official["run_name"]: | |
| raise ValueError(f"official run identity mismatch: {evidence_id}") | |
| if results.get("seed") != 0 or results.get("gate_type") != official["gate_type"]: | |
| raise ValueError(f"official seed/gate mismatch: {evidence_id}") | |
| if not math.isclose( | |
| float(results["metrics"]["top1"]), | |
| float(official["top1"]), | |
| rel_tol=0.0, | |
| abs_tol=1e-9, | |
| ): | |
| raise ValueError(f"official Top-1 mismatch: {evidence_id}") | |
| if results["metrics"].get("samples") != protocol["data"]["expected_val_samples"]: | |
| raise ValueError(f"official sample count mismatch: {evidence_id}") | |
| if results["hashes"].get("config_sha256") != official["checkpoint_config_sha256"]: | |
| raise ValueError(f"checkpoint config identity mismatch: {evidence_id}") | |
| if ( | |
| results["hashes"].get("checkpoint_data_manifest_sha256") | |
| != protocol["data"]["canonical_manifest_sha256"] | |
| ): | |
| raise ValueError(f"checkpoint data identity mismatch: {evidence_id}") | |
| topology = results["topology"] | |
| if ( | |
| topology.get("parameter_count") != official["parameter_count"] | |
| or topology.get("state_tensor_count") != official["state_tensor_count"] | |
| ): | |
| raise ValueError(f"topology mismatch: {evidence_id}") | |
| completion = results["training_completion"] | |
| expected_completion = { | |
| "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, | |
| } | |
| for key, value in expected_completion.items(): | |
| if completion.get(key) != value: | |
| raise ValueError(f"training completion mismatch: {evidence_id}/{key}") | |
| if results.get("checkpoint_epoch") != 299 or results.get("training_epochs") != 300: | |
| raise ValueError(f"training epoch mismatch: {evidence_id}") | |
| data = protocol["data"] | |
| manifest_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, value in manifest_expected.items(): | |
| if manifest.get(key) != value: | |
| raise ValueError(f"data manifest mismatch: {evidence_id}/{key}") | |
| resolved = load_yaml(run_dir / "config_resolved.yaml") | |
| runtime = resolved.get("runtime", {}) | |
| runtime_expected = { | |
| "run_name": official["run_name"], | |
| "seed": 0, | |
| "world_size": 8, | |
| "data_manifest_sha256": data["canonical_manifest_sha256"], | |
| "config_fingerprint": official["checkpoint_config_sha256"], | |
| } | |
| for key, value in runtime_expected.items(): | |
| if runtime.get(key) != value: | |
| raise ValueError(f"resolved runtime mismatch: {evidence_id}/{key}") | |
| 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(f"legacy/current config semantics differ: {evidence_id}") | |
| semantic_sha = stable_sha256(legacy_semantics) | |
| if semantic_sha != record["semantic_projection_sha256"]: | |
| raise ValueError(f"semantic projection hash mismatch: {evidence_id}") | |
| final_epochs = [] | |
| for line_number, line in enumerate( | |
| (run_dir / "metrics.jsonl").read_text(encoding="utf-8").splitlines(), 1 | |
| ): | |
| metric = json.loads(line) | |
| _assert_finite(metric, f"{evidence_id}.metrics[{line_number}]") | |
| if metric.get("kind") == "epoch" and metric.get("epoch") == 299: | |
| final_epochs.append(metric) | |
| if not any( | |
| item.get("epoch_complete") | |
| and item.get("training_complete") | |
| and item.get("global_step") == 187500 | |
| for item in final_epochs | |
| ): | |
| raise ValueError(f"missing complete final epoch metric: {evidence_id}") | |
| if evidence_id == "legacy_learned_smooth_s3_seed0": | |
| model = resolved["model"] | |
| if ( | |
| model.get("smooth_clip_trainable") is not True | |
| or model.get("smooth_clip_init") != 6.0 | |
| or model.get("smooth_clip_beta") != 10.0 | |
| or model.get("smooth_clip_per_channel") is not False | |
| or "raw_clip" | |
| not in resolved["optimizer"].get("no_weight_decay_patterns", []) | |
| ): | |
| raise ValueError("historical smooth controller semantics drifted") | |
| def read_code_manifest() -> dict[str, Any]: | |
| path = JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH | |
| manifest = json.loads(path.read_text(encoding="utf-8")) | |
| if not isinstance(manifest.get("code_sha256"), str): | |
| raise ValueError("invalid code manifest") | |
| return manifest | |
| def verify_code_manifest() -> str: | |
| if str(JOURNAL_ROOT) not in sys.path: | |
| sys.path.insert(0, str(JOURNAL_ROOT)) | |
| from scripts.code_fingerprint import build_manifest | |
| expected = read_code_manifest() | |
| actual = build_manifest(JOURNAL_ROOT) | |
| if actual != expected: | |
| raise ValueError( | |
| "code manifest mismatch: " | |
| f"expected {expected.get('code_sha256')}, " | |
| f"computed {actual.get('code_sha256')}" | |
| ) | |
| return str(expected["code_sha256"]) | |
| def trigger_is_met(protocol: dict[str, Any], task: FollowupTask) -> bool: | |
| if task.trigger is None: | |
| return True | |
| trigger = task.trigger | |
| evidence = protocol["legacy_evidence"][trigger["evidence"]] | |
| observed = float(evidence["official"][trigger["metric"]]) | |
| if not math.isclose( | |
| observed, float(trigger["observed"]), rel_tol=0.0, abs_tol=1e-9 | |
| ): | |
| raise ValueError(f"conditional trigger observation drifted: {task.task_id}") | |
| if trigger["operator"] != "less_than": | |
| raise ValueError(f"unsupported trigger operator: {task.task_id}") | |
| met = observed < float(trigger["threshold"]) | |
| if (trigger.get("state") == "met") != met: | |
| raise ValueError(f"conditional trigger state drifted: {task.task_id}") | |
| return met | |
| def approval_payload( | |
| protocol: dict[str, Any], | |
| task: FollowupTask, | |
| *, | |
| conditional: bool = False, | |
| ) -> dict[str, Any]: | |
| return { | |
| "schema_version": 1, | |
| "protocol_id": protocol["protocol_id"], | |
| "task_id": task.task_id, | |
| "status": "approved", | |
| "approval_basis": ( | |
| "manual_conditional_trigger_acknowledgement" | |
| if conditional | |
| else "registered_ready_task" | |
| ), | |
| "approved_at_utc": ( | |
| datetime.now(timezone.utc).isoformat() | |
| if conditional | |
| else protocol["registered_at_utc"] | |
| ), | |
| "config_path": task.config_path, | |
| "output_dir": str(task.output_dir), | |
| "code_sha256": read_code_manifest()["code_sha256"], | |
| } | |
| def verify_approval( | |
| protocol: dict[str, Any], task: FollowupTask, code_sha256: str | |
| ) -> None: | |
| if not task.approval_path.is_file(): | |
| raise ApprovalError( | |
| f"Follow-up guard denied {task.task_id}: missing " f"{task.approval_path}" | |
| ) | |
| marker = json.loads(task.approval_path.read_text(encoding="utf-8")) | |
| required = { | |
| "schema_version": 1, | |
| "protocol_id": protocol["protocol_id"], | |
| "task_id": task.task_id, | |
| "status": "approved", | |
| "config_path": task.config_path, | |
| "output_dir": str(task.output_dir), | |
| "code_sha256": code_sha256, | |
| } | |
| for key, expected in required.items(): | |
| if marker.get(key) != expected: | |
| raise ApprovalError( | |
| f"Follow-up guard denied {task.task_id}: marker field {key} drifted" | |
| ) | |
| expected_basis = ( | |
| "registered_ready_task" | |
| if task.status == "ready" | |
| else "manual_conditional_trigger_acknowledgement" | |
| ) | |
| if marker.get("approval_basis") != expected_basis: | |
| raise ApprovalError( | |
| f"Follow-up guard denied {task.task_id}: approval basis drifted" | |
| ) | |
| if task.status == "conditional" and not trigger_is_met(protocol, task): | |
| raise ApprovalError( | |
| f"Follow-up guard denied {task.task_id}: trigger is not met" | |
| ) | |
| def verify_task(task_id: str, require_approval: bool) -> None: | |
| protocol = load_protocol() | |
| tasks = build_tasks(protocol) | |
| try: | |
| task = next(task for task in tasks if task.task_id == task_id) | |
| except StopIteration as error: | |
| raise ValueError(f"unknown follow-up task: {task_id}") from error | |
| code_sha256 = verify_code_manifest() | |
| for evidence_id in task.evidence: | |
| verify_evidence(protocol, evidence_id) | |
| if require_approval: | |
| verify_approval(protocol, task, code_sha256) | |
| print( | |
| f"Verified follow-up task {task.task_id}: code={code_sha256}, " | |
| f"evidence={','.join(task.evidence)}" | |
| ) | |
| 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)}") | |
| return {key: copy.deepcopy(source[key]) for key in required} | |
| def build_launch_document( | |
| protocol: dict[str, Any], | |
| task: FollowupTask, | |
| invariants: dict[str, Any], | |
| ) -> dict[str, Any]: | |
| verify = ( | |
| "/tmp/gmnet_venv/bin/python " | |
| "scripts/generate_single_seed_followup.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" | |
| ) | |
| 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_single_seed_followup.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[FollowupTask] | |
| ) -> dict[str, Any]: | |
| records = [] | |
| for task in tasks: | |
| record = asdict(task) | |
| record["evidence"] = list(task.evidence) | |
| record["deploy_path"] = str(task.deploy_path) | |
| record["approval_path"] = str(task.approval_path) | |
| record["output_dir"] = str(task.output_dir) | |
| record["job_name"] = task.job_name | |
| record["eta_class"] = ">12h" | |
| records.append(record) | |
| return { | |
| "schema_version": 1, | |
| "protocol_id": protocol["protocol_id"], | |
| "protocol_source": str(PROTOCOL_PATH), | |
| "generated_by": str(SCRIPT_PATH), | |
| "source_template": str(BASE_TEMPLATE), | |
| "code_manifest": str(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH), | |
| "code_sha256": read_code_manifest()["code_sha256"], | |
| "relationship_to_parent": protocol["relationship_to_parent"], | |
| "post_hoc_registration": copy.deepcopy(protocol["post_hoc_registration"]), | |
| "policy": copy.deepcopy(protocol["policy"]), | |
| "data": copy.deepcopy(protocol["data"]), | |
| "run_root": str(RUN_ROOT), | |
| "summary": { | |
| "task_count": len(tasks), | |
| "initially_approved_count": sum(task.submission_allowed for task in tasks), | |
| "conditional_count": sum(task.status == "conditional" for task in tasks), | |
| }, | |
| "tasks": records, | |
| } | |
| def expected_files() -> dict[Path, str]: | |
| protocol = load_protocol() | |
| tasks = build_tasks(protocol) | |
| 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.yaml"] = dump_yaml( | |
| build_batch_manifest(protocol, tasks) | |
| ) | |
| for task in tasks: | |
| if task.submission_allowed: | |
| payload = approval_payload(protocol, task) | |
| files[task.approval_path] = ( | |
| json.dumps(payload, 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 | |
| path.write_text(content, encoding="utf-8") | |
| 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 approve_conditional(task_id: str, acknowledged: bool) -> None: | |
| if not acknowledged: | |
| raise ApprovalError("conditional approval requires --acknowledge-conditional") | |
| 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 or task.status != "conditional": | |
| raise ApprovalError(f"task is not conditional: {task_id}") | |
| verify_code_manifest() | |
| for evidence_id in task.evidence: | |
| verify_evidence(protocol, evidence_id) | |
| if not trigger_is_met(protocol, task): | |
| raise ApprovalError(f"conditional trigger is not met: {task_id}") | |
| task.approval_path.parent.mkdir(parents=True, exist_ok=True) | |
| task.approval_path.write_text( | |
| json.dumps( | |
| approval_payload(protocol, task, conditional=True), | |
| indent=2, | |
| sort_keys=True, | |
| ) | |
| + "\n", | |
| encoding="utf-8", | |
| ) | |
| print(f"Approved conditional follow-up task: {task_id}") | |
| 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") | |
| action.add_argument("--approve-conditional") | |
| parser.add_argument("--require-approval", action="store_true") | |
| parser.add_argument("--acknowledge-conditional", 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 | |
| if args.approve_conditional: | |
| approve_conditional(args.approve_conditional, args.acknowledge_conditional) | |
| return 0 | |
| protocol = load_protocol() | |
| tasks = build_tasks(protocol) | |
| verify_code_manifest() | |
| for evidence_id in protocol["legacy_evidence"]: | |
| verify_evidence(protocol, evidence_id) | |
| files = expected_files() | |
| if args.check: | |
| errors = check_files(files) | |
| if errors: | |
| print("\n".join(errors), file=sys.stderr) | |
| return 1 | |
| print( | |
| f"Validated {len(tasks)} follow-up launch YAMLs, " | |
| "batch manifest, approvals, code, and legacy evidence" | |
| ) | |
| return 0 | |
| write_files(files) | |
| print( | |
| f"Generated {len(tasks)} follow-up 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()) | |