"""Lazy Qwen3.5/TRL launcher planning and GPU-environment admission.""" from __future__ import annotations import argparse import importlib import importlib.metadata import importlib.util import json import os import sys from dataclasses import dataclass, fields from pathlib import Path from typing import Any from ..atomic_io import read_jsonl from ..hashing import canonical_json_hash from .artifacts import QWEN35_2B_REVISION, RunArtifactError, RuntimeTrainingConfig from .environment import environment_lock_errors from .peft_contract import adapter_checkpoint_errors from .smoke_gate import main_gate_errors _PINNED_TRAIN_DISTRIBUTIONS = { "transformers": "5.14.1", "trl": "1.9.1", "peft": "0.19.1", "accelerate": "1.14.0", "datasets": "5.0.0", "huggingface-hub": "1.25.1", "vllm": "0.25.1", "qwen-vl-utils": "0.0.14", "flash-attn": "2.8.3.post1", "flash-linear-attention": "0.5.2", "causal-conv1d": "1.6.2.post1", } class LauncherUnavailable(RuntimeError): """Raised when a planned run cannot truthfully start.""" @dataclass(frozen=True) class LauncherCheck: ok: bool errors: tuple[str, ...] warnings: tuple[str, ...] = () def build_launch_command( frozen_config_path: str | Path, *, world_size: int, python_executable: str | None = None, ) -> tuple[str, ...]: """Generate a deterministic local torchrun command without importing torch.""" if world_size <= 0: raise ValueError("world_size must be positive") python = python_executable or sys.executable config = str(Path(frozen_config_path).resolve()) if world_size == 1: return ( python, "-m", "explicit_learning.training.launcher", "execute", "--config", config, ) return ( python, "-m", "torch.distributed.run", "--standalone", f"--nproc-per-node={world_size}", "--module", "explicit_learning.training.launcher", "execute", "--config", config, ) def _load_runtime(path: str | Path) -> dict[str, Any]: source = Path(path) try: value = json.loads(source.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise LauncherUnavailable(f"cannot read frozen config {source}: {exc}") from exc runtime = value.get("runtime") if isinstance(value, dict) else None if not isinstance(runtime, dict): raise LauncherUnavailable("frozen config has no runtime object") return runtime def _evaluation_leakage_errors( evaluation_registry_path: Path, training_dataset_path: Path, ) -> list[str]: """Reject any frozen training row whose base ID occurs in certified eval.""" try: registry = json.loads(evaluation_registry_path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: return [f"cannot read certified evaluation ID registry: {exc}"] if not isinstance(registry, dict) or registry.get("schema_version") != 1: return ["evaluation manifest is not a schema-version-1 ID registry"] if ( registry.get("kind") != "certified_evaluation_id_registry" or registry.get("split") != "certified_eval" ): return ["evaluation manifest is not the certified_eval ID registry"] identities = registry.get("identities") if not isinstance(identities, list): return ["evaluation ID registry identities must be a list"] eval_ids: set[str] = set() for identity in identities: if not isinstance(identity, dict) or not isinstance(identity.get("base_id"), str): return ["evaluation ID registry contains a malformed identity"] base_id = str(identity["base_id"]) if base_id in eval_ids: return ["evaluation ID registry contains duplicate base IDs"] eval_ids.add(base_id) if registry.get("group_count") != len(eval_ids): return ["evaluation ID registry group_count mismatch"] try: training_rows = list(read_jsonl(training_dataset_path)) except (OSError, json.JSONDecodeError) as exc: return [f"cannot read frozen training dataset for leakage check: {exc}"] train_ids: set[str] = set() for row in training_rows: base_id = row.get("base_id") if not isinstance(base_id, str) or not base_id: return ["frozen training dataset row has no base_id"] train_ids.add(base_id) overlap = sorted(eval_ids.intersection(train_ids)) if overlap: return [f"certified evaluation base-ID leakage detected: {overlap[:8]}"] return [] def _plan_integrity_errors(frozen_config_path: str | Path) -> list[str]: """Check structural plan consistency without replaying large content hashes.""" source = Path(frozen_config_path) manifest_path = source.with_name("run-manifest.json") try: frozen = json.loads(source.read_text(encoding="utf-8")) manifest = json.loads(manifest_path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: return [f"cannot read frozen config/run manifest pair: {exc}"] if not isinstance(frozen, dict) or not isinstance(manifest, dict): return ["frozen config and run manifest must be JSON objects"] runtime = frozen.get("runtime") if not isinstance(runtime, dict): return ["frozen config has no runtime object"] errors: list[str] = [] actual_frozen_sha = canonical_json_hash(frozen) if manifest.get("frozen_config_sha256") != actual_frozen_sha: errors.append("run manifest frozen_config_sha256 mismatch") for field in ("run_id", "arm", "trainer_kind", "run_mode"): if manifest.get(field) != runtime.get(field): errors.append(f"run manifest {field} differs from frozen runtime") for field in ( "model_snapshot_sha256", "environment_lock_sha256", "evaluation_manifest_sha256", "system_prompt_sha256", ): if manifest.get(field) != runtime.get(field): errors.append(f"run manifest {field} differs from frozen runtime") if manifest.get("comparison_slot_manifest_sha256") != runtime.get( "comparison_slot_manifest_sha256" ): errors.append("run manifest comparison-slot identity mismatch") try: field_names = {field.name for field in fields(RuntimeTrainingConfig)} runtime_fields = {key: value for key, value in runtime.items() if key in field_names} if isinstance(runtime_fields.get("lora_target_modules"), list): runtime_fields["lora_target_modules"] = tuple(runtime_fields["lora_target_modules"]) reconstructed = RuntimeTrainingConfig(**runtime_fields).to_dict() if canonical_json_hash(reconstructed) != canonical_json_hash(runtime): errors.append( "frozen runtime contains derived-field drift from RuntimeTrainingConfig.to_dict()" ) except (RunArtifactError, TypeError, ValueError) as exc: errors.append(f"frozen runtime violates RuntimeTrainingConfig: {exc}") dataset = Path(str(runtime.get("dataset_path", ""))) if dataset.is_file() and dataset.stat().st_size == 0: errors.append("frozen training dataset is empty") model = Path(str(runtime.get("model_path", ""))) if model.is_dir() and not any(path.is_file() for path in model.iterdir()): errors.append("model snapshot directory has no top-level files") # Train/eval overlap is certified once while publishing the training-input # bundle. Re-reading all 46K rows in every torchrun rank only repeated that # release check and held GPUs idle; launch admission trusts the frozen # bundle identity and keeps only structural path checks below. environment_lock = Path(str(runtime.get("environment_lock_path", ""))) if environment_lock.is_file(): errors.extend(environment_lock_errors(environment_lock)) source_config_sha = frozen.get("source_config_sha256") if isinstance(source_config_sha, str): errors.extend( main_gate_errors( runtime, manifest, source_config_sha256=source_config_sha, ) ) else: errors.append("frozen config lacks source_config_sha256") checkpoint = Path(str(runtime.get("initial_checkpoint_path", ""))) if checkpoint.exists(): if checkpoint.is_dir() and not any(path.is_file() for path in checkpoint.rglob("*")): errors.append("initial checkpoint directory is empty") if runtime.get("trainer_kind") != "sft": errors.extend(adapter_checkpoint_errors(checkpoint, runtime)) elif checkpoint.resolve() != model.resolve(): errors.append("SFT initial checkpoint must be the base model snapshot") elif manifest.get("initial_checkpoint_sha256") != runtime.get("model_snapshot_sha256"): errors.append("SFT initial checkpoint SHA must equal model snapshot SHA") # The commit remains provenance in the run manifest, but it is not a hard # launch gate. Documentation/evaluator fixes after plan creation must not # dead-cycle a behavior-compatible training run. return errors def check_launcher_environment(frozen_config_path: str | Path) -> LauncherCheck: """Check data/model/checkpoint, lazy dependencies, and CUDA availability.""" try: runtime = _load_runtime(frozen_config_path) except LauncherUnavailable as exc: return LauncherCheck(False, (str(exc),)) errors: list[str] = [] warnings: list[str] = [] errors.extend(_plan_integrity_errors(frozen_config_path)) expected_types = { "model_path": "directory", "dataset_path": "file", "initial_checkpoint_path": "directory", "dataset_asset_root": "directory", "environment_lock_path": "file", "evaluation_manifest_path": "file", } if runtime.get("run_mode") == "main": expected_types["compatibility_gate_path"] = "file" for field, expected_type in expected_types.items(): raw = runtime.get(field) path = Path(str(raw)) if raw else None if path is None or not path.exists(): errors.append(f"{field} not found: {raw!r}") elif expected_type == "file" and not path.is_file(): errors.append(f"{field} must be a regular file: {path}") elif expected_type == "directory" and not path.is_dir(): errors.append(f"{field} must be a directory: {path}") output = runtime.get("output_dir") if not output: errors.append("output_dir is missing") if runtime.get("base_model_repo_id") != "Qwen/Qwen3.5-2B": errors.append("frozen runtime is not identified as Qwen/Qwen3.5-2B") if runtime.get("model_revision") != QWEN35_2B_REVISION: errors.append("frozen runtime does not use the pinned Qwen3.5-2B revision") entrypoint = runtime.get("backend_entrypoint") if not entrypoint: errors.append("backend_entrypoint is not frozen; no GPU trainer can execute") else: try: _load_backend(str(entrypoint)) except LauncherUnavailable as exc: errors.append(str(exc)) required_modules = [ "torch", "transformers", "trl", "peft", "datasets", "qwen_vl_utils", ] if runtime.get("attention_implementation") == "flash_attention_2": required_modules.append("flash_attn") if runtime.get("trainer_kind") != "sft" and runtime.get("use_vllm", True): required_modules.append("vllm") missing_modules = [ module for module in required_modules if importlib.util.find_spec(module) is None ] if missing_modules: errors.append("missing GPU training dependencies: " + ", ".join(missing_modules)) for distribution, expected_version in _PINNED_TRAIN_DISTRIBUTIONS.items(): if runtime.get("trainer_kind") == "sft" and distribution == "vllm": continue try: actual_version = importlib.metadata.version(distribution) except importlib.metadata.PackageNotFoundError: errors.append(f"missing pinned training distribution: {distribution}") continue if actual_version != expected_version: errors.append( f"{distribution}=={actual_version} is installed; " f"frozen stack requires {expected_version}" ) trainer_kind = runtime.get("trainer_kind") if "trl" not in missing_modules: try: trainer_class = { "sft": ("trl", "SFTTrainer"), "grpo": ("trl", "GRPOTrainer"), "papo": ("explicit_learning.training.papo", "PAPOTrainer"), "evi_po": ("explicit_learning.training.evi_po", "EVITrainer"), }.get(str(trainer_kind)) if trainer_class is None: errors.append(f"unsupported trainer_kind: {trainer_kind!r}") else: module_name, class_name = trainer_class module = importlib.import_module(module_name) if getattr(module, class_name, None) is None: errors.append(f"installed TRL does not expose {module_name}.{class_name}") except Exception as exc: errors.append(f"TRL inspection failed: {exc}") if "torch" not in missing_modules: try: torch = importlib.import_module("torch") if not bool(torch.cuda.is_available()): errors.append("torch.cuda.is_available() is false") else: required_devices = int(runtime.get("world_size", 1)) available = int(torch.cuda.device_count()) if available < required_devices: errors.append( f"CUDA device count {available} is smaller than world_size {required_devices}" ) bf16_supported = getattr(torch.cuda, "is_bf16_supported", None) if ( runtime.get("precision") == "bf16" and callable(bf16_supported) and not bool(bf16_supported()) ): errors.append("CUDA device does not report bf16 support") except Exception as exc: errors.append(f"torch CUDA inspection failed: {exc}") if os.environ.get("CUDA_VISIBLE_DEVICES") == "": warnings.append("CUDA_VISIBLE_DEVICES is explicitly empty") return LauncherCheck(not errors, tuple(errors), tuple(warnings)) def _load_backend(entrypoint: str) -> Any: if ":" not in entrypoint: raise LauncherUnavailable("backend_entrypoint must be module:function") module_name, function_name = entrypoint.split(":", 1) try: module = importlib.import_module(module_name) function = getattr(module, function_name) except (ImportError, AttributeError) as exc: raise LauncherUnavailable(f"cannot load backend entrypoint {entrypoint!r}: {exc}") from exc if not callable(function): raise LauncherUnavailable(f"backend entrypoint {entrypoint!r} is not callable") return function def execute(frozen_config_path: str | Path) -> int: """Run a configured backend only after all launch admission checks pass.""" check = check_launcher_environment(frozen_config_path) if not check.ok: raise LauncherUnavailable("; ".join(check.errors)) runtime = _load_runtime(frozen_config_path) manifest_path = Path(frozen_config_path).with_name("run-manifest.json") manifest = json.loads(manifest_path.read_text(encoding="utf-8")) runtime["_launch_manifest"] = { "run_manifest_path": str(manifest_path.resolve()), "run_manifest_sha256": canonical_json_hash(manifest), "frozen_config_path": str(Path(frozen_config_path).resolve()), "frozen_config_sha256": canonical_json_hash( json.loads(Path(frozen_config_path).read_text(encoding="utf-8")) ), "code_commit": manifest["code_commit"], "dataset_manifest_sha256": manifest["dataset_manifest_sha256"], "comparison_slot_manifest_sha256": manifest.get( "comparison_slot_manifest_sha256" ), "initial_checkpoint_sha256": manifest["initial_checkpoint_sha256"], } entrypoint = runtime.get("backend_entrypoint") if not entrypoint: raise LauncherUnavailable( "GPU preflight passed but no backend_entrypoint is frozen; " "this artifact is a launch plan, not a trained run" ) backend = _load_backend(str(entrypoint)) result = backend(runtime) return int(result or 0) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="python -m explicit_learning.training.launcher") sub = parser.add_subparsers(dest="command", required=True) for name in ("check", "execute"): child = sub.add_parser(name) child.add_argument("--config", type=Path, required=True) args = parser.parse_args(argv) if args.command == "check": check = check_launcher_environment(args.config) print( json.dumps( {"ok": check.ok, "errors": check.errors, "warnings": check.warnings}, sort_keys=True, ) ) return 0 if check.ok else 2 try: return execute(args.config) except LauncherUnavailable as exc: print(f"TRAINING BLOCKED: {exc}", file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())