Datasets:
File size: 14,688 Bytes
e1ced61 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | """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
|