Datasets:
Download src/explicit_learning/cli/train.py from sungguk/visual-answerability: direct link, hf CLI and curl.
- Browser
- Download file 57.3 kB
-
https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/cli/train.py
- Command line
-
hf download hf://datasets/sungguk/visual-answerability/src/explicit_learning/cli/train.py
-
curl -L -o train.py https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/cli/train.py
57.3 kB
| """``explicit-train`` — CPU contracts, frozen plans, and gated GPU launch.""" | |
| from __future__ import annotations | |
| import argparse | |
| import importlib | |
| import json | |
| import os | |
| import shutil | |
| import subprocess | |
| import sys | |
| import tempfile | |
| from collections.abc import Mapping, Sequence | |
| from pathlib import Path | |
| from typing import Any, cast | |
| from ..atomic_io import atomic_write_json, atomic_write_jsonl, read_jsonl | |
| from ..hashing import canonical_config_hash, sha256_file | |
| from ..paths import repo_root | |
| from ..training.artifacts import ( | |
| QWEN35_2B_REVISION, | |
| RunArtifactError, | |
| RunMode, | |
| RuntimeTrainingConfig, | |
| TrainerKind, | |
| build_run_manifest, | |
| write_frozen_run, | |
| ) | |
| from ..training.backend import ( | |
| BackendContractError, | |
| prepare_sft_records, | |
| sft_loss_token_count, | |
| ) | |
| from ..training.data import ( | |
| AdmissionError, | |
| AdmissionValidator, | |
| AdmittedGroup, | |
| certified_release_validator, | |
| load_groups, | |
| ) | |
| from ..training.environment import write_environment_snapshot | |
| from ..training.launcher import ( | |
| LauncherUnavailable, | |
| build_launch_command, | |
| check_launcher_environment, | |
| execute, | |
| ) | |
| from ..training.ledger import LedgerError | |
| from ..training.offline import offline_contract_smoke | |
| from ..training.rewards import ( | |
| ABLATION_ARM_KNOBS, | |
| ABLATION_ARMS, | |
| CORE_ABLATION_ARMS, | |
| GPU_SMOKE_ARMS, | |
| arm_trainer_kind, | |
| ) | |
| from ..training.sft_schedule import SFTScheduleError, match_sft_schedules | |
| from ..training.slots import build_comparison_slots, comparison_slot_manifest_sha256 | |
| from ..training.smoke_gate import ( | |
| SmokeGateError, | |
| certify_smoke_gate, | |
| ) | |
| from ..training.targets import ours_target | |
| _RL_TOKEN_CAP = 24_000_000 | |
| _TOTAL_RL_TOKEN_CAP = 216_000_000 | |
| _TOTAL_ABLATION_TOKEN_CAP = 48_000_000 | |
| _SFT_TOKEN_CAP = 6_000_000 | |
| _EXPECTED_RL_RUNS = { | |
| ("answer_grpo", 1), | |
| ("papo_controlled", 1), | |
| ("papo_controlled", 2), | |
| ("defacto_controlled", 1), | |
| ("defacto_controlled", 2), | |
| ("intervention_grpo", 1), | |
| ("intervention_grpo", 2), | |
| ("evi_po", 1), | |
| ("evi_po", 2), | |
| } | |
| _EXPECTED_SMOKE_RUNS = {(arm, 1) for arm in GPU_SMOKE_ARMS} | |
| # Core ablations are limited to the two direct EVI objective removals. Six | |
| # exploratory target/mask/margin sweeps remain available as explicit one-off | |
| # plans but are not part of the automatic full-budget queue. | |
| _EXPECTED_ABLATION_RUNS = {(arm, 1) for arm in CORE_ABLATION_ARMS} | |
| _EXPECTED_SFT_DATA = {"full_only", "full_plus_certified_intervention"} | |
| def _resolve_validator( | |
| spec: str, | |
| *, | |
| asset_root: Path, | |
| replayed_view_dirs: frozenset[Path] | None = None, | |
| replay_certificates: bool = True, | |
| ) -> AdmissionValidator: | |
| if spec == "builtin-certified-release": | |
| return certified_release_validator( | |
| asset_root, | |
| replayed_view_dirs=replayed_view_dirs, | |
| replay_certificates=replay_certificates, | |
| ) | |
| if ":" not in spec: | |
| raise AdmissionError("--validator must be module:function") | |
| module_name, function_name = spec.split(":", 1) | |
| try: | |
| function = getattr(importlib.import_module(module_name), function_name) | |
| except (ImportError, AttributeError) as exc: | |
| raise AdmissionError(f"cannot load validator {spec!r}: {exc}") from exc | |
| if not callable(function): | |
| raise AdmissionError(f"validator {spec!r} is not callable") | |
| return cast(AdmissionValidator, function) | |
| def _load_yaml(path: Path) -> dict[str, Any]: | |
| try: | |
| import yaml | |
| except ImportError as exc: | |
| raise RunArtifactError("PyYAML is required to load a run matrix") from exc | |
| try: | |
| value = yaml.safe_load(path.read_text(encoding="utf-8")) | |
| except (OSError, yaml.YAMLError) as exc: | |
| raise RunArtifactError(f"cannot read matrix config {path}: {exc}") from exc | |
| if not isinstance(value, dict): | |
| raise RunArtifactError(f"{path} must contain a mapping") | |
| return value | |
| def _validate_runtime_args_against_config( | |
| args: argparse.Namespace, | |
| config: Mapping[str, Any], | |
| *, | |
| sft: bool, | |
| run_mode: RunMode = "main", | |
| ) -> None: | |
| """Reject CLI values that drift from the authoritative experiment config.""" | |
| try: | |
| io = config["input_output"] | |
| student = config["common_student"] | |
| server = student["server_runtime"] | |
| budget = config["training_budget"] | |
| expected = { | |
| "world_size": int(server["world_size"]), | |
| "per_device_batch_size": int(server["per_device_train_batch_size"]), | |
| "gradient_accumulation_steps": int(server["gradient_accumulation_steps"]), | |
| "checkpoint_interval": int(server["checkpoint_interval_steps"]), | |
| "max_prompt_tokens": int(io["max_prompt_tokens"]), | |
| "max_completion_tokens": int(io["max_completion_tokens"]), | |
| "learning_rate": float(student["optimizer"]["learning_rate"]), | |
| "token_cap": int( | |
| budget[ | |
| "max_assistant_tokens_per_sft_run" | |
| if sft | |
| else "max_sampled_completion_tokens_per_rl_run" | |
| ] | |
| ), | |
| } | |
| if not sft: | |
| expected["generations"] = int(student["generations_per_prompt"]) | |
| expected["max_optimizer_steps"] = int( | |
| budget["smoke_steps_per_arm"] | |
| if run_mode == "smoke" | |
| else server["max_optimizer_steps"] | |
| ) | |
| evi_po = config["rewards"]["evi_po"] | |
| expected["evi_direction_loss_weight"] = float(evi_po["lambda_direction"]) | |
| expected["evi_evidence_loss_weight"] = float(evi_po["lambda_evidence"]) | |
| expected["evi_direction_margin"] = float(evi_po["margin"]) | |
| except (KeyError, TypeError, ValueError) as exc: | |
| raise RunArtifactError(f"experiment config lacks runtime authority: {exc}") from exc | |
| drift = { | |
| name: (getattr(args, name), value) | |
| for name, value in expected.items() | |
| if getattr(args, name) != value | |
| } | |
| if drift: | |
| formatted = ", ".join( | |
| f"{name}={actual!r} (config {wanted!r})" | |
| for name, (actual, wanted) in sorted(drift.items()) | |
| ) | |
| raise RunArtifactError( | |
| "runtime arguments drift from authoritative experiment config: " + formatted | |
| ) | |
| target_modules = tuple(args.target_module or ["all-linear"]) | |
| if target_modules != ("all-linear",): | |
| raise RunArtifactError( | |
| "controlled plans require the config-frozen LoRA target_modules=all-linear" | |
| ) | |
| if args.backend_entrypoint != "explicit_learning.training.backend:run": | |
| raise RunArtifactError( | |
| "controlled plans require backend explicit_learning.training.backend:run" | |
| ) | |
| def cmd_dry_run(args: argparse.Namespace) -> int: | |
| try: | |
| summary = offline_contract_smoke( | |
| steps_per_arm=args.steps_per_arm, | |
| seed=args.seed, | |
| token_cap=args.token_cap, | |
| ) | |
| except (ValueError, AdmissionError, LedgerError) as exc: | |
| print(f"OFFLINE DRY RUN FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| print(json.dumps(summary, sort_keys=True)) | |
| return 0 | |
| def cmd_snapshot_environment(args: argparse.Namespace) -> int: | |
| try: | |
| snapshot = write_environment_snapshot(args.output) | |
| except (FileExistsError, OSError, RuntimeError) as exc: | |
| print(f"ENVIRONMENT SNAPSHOT FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| print( | |
| json.dumps( | |
| { | |
| "ok": True, | |
| "output": str(args.output), | |
| "distribution_count": len(snapshot["distributions"]), | |
| "cuda_available": bool( | |
| snapshot.get("torch") and snapshot["torch"]["cuda_available"] | |
| ), | |
| }, | |
| sort_keys=True, | |
| ) | |
| ) | |
| return 0 | |
| def _admitted( | |
| args: argparse.Namespace, | |
| *, | |
| replayed_view_dirs: frozenset[Path] | None = None, | |
| replay_certificates: bool = True, | |
| verify_assets: bool = True, | |
| ) -> tuple[AdmittedGroup, ...]: | |
| validator = _resolve_validator( | |
| args.validator, | |
| asset_root=args.asset_root, | |
| replayed_view_dirs=replayed_view_dirs, | |
| replay_certificates=replay_certificates, | |
| ) | |
| return load_groups( | |
| args.dataset, | |
| dataset_root=args.asset_root, | |
| validator=validator, | |
| verify_assets=verify_assets, | |
| ) | |
| def _common_sft_rows( | |
| groups: tuple[AdmittedGroup, ...], | |
| *, | |
| mode: str, | |
| ) -> list[dict[str, Any]]: | |
| if mode not in {"full_only", "full_plus_certified_intervention"}: | |
| raise ValueError(f"unsupported SFT data mode: {mode!r}") | |
| rows: list[dict[str, Any]] = [] | |
| for group in sorted(groups, key=lambda item: item.base_id): | |
| views = [ | |
| view | |
| for view in group.row["views"] | |
| if mode == "full_plus_certified_intervention" or view["state"] == "FULL" | |
| ] | |
| for view in views: | |
| target = ours_target(view, group.row["full_answer_canonical"]) | |
| rows.append( | |
| { | |
| "schema_version": 2, | |
| "record_kind": mode, | |
| "group_id": group.group_id, | |
| "base_id": group.base_id, | |
| "split": group.row["split"], | |
| "view_id": view["view_id"], | |
| "state": view["state"], | |
| "question": group.row["question"], | |
| "choices": group.row["choices"], | |
| "images": view["images"], | |
| "target": target, | |
| "assistant_response": f"<answer>{target}</answer>", | |
| "answer_type": group.row["answer_type"], | |
| "certificate_id": view["certificate_id"], | |
| "trained": False, | |
| } | |
| ) | |
| return rows | |
| def cmd_build_common_sft_data(args: argparse.Namespace) -> int: | |
| """Build certificate-target SFT records with no teacher or pending trajectory.""" | |
| try: | |
| groups = _admitted(args) | |
| rows = _common_sft_rows(groups, mode=args.mode) | |
| atomic_write_jsonl(args.output, rows) | |
| except (AdmissionError, OSError, StopIteration) as exc: | |
| print(f"SFT DATA BUILD FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| print( | |
| json.dumps( | |
| { | |
| "ok": True, | |
| "trained": False, | |
| "mode": args.mode, | |
| "record_count": len(rows), | |
| "output": str(args.output), | |
| }, | |
| sort_keys=True, | |
| ) | |
| ) | |
| return 0 | |
| def _json_object(path: Path, label: str) -> dict[str, Any]: | |
| try: | |
| value = json.loads(path.read_text(encoding="utf-8")) | |
| except (OSError, json.JSONDecodeError) as exc: | |
| raise ValueError(f"{label} is unreadable: {exc}") from exc | |
| if not isinstance(value, dict): | |
| raise ValueError(f"{label} must contain a JSON object") | |
| return value | |
| def cmd_build_training_inputs(args: argparse.Namespace) -> int: | |
| """Admit once and atomically publish slots plus both raw SFT datasets.""" | |
| output_dir = args.output_dir | |
| staging: Path | None = None | |
| try: | |
| if output_dir.exists(): | |
| raise FileExistsError(f"output directory already exists: {output_dir}") | |
| if len(args.code_commit) != 40 or any( | |
| char not in "0123456789abcdef" for char in args.code_commit | |
| ): | |
| raise ValueError("--code-commit must be a full lowercase 40-hex revision") | |
| if args.workers < 1: | |
| raise ValueError("--workers must be at least 1") | |
| release = _json_object(args.release_manifest, "release manifest") | |
| if ( | |
| release.get("reasoning_vlm_calls") != 0 | |
| or release.get("per_example_human_decisions") != 0 | |
| ): | |
| raise ValueError("release manifest violates zero-VLM/zero-human data policy") | |
| from ..datasets.evi_core_release import EVI_CORE_RELEASE_CONTRACT | |
| core_release = release.get("contract") == EVI_CORE_RELEASE_CONTRACT | |
| replay: dict[str, Any] | None = None | |
| if not core_release: | |
| if args.replay_report is None: | |
| raise ValueError("--replay-report is required for legacy release bundles") | |
| replay = _json_object(args.replay_report, "train replay report") | |
| if ( | |
| not isinstance(replay.get("view_count"), int) | |
| or replay.get("passed") != replay["view_count"] | |
| or replay.get("failed") != 0 | |
| ): | |
| raise ValueError("train replay report is not an exact all-pass result") | |
| replayed_view_dirs: frozenset[Path] | None = None | |
| admission_replay_count = 0 | |
| if args.validator == "builtin-certified-release" and not core_release: | |
| from ..certificates.replay import replay_dataset | |
| admission_results = replay_dataset(args.asset_root, workers=args.workers) | |
| failures = [result for result in admission_results if not result.ok] | |
| if failures: | |
| raise AdmissionError( | |
| "parallel admission replay failed: " + "; ".join(failures[0].errors[:3]) | |
| ) | |
| assert replay is not None | |
| if len(admission_results) != replay["view_count"]: | |
| raise ValueError("parallel admission replay count differs from replay report") | |
| replayed_view_dirs = frozenset( | |
| Path(result.view_dir).resolve() for result in admission_results | |
| ) | |
| admission_replay_count = len(admission_results) | |
| groups = _admitted( | |
| args, | |
| replayed_view_dirs=replayed_view_dirs, | |
| replay_certificates=not core_release, | |
| verify_assets=not core_release, | |
| ) | |
| expected_views = sum(len(group.row["views"]) for group in groups) | |
| if core_release: | |
| group_counts = release.get("group_counts") | |
| if not isinstance(group_counts, Mapping) or group_counts.get("train") != len(groups): | |
| raise ValueError("EVI core release/train group count differs from admitted groups") | |
| split_view_counts = release.get("split_view_counts") | |
| if ( | |
| not isinstance(split_view_counts, Mapping) | |
| or split_view_counts.get("train") != expected_views | |
| ): | |
| raise ValueError("EVI core release/train view count differs from admitted views") | |
| else: | |
| assert replay is not None | |
| split_manifests = release.get("split_manifests") | |
| train_manifest = ( | |
| split_manifests.get("train") if isinstance(split_manifests, Mapping) else None | |
| ) | |
| if not isinstance(train_manifest, Mapping): | |
| raise ValueError("release manifest has no train split manifest") | |
| if train_manifest.get("group_count") != len(groups): | |
| raise ValueError("release/train group count differs from admitted groups") | |
| if train_manifest.get("view_count") != expected_views: | |
| raise ValueError("release/train view count differs from admitted views") | |
| if ( | |
| replay.get("view_count") != expected_views | |
| or replay.get("passed") != expected_views | |
| or replay.get("failed") != 0 | |
| ): | |
| raise ValueError("train replay report is not an exact all-pass result") | |
| slots = build_comparison_slots(groups, seed=args.seed, max_slots=args.max_slots) | |
| if len(slots) != expected_views: | |
| raise ValueError( | |
| f"comparison slots must cover all admitted views: {len(slots)} != {expected_views}" | |
| ) | |
| full_rows = _common_sft_rows(groups, mode="full_only") | |
| pair_rows = _common_sft_rows( | |
| groups, | |
| mode="full_plus_certified_intervention", | |
| ) | |
| if len(full_rows) != len(groups) or len(pair_rows) != expected_views: | |
| raise ValueError("raw SFT datasets do not exactly cover admitted groups/views") | |
| output_dir.parent.mkdir(parents=True, exist_ok=True) | |
| staging = Path( | |
| tempfile.mkdtemp(prefix=f".{output_dir.name}.staging.", dir=output_dir.parent) | |
| ) | |
| slots_path = staging / "comparison-slots.jsonl" | |
| full_path = staging / "full-only.raw.jsonl" | |
| pair_path = staging / "full-plus-intervention.raw.jsonl" | |
| atomic_write_jsonl(slots_path, (slot.to_row() for slot in slots)) | |
| atomic_write_jsonl(full_path, full_rows) | |
| atomic_write_jsonl(pair_path, pair_rows) | |
| state_counts: dict[str, int] = {} | |
| for row in pair_rows: | |
| state = str(row["state"]) | |
| state_counts[state] = state_counts.get(state, 0) + 1 | |
| manifest = { | |
| "schema_version": 1, | |
| "kind": "certified_model_independent_training_inputs", | |
| "trained": False, | |
| "builder_code_commit": args.code_commit, | |
| "group_count": len(groups), | |
| "view_count": expected_views, | |
| "comparison_slot_count": len(slots), | |
| "comparison_slot_manifest_sha256": comparison_slot_manifest_sha256(slots), | |
| "full_only_raw_rows": len(full_rows), | |
| "full_plus_intervention_raw_rows": len(pair_rows), | |
| "full_plus_intervention_state_counts": dict(sorted(state_counts.items())), | |
| "admission_replay_count": admission_replay_count, | |
| "admission_replay_workers": args.workers, | |
| "admission_mode": ( | |
| "structural_no_content_hash_replay" | |
| if core_release | |
| else "legacy_full_certificate_replay" | |
| ), | |
| "reasoning_vlm_calls": 0, | |
| "per_example_human_decisions": 0, | |
| "row_duplication_allowed": False, | |
| } | |
| if not core_release: | |
| assert args.replay_report is not None | |
| manifest.update( | |
| { | |
| "comparison_slots_sha256": sha256_file(slots_path), | |
| "full_only_raw_sha256": sha256_file(full_path), | |
| "full_plus_intervention_raw_sha256": sha256_file(pair_path), | |
| "source_groups_sha256": sha256_file(args.dataset), | |
| "release_manifest_sha256": sha256_file(args.release_manifest), | |
| "train_replay_report_sha256": sha256_file(args.replay_report), | |
| } | |
| ) | |
| atomic_write_json(staging / "manifest.json", manifest) | |
| os.replace(staging, output_dir) | |
| staging = None | |
| except ( | |
| AdmissionError, | |
| FileExistsError, | |
| OSError, | |
| StopIteration, | |
| ValueError, | |
| ) as exc: | |
| if staging is not None: | |
| shutil.rmtree(staging, ignore_errors=True) | |
| print(f"TRAINING INPUT BUILD FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| print(json.dumps({"ok": True, "output_dir": str(output_dir), **manifest}, sort_keys=True)) | |
| return 0 | |
| def cmd_build_comparison_slots(args: argparse.Namespace) -> int: | |
| try: | |
| groups = _admitted(args) | |
| slots = build_comparison_slots(groups, seed=args.seed, max_slots=args.max_slots) | |
| atomic_write_jsonl(args.output, (slot.to_row() for slot in slots)) | |
| except (AdmissionError, OSError, ValueError) as exc: | |
| print(f"COMPARISON SLOT BUILD FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| print( | |
| json.dumps( | |
| { | |
| "ok": True, | |
| "slot_count": len(slots), | |
| "slot_manifest_sha256": comparison_slot_manifest_sha256(slots), | |
| "output": str(args.output), | |
| }, | |
| sort_keys=True, | |
| ) | |
| ) | |
| return 0 | |
| def cmd_match_sft_schedules(args: argparse.Namespace) -> int: | |
| """Loss-token and row-count match the two one-epoch SFT ablations.""" | |
| try: | |
| if not args.model_path.is_dir() or not (args.model_path / "config.json").is_file(): | |
| raise SFTScheduleError("processor/model snapshot is missing config.json") | |
| from transformers import AutoProcessor | |
| processor = AutoProcessor.from_pretrained( | |
| str(args.model_path), | |
| revision=args.model_revision, | |
| ) | |
| full_rows = list(read_jsonl(args.full_input)) | |
| pair_rows = list(read_jsonl(args.pair_input)) | |
| prepared_by_kind = { | |
| kind: prepare_sft_records( | |
| { | |
| "dataset_path": str(path), | |
| "dataset_asset_root": str(args.asset_root), | |
| "arm": kind, | |
| } | |
| ) | |
| for kind, path in ( | |
| ("full_only", args.full_input), | |
| ("full_plus_certified_intervention", args.pair_input), | |
| ) | |
| } | |
| loss_counts: dict[tuple[str, str, str], int] = {} | |
| for kind, prepared in prepared_by_kind.items(): | |
| for row in prepared.rows: | |
| identity = (kind, str(row["group_id"]), str(row["view_id"])) | |
| loss_counts[identity] = sft_loss_token_count(processor, row) | |
| def loss_token_counter(row: Mapping[str, Any]) -> int: | |
| identity = ( | |
| str(row.get("record_kind", "")), | |
| str(row.get("group_id", "")), | |
| str(row.get("view_id", "")), | |
| ) | |
| try: | |
| return loss_counts[identity] | |
| except KeyError as exc: | |
| raise SFTScheduleError(f"prepared loss-token count missing for {identity}") from exc | |
| matched = match_sft_schedules( | |
| full_rows, | |
| pair_rows, | |
| loss_token_counter=loss_token_counter, | |
| intervention_per_state=args.intervention_per_state, | |
| ) | |
| atomic_write_jsonl(args.full_output, matched.full_only) | |
| atomic_write_jsonl(args.pair_output, matched.full_plus_intervention) | |
| manifest = { | |
| "schema_version": 2, | |
| "kind": "loss_token_and_record_matched_sft_schedules", | |
| "model_revision": args.model_revision, | |
| "model_snapshot_sha256": args.model_snapshot_sha256, | |
| "full_source": str(args.full_input.resolve()), | |
| "pair_source": str(args.pair_input.resolve()), | |
| "full_output": str(args.full_output.resolve()), | |
| "pair_output": str(args.pair_output.resolve()), | |
| "loss_tokens_each": matched.loss_tokens, | |
| "records_each": matched.record_count, | |
| "full_record_count": len(matched.full_only), | |
| "pair_record_count": len(matched.full_plus_intervention), | |
| "pair_state_counts": matched.state_counts, | |
| "row_duplication_allowed": False, | |
| "counting_contract": ( | |
| "trl_1.9.1_vlm_prompt_completion_attention_mask_non_padding_tokens" | |
| ), | |
| } | |
| atomic_write_json(args.manifest_output, manifest) | |
| except ( | |
| BackendContractError, | |
| ImportError, | |
| OSError, | |
| SFTScheduleError, | |
| AttributeError, | |
| TypeError, | |
| ValueError, | |
| ) as exc: | |
| print(f"SFT SCHEDULE MATCH FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| print(json.dumps({"ok": True, **manifest}, sort_keys=True)) | |
| return 0 | |
| def _runtime_from_args( | |
| args: argparse.Namespace, | |
| *, | |
| run_id: str, | |
| trainer_kind: TrainerKind, | |
| arm: str, | |
| seed: int, | |
| output_dir: Path, | |
| run_mode: RunMode, | |
| dataset_path: Path | None = None, | |
| ) -> RuntimeTrainingConfig: | |
| # Ablation arms carry code-defined numeric knobs (ABLATION_ARM_KNOBS) that | |
| # override the free CLI --evi-* / papo defaults, so the frozen config is | |
| # pinned to the version-controlled source of truth rather than a YAML value. | |
| # Main-ladder arms are absent from that map and fall back to the CLI args | |
| # (which _validate_runtime_args_against_config has already bound to the | |
| # experiment config). C/D are pure target-function variants with no knob. | |
| ablation_knobs: Mapping[str, float] = ABLATION_ARM_KNOBS.get(arm, {}) if arm in ABLATION_ARMS else {} | |
| return RuntimeTrainingConfig( | |
| run_id=run_id, | |
| trainer_kind=trainer_kind, | |
| arm=arm, | |
| seed=seed, | |
| model_path=str(args.model_path.resolve()), | |
| model_revision=args.model_revision, | |
| model_snapshot_sha256=args.model_snapshot_sha256, | |
| dataset_path=str((dataset_path or args.dataset).resolve()), | |
| dataset_asset_root=str(args.dataset_asset_root.resolve()), | |
| output_dir=str(output_dir.resolve()), | |
| initial_checkpoint_path=str(args.initial_checkpoint.resolve()), | |
| environment_lock_path=str(args.environment_lock.resolve()), | |
| environment_lock_sha256=args.environment_lock_sha256, | |
| evaluation_manifest_path=str(args.evaluation_manifest.resolve()), | |
| evaluation_manifest_sha256=args.evaluation_manifest_sha256, | |
| system_prompt_sha256=sha256_file(repo_root() / "prompts" / "common_system.txt"), | |
| precision="bf16", | |
| attention_implementation="flash_attention_2", | |
| max_prompt_tokens=args.max_prompt_tokens, | |
| max_completion_tokens=args.max_completion_tokens, | |
| total_context_tokens=args.max_prompt_tokens + args.max_completion_tokens, | |
| per_device_train_batch_size=args.per_device_batch_size, | |
| gradient_accumulation_steps=args.gradient_accumulation_steps, | |
| world_size=args.world_size, | |
| generations_per_prompt=1 if trainer_kind == "sft" else args.generations, | |
| checkpoint_interval=args.checkpoint_interval, | |
| max_optimizer_steps=-1 if trainer_kind == "sft" else args.max_optimizer_steps, | |
| max_completion_tokens_per_run=args.token_cap, | |
| learning_rate=args.learning_rate, | |
| lora_rank=64, | |
| lora_alpha=128, | |
| lora_dropout=0.0, | |
| lora_target_modules=tuple(args.target_module or ["all-linear"]), | |
| comparison_slot_manifest_sha256=args.comparison_slot_manifest_sha256, | |
| backend_entrypoint=args.backend_entrypoint, | |
| use_vllm=trainer_kind != "sft", | |
| run_mode=run_mode, | |
| compatibility_gate_path=( | |
| str(args.compatibility_gate.resolve()) | |
| if run_mode == "main" and args.compatibility_gate is not None | |
| else None | |
| ), | |
| evi_direction_loss_weight=( | |
| ablation_knobs.get("lambda_direction", args.evi_direction_loss_weight) | |
| if trainer_kind == "evi_po" | |
| else 0.0 | |
| ), | |
| evi_evidence_loss_weight=( | |
| ablation_knobs.get("lambda_evidence", args.evi_evidence_loss_weight) | |
| if trainer_kind == "evi_po" | |
| else 0.0 | |
| ), | |
| evi_direction_margin=( | |
| ablation_knobs.get("margin", args.evi_direction_margin) | |
| if trainer_kind == "evi_po" | |
| else 0.0 | |
| ), | |
| papo_mask_ratio=( | |
| ablation_knobs.get("mask_ratio", 0.6) if trainer_kind == "papo" else 0.6 | |
| ), | |
| papo_perception_loss_weight=( | |
| ablation_knobs.get("perception_loss_weight", 0.02) | |
| if trainer_kind == "papo" | |
| else 0.02 | |
| ), | |
| ) | |
| def _write_plan( | |
| args: argparse.Namespace, | |
| *, | |
| runtime: RuntimeTrainingConfig, | |
| run_dir: Path, | |
| source_config_sha256: str, | |
| dataset_manifest_sha256: str | None = None, | |
| ) -> tuple[Path, Path, tuple[str, ...]]: | |
| config_path = run_dir / "frozen-config.json" | |
| command = build_launch_command( | |
| config_path, | |
| world_size=runtime.world_size, | |
| python_executable=args.python_executable, | |
| ) | |
| frozen, manifest = build_run_manifest( | |
| runtime, | |
| source_config_sha256=source_config_sha256, | |
| dataset_manifest_sha256=dataset_manifest_sha256 or args.dataset_manifest_sha256, | |
| initial_checkpoint_sha256=args.initial_checkpoint_sha256, | |
| code_commit=args.code_commit, | |
| created_at=args.created_at, | |
| launcher_command=command, | |
| ) | |
| written_config, written_manifest = write_frozen_run( | |
| run_dir, | |
| frozen_config=frozen, | |
| run_manifest=manifest, | |
| ) | |
| return written_config, written_manifest, command | |
| def cmd_sft(args: argparse.Namespace) -> int: | |
| try: | |
| experiment = _load_yaml(args.experiment_config) | |
| _validate_runtime_args_against_config(args, experiment, sft=True) | |
| runtime = _runtime_from_args( | |
| args, | |
| run_id=args.run_id, | |
| trainer_kind="sft", | |
| arm=args.arm, | |
| seed=args.seed, | |
| output_dir=args.run_dir, | |
| run_mode="sft", | |
| ) | |
| config_path, manifest_path, command = _write_plan( | |
| args, | |
| runtime=runtime, | |
| run_dir=args.run_dir, | |
| source_config_sha256=canonical_config_hash(experiment), | |
| ) | |
| except (RunArtifactError, OSError, ValueError) as exc: | |
| print(f"SFT PLAN FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| if args.execute: | |
| try: | |
| return execute(config_path) | |
| except LauncherUnavailable as exc: | |
| print(f"TRAINING BLOCKED: {exc}", file=sys.stderr) | |
| return 2 | |
| check = check_launcher_environment(config_path) if args.check_launcher else None | |
| print( | |
| json.dumps( | |
| { | |
| "status": "planned", | |
| "trained": False, | |
| "config": str(config_path), | |
| "manifest": str(manifest_path), | |
| "launcher_command": command, | |
| "launcher_ready": check.ok if check else None, | |
| "launcher_errors": check.errors if check else (), | |
| }, | |
| sort_keys=True, | |
| ) | |
| ) | |
| return 0 if check is None or check.ok else 2 | |
| def _plan_matrix( | |
| args: argparse.Namespace, | |
| *, | |
| rows: list[Mapping[str, Any]], | |
| source_config_sha256: str, | |
| sft: bool, | |
| run_mode: RunMode, | |
| dataset_by_identity: Mapping[str, Path] | None = None, | |
| dataset_sha_by_identity: Mapping[str, str] | None = None, | |
| ) -> list[dict[str, Any]]: | |
| planned: list[dict[str, Any]] = [] | |
| for row in rows: | |
| if not isinstance(row, Mapping): | |
| raise RunArtifactError("matrix rows must be mappings") | |
| run_id = str(row.get("run_id", "")) | |
| if not run_id: | |
| raise RunArtifactError("matrix row has no run_id") | |
| arm = str(row.get("arm") or row.get("data") or "") | |
| seed = int(row.get("seed", args.seed)) | |
| trainer_kind: TrainerKind = "sft" if sft else arm_trainer_kind(arm) | |
| run_dir = args.run_root / run_id | |
| runtime = _runtime_from_args( | |
| args, | |
| run_id=run_id, | |
| trainer_kind=trainer_kind, | |
| arm=arm, | |
| seed=seed, | |
| output_dir=run_dir, | |
| run_mode=run_mode, | |
| dataset_path=dataset_by_identity.get(arm) if dataset_by_identity else None, | |
| ) | |
| config_path, manifest_path, command = _write_plan( | |
| args, | |
| runtime=runtime, | |
| run_dir=run_dir, | |
| source_config_sha256=source_config_sha256, | |
| dataset_manifest_sha256=( | |
| dataset_sha_by_identity.get(arm) if dataset_sha_by_identity else None | |
| ), | |
| ) | |
| planned.append( | |
| { | |
| "run_id": run_id, | |
| "arm": arm, | |
| "seed": seed, | |
| "trainer_kind": trainer_kind, | |
| "config": str(config_path), | |
| "manifest": str(manifest_path), | |
| "launcher_command": command, | |
| } | |
| ) | |
| return planned | |
| def _validate_rl_matrix(rows: Any, *, token_cap: int) -> list[Mapping[str, Any]]: | |
| if not isinstance(rows, list): | |
| raise RunArtifactError("main_rl_runs must be a list") | |
| if len(rows) != len(_EXPECTED_RL_RUNS): | |
| raise RunArtifactError( | |
| f"main_rl_runs must contain exactly {len(_EXPECTED_RL_RUNS)} rows, found {len(rows)}" | |
| ) | |
| validated: list[Mapping[str, Any]] = [] | |
| identities: set[tuple[str, int]] = set() | |
| run_ids: set[str] = set() | |
| for index, row in enumerate(rows): | |
| if not isinstance(row, Mapping): | |
| raise RunArtifactError(f"main_rl_runs[{index}] must be a mapping") | |
| run_id = str(row.get("run_id", "")) | |
| if not run_id or run_id in run_ids: | |
| raise RunArtifactError(f"main_rl_runs[{index}] has missing or duplicate run_id") | |
| run_ids.add(run_id) | |
| if row.get("model") != "qwen35_2b": | |
| raise RunArtifactError(f"main_rl_runs[{index}] must use model qwen35_2b") | |
| arm = str(row.get("arm", "")) | |
| raw_seed = row.get("seed") | |
| if isinstance(raw_seed, bool) or not isinstance(raw_seed, int): | |
| raise RunArtifactError(f"main_rl_runs[{index}] has invalid seed") | |
| seed = raw_seed | |
| identity = (arm, seed) | |
| if identity in identities: | |
| raise RunArtifactError(f"duplicate main RL arm/seed identity: {identity}") | |
| identities.add(identity) | |
| validated.append(row) | |
| if identities != _EXPECTED_RL_RUNS: | |
| missing = sorted(_EXPECTED_RL_RUNS - identities) | |
| extra = sorted(identities - _EXPECTED_RL_RUNS) | |
| raise RunArtifactError( | |
| f"{len(_EXPECTED_RL_RUNS)}-run matrix identity drift; missing={missing}, extra={extra}" | |
| ) | |
| if token_cap > _RL_TOKEN_CAP: | |
| raise RunArtifactError(f"per-run completion-token cap exceeds {_RL_TOKEN_CAP}") | |
| if token_cap * len(validated) > _TOTAL_RL_TOKEN_CAP: | |
| raise RunArtifactError(f"matrix completion-token cap exceeds {_TOTAL_RL_TOKEN_CAP}") | |
| return validated | |
| def _validate_ablation_matrix(rows: Any, *, token_cap: int) -> list[Mapping[str, Any]]: | |
| """Validate the two-run core ingredient-isolation ablation matrix.""" | |
| if not isinstance(rows, list): | |
| raise RunArtifactError("ablation_rl_runs must be a list") | |
| if len(rows) != len(_EXPECTED_ABLATION_RUNS): | |
| raise RunArtifactError( | |
| f"ablation_rl_runs must contain exactly {len(_EXPECTED_ABLATION_RUNS)} rows, " | |
| f"found {len(rows)}" | |
| ) | |
| validated: list[Mapping[str, Any]] = [] | |
| identities: set[tuple[str, int]] = set() | |
| run_ids: set[str] = set() | |
| for index, row in enumerate(rows): | |
| if not isinstance(row, Mapping): | |
| raise RunArtifactError(f"ablation_rl_runs[{index}] must be a mapping") | |
| run_id = str(row.get("run_id", "")) | |
| if not run_id or run_id in run_ids: | |
| raise RunArtifactError(f"ablation_rl_runs[{index}] has missing or duplicate run_id") | |
| run_ids.add(run_id) | |
| if row.get("model") != "qwen35_2b": | |
| raise RunArtifactError(f"ablation_rl_runs[{index}] must use model qwen35_2b") | |
| arm = str(row.get("arm", "")) | |
| if arm not in CORE_ABLATION_ARMS: | |
| raise RunArtifactError(f"ablation_rl_runs[{index}] has non-core ablation arm {arm!r}") | |
| raw_seed = row.get("seed") | |
| if isinstance(raw_seed, bool) or not isinstance(raw_seed, int): | |
| raise RunArtifactError(f"ablation_rl_runs[{index}] has invalid seed") | |
| identity = (arm, int(raw_seed)) | |
| if identity in identities: | |
| raise RunArtifactError(f"duplicate ablation arm/seed identity: {identity}") | |
| identities.add(identity) | |
| validated.append(row) | |
| if identities != _EXPECTED_ABLATION_RUNS: | |
| missing = sorted(_EXPECTED_ABLATION_RUNS - identities) | |
| extra = sorted(identities - _EXPECTED_ABLATION_RUNS) | |
| raise RunArtifactError( | |
| f"{len(_EXPECTED_ABLATION_RUNS)}-run ablation identity drift; " | |
| f"missing={missing}, extra={extra}" | |
| ) | |
| if token_cap > _RL_TOKEN_CAP: | |
| raise RunArtifactError(f"per-run completion-token cap exceeds {_RL_TOKEN_CAP}") | |
| if token_cap * len(validated) > _TOTAL_ABLATION_TOKEN_CAP: | |
| raise RunArtifactError( | |
| f"ablation completion-token cap exceeds {_TOTAL_ABLATION_TOKEN_CAP}" | |
| ) | |
| return validated | |
| def _validate_smoke_matrix(rows: Any, *, token_cap: int) -> list[Mapping[str, Any]]: | |
| if not isinstance(rows, list) or len(rows) != len(_EXPECTED_SMOKE_RUNS): | |
| raise RunArtifactError( | |
| f"smoke_rl_runs must contain exactly {len(_EXPECTED_SMOKE_RUNS)} rows" | |
| ) | |
| validated: list[Mapping[str, Any]] = [] | |
| identities: set[tuple[str, int]] = set() | |
| run_ids: set[str] = set() | |
| for index, row in enumerate(rows): | |
| if not isinstance(row, Mapping): | |
| raise RunArtifactError(f"smoke_rl_runs[{index}] must be a mapping") | |
| run_id = str(row.get("run_id", "")) | |
| arm = str(row.get("arm", "")) | |
| seed = row.get("seed") | |
| if not run_id or run_id in run_ids or isinstance(seed, bool) or not isinstance(seed, int): | |
| raise RunArtifactError(f"smoke_rl_runs[{index}] has an invalid run_id or seed") | |
| if row.get("model") != "qwen35_2b": | |
| raise RunArtifactError(f"smoke_rl_runs[{index}] must use model qwen35_2b") | |
| run_ids.add(run_id) | |
| identities.add((arm, seed)) | |
| validated.append(row) | |
| if identities != _EXPECTED_SMOKE_RUNS: | |
| raise RunArtifactError( | |
| "controlled-arm smoke identity drift; expected " | |
| f"{sorted(_EXPECTED_SMOKE_RUNS)}, found {sorted(identities)}" | |
| ) | |
| if token_cap > _RL_TOKEN_CAP: | |
| raise RunArtifactError(f"smoke completion-token cap exceeds {_RL_TOKEN_CAP}") | |
| return validated | |
| def _validate_sft_matrix(rows: Any) -> list[Mapping[str, Any]]: | |
| if not isinstance(rows, list): | |
| raise RunArtifactError("sft_ablation_runs must be a list") | |
| if len(rows) != 2: | |
| raise RunArtifactError( | |
| f"sft_ablation_runs must contain exactly two rows, found {len(rows)}" | |
| ) | |
| validated: list[Mapping[str, Any]] = [] | |
| run_ids: set[str] = set() | |
| data_identities: set[str] = set() | |
| for index, row in enumerate(rows): | |
| if not isinstance(row, Mapping): | |
| raise RunArtifactError(f"sft_ablation_runs[{index}] must be a mapping") | |
| run_id = str(row.get("run_id", "")) | |
| data = str(row.get("data", "")) | |
| if not run_id or run_id in run_ids: | |
| raise RunArtifactError(f"sft_ablation_runs[{index}] has missing or duplicate run_id") | |
| if data in data_identities: | |
| raise RunArtifactError(f"duplicate SFT data identity: {data!r}") | |
| if row.get("model") not in {None, "qwen35_2b"}: | |
| raise RunArtifactError(f"sft_ablation_runs[{index}] must use model qwen35_2b") | |
| run_ids.add(run_id) | |
| data_identities.add(data) | |
| validated.append(row) | |
| if data_identities != _EXPECTED_SFT_DATA: | |
| raise RunArtifactError( | |
| "SFT ablation identity drift; expected " | |
| f"{sorted(_EXPECTED_SFT_DATA)}, found {sorted(data_identities)}" | |
| ) | |
| return validated | |
| def cmd_run_matrix(args: argparse.Namespace) -> int: | |
| try: | |
| config = _load_yaml(args.matrix_config) | |
| _validate_runtime_args_against_config(args, config, sft=False) | |
| rows = _validate_rl_matrix(config.get("main_rl_runs"), token_cap=args.token_cap) | |
| planned = _plan_matrix( | |
| args, | |
| rows=rows, | |
| source_config_sha256=canonical_config_hash(config), | |
| sft=False, | |
| run_mode="main", | |
| ) | |
| except (RunArtifactError, OSError, ValueError) as exc: | |
| print(f"RUN MATRIX PLAN FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| print(json.dumps({"status": "planned", "trained": False, "runs": planned}, sort_keys=True)) | |
| return 0 | |
| def cmd_run_rl_ablation(args: argparse.Namespace) -> int: | |
| try: | |
| config = _load_yaml(args.matrix_config) | |
| _validate_runtime_args_against_config(args, config, sft=False, run_mode="main") | |
| rows = _validate_ablation_matrix(config.get("ablation_rl_runs"), token_cap=args.token_cap) | |
| planned = _plan_matrix( | |
| args, | |
| rows=rows, | |
| source_config_sha256=canonical_config_hash(config), | |
| sft=False, | |
| run_mode="main", | |
| ) | |
| except (RunArtifactError, OSError, ValueError) as exc: | |
| print(f"RL ABLATION PLAN FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| print(json.dumps({"status": "planned", "trained": False, "runs": planned}, sort_keys=True)) | |
| return 0 | |
| def _execute_smoke_plan(plan: Mapping[str, Any]) -> dict[str, Any]: | |
| import time | |
| config = Path(str(plan["config"])) | |
| command = tuple(str(part) for part in plan["launcher_command"]) | |
| output = config.parent | |
| completion = output / "training-complete.json" | |
| resume_boundary = output / "smoke-resume-boundary.json" | |
| phase_seconds: dict[int, float] = {} | |
| started = time.monotonic() | |
| for phase in (1, 2): | |
| phase_start = time.monotonic() | |
| completed = subprocess.run(command, check=False).returncode | |
| phase_seconds[phase] = time.monotonic() - phase_start | |
| if completed == 0 and completion.is_file(): | |
| return { | |
| "run_id": plan["run_id"], | |
| "completed": True, | |
| "process_phases": phase, | |
| "completion": str(completion), | |
| "wall_clock_seconds": time.monotonic() - started, | |
| "phase_seconds": phase_seconds, | |
| } | |
| if phase == 1 and resume_boundary.is_file() and not completion.exists(): | |
| continue | |
| raise RunArtifactError( | |
| f"smoke subprocess failed for {plan['run_id']} in phase {phase} " | |
| f"(exit={completed}, boundary={resume_boundary.exists()})" | |
| ) | |
| raise AssertionError("smoke process loop exhausted") | |
| def _print_smoke_timing( | |
| planned: Sequence[Mapping[str, Any]], completed: Sequence[Mapping[str, Any]] | |
| ) -> None: | |
| """Print a per-arm wall-clock timing table (markdown) to stdout. | |
| Columns: run_id | arm | seed | phases | wall-clock | phase-1 | phase-2. | |
| ``phase-1`` is the step-0..5 run ending at the forced resume boundary; | |
| ``phase-2`` is the resume-to-20 run. Times are seconds. | |
| """ | |
| plan_by_id = {plan["run_id"]: plan for plan in planned} | |
| def _s(v: Any) -> str: | |
| return f"{v:.1f}" if isinstance(v, float) else "?" | |
| print("\n## smoke matrix timing (per run, seconds)\n") | |
| print("| run_id | arm | seed | phases | wall-clock | phase-1 | phase-2 |") | |
| print("|--------|-----|------|--------|-----------|---------|---------|") | |
| for done in completed: | |
| plan = plan_by_id.get(done.get("run_id", ""), {}) | |
| rid = done.get("run_id", "?") | |
| arm = plan.get("arm", "?") | |
| seed = plan.get("seed", "?") | |
| phases = done.get("process_phases", "?") | |
| wall = done.get("wall_clock_seconds") | |
| secs = done.get("phase_seconds") or {} | |
| print( | |
| f"| {rid} | {arm} | {seed} | {phases} | " | |
| f"{_s(wall)} | {_s(secs.get(1))} | {_s(secs.get(2))} |" | |
| ) | |
| total = sum(d.get("wall_clock_seconds") or 0.0 for d in completed) | |
| print(f"\n**total wall-clock: {total:.1f}s** across {len(completed)} runs\n") | |
| def cmd_run_smoke_matrix(args: argparse.Namespace) -> int: | |
| """Freeze or execute one 20-step, forced-resume smoke per GPU trainer.""" | |
| try: | |
| config = _load_yaml(args.matrix_config) | |
| _validate_runtime_args_against_config( | |
| args, | |
| config, | |
| sft=False, | |
| run_mode="smoke", | |
| ) | |
| rows = _validate_smoke_matrix( | |
| config.get("smoke_rl_runs"), | |
| token_cap=args.token_cap, | |
| ) | |
| planned = _plan_matrix( | |
| args, | |
| rows=rows, | |
| source_config_sha256=canonical_config_hash(config), | |
| sft=False, | |
| run_mode="smoke", | |
| ) | |
| completed = [_execute_smoke_plan(plan) for plan in planned] if args.execute else [] | |
| except (RunArtifactError, OSError, ValueError) as exc: | |
| print(f"SMOKE MATRIX FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| if args.execute and completed: | |
| _print_smoke_timing(planned, completed) | |
| print( | |
| json.dumps( | |
| { | |
| "status": "completed" if args.execute else "planned", | |
| "trained": bool(args.execute), | |
| "forced_process_resume_step": 5, | |
| "runs": planned, | |
| "completed_runs": completed, | |
| }, | |
| sort_keys=True, | |
| ) | |
| ) | |
| return 0 | |
| def cmd_certify_smoke_gate(args: argparse.Namespace) -> int: | |
| try: | |
| gate = certify_smoke_gate(args.config, args.output) | |
| except (OSError, SmokeGateError, TypeError, ValueError) as exc: | |
| print(f"SMOKE GATE CERTIFICATION FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| print( | |
| json.dumps( | |
| { | |
| "status": gate["status"], | |
| "output": str(args.output), | |
| "common_contract_sha256": gate["common_contract_sha256"], | |
| }, | |
| sort_keys=True, | |
| ) | |
| ) | |
| return 0 | |
| def cmd_run_sft_ablation(args: argparse.Namespace) -> int: | |
| try: | |
| config = _load_yaml(args.matrix_config) | |
| _validate_runtime_args_against_config(args, config, sft=True) | |
| rows = _validate_sft_matrix(config.get("sft_ablation_runs")) | |
| planned = _plan_matrix( | |
| args, | |
| rows=rows, | |
| source_config_sha256=canonical_config_hash(config), | |
| sft=True, | |
| run_mode="sft", | |
| dataset_by_identity={ | |
| "full_only": args.full_only_dataset, | |
| "full_plus_certified_intervention": args.full_intervention_dataset, | |
| }, | |
| dataset_sha_by_identity={ | |
| "full_only": args.full_only_dataset_sha256, | |
| "full_plus_certified_intervention": args.full_intervention_dataset_sha256, | |
| }, | |
| ) | |
| except (RunArtifactError, OSError, ValueError) as exc: | |
| print(f"SFT ABLATION PLAN FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| print(json.dumps({"status": "planned", "trained": False, "runs": planned}, sort_keys=True)) | |
| return 0 | |
| def cmd_rl_smoke(args: argparse.Namespace) -> int: | |
| if args.offline: | |
| try: | |
| summary = offline_contract_smoke( | |
| steps_per_arm=args.steps, | |
| seed=args.seed, | |
| token_cap=args.token_cap, | |
| ) | |
| except (ValueError, AdmissionError, LedgerError) as exc: | |
| print(f"RL OFFLINE SMOKE FAILED: {exc}", file=sys.stderr) | |
| return 1 | |
| summary["requested_arm"] = args.arm | |
| print(json.dumps(summary, sort_keys=True)) | |
| return 0 | |
| if args.frozen_config is None: | |
| print("RL SMOKE BLOCKED: provide --offline or --frozen-config", file=sys.stderr) | |
| return 2 | |
| check = check_launcher_environment(args.frozen_config) | |
| print(json.dumps({"ok": check.ok, "trained": False, "errors": check.errors}, sort_keys=True)) | |
| return 0 if check.ok else 2 | |
| def _add_dataset_admission(parser: argparse.ArgumentParser) -> None: | |
| parser.add_argument("--dataset", type=Path, required=True, help="intervention groups JSONL.") | |
| parser.add_argument("--asset-root", type=Path, required=True) | |
| parser.add_argument( | |
| "--validator", | |
| default="builtin-certified-release", | |
| help="module:function callback invoked for group, image, and certificate admission.", | |
| ) | |
| parser.add_argument("--output", type=Path, required=True) | |
| def _add_runtime_args( | |
| parser: argparse.ArgumentParser, | |
| *, | |
| include_run_id: bool, | |
| default_token_cap: int, | |
| include_dataset: bool = True, | |
| default_optimizer_steps: int = 5750, | |
| ) -> None: | |
| if include_run_id: | |
| parser.add_argument("--run-id", required=True) | |
| parser.add_argument("--run-dir", type=Path, required=True) | |
| parser.add_argument( | |
| "--experiment-config", | |
| type=Path, | |
| default=Path("configs/experiment.yaml"), | |
| ) | |
| else: | |
| parser.add_argument("--run-root", type=Path, required=True) | |
| parser.add_argument("--matrix-config", type=Path, required=True) | |
| parser.add_argument("--model-path", type=Path, required=True) | |
| parser.add_argument("--model-revision", default=QWEN35_2B_REVISION) | |
| parser.add_argument("--model-snapshot-sha256", required=True) | |
| parser.add_argument("--dataset-asset-root", type=Path, required=True) | |
| if include_dataset: | |
| parser.add_argument("--dataset", type=Path, required=True) | |
| parser.add_argument("--dataset-manifest-sha256", required=True) | |
| parser.add_argument( | |
| "--comparison-slot-manifest-sha256", | |
| help="Required for RL plans; binds every arm to one ordered slot schedule.", | |
| ) | |
| parser.add_argument("--initial-checkpoint", type=Path, required=True) | |
| parser.add_argument("--initial-checkpoint-sha256", required=True) | |
| parser.add_argument("--environment-lock", type=Path, required=True) | |
| parser.add_argument("--environment-lock-sha256", required=True) | |
| parser.add_argument("--evaluation-manifest", type=Path, required=True) | |
| parser.add_argument("--evaluation-manifest-sha256", required=True) | |
| parser.add_argument("--compatibility-gate", type=Path) | |
| parser.add_argument("--code-commit", required=True) | |
| parser.add_argument("--created-at", required=True) | |
| parser.add_argument("--seed", type=int, default=1) | |
| parser.add_argument("--per-device-batch-size", type=int, default=1) | |
| parser.add_argument("--gradient-accumulation-steps", type=int, default=16) | |
| parser.add_argument("--world-size", type=int, default=2) | |
| parser.add_argument("--generations", type=int, default=4) | |
| parser.add_argument("--checkpoint-interval", type=int, default=100) | |
| parser.add_argument( | |
| "--max-optimizer-steps", | |
| type=int, | |
| default=default_optimizer_steps, | |
| ) | |
| parser.add_argument("--token-cap", type=int, default=default_token_cap) | |
| parser.add_argument("--learning-rate", type=float, default=1e-6) | |
| parser.add_argument("--max-prompt-tokens", type=int, default=4096) | |
| parser.add_argument("--max-completion-tokens", type=int, default=256) | |
| parser.add_argument("--evi-direction-loss-weight", type=float, default=0.1) | |
| parser.add_argument("--evi-evidence-loss-weight", type=float, default=0.1) | |
| parser.add_argument("--evi-direction-margin", type=float, default=0.5) | |
| parser.add_argument("--target-module", action="append") | |
| parser.add_argument( | |
| "--backend-entrypoint", | |
| default="explicit_learning.training.backend:run", | |
| ) | |
| parser.add_argument("--python-executable", default=sys.executable) | |
| def build_parser() -> argparse.ArgumentParser: | |
| parser = argparse.ArgumentParser(prog="explicit-train") | |
| sub = parser.add_subparsers(dest="command", required=True) | |
| dry = sub.add_parser("dry-run", help="CPU-only all-arm contract exercise; never trains.") | |
| dry.add_argument("--steps-per-arm", type=int, default=2) | |
| dry.add_argument("--seed", type=int, default=20260728) | |
| dry.add_argument("--token-cap", type=int, default=1024) | |
| dry.set_defaults(func=cmd_dry_run) | |
| environment = sub.add_parser( | |
| "snapshot-environment", | |
| help="Write the immutable installed Python/CUDA/wheel environment lock.", | |
| ) | |
| environment.add_argument("--output", type=Path, required=True) | |
| environment.set_defaults(func=cmd_snapshot_environment) | |
| sft_data = sub.add_parser("build-common-sft-data") | |
| _add_dataset_admission(sft_data) | |
| sft_data.add_argument( | |
| "--mode", | |
| choices=["full_only", "full_plus_certified_intervention"], | |
| default="full_only", | |
| ) | |
| sft_data.set_defaults(func=cmd_build_common_sft_data) | |
| slots = sub.add_parser("build-comparison-slots") | |
| _add_dataset_admission(slots) | |
| slots.add_argument("--seed", type=int, default=20260728) | |
| slots.add_argument("--max-slots", type=int, default=46000) | |
| slots.set_defaults(func=cmd_build_comparison_slots) | |
| training_inputs = sub.add_parser( | |
| "build-training-inputs", | |
| help="Admit once and atomically publish slots plus both raw SFT datasets.", | |
| ) | |
| training_inputs.add_argument("--dataset", type=Path, required=True) | |
| training_inputs.add_argument("--asset-root", type=Path, required=True) | |
| training_inputs.add_argument( | |
| "--validator", | |
| default="builtin-certified-release", | |
| help="module:function callback invoked for group, image, and certificate admission.", | |
| ) | |
| training_inputs.add_argument("--release-manifest", type=Path, required=True) | |
| training_inputs.add_argument( | |
| "--replay-report", | |
| type=Path, | |
| default=None, | |
| help="Required only for legacy bundles that use full certificate replay.", | |
| ) | |
| training_inputs.add_argument("--output-dir", type=Path, required=True) | |
| training_inputs.add_argument("--code-commit", required=True) | |
| training_inputs.add_argument("--seed", type=int, default=20260728) | |
| training_inputs.add_argument("--max-slots", type=int, default=46000) | |
| training_inputs.add_argument("--workers", type=int, default=8) | |
| training_inputs.set_defaults(func=cmd_build_training_inputs) | |
| schedules = sub.add_parser( | |
| "match-sft-schedules", | |
| help="Build token-matched, non-duplicated one-epoch SFT schedules.", | |
| ) | |
| schedules.add_argument("--full-input", type=Path, required=True) | |
| schedules.add_argument("--pair-input", type=Path, required=True) | |
| schedules.add_argument("--full-output", type=Path, required=True) | |
| schedules.add_argument("--pair-output", type=Path, required=True) | |
| schedules.add_argument("--manifest-output", type=Path, required=True) | |
| schedules.add_argument("--model-path", type=Path, required=True) | |
| schedules.add_argument("--model-revision", default=QWEN35_2B_REVISION) | |
| schedules.add_argument("--model-snapshot-sha256", required=True) | |
| schedules.add_argument("--asset-root", type=Path, required=True) | |
| schedules.add_argument("--intervention-per-state", type=int, default=300) | |
| schedules.set_defaults(func=cmd_match_sft_schedules) | |
| sft = sub.add_parser("sft", help="Freeze an SFT launch plan; --execute is explicit.") | |
| _add_runtime_args(sft, include_run_id=True, default_token_cap=_SFT_TOKEN_CAP) | |
| sft.add_argument( | |
| "--arm", | |
| choices=["full_only", "full_plus_certified_intervention"], | |
| default="full_only", | |
| ) | |
| sft.add_argument("--check-launcher", action="store_true") | |
| sft.add_argument("--execute", action="store_true") | |
| sft.set_defaults(func=cmd_sft) | |
| smoke = sub.add_parser("rl-smoke") | |
| smoke.add_argument("--offline", action="store_true") | |
| smoke.add_argument( | |
| "--arm", | |
| choices=[ | |
| "answer_grpo", | |
| "papo_controlled", | |
| "defacto_controlled", | |
| "intervention_grpo", | |
| "evi_po", | |
| ], | |
| ) | |
| smoke.add_argument("--steps", type=int, default=2) | |
| smoke.add_argument("--seed", type=int, default=1) | |
| smoke.add_argument("--token-cap", type=int, default=1024) | |
| smoke.add_argument("--frozen-config", type=Path) | |
| smoke.set_defaults(func=cmd_rl_smoke) | |
| smoke_matrix = sub.add_parser( | |
| "run-smoke-matrix", | |
| help="Freeze or execute one 20-step smoke per GPU trainer with forced resume.", | |
| ) | |
| _add_runtime_args( | |
| smoke_matrix, | |
| include_run_id=False, | |
| default_token_cap=_RL_TOKEN_CAP, | |
| default_optimizer_steps=20, | |
| ) | |
| smoke_matrix.add_argument("--execute", action="store_true") | |
| smoke_matrix.set_defaults(func=cmd_run_smoke_matrix) | |
| smoke_gate = sub.add_parser( | |
| "certify-smoke-gate", | |
| help="Certify the three completed 20-step GPU trainer smokes once.", | |
| ) | |
| smoke_gate.add_argument("--config", type=Path, action="append", required=True) | |
| smoke_gate.add_argument("--output", type=Path, required=True) | |
| smoke_gate.set_defaults(func=cmd_certify_smoke_gate) | |
| matrix = sub.add_parser( | |
| "run-matrix", | |
| help="Freeze the controlled launch matrix; does not submit jobs.", | |
| ) | |
| _add_runtime_args(matrix, include_run_id=False, default_token_cap=_RL_TOKEN_CAP) | |
| matrix.set_defaults(func=cmd_run_matrix) | |
| rl_ablation = sub.add_parser( | |
| "run-rl-ablation", | |
| help="Freeze the two direct EVI ingredient ablations; does not submit jobs.", | |
| ) | |
| _add_runtime_args( | |
| rl_ablation, include_run_id=False, default_token_cap=_RL_TOKEN_CAP | |
| ) | |
| rl_ablation.set_defaults(func=cmd_run_rl_ablation) | |
| ablation = sub.add_parser( | |
| "run-sft-ablation", help="Freeze SFT ablation plans; does not submit jobs." | |
| ) | |
| _add_runtime_args( | |
| ablation, | |
| include_run_id=False, | |
| default_token_cap=_SFT_TOKEN_CAP, | |
| include_dataset=False, | |
| ) | |
| ablation.add_argument("--full-only-dataset", type=Path, required=True) | |
| ablation.add_argument("--full-only-dataset-sha256", required=True) | |
| ablation.add_argument("--full-intervention-dataset", type=Path, required=True) | |
| ablation.add_argument("--full-intervention-dataset-sha256", required=True) | |
| ablation.set_defaults(func=cmd_run_sft_ablation) | |
| return parser | |
| def main(argv: list[str] | None = None) -> int: | |
| if argv == []: | |
| build_parser().print_usage(sys.stderr) | |
| return 2 | |
| args = build_parser().parse_args(argv) | |
| return int(args.func(args)) | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |