"""Pydantic models for the resource manifest and experiment defaults. These models are the runtime source of truth for ``configs/resources.yaml`` and ``configs/experiment.yaml``. They enforce the research invariants that ``scripts/validate_spec.py`` checks statically, so a config that loads here is safe to use in a run. Floating revisions, MathVista in training, invented MMK12 licenses, and a malformed run matrix all fail at load time. """ from __future__ import annotations import math from pathlib import Path from typing import Any import yaml from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator from .hashing import canonical_config_hash, is_git_revision # Revision policy: every HF/Git resource must resolve to an exact 40-hex commit. # ADR-0002: gold authority is a machine-checkable executor certificate; no # per-example human edit/label/review/adjudication is permitted. EXPECTED_MAIN_RUNS = 9 EXPECTED_RUN_COUNTS: dict[tuple[str, str], int] = { ("qwen35_2b", "answer_grpo"): 1, ("qwen35_2b", "papo_controlled"): 2, ("qwen35_2b", "defacto_controlled"): 2, ("qwen35_2b", "intervention_grpo"): 2, ("qwen35_2b", "evi_po"): 2, } # Core ingredient isolation: remove each EVI-PO auxiliary loss once. Broader # target/PAPO/margin sweeps remain opt-in rather than an automatic GPU queue. EXPECTED_ABLATION_RUNS = 2 EXPECTED_ABLATION_ARMS: tuple[str, ...] = ( "evi_po_no_direction", "evi_po_no_evidence", ) class ConfigError(ValueError): """Raised when a config file violates a research invariant.""" def _load_yaml(path: str | Path) -> dict[str, Any]: text = Path(path).read_text(encoding="utf-8") data = yaml.safe_load(text) if not isinstance(data, dict): raise ConfigError(f"{path} must contain a top-level mapping") return data class ResourceModel(BaseModel): model_config = ConfigDict(extra="allow") role: str provider: str repo_id: str revision: str url: str license: str | None = None access: str = "public" estimated_size_bytes: int | None = None use: str | None = None @model_validator(mode="after") def _check_revision(self) -> ResourceModel: if not is_git_revision(self.revision): raise ConfigError( f"models.{self.repo_id}.revision must be a 40-hex commit, got {self.revision!r}" ) return self class ResourceDataset(BaseModel): model_config = ConfigDict(extra="allow") role: str provider: str repo_id: str revision: str url: str declared_license: str | None = None policy: str = "" configs: list[str] | None = None # Split metadata is heterogeneous across sources (flat counts for most, # per-config counts for MMMU), so values are left loosely typed; specific # guards in validate_against_resources check exact values where it matters. splits: dict[str, Any] | None = None splits_per_config: dict[str, Any] | None = None notes: list[str] | None = None @model_validator(mode="after") def _check_revision(self) -> ResourceDataset: if not is_git_revision(self.revision): raise ConfigError( f"datasets.{self.repo_id}.revision must be a 40-hex commit, got {self.revision!r}" ) return self class ResourceCheckpoint(BaseModel): model_config = ConfigDict(extra="allow") role: str provider: str repo_id: str revision: str url: str policy: str = "" @model_validator(mode="after") def _check_revision(self) -> ResourceCheckpoint: if not is_git_revision(self.revision): raise ConfigError( f"checkpoints.{self.repo_id}.revision must be a 40-hex commit, " f"got {self.revision!r}" ) return self class ResourceRepository(BaseModel): model_config = ConfigDict(extra="allow") url: str revision: str role: str @model_validator(mode="after") def _check_revision(self) -> ResourceRepository: if not is_git_revision(self.revision): raise ConfigError( f"repositories.{self.url}.revision must be a 40-hex commit, got {self.revision!r}" ) return self class ResourcesManifest(BaseModel): model_config = ConfigDict(extra="allow") manifest_version: int models: dict[str, ResourceModel] = Field(default_factory=dict) datasets: dict[str, ResourceDataset] = Field(default_factory=dict) checkpoints: dict[str, ResourceCheckpoint] = Field(default_factory=dict) repositories: dict[str, ResourceRepository] = Field(default_factory=dict) # C1 source-native structured worlds (PlotQA, Geometry3K) live outside the HF # ``datasets`` map: they are fetched from pinned GitHub revisions and feed the # certificate pipeline directly (docs/02 ยง4-6). Kept loosely typed here; the # adapter layer owns their detailed schema. structured_sources: dict[str, Any] = Field(default_factory=dict) def model(self, name: str) -> ResourceModel: if name not in self.models: raise ConfigError(f"unknown model resource {name!r}") return self.models[name] def dataset(self, name: str) -> ResourceDataset: if name not in self.datasets: raise ConfigError(f"unknown dataset resource {name!r}") return self.datasets[name] class ExperimentRun(BaseModel): model_config = ConfigDict(extra="forbid") run_id: str model: str arm: str seed: int class CommonStudent(BaseModel): model_config = ConfigDict(extra="allow") # One trainable 2B student. The v1 C1 release uses no teacher/verifier model. model_resource: str precision: str = "bf16" attention_implementation: str = "flash_attention_2" class ExperimentData(BaseModel): model_config = ConfigDict(extra="allow") train_sources: dict[str, Any] = Field(default_factory=dict) evaluation: dict[str, Any] = Field(default_factory=dict) class ExperimentConfig(BaseModel): model_config = ConfigDict(extra="allow") experiment_schema_version: int study_name: str reproducibility: dict[str, Any] = Field(default_factory=dict) labels: dict[str, Any] = Field(default_factory=dict) data: ExperimentData = Field(default_factory=ExperimentData) # Automated release/audit contract. V1 requires zero per-example model calls; # Terra/Luna are one-time diagnostics and never admission/gold authorities. automated_compilation_and_audit: dict[str, Any] common_student: CommonStudent rewards: dict[str, Any] = Field(default_factory=dict) main_rl_runs: list[ExperimentRun] # Ingredient-isolation suite (see EXPECTED_ABLATION_ARMS). Numeric knobs # (lambda_direction, mask_ratio, ...) live in code (rewards.ABLATION_ARM_KNOBS); # the manifest only pins identities. ablation_rl_runs: list[ExperimentRun] = Field(default_factory=list) sft_ablation_runs: list[dict[str, Any]] = Field(default_factory=list) @model_validator(mode="after") def _validate_run_matrix(self) -> ExperimentConfig: runs = self.main_rl_runs if len(runs) != EXPECTED_MAIN_RUNS: raise ConfigError( f"main_rl_runs must contain {EXPECTED_MAIN_RUNS} runs, found {len(runs)}" ) run_ids = [run.run_id for run in runs] if len(run_ids) != len(set(run_ids)): duplicates = sorted({rid for rid in run_ids if run_ids.count(rid) > 1}) raise ConfigError(f"duplicate run_id in main_rl_runs: {duplicates}") counts: dict[tuple[str, str], int] = {} for run in runs: key = (run.model, run.arm) counts[key] = counts.get(key, 0) + 1 if counts != EXPECTED_RUN_COUNTS: raise ConfigError(f"unexpected main RL run matrix: {counts}") evi_po = self.rewards.get("evi_po") if not isinstance(evi_po, dict): raise ConfigError("rewards.evi_po must be an object") if evi_po.get("required_relationships") != ["FULL", "CONTROL", "MISSING"]: raise ConfigError("EVI-PO requires FULL, CONTROL, and MISSING relationships") if evi_po.get("optional_relationships") != ["SUBSTITUTE"]: raise ConfigError("EVI-PO SUBSTITUTE relationship must remain optional") for name in ("lambda_direction", "lambda_evidence", "margin"): value = evi_po.get(name) if ( isinstance(value, bool) or not isinstance(value, int | float) or not math.isfinite(float(value)) or value < 0 ): raise ConfigError(f"rewards.evi_po.{name} must be non-negative") if evi_po.get("require_usable_response_to_image_attention") is not True: raise ConfigError("EVI-PO must require usable response-to-image attention") self._validate_ablation_matrix() return self def _validate_ablation_matrix(self) -> None: """Enforce the two direct EVI objective-removal runs.""" runs = self.ablation_rl_runs if len(runs) != EXPECTED_ABLATION_RUNS: raise ConfigError( f"ablation_rl_runs must contain {EXPECTED_ABLATION_RUNS} runs, " f"found {len(runs)}" ) run_ids = [run.run_id for run in runs] if len(run_ids) != len(set(run_ids)): duplicates = sorted({rid for rid in run_ids if run_ids.count(rid) > 1}) raise ConfigError(f"duplicate run_id in ablation_rl_runs: {duplicates}") identities = {(run.model, run.arm, run.seed) for run in runs} expected = {(model, arm, seed) for arm in EXPECTED_ABLATION_ARMS for model in ("qwen35_2b",) for seed in (1,)} if identities != expected: raise ConfigError(f"unexpected ablation RL run matrix: {sorted(identities)}") def validate_against_resources(self, resources: ResourcesManifest) -> None: """Enforce cross-file invariants between experiment and resources.""" name = self.common_student.model_resource if name not in resources.models: raise ConfigError(f"common_student.model_resource references unknown model {name!r}") aca = self.automated_compilation_and_audit if aca.get("total_reasoning_vlm_calls_for_data_generation") != 0: raise ConfigError("v1 data generation must use exactly zero reasoning VLM calls") if aca.get("total_ocr_vlm_calls_for_data_generation") != 0: raise ConfigError("v1 data generation must use exactly zero OCR VLM calls") if aca.get("gold_authority") != ( "deterministic_primary_and_reference_executor_certificates" ): raise ConfigError("v1 gold authority must be deterministic executor certificates") # Train sources may be HF datasets (C2) or GitHub structured worlds (C1, # e.g. PlotQA/Geometry3K); either is acceptable. for name in self.data.train_sources: if name not in resources.datasets and name not in resources.structured_sources: raise ConfigError(f"train source {name!r} is absent from resources") if "mathvista" in self.data.train_sources: raise ConfigError("MathVista must never appear in train_sources") for name in self.data.evaluation.get("certified_intervention", {}): if name not in resources.datasets and name not in resources.structured_sources: raise ConfigError( f"certified_intervention source {name!r} is absent from resources" ) for name in self.data.evaluation.get("untouched", []): if name not in resources.datasets: raise ConfigError(f"untouched source {name!r} is absent from resources.yaml") # Dataset-specific guards mirrored from validate_spec.py. mv = resources.datasets.get("mathvista") if mv and mv.policy != "strict_evaluation_only_training_prohibited_by_card": raise ConfigError("MathVista policy must remain strict evaluation-only") mmk = resources.datasets.get("mmk12") if mmk and mmk.declared_license is not None: raise ConfigError("MMK12 must not be assigned an invented license") chart = resources.datasets.get("chartqa") if chart: splits = chart.splits or {} if splits.get("val") != 1920 or "validation" in splits: raise ConfigError("ChartQA must use its actual split name 'val'") mmmu_pro = resources.datasets.get("mmmu_pro") if mmmu_pro and mmmu_pro.configs != [ "standard (10 options)", "standard (4 options)", "vision", ]: raise ConfigError("MMMU-Pro config names must match Hugging Face metadata exactly") def canonical_hash(self) -> str: """Machine/path-independent hash of this experiment config.""" return canonical_config_hash(self.model_dump(mode="python")) def _format_validation_error(exc: ValidationError) -> str: """Render a pydantic ``ValidationError`` as a compact, human-readable string. Validators raise :class:`ConfigError` (a ``ValueError``), which pydantic wraps into a ``ValidationError``; we surface the original messages here so callers see the research-invariant reason rather than pydantic's envelope. """ parts: list[str] = [] for err in exc.errors(): loc = ".".join(str(part) for part in err.get("loc", ())) msg = err.get("msg", "") if msg.startswith("Value error, "): msg = msg[len("Value error, ") :] parts.append(f"{loc}: {msg}" if loc else msg) return "; ".join(parts) or str(exc) def load_resources(path: str | Path) -> ResourcesManifest: try: return ResourcesManifest.model_validate(_load_yaml(path)) except ValidationError as exc: raise ConfigError(_format_validation_error(exc)) from exc def load_experiment(path: str | Path) -> ExperimentConfig: try: return ExperimentConfig.model_validate(_load_yaml(path)) except ValidationError as exc: raise ConfigError(_format_validation_error(exc)) from exc def load_config_pair( resources_path: str | Path, experiment_path: str | Path, ) -> tuple[ResourcesManifest, ExperimentConfig]: """Load both configs and enforce their cross-file invariants.""" resources = load_resources(resources_path) experiment = load_experiment(experiment_path) experiment.validate_against_resources(resources) return resources, experiment