"""Frozen training config and immutable planned-run manifest builders.""" from __future__ import annotations import json import math from dataclasses import asdict, dataclass from datetime import datetime from pathlib import Path from typing import Any, Literal from ..atomic_io import atomic_write_json from ..hashing import canonical_json, canonical_json_hash, is_git_revision, is_sha256 from .evi_po_contract import EVI_PO_ADAPTER_VERSION from .papo_contract import ( PAPO_ADAPTER_VERSION, PAPO_UPSTREAM_SOURCE_SHA256, PAPO_UPSTREAM_SOURCE_URL, ) from .rewards import arm_trainer_kind, canonical_arm TrainerKind = Literal["sft", "grpo", "papo", "evi_po"] RunMode = Literal["sft", "smoke", "main"] QWEN35_2B_REVISION = "15852e8c16360a2fea060d615a32b45270f8a8fc" TRAINING_CONTRACT_VERSION = "evi_v2_constrained_answer_256_v1" # Constrained decoding removes irrelevant formatting/runaway-generation noise # while preserving every certified answer, including the public abstention # token. vLLM completes the regex and emits EOS; the 256-token cap remains a # hard safety boundary rather than a routinely reached training event. ANSWER_SCHEMA_REGEX = r"(|[^<>\r\n]{1,128})" class RunArtifactError(RuntimeError): """Raised when a frozen run identity or write-once artifact drifts.""" @dataclass(frozen=True) class RuntimeTrainingConfig: """Fully resolved values required before a GPU launcher may run.""" run_id: str trainer_kind: TrainerKind arm: str seed: int model_path: str model_revision: str model_snapshot_sha256: str dataset_path: str dataset_asset_root: str output_dir: str initial_checkpoint_path: str environment_lock_path: str environment_lock_sha256: str evaluation_manifest_path: str evaluation_manifest_sha256: str system_prompt_sha256: str precision: str attention_implementation: str max_prompt_tokens: int max_completion_tokens: int total_context_tokens: int per_device_train_batch_size: int gradient_accumulation_steps: int world_size: int generations_per_prompt: int checkpoint_interval: int max_optimizer_steps: int max_completion_tokens_per_run: int learning_rate: float lora_rank: int lora_alpha: int lora_dropout: float lora_target_modules: tuple[str, ...] comparison_slot_manifest_sha256: str | None = None backend_entrypoint: str | None = None use_vllm: bool = True run_mode: RunMode = "main" compatibility_gate_path: str | None = None evi_direction_loss_weight: float = 0.0 evi_evidence_loss_weight: float = 0.0 evi_direction_margin: float = 0.0 papo_mask_ratio: float = 0.6 papo_perception_loss_weight: float = 0.02 def __post_init__(self) -> None: if not isinstance(self.run_id, str) or not self.run_id: raise RunArtifactError("run_id must be non-empty") if self.trainer_kind not in {"sft", "grpo", "papo", "evi_po"}: raise RunArtifactError(f"unsupported trainer kind: {self.trainer_kind}") if self.run_mode not in {"sft", "smoke", "main"}: raise RunArtifactError(f"unsupported run mode: {self.run_mode}") if self.trainer_kind == "sft" and self.run_mode != "sft": raise RunArtifactError("SFT trainer requires run_mode=sft") if self.trainer_kind != "sft" and self.run_mode not in {"smoke", "main"}: raise RunArtifactError("RL trainer requires run_mode=smoke or main") if self.trainer_kind != "sft": try: canonical = canonical_arm(self.arm) except ValueError as exc: raise RunArtifactError(f"unsupported RL arm: {self.arm}") from exc if canonical != self.arm: object.__setattr__(self, "arm", canonical) if self.trainer_kind != "sft" and self.trainer_kind != arm_trainer_kind(self.arm): raise RunArtifactError( f"trainer kind {self.trainer_kind!r} does not match arm {self.arm!r}" ) evi_values = ( self.evi_direction_loss_weight, self.evi_evidence_loss_weight, self.evi_direction_margin, ) if any( isinstance(value, bool) or not isinstance(value, int | float) or not math.isfinite(float(value)) or value < 0 for value in evi_values ): raise RunArtifactError("EVI-PO weights and margin must be finite and non-negative") if self.trainer_kind != "evi_po" and any(value != 0.0 for value in evi_values): raise RunArtifactError("non-EVI trainers may not carry EVI-PO objective values") if self.trainer_kind != "sft": if not self.comparison_slot_manifest_sha256: raise RunArtifactError( "RL runs require comparison_slot_manifest_sha256 for schedule fairness" ) if not is_sha256(self.comparison_slot_manifest_sha256): raise RunArtifactError("comparison_slot_manifest_sha256 must be a SHA-256") elif self.comparison_slot_manifest_sha256 is not None and not is_sha256( self.comparison_slot_manifest_sha256 ): raise RunArtifactError("comparison_slot_manifest_sha256 must be a SHA-256") if isinstance(self.seed, bool) or not isinstance(self.seed, int) or self.seed < 0: raise RunArtifactError("seed must be a non-negative integer") if not isinstance(self.model_revision, str) or not is_git_revision(self.model_revision): raise RunArtifactError("model_revision must be an exact 40-hex revision") if self.model_revision != QWEN35_2B_REVISION: raise RunArtifactError("model_revision does not match pinned Qwen3.5-2B") for name in ( "model_snapshot_sha256", "environment_lock_sha256", "evaluation_manifest_sha256", "system_prompt_sha256", ): if not is_sha256(str(getattr(self, name))): raise RunArtifactError(f"{name} must be a SHA-256") numeric_positive = ( "max_prompt_tokens", "max_completion_tokens", "total_context_tokens", "per_device_train_batch_size", "gradient_accumulation_steps", "world_size", "generations_per_prompt", "checkpoint_interval", "max_completion_tokens_per_run", "lora_rank", "lora_alpha", ) for name in numeric_positive: value = getattr(self, name) if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise RunArtifactError(f"{name} must be a positive integer") if self.max_prompt_tokens + self.max_completion_tokens != self.total_context_tokens: raise RunArtifactError("prompt + completion tokens must equal total context") if ( isinstance(self.learning_rate, bool) or not isinstance(self.learning_rate, int | float) or not math.isfinite(self.learning_rate) or self.learning_rate <= 0 ): raise RunArtifactError("learning_rate must be finite and positive") if ( isinstance(self.lora_dropout, bool) or not isinstance(self.lora_dropout, int | float) or not math.isfinite(self.lora_dropout) or not 0 <= self.lora_dropout < 1 ): raise RunArtifactError("lora_dropout must be finite and in [0,1)") if self.lora_target_modules != ("all-linear",): raise RunArtifactError("controlled runs require lora_target_modules=all-linear") for name in ( "model_path", "dataset_path", "dataset_asset_root", "output_dir", "initial_checkpoint_path", "environment_lock_path", "evaluation_manifest_path", ): value = getattr(self, name) if ( not isinstance(value, str) or not value.strip() or value.strip() in { "required", "set_by_common_oom_smoke", "set_to_match_global_batch", "TODO", "TBD", } ): raise RunArtifactError(f"{name} is unresolved") if self.trainer_kind == "sft": if self.max_optimizer_steps != -1: raise RunArtifactError("SFT requires max_optimizer_steps=-1 for one epoch") if Path(self.initial_checkpoint_path).resolve() != Path(self.model_path).resolve(): raise RunArtifactError( "SFT initial_checkpoint_path must equal model_path (base initialization)" ) elif self.run_mode == "smoke" and self.max_optimizer_steps != 20: raise RunArtifactError("controlled RL smoke requires exactly 20 optimizer steps") elif self.run_mode == "main" and self.max_optimizer_steps != 5750: raise RunArtifactError("controlled main RL runs require exactly 5,750 optimizer steps") if self.run_mode == "main": if ( not isinstance(self.compatibility_gate_path, str) or not self.compatibility_gate_path.strip() ): raise RunArtifactError("main RL runs require compatibility_gate_path") elif self.compatibility_gate_path is not None: raise RunArtifactError("SFT and smoke plans may not carry a compatibility gate") if self.precision != "bf16": raise RunArtifactError("Qwen3.5 controlled runs require bf16 precision") if self.attention_implementation != "flash_attention_2": raise RunArtifactError("Qwen3.5 controlled runs require flash_attention_2") if not isinstance(self.use_vllm, bool): raise RunArtifactError("use_vllm must be boolean") if self.backend_entrypoint != "explicit_learning.training.backend:run": raise RunArtifactError("controlled runs require explicit_learning.training.backend:run") if (self.lora_rank, self.lora_alpha, self.lora_dropout) != (64, 128, 0.0): raise RunArtifactError("controlled runs require LoRA r=64, alpha=128, dropout=0") if self.learning_rate != 1e-6: raise RunArtifactError("controlled runs require learning_rate=1e-6") if (self.max_prompt_tokens, self.max_completion_tokens, self.total_context_tokens) != ( 4096, 256, 4352, ): raise RunArtifactError("controlled runs require a 4096/256/4352 token envelope") expected_generations = 1 if self.trainer_kind == "sft" else 4 if self.generations_per_prompt != expected_generations: raise RunArtifactError( f"{self.trainer_kind} requires generations_per_prompt={expected_generations}" ) if ( self.trainer_kind != "sft" and self.global_prompt_batch_size % self.generations_per_prompt != 0 ): raise RunArtifactError( "global prompt batch size must be divisible by generations_per_prompt" ) token_cap = 6_000_000 if self.trainer_kind == "sft" else 24_000_000 if self.max_completion_tokens_per_run > token_cap: raise RunArtifactError( f"{self.trainer_kind} token budget exceeds protocol cap {token_cap}" ) @property def global_prompt_batch_size(self) -> int: return self.per_device_train_batch_size * self.gradient_accumulation_steps * self.world_size def to_dict(self) -> dict[str, Any]: value = asdict(self) value["lora_target_modules"] = list(self.lora_target_modules) value["global_prompt_batch_size"] = self.global_prompt_batch_size value["effective_completion_batch_size"] = self.global_prompt_batch_size value["unique_prompt_groups_per_optimizer_step"] = ( self.global_prompt_batch_size if self.trainer_kind == "sft" else self.global_prompt_batch_size // self.generations_per_prompt ) value["train_full_weights"] = False value["base_model_resource"] = "qwen35_2b" value["base_model_repo_id"] = "Qwen/Qwen3.5-2B" value["training_contract_version"] = TRAINING_CONTRACT_VERSION value["completion_only_sft_loss"] = self.trainer_kind == "sft" value["assistant_only_sft_loss"] = False value["reject_overlength_samples"] = True # No-thinking protocol: the system prompt, SFT gold, structured rollout # regex, and reward all share the same concise answer contract. value["enable_thinking"] = False value["structured_output_regex"] = ( None if self.trainer_kind == "sft" else ANSWER_SCHEMA_REGEX ) value["optimizer"] = { "name": "adamw_torch", "learning_rate": self.learning_rate, "weight_decay": 0.0, "betas": [0.9, 0.999], "eps": 1.0e-8, } value["scheduler"] = {"name": "cosine", "warmup_ratio": 0.03} value["gradient_checkpointing"] = True value["max_grad_norm"] = 1.0 value["num_train_epochs"] = 1 value["max_optimizer_steps"] = self.max_optimizer_steps value["temperature"] = None if self.trainer_kind == "sft" else 1.0 value["top_p"] = None if self.trainer_kind == "sft" else 1.0 value["loss_type"] = ( "assistant_only_cross_entropy" if self.trainer_kind == "sft" else ("grpo" if self.trainer_kind == "papo" else "dr_grpo") ) value["beta"] = ( None if self.trainer_kind == "sft" else (0.01 if self.trainer_kind == "papo" else 0.0) ) value["freeze_vision_tower"] = False value["freeze_multimodal_projector"] = False value["lora_exclude_modules"] = ["embeddings", "lm_head"] value["papo_config"] = ( { "variant": "PAPO-G", "mask_ratio": self.papo_mask_ratio, "mask_type": "random", "perception_loss_weight": self.papo_perception_loss_weight, "der_loss_weight1": 0.0, "der_loss_weight2": 0.0, "require_gpu_contract_probe": self.run_mode == "smoke", "adapter_version": PAPO_ADAPTER_VERSION, "upstream_source_url": PAPO_UPSTREAM_SOURCE_URL, "upstream_source_sha256": PAPO_UPSTREAM_SOURCE_SHA256, } if self.trainer_kind == "papo" else None ) value["evi_po_config"] = ( { "adapter_version": EVI_PO_ADAPTER_VERSION, "lambda_direction": self.evi_direction_loss_weight, "lambda_evidence": self.evi_evidence_loss_weight, "margin": self.evi_direction_margin, "required_relationships": ["FULL", "CONTROL", "MISSING"], "optional_relationships": ["SUBSTITUTE"], "candidate_support": "group_answers_plus_unanswerable", "evidence_supervision_relation": "FULL", "evidence_sources": [ "executor_dependency_nodes_projected_through_node_map", "source_annotation_explicit_mask", "source_annotation_bboxes", ], "attention_capture": "last_full_attention_layer_eager_forward_hook", "require_gpu_contract_probe": ( self.run_mode == "smoke" and ( self.evi_direction_loss_weight > 0.0 or self.evi_evidence_loss_weight > 0.0 ) ), "zero_weight_reduction": "exact_parent_grpo_path", } if self.trainer_kind == "evi_po" else None ) value["vllm_config"] = ( { "mode": "colocate", # Throughput-only knob: this is the fraction of GPU memory vLLM # reserves for its KV cache during the rollout (generation) phase. # Raising it lets more completions generate concurrently, which # speeds up RL rollout — the dominant runtime cost — WITHOUT # changing which tokens are sampled (seed + prompt + sampling # params are unchanged), so completions, gradients, and the # trained model are identical. The experimental batch sizes # (per_device_train_batch_size, gradient_accumulation_steps, # generations_per_prompt) are untouched. With enable_sleep_mode # vLLM frees its KV cache for the batch-1 LoRA training step, so # the rollout cap and the training step do not contend: a high # cap enlarges only the rollout KV cache. 0.85 on 80GB H100s # keeps ~67GB for vLLM weights+KV during rollout while the # sleep-mode training step reclaims the KV portion. Lower if a # colocate OOM appears (the smoke gate requires 0). "gpu_memory_utilization": 0.85, "max_model_length": self.total_context_tokens, "tensor_parallel_size": 1, "enable_sleep_mode": True, "structured_outputs_regex": ANSWER_SCHEMA_REGEX, } if self.use_vllm else None ) value["token_budget_kind"] = ( "assistant_tokens" if self.trainer_kind == "sft" else "sampled_completion_tokens" ) value["sampled_completion_token_budget_role"] = ( None if self.trainer_kind == "sft" else "hard_safety_ceiling_not_equality_target" ) value["requires_forced_five_step_process_resume"] = self.run_mode == "smoke" return value def build_run_manifest( config: RuntimeTrainingConfig, *, source_config_sha256: str, dataset_manifest_sha256: str, initial_checkpoint_sha256: str, code_commit: str, created_at: str, launcher_command: tuple[str, ...], ) -> tuple[dict[str, Any], dict[str, Any]]: """Return frozen config and a manifest that says ``planned``, never trained.""" for name, value in ( ("source_config_sha256", source_config_sha256), ("dataset_manifest_sha256", dataset_manifest_sha256), ("initial_checkpoint_sha256", initial_checkpoint_sha256), ): if not isinstance(value, str) or not is_sha256(value): raise RunArtifactError(f"{name} must be a SHA-256") if not isinstance(code_commit, str) or not is_git_revision(code_commit): raise RunArtifactError("code_commit must be an exact 40-hex revision") if not isinstance(created_at, str) or not created_at: raise RunArtifactError("created_at must be supplied") try: parsed_created_at = datetime.fromisoformat(created_at.replace("Z", "+00:00")) except ValueError as exc: raise RunArtifactError("created_at must be ISO-8601") from exc if parsed_created_at.tzinfo is None: raise RunArtifactError("created_at must include a timezone") if not launcher_command or any(not str(part) for part in launcher_command): raise RunArtifactError("launcher_command must be explicit and non-empty") frozen = { "schema_version": 1, "source_config_sha256": source_config_sha256, "runtime": config.to_dict(), } frozen_sha = canonical_json_hash(frozen) manifest = { "schema_version": 1, "kind": "training_run_plan", "status": "planned", "trained": False, "run_id": config.run_id, "arm": config.arm, "seed": config.seed, "trainer_kind": config.trainer_kind, "run_mode": config.run_mode, "code_commit": code_commit, "created_at": created_at, "frozen_config_sha256": frozen_sha, "dataset_manifest_sha256": dataset_manifest_sha256, "initial_checkpoint_sha256": initial_checkpoint_sha256, "model_snapshot_sha256": config.model_snapshot_sha256, "environment_lock_sha256": config.environment_lock_sha256, "evaluation_manifest_sha256": config.evaluation_manifest_sha256, "system_prompt_sha256": config.system_prompt_sha256, "comparison_slot_manifest_sha256": config.comparison_slot_manifest_sha256, "launcher_command": list(launcher_command), } return frozen, manifest def _write_once(path: Path, value: dict[str, Any]) -> None: if path.exists(): try: existing = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError as exc: raise RunArtifactError(f"existing frozen artifact is invalid JSON: {path}") from exc if canonical_json(existing) != canonical_json(value): raise RunArtifactError(f"refusing to overwrite drifted frozen artifact: {path}") return atomic_write_json(path, value) def write_frozen_run( run_dir: str | Path, *, frozen_config: dict[str, Any], run_manifest: dict[str, Any], ) -> tuple[Path, Path]: directory = Path(run_dir) directory.mkdir(parents=True, exist_ok=True) config_path = directory / "frozen-config.json" manifest_path = directory / "run-manifest.json" _write_once(config_path, frozen_config) _write_once(manifest_path, run_manifest) return config_path, manifest_path