#!/usr/bin/env python3 """Generate the staged ImageNet-v2 launch matrix without submitting jobs.""" from __future__ import annotations import argparse import copy import re import sys from collections import Counter 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 DEPLOY_ROOT = GMNET_ROOT / "depoly" PROTOCOL_PATH = JOURNAL_ROOT / "configs/imagenet_v2_protocol.yaml" BASE_TEMPLATE = Path("/nfs/ywang29/LongLive/deploy/jul11_vgp/j11_vgp01_base.yaml") EXPECTED_RUN_ROOT = GMNET_ROOT / "runs/imagenet_v2" CODE_MANIFEST_RELATIVE_PATH = "configs/imagenet_v2_code_manifest.json" 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", ) GENERATED_HEADER = ( "# Generated by journal_exp/scripts/generate_deploy.py; do not edit.\n" ) VALID_STATUSES = {"ready", "held", "conditional"} TASK_ID_PATTERN = re.compile(r"[a-z0-9_]+") @dataclass(frozen=True) class LaunchTask: task_id: str experiment: str model: str gate: str seed: int config_path: str deploy_group: str phase: str role: str depends_on: tuple[str, ...] external_prerequisites: tuple[str, ...] status: str submission_allowed: bool condition: str | None = None @property def deploy_path(self) -> str: return f"{self.deploy_group}/{self.task_id}.yaml" @property def job_name(self) -> str: return "gmnet-" + self.task_id.replace("_", "-") @property def output_dir(self) -> str: return str(EXPECTED_RUN_ROOT / self.task_id) def load_protocol() -> dict[str, Any]: if not PROTOCOL_PATH.is_file(): raise FileNotFoundError(f"protocol does not exist: {PROTOCOL_PATH}") with PROTOCOL_PATH.open("r", encoding="utf-8") as handle: protocol = yaml.safe_load(handle) if not isinstance(protocol, dict): raise ValueError("ImageNet-v2 protocol must be a mapping") return protocol def build_launch_tasks(protocol: dict[str, Any] | None = None) -> list[LaunchTask]: protocol = load_protocol() if protocol is None else protocol raw_tasks = protocol.get("tasks") if not isinstance(raw_tasks, list): raise ValueError("protocol tasks must be a list") tasks: list[LaunchTask] = [] for record in raw_tasks: if not isinstance(record, dict): raise ValueError("each protocol task must be a mapping") tasks.append( LaunchTask( 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"]), deploy_group=str(record["deploy_group"]), phase=str(record["phase"]), role=str(record["role"]), depends_on=tuple(record.get("depends_on", [])), external_prerequisites=tuple(record.get("external_prerequisites", [])), status=str(record["status"]), submission_allowed=bool(record["submission_allowed"]), condition=record.get("condition"), ) ) validate_protocol(protocol, tasks) return tasks def load_resolved_config(path: Path) -> dict[str, Any]: """Load a task config through the same inheritance code used by training.""" 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_config_value( task: LaunchTask, config: dict[str, Any], dotted_key: str, expected: object, ) -> None: value: object = config for part in dotted_key.split("."): if not isinstance(value, dict) or part not in value: raise ValueError( f"resolved config for {task.task_id} is missing {dotted_key}" ) value = value[part] if value != expected: raise ValueError( f"resolved config mismatch for {task.task_id}: " f"{dotted_key}={value!r}, expected {expected!r}" ) def validate_resolved_config(task: LaunchTask, config: dict[str, Any]) -> None: """Ensure protocol labels describe the resolved training semantics.""" expected_gate = ( "smooth_clipped_self" if task.gate == "smooth_clipped_self_fixed_c6" else task.gate ) is_release_audit = task.role == "conditional_recipe_audit" expected_recipe = ( "release-readme-legacy-audit-only" if is_release_audit else "paper-supplementary-table8-v1" ) expected_epochs = 310 if is_release_audit else 300 expected_drop_path = 0.0 if is_release_audit or task.model in {"s1", "s2"} else 0.02 invariants = { "recipe_id": expected_recipe, "model.variant": task.model, "model.gate_type": expected_gate, "model.num_classes": 1000, "model.drop_path_rate": expected_drop_path, "data.dataset": "imagenet", "data.num_classes": 1000, "data.expected_train_samples": 1_281_167, "data.expected_val_samples": 50_000, "data.expected_manifest_sha256": str( load_protocol()["canonical_data_manifest"]["manifest_sha256"] ), "train.epochs": expected_epochs, "train.eval_interval": expected_epochs, "train.official_validation_policy": "final_epoch_only", "train.save_best_checkpoint": False, "train.fail_on_nonfinite": True, "train.strict_resume": True, } for dotted_key, expected in invariants.items(): _require_config_value(task, config, dotted_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"resolved config for {task.task_id} must exclude raw_clip from weight decay" ) is_smooth = task.gate in { "smooth_clipped_self", "smooth_clipped_self_fixed_c6", } if is_smooth: _require_config_value(task, config, "model.smooth_clip_per_channel", False) _require_config_value(task, config, "model.smooth_clip_init", 6.0) _require_config_value(task, config, "model.smooth_clip_beta", 10.0) _require_config_value( task, config, "model.smooth_clip_trainable", task.gate == "smooth_clipped_self", ) if task.task_id == "imv2_e0_s3_release_fullbn_seed0": expected_bn = (True, True) else: expected_bn = (False, False) _require_config_value(task, config, "model.f12_bn", expected_bn[0]) _require_config_value(task, config, "model.second_dw_bn", expected_bn[1]) _require_config_value(task, config, "model.projection_bn", True) def resolved_config_summary(task: LaunchTask) -> dict[str, object]: config = load_resolved_config(JOURNAL_ROOT / task.config_path) model = config["model"] return { "recipe_id": config["recipe_id"], "variant": model["variant"], "gate_type": model["gate_type"], "smooth_clip_trainable": model.get("smooth_clip_trainable"), "epochs": config["train"]["epochs"], "final_epoch_only": ( config["train"]["official_validation_policy"] == "final_epoch_only" ), "raw_clip_zero_weight_decay": ( "raw_clip" in config["optimizer"].get("no_weight_decay_patterns", []) ), } def validate_protocol(protocol: dict[str, Any], tasks: list[LaunchTask]) -> None: if protocol.get("schema_version") != 2: raise ValueError("ImageNet-v2 protocol schema_version must be 2") if Path(str(protocol.get("run_root"))) != EXPECTED_RUN_ROOT: raise ValueError(f"protocol run_root must be {EXPECTED_RUN_ROOT}") if len(tasks) != 21: raise ValueError( f"ImageNet-v2 protocol must contain 21 tasks, got {len(tasks)}" ) task_ids = [task.task_id for task in tasks] if len(task_ids) != len(set(task_ids)): raise ValueError("duplicate task IDs in ImageNet-v2 protocol") task_id_set = set(task_ids) if any(TASK_ID_PATTERN.fullmatch(task_id) is None for task_id in task_ids): raise ValueError( "ImageNet-v2 task IDs may contain only lowercase letters, digits, and underscores" ) job_names = [task.job_name for task in tasks] if len(job_names) != len(set(job_names)): raise ValueError("duplicate launchjob names in ImageNet-v2 protocol") phases = protocol.get("phases", {}) external = protocol.get("external_prerequisites", {}) if not isinstance(external, dict): raise ValueError("protocol external_prerequisites must be a mapping") external_ids = set(external) decision_rule_ids = { str(rule.get("id")) for rule in protocol.get("decision_rules", []) if isinstance(rule, dict) } for prerequisite_id, prerequisite in external.items(): if not isinstance(prerequisite, dict): raise ValueError( f"external prerequisite {prerequisite_id} must be a mapping" ) if prerequisite.get("decision_rule") not in decision_rule_ids: raise ValueError( f"external prerequisite {prerequisite_id} references an unknown decision rule" ) if prerequisite.get("required_state") != "passed": raise ValueError( f"external prerequisite {prerequisite_id} must require passed state" ) state = prerequisite.get("state") if state not in {"pending", "passed", "failed"}: raise ValueError( f"external prerequisite {prerequisite_id} has invalid state {state!r}" ) if state == "passed": evidence = prerequisite.get("evidence") if not isinstance(evidence, str) or not Path(evidence).is_file(): raise ValueError( f"passed external prerequisite {prerequisite_id} lacks evidence" ) for task in tasks: if not task.task_id.startswith("imv2_"): raise ValueError(f"task ID lacks imv2 namespace: {task.task_id}") if task.status not in VALID_STATUSES: raise ValueError(f"invalid status for {task.task_id}: {task.status}") if task.submission_allowed and task.status != "ready": raise ValueError(f"only ready tasks may be submitted: {task.task_id}") if task.phase not in phases: raise ValueError(f"undefined phase for {task.task_id}: {task.phase}") missing_dependencies = set(task.depends_on) - task_id_set if missing_dependencies: raise ValueError( f"unknown dependencies for {task.task_id}: " + ", ".join(sorted(missing_dependencies)) ) if task.task_id in task.depends_on: raise ValueError(f"task depends on itself: {task.task_id}") missing_external = set(task.external_prerequisites) - external_ids if missing_external: raise ValueError( f"unknown external prerequisites for {task.task_id}: " + ", ".join(sorted(missing_external)) ) if task.submission_allowed != (task.status == "ready"): raise ValueError(f"ready/submission state mismatch for {task.task_id}") if task.status == "conditional" and not task.condition: raise ValueError(f"conditional task lacks condition: {task.task_id}") config = JOURNAL_ROOT / task.config_path if not config.is_file(): raise FileNotFoundError(f"missing config for {task.task_id}: {config}") validate_resolved_config(task, load_resolved_config(config)) allowed = [task.task_id for task in tasks if task.submission_allowed] expected_allowed = ["imv2_e0_s3_relu6_seed0"] if allowed != expected_allowed: raise ValueError( "initial submission policy must allow only " + expected_allowed[0] ) confirmatory = [task for task in tasks if task.role.startswith("confirmatory_")] gate_counts = Counter(task.gate for task in confirmatory) expected_gate_counts = { "relu6_self": 3, "relu_self": 3, "smooth_clipped_self": 3, "relu6_only": 3, "no_gate": 3, } if dict(gate_counts) != expected_gate_counts: raise ValueError(f"confirmatory gate matrix mismatch: {dict(gate_counts)}") smooth_seed0 = next( task for task in tasks if task.task_id == "imv2_e3_s3_smooth_corrected_seed0" ) if smooth_seed0.external_prerequisites != ("smooth_local_pregate",): raise ValueError( "learned-smooth seed0 must require external smooth_local_pregate" ) primary = protocol.get("primary_analysis", {}) if not isinstance(primary, dict): raise ValueError("primary_analysis must be a mapping") expected_control = "fixed_entry_gate_then_parallel_holm" if ( primary.get("alpha") != 0.05 or primary.get("familywise_error_control") != expected_control ): raise ValueError( "primary analysis must use a fixed entry gate followed by Holm " "control at alpha 0.05" ) entry = primary.get("fixed_entry_gate", {}) if ( entry.get("id") != "h1_no_gate_material_loss" or entry.get("candidate_gate") != "no_gate" ): raise ValueError("primary entry gate does not match the frozen protocol") downstream = primary.get("downstream_holm_family", {}) expected_hypotheses = [ ("h2_relu6_only_noninferiority", "relu6_only"), ("h3_relu_equivalence", "relu_self"), ("h4_smooth_noninferiority", "smooth_clipped_self"), ] observed_hypotheses = [ (hypothesis.get("id"), hypothesis.get("candidate_gate")) for hypothesis in downstream.get("hypotheses", []) ] if observed_hypotheses != expected_hypotheses: raise ValueError( "primary downstream Holm hypotheses do not match the frozen protocol" ) def load_base_invariants() -> dict[str, object]: if not BASE_TEMPLATE.is_file(): raise FileNotFoundError(f"launch template does not exist: {BASE_TEMPLATE}") with BASE_TEMPLATE.open("r", encoding="utf-8") as handle: source = yaml.safe_load(handle) required = (*RESOURCE_KEYS, *PROJECT_KEYS) missing = [key for key in required if key not in source] if missing: raise ValueError(f"launch template is missing fields: {', '.join(missing)}") return {key: copy.deepcopy(source[key]) for key in required} def unlock_guard(task: LaunchTask) -> str | None: if task.submission_allowed: return None variable = "GMNET_PROTOCOL_UNLOCK_TASK" return ( f'if [ "${{{variable}:-}}" != "{task.task_id}" ]; then ' f'echo "Protocol guard denied {task.task_id}; set {variable}={task.task_id} ' 'only after documented prerequisite review" >&2; exit 64; fi' ) def _guarded_command(task: LaunchTask, command: str) -> str: guard = unlock_guard(task) return command if guard is None else f"{guard}; {command}" def build_command(task: LaunchTask, data_root: str) -> str: assignments = ( f"RUN_NAME={task.task_id}", f"CONFIG_PATH={task.config_path}", f"DATA_ROOT={data_root}", f"OUTPUT_DIR={task.output_dir}", f"SEED={task.seed}", "NPROC_PER_NODE=8", f"CODE_MANIFEST_PATH={CODE_MANIFEST_RELATIVE_PATH}", ) command = ( f"cd {JOURNAL_ROOT} && " + " ".join(assignments) + " bash scripts/init_run.sh" ) return _guarded_command(task, command) def build_launch_document( task: LaunchTask, invariants: dict[str, object], data_root: str, ) -> dict[str, object]: document: dict[str, object] = {} for key in RESOURCE_KEYS: document[key] = copy.deepcopy(invariants[key]) pre_run_event = ( f"cd {JOURNAL_ROOT} && chmod +x ./scripts/*.sh && " "INSTALL_DEV=0 bash ./scripts/setup_env.sh && " "KEEP_ARCHIVE=0 bash ./scripts/stage_imagenet.sh full" ) document["script"] = { "pre_run_event": _guarded_command(task, pre_run_event), "command": build_command(task, data_root), "jobs": [{"name": task.job_name}], } for key in PROJECT_KEYS: document[key] = copy.deepcopy(invariants[key]) return document def dump_yaml(document: object) -> str: body = yaml.safe_dump( document, sort_keys=False, default_flow_style=False, width=1_000_000, ) return GENERATED_HEADER + body def _counts(tasks: list[LaunchTask], field: str) -> dict[str, int]: counts = Counter(str(getattr(task, field)) for task in tasks) return dict(sorted(counts.items())) def build_task_matrix( protocol: dict[str, Any], tasks: list[LaunchTask] ) -> dict[str, object]: records = [] for task in tasks: record = asdict(task) record["depends_on"] = list(task.depends_on) record["external_prerequisites"] = list(task.external_prerequisites) record.update( { "deploy_path": task.deploy_path, "job_name": task.job_name, "eta_class": ">12h", "runner": "imagenet_classification", "data_root": str(protocol["data_root"]), "output_dir": task.output_dir, "resolved_config": resolved_config_summary(task), } ) if record["condition"] is None: del record["condition"] records.append(record) return { "schema_version": 2, "protocol_id": protocol["protocol_id"], "protocol_source": str(PROTOCOL_PATH), "generated_by": str(SCRIPT_PATH), "source_template": str(BASE_TEMPLATE), "policy": copy.deepcopy(protocol["policy"]), "technical_validity": copy.deepcopy(protocol["technical_validity"]), "external_prerequisites": copy.deepcopy(protocol["external_prerequisites"]), "data_root": str(protocol["data_root"]), "data_staging": copy.deepcopy(protocol["data_staging"]), "canonical_data_uri": str(protocol["canonical_data_uri"]), "canonical_data_manifest": copy.deepcopy(protocol["canonical_data_manifest"]), "run_root": str(EXPECTED_RUN_ROOT), "code_manifest": str(JOURNAL_ROOT / CODE_MANIFEST_RELATIVE_PATH), "summary": { "launch_yaml_count": len(tasks), "submission_allowed_count": sum(task.submission_allowed for task in tasks), "by_status": _counts(tasks, "status"), "by_phase": _counts(tasks, "phase"), "by_role": _counts(tasks, "role"), "by_experiment": _counts(tasks, "experiment"), }, "decision_rules": copy.deepcopy(protocol.get("decision_rules", [])), "primary_analysis": copy.deepcopy(protocol["primary_analysis"]), "secondary_analysis": copy.deepcopy(protocol["secondary_analysis"]), "tasks": records, } def expected_files() -> dict[Path, str]: protocol = load_protocol() tasks = build_launch_tasks(protocol) invariants = load_base_invariants() data_root = str(protocol["data_root"]) files: dict[Path, str] = {} for task in tasks: document = build_launch_document(task, invariants, data_root) for key in (*RESOURCE_KEYS, *PROJECT_KEYS): if document[key] != invariants[key]: raise AssertionError(f"{task.task_id} changed invariant field {key}") files[DEPLOY_ROOT / task.deploy_path] = dump_yaml(document) files[DEPLOY_ROOT / "task_matrix.yaml"] = dump_yaml( build_task_matrix(protocol, tasks) ) return files def find_stale_generated_files(expected_paths: set[Path]) -> list[Path]: stale = [] if not DEPLOY_ROOT.is_dir(): return stale for path in DEPLOY_ROOT.rglob("*.yaml"): if path in expected_paths or not path.is_file(): continue try: generated = path.read_text(encoding="utf-8").startswith(GENERATED_HEADER) except UnicodeDecodeError: generated = False if generated: stale.append(path) return sorted(stale) def write_files(files: dict[Path, str]) -> list[Path]: for path, content in files.items(): path.parent.mkdir(parents=True, exist_ok=True) if path.exists() and path.read_text(encoding="utf-8") == content: continue path.write_text(content, encoding="utf-8") stale = find_stale_generated_files(set(files)) for path in stale: path.unlink() for directory in sorted(DEPLOY_ROOT.rglob("*"), reverse=True): if directory.is_dir() and not any(directory.iterdir()): directory.rmdir() return stale 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}") continue actual = path.read_text(encoding="utf-8") if actual != expected: errors.append(f"stale: {path}") continue parsed = yaml.safe_load(actual) if path.name != "task_matrix.yaml": jobs = parsed.get("script", {}).get("jobs", []) if len(jobs) != 1: errors.append(f"expected one job: {path}") errors.extend( f"stale generated file: {path}" for path in find_stale_generated_files(set(files)) ) return errors def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--check", action="store_true", help="verify generated files without modifying them", ) return parser.parse_args() def main() -> int: args = parse_args() files = expected_files() launch_count = len(files) - 1 if args.check: errors = check_files(files) if errors: print("\n".join(errors), file=sys.stderr) return 1 print( f"Validated {launch_count} ImageNet-v2 launch YAML files " "and task_matrix.yaml" ) return 0 removed = write_files(files) print( f"Generated {launch_count} ImageNet-v2 launch YAML files under " f"{DEPLOY_ROOT}; removed {len(removed)} stale generated YAML files" ) return 0 if __name__ == "__main__": raise SystemExit(main())