diff --git a/experiments/evaluation/launch.py b/experiments/evaluation/launch.py index 71fc7682612..4fb62f71be2 100644 --- a/experiments/evaluation/launch.py +++ b/experiments/evaluation/launch.py @@ -29,6 +29,7 @@ ModelConfigRef, ModelRef, PromptFormat, + RLAttemptRef, RunStatus, TaskEvidence, list_records, @@ -176,6 +177,7 @@ class LaunchSpec: """Reuse evaluation records for this key and the same resolved configuration.""" run_id: str | None = None policy_finalization: PolicyFinalization | None = None + rl_attempt: RLAttemptRef | None = None # EvalDash scans these record roots (`DEFAULT_SCAN_PREFIXES` adds read-only legacy roots). @@ -542,6 +544,7 @@ def build_evaluation_batch( user=user, version=spec.version, description=spec.description, + rl_attempt=spec.rl_attempt, records_prefix=records_prefix, model=model, accelerator=accelerator, diff --git a/experiments/evaluation/pipeline.py b/experiments/evaluation/pipeline.py index b4b745c7bc7..29154ea3099 100644 --- a/experiments/evaluation/pipeline.py +++ b/experiments/evaluation/pipeline.py @@ -29,7 +29,7 @@ from collections.abc import Callable from dataclasses import dataclass -from evalrecords.records import read_record, record_path +from evalrecords.records import RLAttemptRef, read_record, record_path from iris.client.client import iris_ctx from iris.rpc import job_pb2 from marin.evaluation.hardware import default_platform @@ -68,6 +68,7 @@ class EvalStepConfig: federated_cluster: str | None version: str instances: int = 1 + rl_attempt: RLAttemptRef | None = None @dataclass(frozen=True) @@ -104,6 +105,7 @@ def run_eval_pipeline_step(config: EvalStepConfig) -> EvaluationResult: federated_cluster=config.federated_cluster, priority_band=job_pb2.PRIORITY_BAND_INHERIT, version=config.version, + rl_attempt=config.rl_attempt, cache_key=None if is_mutable_version(config.version) else config.artifact_path, ) submitted = launch_group(prepare_evaluation_batch(spec), iris_ctx().client) @@ -127,6 +129,7 @@ def eval_step( version: str, deps: tuple[ArtifactStep, ...] = (), resolve_model: Callable[[StepContext], ModelConfig] | None = None, + resolve_rl_attempt: Callable[[StepContext], RLAttemptRef | None] | None = None, limit: int | None = None, max_concurrent: int = DEFAULT_EVAL_CONCURRENCY, instances: int = 1, @@ -163,6 +166,7 @@ def build_config(ctx: StepContext) -> EvalStepConfig | EvalStepFingerprint: submission_cluster=ctx.runtime_arg(_SUBMISSION_CLUSTER_RUNTIME_ARG), federated_cluster=ctx.runtime_arg(_FEDERATED_CLUSTER_RUNTIME_ARG), version=version, + rl_attempt=resolve_rl_attempt(ctx) if resolve_rl_attempt is not None else None, ) return ArtifactStep( diff --git a/experiments/post_training/curriculum_rl/launch.py b/experiments/post_training/curriculum_rl/launch.py index 6b19e5355b0..e6220e5f709 100644 --- a/experiments/post_training/curriculum_rl/launch.py +++ b/experiments/post_training/curriculum_rl/launch.py @@ -43,6 +43,7 @@ ArtifactHfModel, IrisSkyRLExecution, MegatronGeometry, + SkyRLPolicyModel, SkyRLRetentionPolicy, SkyRLRolePlan, SkyRLRun, @@ -66,7 +67,7 @@ VALIDATION_FILENAME, pool_step, ) -from experiments.post_training.skyrl_evaluation import SKYRL_POLICY_LOCATION, skyrl_eval_step +from experiments.post_training.skyrl_evaluation import evaluate_model logger = logging.getLogger(__name__) @@ -595,12 +596,10 @@ class CurriculumArm: def evaluation_model_config(policy: PolicySpec, preset: ScalePreset, name: str) -> ModelConfig: - """Model configuration for the trained policy checkpoint, from the policy's - ``serve_*`` fields and the preset's context window.""" + """Build serving settings from the policy's profile and the preset's context window.""" return ModelConfig( name=name, - location=SKYRL_POLICY_LOCATION, - tokenizer=policy.tokenizer_uri, + location="", apply_chat_template=True, resource_hint=ResourceHint(gpu={GPU_VARIANT: policy.serve_gpus}, memory=policy.serve_memory), serve=ServeConfig( @@ -678,8 +677,8 @@ def build_arm( evaluation_base_name = f"evals/{evaluation_model_name}/{preset.evals}" evaluation_version = version or resolve_version(evaluation_base_name, None) evaluation_model = evaluation_model_config(policy, preset, evaluation_model_name) - evaluation = skyrl_eval_step( - rl, + evaluation = evaluate_model( + SkyRLPolicyModel(rl), evaluation_model, resolve_evaluations(preset.evals), version=evaluation_version, diff --git a/experiments/post_training/iceball_micro.py b/experiments/post_training/iceball_micro.py index c413bd053b6..0ae30b89665 100644 --- a/experiments/post_training/iceball_micro.py +++ b/experiments/post_training/iceball_micro.py @@ -54,6 +54,7 @@ ArtifactDataSource, ArtifactHfModel, IrisSkyRLExecution, + SkyRLPolicyModel, SkyRLRetentionPolicy, SkyRLRolePlan, SkyRLRun, @@ -68,7 +69,7 @@ from experiments.evaluation.evals import resolve_evaluations from experiments.evaluation.pipeline import EvaluationResult -from experiments.post_training.skyrl_evaluation import SKYRL_POLICY_LOCATION, skyrl_eval_step +from experiments.post_training.skyrl_evaluation import evaluate_model from experiments.sft.launcher import DatasetSpec, LevanterCheckpointModel, SFTSpec, resources_from_accelerator, sft_step logger = logging.getLogger(__name__) @@ -445,8 +446,7 @@ def build_workflow(*, version: str | None = None) -> IceballMicroWorkflow: evaluation_version = version or resolve_version(evaluation_name, None) evaluation_model = ModelConfig( name=ICEBALL_MODEL_NAME, - location=SKYRL_POLICY_LOCATION, - tokenizer=QWEN_TOKENIZER, + location="", apply_chat_template=True, resource_hint=ResourceHint(gpu={ICEBALL_GPU_VARIANT: 1}), serve=ServeConfig( @@ -459,8 +459,8 @@ def build_workflow(*, version: str | None = None) -> IceballMicroWorkflow: ), generation=GenerationConfig(max_gen_toks=256), ) - evaluation = skyrl_eval_step( - rl, + evaluation = evaluate_model( + SkyRLPolicyModel(rl), evaluation_model, resolve_evaluations(ICEBALL_EVALS), version=evaluation_version, diff --git a/experiments/post_training/rl.py b/experiments/post_training/rl.py index 00cbf228185..68bc819fa77 100644 --- a/experiments/post_training/rl.py +++ b/experiments/post_training/rl.py @@ -9,11 +9,13 @@ from __future__ import annotations +import io import json import logging import os import subprocess import sys +import tarfile import tempfile import time from collections.abc import Callable, Sequence @@ -37,7 +39,7 @@ from marin.execution.step_status import get_status_path from marin.experiment.cli import build_options_with_runner from marin.experiment.namespacing import user_owned_name -from marin.rl.cli import RUN_INDEX_ENV, submit_or_run, validate_coordinator_graph +from marin.rl.cli import BASE_PRESET_REVISION_ENV, RUN_INDEX_ENV, submit_or_run, validate_coordinator_graph from marin.rl.skyrl import ( IRIS_HUB_CLUSTER_CONFIG, SkyRLModelSource, @@ -118,6 +120,7 @@ def _run_rl( index = _SUBMITTED_INDEX.validate_json(metadata).get(config.run_id) if metadata is not None else None if issue is not None or index is not None: issue = rl_publication.reserve_issue(config.output.export_root, issue) + base_revision = os.environ.get(BASE_PRESET_REVISION_ENV) if index is not None else None write_attempt( config.output.export_root, AttemptRecord( @@ -125,6 +128,7 @@ def _run_rl( attempt_id=config.attempt_id, issue=issue, index=index, + base_preset_revision=base_revision or None, ), ) return run_skyrl(config, forward_env=forward_env) @@ -431,6 +435,69 @@ def run_index_identity( ) +def _base_preset_revision(module: str, model: str, preset: str, source_revision: str) -> str | None: + root = recipe.REPO_ROOT + program = """ +import sys +from importlib import import_module +from pathlib import Path +from experiments.post_training.rl_presets import ModelPresets + +module, model, preset = sys.argv[1:] +entry = import_module(module) +if not Path(entry.__file__).resolve().is_relative_to(Path.cwd()): + raise ImportError(f"{module} did not load from the main snapshot") +revisions = {value.by_name[preset].revision for value in vars(entry).values() + if isinstance(value, ModelPresets) and value.model == model and preset in value.by_name} +if len(revisions) == 1: + print(revisions.pop()) +""" + try: + base = git_output(["merge-base", source_revision, "origin/main"], cwd=root, timeout=4) + except (OSError, RuntimeError): + logger.debug("Git could not resolve the main merge base for preset %s", preset) + return None + try: + snapshot = subprocess.run( + [ + "git", + "archive", + base, + "experiments/__init__.py", + "experiments/post_training", + "experiments/evaluation", + "pyproject.toml", + "infra/marina/apps/rl_progress/applet.toml", + "lib", + ], + cwd=root, + capture_output=True, + check=True, + timeout=8, + ).stdout + with tempfile.TemporaryDirectory(prefix="rl-main-base-") as directory: + path = Path(directory) + with tarfile.open(fileobj=io.BytesIO(snapshot)) as archive: + archive.extractall(path, filter="data") + result = subprocess.run( + [sys.executable, "-c", program, module, model, preset], + text=True, + capture_output=True, + check=True, + cwd=path, + env={ + "PATH": os.defpath, + "PYTHONNOUSERSITE": "1", + "PYTHONPATH": os.pathsep.join(str(source) for source in sorted(path.glob("lib/*/src"))), + }, + timeout=30, + ) + return result.stdout.strip() or None + except (OSError, subprocess.SubprocessError, tarfile.TarError) as error: + logger.debug("Could not load preset %s from main commit %s (%s)", preset, base, type(error).__name__) + return None + + class _PublicationWatch(BaseModel): job: str preset: str @@ -560,13 +627,16 @@ def _submit_from_launcher( if not module: raise click.UsageError("submit from python -m MODULE, or pass entry_module to rl.main") submitted_at = datetime.now(UTC).isoformat() - index = context.meta["rl_index"].model_copy(update={"submitted_at": submitted_at}) + index: RunIndexIdentity = context.meta["rl_index"] + base_preset_revision = _base_preset_revision(module, index.model, index.preset, index.source_revision) + index = index.model_copy(update={"submitted_at": submitted_at}) runs = _from_handles(handles).runs indexed_runs = { step.build_config(StepContext.for_fingerprint(step.runtime_args, step.deps)).run_id: index for step in runs } metadata = _SUBMITTED_INDEX.dump_json(indexed_runs).decode() - job = submit_or_run(module, handles, max_concurrent, {**os.environ, RUN_INDEX_ENV: metadata}, argv=argv) + environment = {**os.environ, RUN_INDEX_ENV: metadata, BASE_PRESET_REVISION_ENV: base_preset_revision or ""} + job = submit_or_run(module, handles, max_concurrent, environment, argv=argv) submitted = [ { "name": step.name, @@ -581,6 +651,7 @@ def _submit_from_launcher( "coordinator_job_id": str(job), "iris_url": job.dashboard_url(_IRIS_DASHBOARD_URL), "submitted_at": submitted_at, + "base_preset_revision": base_preset_revision, "runs": submitted, } _print_status(result) diff --git a/experiments/post_training/rl_gate.py b/experiments/post_training/rl_gate.py index 3c55d2bdc69..1e9f85a1152 100644 --- a/experiments/post_training/rl_gate.py +++ b/experiments/post_training/rl_gate.py @@ -718,7 +718,7 @@ def _write_gate( update={"attempt_ids": tuple(receipt.attempt_id for receipt in receipts if receipt)} ) runs = [ - with_requirements(with_objectives(read_measurements(path, preset, inputs), preset), inputs.requirements) + with_requirements(with_objectives(read_measurements(path, preset), preset), inputs.requirements) for path in run_paths ] if runs: diff --git a/experiments/post_training/rl_measurements.py b/experiments/post_training/rl_measurements.py index 3fd59d03bfa..c37c1449693 100644 --- a/experiments/post_training/rl_measurements.py +++ b/experiments/post_training/rl_measurements.py @@ -298,17 +298,17 @@ def count(*outcomes: str) -> float: def _session_invariants( name: str, table: pa.Table, - evaluation: presets.Evaluation, - preset: presets.Preset, - expected: int, task_ids: Sequence[str], + answers_per_task: int, + required_coverage: bool, ) -> list[Invariant]: rows = table.to_pylist() counts = Counter(row["task_id"] for row in rows) - holds = len(rows) == expected and set(counts.values()) == {evaluation.answers} and set(counts) == set(task_ids) + expected = len(task_ids) * answers_per_task + holds = len(rows) == expected and set(counts.values()) == {answers_per_task} and set(counts) == set(task_ids) result = [Invariant(name=f"{name}/answers_complete", value=len(rows), limit=expected, comparator="==", holds=holds)] - if evaluation == preset.guarded or (preset.checkpoint_every and evaluation.held_out): - coverage = len({row["task_id"] for row in rows if row["scored"]}) / (expected // evaluation.answers) + if required_coverage: + coverage = len({row["task_id"] for row in rows if row["scored"]}) / len(task_ids) if task_ids else 0.0 result.append( Invariant( name=f"{name}/task_coverage", @@ -352,11 +352,7 @@ def evaluation_status( return EvaluationStatus() try: effective = preset.with_updates(launch.max_steps if launch.max_steps is not None else preset.updates) - try: - inputs = read_run_inputs(path) - except FileNotFoundError: - inputs = None - data = read_measurements(path, effective, inputs, attempt=attempt) + data = read_measurements(path, effective, attempt=attempt) return EvaluationStatus( evaluations=data.evaluations, evaluation_invariants=tuple( @@ -382,11 +378,9 @@ def training_invariants(preset: presets.Preset, metrics: Mapping[int, Mapping[st def read_measurements( path: str, preset: presets.Preset, - inputs: RunInputs | None = None, *, attempt: AttemptRecord | None = None, ) -> RunMeasurements: - inputs = inputs or RunInputs(preset_name=preset.name) terminal = attempt or read_skyrl_attempt(path) if terminal is None: raise FileNotFoundError(f"no terminal attempt record at {path}") @@ -414,9 +408,6 @@ def read_measurements( } except (KeyError, TypeError, ValueError) as error: raise InvalidComparison(f"recorded evaluation identity is malformed: {error}") from error - default, selection = recipe.task_selections( - preset, recipe.selection_artifact(inputs.tasks) if inputs.tasks else None - ) task_set = preset.held_out_tasks if preset.held_out is not None else None scores, initial_scores = [ANSWER_SCHEMA.empty_table()], [] evaluations = [] @@ -424,9 +415,9 @@ def read_measurements( primary_answers = 0 for index, evaluation in enumerate(preset.evaluations): quality = evaluation.held_out and (evaluation == preset.guarded or bool(preset.checkpoint_every)) - expected = recipe.evaluation_answer_count( - evaluation, recipe.evaluation_source(evaluation, selection, default, preset.held_out_tasks) - ) + required_coverage = evaluation == preset.guarded or bool(preset.checkpoint_every and evaluation.held_out) + recorded_tasks = recorded_task_sets[evaluation.name].task_ids + recorded_answers = identities[evaluation.name][1]["n_samples_per_prompt"] all_scores = read_answers(evaluation, path, launch=launch, attempt=terminal) if index == 0: primary_answers = all_scores.num_rows @@ -466,9 +457,7 @@ def read_measurements( ) ) invariants.extend( - _session_invariants( - session_name, session, evaluation, preset, expected, recorded_task_sets[evaluation.name].task_ids - ) + _session_invariants(session_name, session, recorded_tasks, recorded_answers, required_coverage) ) if quality: invariants.append( diff --git a/experiments/post_training/rl_publication.py b/experiments/post_training/rl_publication.py index 0efe94ee946..6c72db7d7c2 100644 --- a/experiments/post_training/rl_publication.py +++ b/experiments/post_training/rl_publication.py @@ -43,6 +43,7 @@ from rigging.filesystem.conditional_object import ConditionalWriteError, VersionedBytes, conditional_object from rigging.filesystem.s3_compat import configure_coreweave_s3 from rigging.filesystem.storage_path import StoragePath +from taskcompendium.identity import canonical_sha256 from experiments.post_training import rl_compose as recipe from experiments.post_training import rl_gate as gate @@ -51,6 +52,7 @@ from experiments.post_training.rl_measurements import ( InvalidComparison, RunInputs, + evaluation_protocol, evaluation_status, read_run_inputs, training_invariants, @@ -183,17 +185,47 @@ def _read_grader_report(launch: RecordedLaunch, attempt_id: str, evidence: list[ def _gate_result(report: gate.GateReport | None) -> GateResult | None: if report is None: return None + decisions = report.rows(ComparisonRole.OBJECTIVE, ComparisonRole.GUARD, ComparisonRole.REQUIREMENT) + decision_metrics = {row.metric for row in decisions} + history_scores = [ + row + for row in report.rows(ComparisonRole.SLICE) + if row.metric not in decision_metrics + and ( + row.metric.partition("/")[2] in {"mean", "family_mean"} + or ("/family/" in row.metric and row.metric.endswith("/mean")) + ) + ] return GateResult( verdict=report.verdict, effect=report.effect, reason=report.reason, - invariants=list(report.invariants), - comparisons=list(report.rows(ComparisonRole.OBJECTIVE, ComparisonRole.GUARD, ComparisonRole.REQUIREMENT)), + invariants=[ + fact.model_copy(update={"replicate": None}) if fact.name.endswith("/shared_tasks") else fact + for fact in report.invariants + ], + comparisons=[*decisions, *history_scores], attempt_ids=list(report.run.attempt_ids), replicates=report.run.replicates, + control_commit=report.control.commit, + control_revision=report.control.revision, ) +def _evaluation_identities(launch: RecordedLaunch, evidence: list[str]) -> tuple[str | None, str | None]: + """Return the stored evaluation sources and the evaluation protocol digest.""" + sources = [*launch.validation_data, *(source for group in launch.evaluation_data.values() for source in group)] + if not sources: + return None, None + data = "; ".join(sorted({f"{source.identity}/{source.relative_path}" for source in sources})) + try: + protocols = {name: evaluation_protocol(launch, name) for name in ("", *launch.evaluation_data)} + except InvalidComparison: + evidence.append("The stored evaluation protocol is unavailable.") + return data, None + return data, canonical_sha256(protocols) + + def build_record( run_output: str, preset: presets.Preset, @@ -237,15 +269,24 @@ def build_record( failed.append("required_gate_report") if not provenance and index is None and terminal: evidence.append("Recorded source provenance is unavailable.") + if index is not None and attempt.base_preset_revision is None: + evidence.append("The base preset version is unavailable from the branch's main merge base.") grader_report = _read_grader_report(launch, attempt_id, evidence) if terminal else None + evaluation_data, evaluation_protocol_id = _evaluation_identities(launch, evidence) return AttemptSummary( + format_version=2, run_id=attempt.index_run_id, + native_run_id=attempt.run_id, attempt_id=attempt_id, label=run_label(inputs), series=preset.name, - model=index.model if index is not None else launch.model_name, + model=index.model if index is not None else launch.model_name or table.model, preset=preset.name, preset_revision=index.preset_revision if index is not None else None, + base_preset_revision=attempt.base_preset_revision, + control_preset=preset.control_preset if preset.gated else None, + evaluation_data_identity=evaluation_data, + evaluation_protocol_identity=evaluation_protocol_id, user=index.user if index is not None else None, branch=index.branch if index is not None else None, dirty=index.dirty if index is not None else None, @@ -394,6 +435,41 @@ def _link_issue(receipt: AttemptRecord, issue: int) -> int | None: return assigned +def _with_evaldash_links(summary: AttemptSummary, service_url: str | None) -> AttemptSummary: + try: + from marina import client # noqa: PLC0415 + + rows = client.marina_request( + service_url or client.DEFAULT_MARINA_URL, + "GET", + "/evaldash/api/runs", + params={ + "rl_run": summary.run_id, + "rl_native_run": summary.native_run_id or summary.run_id, + "rl_attempt": summary.attempt_id, + "limit": 1000, + }, + timeout=4, + ) + except (ImportError, OSError, ValueError, RuntimeError) as error: + logger.debug("EvalDash lookup unavailable for %s (%s)", summary.attempt_id, type(error).__name__) + rows = None + if not isinstance(rows, list): + return summary.model_copy(update={"evidence": [*summary.evidence, "EvalDash catalog lookup was unavailable."]}) + run_ids = (summary.run_id, summary.native_run_id or summary.run_id) + links = list(summary.evaldash_run_ids or ()) + links.extend( + row["run_id"] + for row in rows + if isinstance(row, dict) + and row.get("rl_run_id") in run_ids + and row.get("rl_attempt_id") == summary.attempt_id + and isinstance(row.get("run_id"), str) + and row["run_id"] + ) + return summary.model_copy(update={"evaldash_run_ids": list(dict.fromkeys(links))}) if links else summary + + def publish_runs( outputs: Sequence[str], preset: presets.Preset, @@ -466,6 +542,8 @@ def publish_runs( ) if issue is not None: record = record.model_copy(update={"issue": _link_issue(receipt, issue)}) + if receipt.native.result.state.is_terminal: + record = _with_evaldash_links(record, service_url) url = publish_result(record, service_url) result.served_records.append(destination) if selected_id == current_id: diff --git a/experiments/post_training/rl_tests/test_rl.py b/experiments/post_training/rl_tests/test_rl.py index 9b34e823504..d09ae7fd41f 100644 --- a/experiments/post_training/rl_tests/test_rl.py +++ b/experiments/post_training/rl_tests/test_rl.py @@ -27,7 +27,7 @@ from marin.execution.artifact import Artifact from marin.execution.lazy import OUT, ArtifactStep, apply, materialized_config, run from marin.rl import skyrl as skyrl_api -from marin.rl.cli import RUN_INDEX_ENV +from marin.rl.cli import BASE_PRESET_REVISION_ENV, RUN_INDEX_ENV from marin.rl.skyrl import ArtifactHfModel, SkyRLRun from marin.rl.skyrl_records import read_skyrl_metrics from marin.training.training import LevanterCheckpoint @@ -769,7 +769,7 @@ def reenter(**kwargs): return if not publication_case: return - snapshot = printed_status(result.output) + snapshot = printed_status(result.stdout) if case == "data-short": assert snapshot["publication"]["unserved_records"] == [], snapshot["publication"] assert len(published) == 1 and published[0]["status"] == "succeeded" @@ -813,7 +813,7 @@ def reenter(**kwargs): repeated.output, repeated.exception, ) - recovered = printed_status(repeated.output) + recovered = printed_status(repeated.stdout) assert recovered["publication"]["unserved_records"] == [] and recovered["publication"]["errors"] == [] assert {row["attempt_id"]: row["issue"] for row in recovered["runs"]} == ( {"native-retry": 73, "native-1": 73} if case == "mixed-native-failed" else {attempt: 73 for _, attempt in paths} @@ -832,7 +832,8 @@ def test_detached_ungated_launch_indexes_prepared_then_terminal_attempt( ): early_failure = outcome != "succeeded" table = snowball_model.SNOWBALL - preset = replace(table.by_name["train-long"].with_updates(2), checkpoint_every=None, evaluations=()) + historical = table.by_name["train-long"] + preset = replace(historical.with_updates(2), revision="2026.01.02", checkpoint_every=None, evaluations=()) table = preset_table(preset) built = snowball.build_experiment(preset, table=table) source = recorded_runs(preset.name, built.runs[0].name, inputs=built.inputs, attempt_id="native-old") @@ -844,6 +845,21 @@ def test_detached_ungated_launch_indexes_prepared_then_terminal_attempt( client, job = fake_iris(monkeypatch, "index-coordinator") monkeypatch.setenv("WANDB_API_KEY", "test-only-mocked-submission") monkeypatch.setattr(snowball, "_PUBLICATION_POLL_SECONDS", 0) + git_output = snowball.git_output + source_ref = git_output(["rev-parse", "HEAD"], cwd=recipe.REPO_ROOT) + historical_ref = git_output(["rev-parse", "--verify", "HEAD^"], cwd=recipe.REPO_ROOT, check=False) + historical_ref = historical_ref or git_output(["rev-parse", "HEAD^{tree}"], cwd=recipe.REPO_ROOT) + monkeypatch.setattr( + Provenance, "capture", lambda *args, **kwargs: Provenance("tree-one", source_ref, False, "branch", "test") + ) + + def historical_source(args, cwd, **kwargs): + if args[0] == "merge-base": + assert args == ["merge-base", source_ref, "origin/main"] + return historical_ref + return git_output(args, cwd, **kwargs) + + monkeypatch.setattr(snowball, "git_output", historical_source) publications = [] unavailable = outcome == "interrupted" @@ -856,11 +872,17 @@ def publish(record): fake_publication(monkeypatch, publish, "https://progress.test") followers = [] + + def archive_history(argv, **kwargs): + if argv[:2] == ["git", "archive"]: + assert argv[2] == historical_ref + return subprocess.run(argv, **kwargs) + monkeypatch.setattr( snowball, "subprocess", SimpleNamespace( - run=subprocess.run, + run=archive_history, SubprocessError=subprocess.SubprocessError, DEVNULL=subprocess.DEVNULL, STDOUT=subprocess.STDOUT, @@ -870,7 +892,8 @@ def publish(record): def native_prepared(**kwargs): run_id = launch["run"]["id"] - index = RunIndexIdentity.model_validate(json.loads(kwargs["environment"].env_vars[RUN_INDEX_ENV])[run_id]) + environment = kwargs["environment"].env_vars + index = RunIndexIdentity.model_validate(json.loads(environment[RUN_INDEX_ENV])[run_id]) launch["run"].update(attempt_id="native-indexed", coordinator_iris_job_id=str(job)) other_config = { **launch, @@ -888,6 +911,7 @@ def native_prepared(**kwargs): attempt_id="native-indexed", config=launch, index=index, + base_preset_revision=environment[BASE_PRESET_REVISION_ENV], metrics_started_at=None if early_failure else receipt["result"]["started_at"], elapsed_excluding_eval_seconds=None if early_failure else 123.0, result=( @@ -917,7 +941,9 @@ def state(): client.submit.side_effect = native_prepared client.job.return_value.state_only.side_effect = state arguments = ["--preset", preset.name, "--version", preset.revision, "--run"] - result = CliRunner().invoke(snowball.command(table, argv=tuple(arguments), entry_module=__name__), arguments) + result = CliRunner().invoke( + snowball.command(table, argv=tuple(arguments), entry_module=snowball_model.__name__), arguments + ) assert result.exit_code == 0, (result.output, result.exception) grafana_link = next( line.strip().removeprefix("run: ") for line in reversed(result.output.splitlines()) if "grafana.oa.dev" in line @@ -946,6 +972,7 @@ def follow(): running, terminal = [row for row in publications if row.attempt_id == "native-indexed"] assert running.status == "running" and terminal.status == ("failed" if early_failure else "succeeded") assert running.run_id == terminal.run_id + assert running.base_preset_revision == terminal.base_preset_revision == historical.revision assert parse_qs(urlsplit(grafana_link).query)["var-run"] == [terminal.run_id] assert re.fullmatch(r"snowball-train-long-[^/]+-[0-9a-f]{8}", terminal.run_id) assert terminal.gate_result is None @@ -1257,7 +1284,7 @@ def entry(): planning_args, ) assert result.exit_code == 1, (result.output, result.exception) - [status] = printed_status(result.output)["runs"] + [status] = printed_status(result.stdout)["runs"] assert status["best_checkpoint_step"] == "none eligible" facts = {fact["name"]: fact for fact in status["evaluation_invariants"]} assert not facts[f"{preset.evaluations[0].name}/step-2/answers_complete"]["holds"] diff --git a/experiments/post_training/rl_tests/test_rl_publication.py b/experiments/post_training/rl_tests/test_rl_publication.py index 08a135a3161..b8279808740 100644 --- a/experiments/post_training/rl_tests/test_rl_publication.py +++ b/experiments/post_training/rl_tests/test_rl_publication.py @@ -14,7 +14,7 @@ import click import pytest from click.testing import CliRunner -from finestore.rl.rl_progress import AttemptSummary +from finestore.rl.rl_progress import AttemptSummary, Invariant, RunIndexIdentity, Verdict from finestore.rl.run_records import ( AttemptRecord, CheckpointReference, @@ -52,6 +52,7 @@ write_skyrl_run_record, ) from experiments.post_training.rl_tests.fixtures import controls as write_controls +from experiments.post_training.skyrl_test_support import selection_summary from infra.marina.tests.rl_progress_fixtures import grader_report pytestmark = pytest.mark.usefixtures("source_provenance") @@ -314,8 +315,21 @@ def saved_gate(requirements=()): report, first_gate = saved_gate() interrupted = {"once": True} + logical_id = "snowball-learning-medium-tester-1234abcd" + native_id = f"tests/publication-0-{preset.revision}" + automatic_links = ["linked-export", "native-export"] def unavailable_readback(origin, method, path, *, json_body=None, **kwargs): + if method == "GET" and path == "/evaldash/api/runs": + if kwargs["params"]["rl_attempt"] == "native-0": + assert kwargs["params"]["rl_run"] == logical_id + assert kwargs["params"]["rl_native_run"] == native_id + return [ + {"run_id": "linked-export", "rl_run_id": logical_id, "rl_attempt_id": "native-0"}, + {"run_id": "native-export", "rl_run_id": native_id, "rl_attempt_id": "native-0"}, + {"run_id": "cached-export", "rl_run_id": logical_id, "rl_attempt_id": "earlier-attempt"}, + {"run_id": "other-run", "rl_run_id": "unrelated", "rl_attempt_id": "native-0"}, + ] response = request(origin, method, path, json_body=json_body) if method == "POST" and path.endswith("/api/runs") and interrupted["once"]: interrupted["once"] = False @@ -328,12 +342,33 @@ def unavailable_readback(origin, method, path, *, json_body=None, **kwargs): attempt = read_stored_skyrl_attempts(str(source))[1][attempt_id] write_attempt( str(source / "exports"), - AttemptRecord(run_id=attempt.run_id, attempt_id=attempt_id, issue=73 if index == 0 else None), + AttemptRecord( + run_id=attempt.run_id, + attempt_id=attempt_id, + issue=73 if index == 0 else None, + base_preset_revision=preset.revision if index == 0 else None, + index=( + RunIndexIdentity( + run_id=logical_id, + model=table.model, + preset=preset.name, + preset_revision=preset.revision, + user="tester", + branch="fixture", + source_revision="fixture", + dirty=False, + ) + if index == 0 + else None + ), + ), ) first = publish(first_gate) assert len(first.served_records) == 1 and first.errors == ["Response unavailable after insert"] persisted = stored() assert set(persisted) == {"native-0", "native-1"} and persisted["native-0"]["issue"] == 73 + assert persisted["native-0"]["evaldash_run_ids"] == automatic_links + assert persisted["native-1"]["evaldash_run_ids"] is None # A numeric bound is stored only as an invariant, with distinct replicate outcomes. relative_key = "eval_lite/aai_category/coding/mean" report, second_gate = saved_gate(("policy/entropy<=0", "policy/entropy>=0", f"{relative_key}>=control")) @@ -342,13 +377,40 @@ def unavailable_readback(origin, method, path, *, json_body=None, **kwargs): receipt["result"]["finished_at"] = ( datetime.fromisoformat(receipt["result"]["started_at"]) + timedelta(hours=2) ).isoformat() - monkeypatch.setattr("marina.client.marina_request", request) + + def unavailable_catalog(origin, method, path, **kwargs): + if method == "GET" and path == "/evaldash/api/runs": + raise RuntimeError("EvalDash unavailable") + return request(origin, method, path, **kwargs) + + monkeypatch.setattr("marina.client.marina_request", unavailable_catalog) repeated = publish(second_gate) assert repeated.unserved_records == [] and repeated.errors == [] payload = client.get(f"/a/{publication.APPLET_ID}/api/runs").json() assert payload["skipped_records"] == [] and len(payload["runs"]) == 2 rows = {row["attempt_id"]: row for row in payload["runs"]} - assert repeated.urls[str(sources[0])].endswith(f"#run=tests%2Fpublication-0-{preset.revision}&attempt=native-0") + assert rows["native-0"]["evaldash_run_ids"] == automatic_links + assert "EvalDash catalog lookup was unavailable." in rows["native-0"]["evidence"] + assert rows["native-0"]["evaluation_data_identity"].endswith("/full_validation.parquet") + assert repeated.urls[str(sources[0])].endswith(f"#run={logical_id}&attempt=native-0") + newer = replace(preset, held_out_tasks="eval-lite@2026.11.24.99") + newer_selection = recipe.selection_artifact(newer.held_out_tasks).path() + write_json(Path(newer_selection) / "summary.json", selection_summary(40)) + saved_attempt = read_stored_skyrl_attempts(str(sources[0]))[1]["native-0"] + earlier = publication.build_record(str(sources[0]), newer, table=preset_table(newer), attempt=saved_attempt) + assert earlier.status == "succeeded" + assert earlier.evaluation_data_identity == rows["native-0"]["evaluation_data_identity"] + insufficient_overlap = report.model_copy( + update={ + "verdict": Verdict.INVALID, + "invariants": (Invariant(name="eval_lite/shared_tasks", value=9, limit=18, holds=False),), + } + ) + control = publication.build_record( + str(sources[0]), preset, table=table, attempt=saved_attempt, report=insufficient_overlap + ) + assert control.status == "succeeded" and not control.failed_facts + assert control.gate_result.invariants[0].replicate is None def wrong_returned_key(origin, method, path, *, json_body=None, **kwargs): response = request(origin, method, path, json_body=json_body) @@ -363,24 +425,29 @@ def wrong_returned_key(origin, method, path, *, json_body=None, **kwargs): AttemptSummary.model_validate_json(json.dumps(returned_row), strict=True), "http://localhost" ) monkeypatch.setattr("marina.client.marina_request", request) + expected_metrics = { + "eval_lite/family_mean": "objective", + "eval_lite/family_mean/gain_per_gpu_hour": "objective", + "policy/entropy": "guard", + relative_key: "requirement", + "eval_lite/mean": "slice", + "eval_lite/family/small/mean": "slice", + "eval_lite/family/large/mean": "slice", + } expected = report.model_dump(mode="json", include={"verdict", "effect", "reason", "invariants"}) | { "comparisons": [ - row.model_dump(mode="json") - for row in report.comparisons - if row.role in ("objective", "guard", "requirement") + row.model_dump(mode="json") for row in report.comparisons if expected_metrics.get(row.metric) == row.role ], "attempt_ids": ["native-0", "native-1"], "replicates": 2, + "control_commit": pin.commit, + "control_revision": pin.revision, } assert rows["native-0"]["gate_result"] == rows["native-1"]["gate_result"] == expected - assert {(item["metric"], item["role"]) for item in rows["native-0"]["gate_result"]["comparisons"]} == { - ("eval_lite/family_mean", "objective"), - ("eval_lite/family_mean/gain_per_gpu_hour", "objective"), - ("policy/entropy", "guard"), - (relative_key, "requirement"), - } + assert {item["metric"]: item["role"] for item in rows["native-0"]["gate_result"]["comparisons"]} == expected_metrics run_ids = ("eval-initial-policy", "eval-terminal-policy") + monkeypatch.setattr("marina.client.marina_request", unavailable_catalog) for index in range(2): @click.command() @@ -414,7 +481,7 @@ def republish_current(index=index): assert retained["gate_result"] == expected and retained["gate"] == rows[f"native-{index}"]["gate"] assert retained["issue"] == 73 + index assert read_stored_skyrl_attempts(str(sources[index]))[1][f"native-{index}"].issue == 73 + index - assert retained["evaldash_run_ids"] == list(run_ids) + assert retained["evaldash_run_ids"] == ([*automatic_links, *run_ids] if index == 0 else list(run_ids)) assert retained["wandb_url"] == rows[f"native-{index}"]["wandb_url"] assert (retained["status"], retained["failed_facts"]) == ( rows[f"native-{index}"]["status"], @@ -443,7 +510,7 @@ def republish_current(index=index): grafana = urlparse(rows["native-0"]["grafana_url"]) assert grafana.path == "/d/marin-rl-runs/rl-post-training" query = parse_qs(grafana.query) - assert query["var-run"] == [receipt["config"]["run"]["id"]] + assert query["var-run"] == [logical_id] assert query["var-cluster"] == [receipt["config"]["iris"]["cluster"]] assert query["to"] == ["1793997600000"] evaluation = {item["metric"]: item for item in rows["native-0"]["evaluations"]} @@ -476,7 +543,7 @@ def republish_current(index=index): assert fresh.unserved_records == [] and fresh.errors == [] assert fresh_report.run.attempt_ids == ("native-retry", "native-1") historical = stored()["native-0"] - assert historical["issue"] == 73 and historical["evaldash_run_ids"] == list(run_ids) + assert historical["issue"] == 73 and historical["evaldash_run_ids"] == [*automatic_links, *run_ids] with pytest.raises(ValueError, match="one output and its explicit attempt ID"): publication.publish_runs([str(sources[0])], preset, table=table, evaldash_run_ids=run_ids) with pytest.raises(ValueError, match="one output and its explicit attempt ID"): @@ -489,7 +556,7 @@ def republish_current(index=index): assert linked.served_records == [(receipt["config"]["run"]["id"], "native-retry")] and not linked.errors linked_rows = stored() assert linked_rows["native-retry"]["evaldash_run_ids"] == ["eval-for-retry"] - assert linked_rows["native-0"]["evaldash_run_ids"] == list(run_ids) + assert linked_rows["native-0"]["evaldash_run_ids"] == [*automatic_links, *run_ids] saved_evaluations = {} for root in sources: current_id, _ = read_stored_skyrl_attempts(str(root)) @@ -548,7 +615,7 @@ def gate_marker_unavailable(self, path, **kwargs): assert blocked.unserved_records == [(receipt["config"]["run"]["id"], "native-retry")] assert blocked.errors == ["Gate storage unavailable"] assert set(blocked.served_records) == { - (receipt["config"]["run"]["id"], "native-0"), + (logical_id, "native-0"), (second_receipt["config"]["run"]["id"], "native-1"), } failed_row = stored()["native-1"] @@ -598,7 +665,7 @@ def gate_marker_unavailable(self, path, **kwargs): ], ) assert command.exit_code == 0, (command.output, command.exception) - assert json.loads(command.output)["served_records"] == [[receipt["config"]["run"]["id"], "native-0"]] + assert json.loads(command.output)["served_records"] == [[logical_id, "native-0"]] after = stored() assert after["native-retry"] == before["native-retry"] and after["native-1"] == before["native-1"] assert after["native-0"]["evaluations"] == before["native-0"]["evaluations"] diff --git a/experiments/post_training/skyrl_evaluation.py b/experiments/post_training/skyrl_evaluation.py index a9a0d47d1aa..42c62810f37 100644 --- a/experiments/post_training/skyrl_evaluation.py +++ b/experiments/post_training/skyrl_evaluation.py @@ -1,38 +1,25 @@ # Copyright The Marin Authors # SPDX-License-Identifier: Apache-2.0 -"""Resolve completed SkyRL policies for experiment evaluations.""" +"""Bind model artifacts to the evaluation pipeline.""" from dataclasses import replace +from evalrecords.records import RLAttemptRef +from finestore.rl.run_records import read_attempt from marin.evaluation.model_config import ModelConfig from marin.execution.lazy import ArtifactStep, StepContext -from marin.rl.skyrl import SkyRLRun, resolve_skyrl_policy +from marin.rl.skyrl import SkyRLModelSource, SkyRLPolicyModel +from marin.rl.skyrl_records import EXPORTS_SUBDIRECTORY +from rigging.filesystem.storage_path import prefix_join from experiments.evaluation.evals import EvaluationDefinition from experiments.evaluation.pipeline import EvaluationResult, eval_step -SKYRL_POLICY_LOCATION = "" - -def resolve_skyrl_model(ctx: StepContext, source: ArtifactStep[SkyRLRun], model: ModelConfig) -> ModelConfig: - """Resolve a terminal policy's export URI and tokenizer in an evaluation step.""" - if model.location != SKYRL_POLICY_LOCATION: - raise ValueError(f"SkyRL evaluation model location must be {SKYRL_POLICY_LOCATION!r}") - - resolved = resolve_skyrl_policy(ctx, source) - return replace( - model, - location=resolved.uri, - identity=resolved.identity, - tokenizer=resolved.tokenizer_uri or resolved.uri, - tokenizer_revision=resolved.tokenizer_revision, - ) - - -def skyrl_eval_step( - source: ArtifactStep[SkyRLRun], - model: ModelConfig, +def evaluate_model( + model: SkyRLModelSource, + serving: ModelConfig, evals: tuple[EvaluationDefinition, ...], *, version: str, @@ -40,13 +27,40 @@ def skyrl_eval_step( submission_cluster: str, federated_cluster: str | None, ) -> ArtifactStep[EvaluationResult]: - """Build an evaluation that resolves a completed SkyRL policy export.""" + """Evaluate an artifact using a serving config with an empty location.""" + if serving.location or any( + value is not None + for value in (serving.revision, serving.identity, serving.tokenizer, serving.tokenizer_revision) + ): + raise ValueError("Evaluation location, revision, identity, tokenizer and tokenizer_revision come from the model") + + def resolve_model(ctx: StepContext) -> ModelConfig: + resolved = model.resolve(ctx) + return replace( + serving, + location=resolved.uri, + identity=resolved.identity, + tokenizer=resolved.tokenizer_uri or resolved.uri, + tokenizer_revision=resolved.tokenizer_revision, + ) + + def resolve_rl_attempt(ctx: StepContext) -> RLAttemptRef | None: + if not isinstance(model, SkyRLPolicyModel): + return None + run = ctx.resolved(model.step) + if run.run_id is None or run.attempt_id is None: + return None + record = read_attempt(prefix_join(ctx.artifact_path(model.step), EXPORTS_SUBDIRECTORY), run.attempt_id) + run_id = record.index_run_id if record is not None and record.run_id == run.run_id else run.run_id + return RLAttemptRef(run_id=run_id, attempt_id=run.attempt_id, step=run.global_step) + return eval_step( - model, + serving, evals, version=version, - deps=(source,), - resolve_model=lambda ctx: resolve_skyrl_model(ctx, source, model), + deps=model.deps(), + resolve_model=resolve_model, + resolve_rl_attempt=resolve_rl_attempt, accelerator=accelerator, submission_cluster=submission_cluster, federated_cluster=federated_cluster, diff --git a/experiments/post_training/skyrl_port_smoke.py b/experiments/post_training/skyrl_port_smoke.py index cee2dbcc582..4442e4ec1f4 100644 --- a/experiments/post_training/skyrl_port_smoke.py +++ b/experiments/post_training/skyrl_port_smoke.py @@ -17,6 +17,7 @@ ArtifactDataSource, ArtifactHfModel, IrisSkyRLExecution, + SkyRLPolicyModel, SkyRLRetentionPolicy, SkyRLRun, SkyRLRunConfig, @@ -32,7 +33,7 @@ from experiments.models import qwen2_5_0_5b_instruct from experiments.post_training.cat_count_canary.data import TRAIN_FILENAME, VALIDATION_FILENAME, cat_count_data_step from experiments.post_training.cat_count_canary.launcher import role_plan, training_config, with_role_plan -from experiments.post_training.skyrl_evaluation import SKYRL_POLICY_LOCATION, skyrl_eval_step +from experiments.post_training.skyrl_evaluation import evaluate_model CLUSTER = "cw-rno2a" MODEL = "Qwen/Qwen2.5-0.5B-Instruct" @@ -151,13 +152,11 @@ def resume_config(ctx: StepContext) -> SkyRLRunConfig: ) resume = replace(resume, build_config=resume_config, deps=(*resume.deps, train)) - evaluate = skyrl_eval_step( - resume, + evaluate = evaluate_model( + SkyRLPolicyModel(resume), ModelConfig( name="skyrl-port-smoke", - location=SKYRL_POLICY_LOCATION, - tokenizer=MODEL, - tokenizer_revision=MODEL_REVISION, + location="", apply_chat_template=True, resource_hint=ResourceHint(gpu={"H100": 1}), serve=ServeConfig(tensor_parallel_size=1, max_model_len=4096, max_num_seqs=16), diff --git a/experiments/post_training/task_curation/datasets/structure_closure.py b/experiments/post_training/task_curation/datasets/structure_closure.py index 677ca60b145..deacef18036 100644 --- a/experiments/post_training/task_curation/datasets/structure_closure.py +++ b/experiments/post_training/task_curation/datasets/structure_closure.py @@ -16,6 +16,8 @@ REPOSITORY = "open-athena/Snowball-Smartie-RL-2026.10.15.32-Data" REVISION = "cb728a7636caad3fc6fa6b6ba85a49194d9d69a3" +SOURCE_ID = "SnowballV01:structure-closure" +VALIDATION_SOURCE_ID = f"{SOURCE_ID}/validation" RUBRIC = """ These tasks complete an unfinished assistant message. Present its text as an assistant prefill and @@ -44,7 +46,7 @@ def sources() -> list[RlDataSource[CurationRecipe]]: return [ RlDataSource( info=SourceInfo( - id="SnowballV01:structure-closure" + ("/validation" if intended_use == IntendedUse.EVAL else ""), + id=VALIDATION_SOURCE_ID if intended_use == IntendedUse.EVAL else SOURCE_ID, title=f"Snowball v0.1 structural closure · {split}", origin="SnowballV01", family="structural", diff --git a/experiments/post_training/task_curation/selection.py b/experiments/post_training/task_curation/selection.py index 9d86df0f9c1..7ab0237778c 100644 --- a/experiments/post_training/task_curation/selection.py +++ b/experiments/post_training/task_curation/selection.py @@ -399,12 +399,16 @@ def _admitted_records(source: SelectionInput) -> Iterator[dict[str, str]]: yield from _parquet_rows(path, TASK_JSON_COLUMN) -def _grader_environments(sources: tuple[SelectionInput, ...]) -> dict[str, EnvironmentRequirements]: +def _heldout_catalog_ids() -> dict[str, str]: from experiments.post_training.task_curation.datasets.nemotron_ultra.components import ( # noqa: PLC0415 - curation-only dependency BLENDS, ) - components = {BLENDS[HELDOUT_BLEND][dataset].id: dataset for dataset in HELDOUT_FAMILIES} + return {dataset: BLENDS[HELDOUT_BLEND][dataset].id for dataset in HELDOUT_FAMILIES} + + +def _grader_environments(sources: tuple[SelectionInput, ...]) -> dict[str, EnvironmentRequirements]: + components = {source_id: dataset for dataset, source_id in _heldout_catalog_ids().items()} environments = {} for source in sources: if source.source_id not in components: @@ -435,14 +439,25 @@ def _grader_kind(task: TaskSpec) -> GraderKind: def _manifest_records(tasks: tuple[TaskSpec, ...], active: set[str]) -> Iterator[dict[str, Any]]: + from experiments.post_training.task_curation.datasets.structure_closure import ( # noqa: PLC0415 - curation-only dependency + VALIDATION_SOURCE_ID, + ) + + catalog_ids = _heldout_catalog_ids() for task in tasks: family = validation_family(task) + structural = family == STRUCTURAL_FAMILY + contract = {} if structural else _grader_contract(task) row = _selection_row( task, - TaskStrata(family=family, aai_category=AAII_CATEGORIES[family], source=task.source.dataset), + TaskStrata( + family=family, + aai_category=AAII_CATEGORIES[family], + source=VALIDATION_SOURCE_ID if structural else catalog_ids[contract["dataset"]], + ), state=MembershipState.ACTIVE if task.id in active else MembershipState.CANDIDATE, ) - upstream = None if family == STRUCTURAL_FAMILY else _grader_contract(task).get("pass_rate") + upstream = contract.get("pass_rate") yield row.model_copy(update={"measured_difficulty": 1 - upstream if upstream is not None else None}).model_dump( mode="json" ) @@ -516,7 +531,7 @@ def selected_records() -> Iterator[dict[str, Any]]: **TaskStrata( family=family, aai_category=AAII_CATEGORIES.get(family, "untagged"), - source=task.source.dataset, + source=row.source_id, agentic="agentic" in task.tags, ).model_dump(), } @@ -795,9 +810,7 @@ def prepare_eval_lite(config: EvalLiteConfig) -> None: for task, part in selection.tasks: row = _selection_row( task, - TaskStrata( - family=part.family, aai_category=part.aaii_category, source=task.source.dataset, topic=part.topic - ), + TaskStrata(family=part.family, aai_category=part.aaii_category, source=part.source_id, topic=part.topic), state=MembershipState.CANDIDATE, ).model_copy(update={"license": part.license}) if task.id in rows: diff --git a/experiments/post_training/task_curation/tests/test_selection.py b/experiments/post_training/task_curation/tests/test_selection.py index 35b3f1e4b73..3e704578a14 100644 --- a/experiments/post_training/task_curation/tests/test_selection.py +++ b/experiments/post_training/task_curation/tests/test_selection.py @@ -216,7 +216,7 @@ def test_selection_filters_full_heldout_and_duplicates_before_sampling(tmp_path, assert {row["aai_category"] for row in carried} == {AAII_CATEGORIES["calendar"]} assert all(row["agentic"] is True for row in carried) assert all( - row["source"] == json.loads(row["task_spec"])["source"]["dataset"] + row["source"] == ("fixture:second" if json.loads(row["task_spec"])["id"] == "training-c" else "fixture:first") and row["topic"] == row["difficulty"] == "untagged" for row in carried ) @@ -247,6 +247,11 @@ def test_selection_filters_full_heldout_and_duplicates_before_sampling(tmp_path, structural = next(task for task in full if families[task.id] == STRUCTURAL_FAMILY) assert structural.context.events[-1] == TextMessage(role="assistant", content='{"a":[1') assert structural.grader.mode == "structure_closure" + assert panel.identity(structural.id).strata.source == "SnowballV01:structure-closure/validation" + assert ( + panel.identity("heldout-calendar-0").strata.source + == "MarinSkyRL:nemotron_ultra_rlvr1/ultra_sft_step3200_calendar_v2" + ) summary = json.loads((output / "summary.json").read_text()) assert summary["source_counts"] == { "fixture:first": { @@ -730,7 +735,7 @@ def test_eval_lite_publication_preserves_untouched_strata_and_joins_initializer_ "agents" if agent else questions.family, "agents" if agent else questions.aaii_category, "in_process" if agent else "package", - task.source.dataset, + "NeMo:predicted-action" if agent else questions.source_id, task.source.model_dump_json(), "fixture-agents" if agent else "fixture-general", ) @@ -854,7 +859,7 @@ def retained_tasks(path): 1.0, sum(settings.fast_counts.values()), (), () ) cells = Counter((row.source, row.topic, row.difficulty) for row in active if row.family == questions.family) - parent_source = template.source.dataset + parent_source = questions.source_id assert cells == { (parent_source, "untagged", "learnable"): 1, ("fixture:a", "topic-a", "hard"): 1, diff --git a/infra/marina/apps/evaldash/README.md b/infra/marina/apps/evaldash/README.md index 5532d72e1b1..dc8bf06e279 100644 --- a/infra/marina/apps/evaldash/README.md +++ b/infra/marina/apps/evaldash/README.md @@ -391,6 +391,12 @@ Release from clean current main by default. The release transaction applies appl migrations before selecting the package. `/evaldash/`, the `evaldash` schema and `EVALDASH_INGEST_JOB` stay stable. The scheduled base-image runner snapshots and executes the package's `ingest` module; running jobs keep their selected code. + +For RL attempt links, deploy a runtime and ingestion image that support +`RLAttemptRef.step`, then release the EvalDash package before publishing +checkpoint evaluations with step metadata. Inspect a stored record through +the run API and verify its attempt link and checkpoint step. The EvalDash +package release installs the view and filters separately from RL Progress. Marina deployment and restart do not publish EvalDash or run its migrations. Pass `--allow-dirty` to explicitly release branch or uncommitted source diff --git a/infra/marina/apps/evaldash/app.py b/infra/marina/apps/evaldash/app.py index 17980ed748d..7022f2bfca4 100644 --- a/infra/marina/apps/evaldash/app.py +++ b/infra/marina/apps/evaldash/app.py @@ -364,6 +364,7 @@ def record_to_row(record: EvalRunRecord) -> dict: The single definition of that shape, so the run list is identical whichever store produced it. """ + attempt = record.rl_attempt return { "run_id": record.run_id, "group_id": record.group_id, @@ -386,9 +387,23 @@ def record_to_row(record: EvalRunRecord) -> dict: "error": record.error, "tasks": [task.name for task in record.evaluation.tasks], "jobs": dict(record.jobs), + "rl_run_id": attempt.run_id if attempt is not None else None, + "rl_attempt_id": attempt.attempt_id if attempt is not None else None, + "rl_step": getattr(attempt, "step", None), } +def _matches_rl_attempt(record: EvalRunRecord, run_ids: tuple[str, ...], attempt_id: str | None) -> bool: + if not run_ids and attempt_id is None: + return True + ref = record.rl_attempt + return ( + ref is not None + and (not run_ids or ref.run_id in run_ids) + and (attempt_id is None or ref.attempt_id == attempt_id) + ) + + def _group_sibling_row(record: EvalRunRecord) -> dict: """One sibling run in a group, for the run-detail group panel.""" return { @@ -473,10 +488,12 @@ def fetch_runs( group: str | None = None, version: str | None = None, accelerator: str | None = None, + rl_runs: tuple[str, ...] = (), + rl_attempt: str | None = None, limit: int = DEFAULT_RUNS_LIMIT, ) -> list[dict]: records, _by_id = self._snapshot() - rows = [record_to_row(record) for record in records] + rows = [record_to_row(record) for record in records if _matches_rl_attempt(record, rl_runs, rl_attempt)] rows = [ row for row in rows @@ -527,6 +544,8 @@ def groups( status: str | None = None, version: str | None = None, accelerator: str | None = None, + rl_runs: tuple[str, ...] = (), + rl_attempt: str | None = None, limit: int = DEFAULT_RUNS_LIMIT, ) -> list[dict]: """Runs collapsed into launches (one per ``group_id``), newest first. @@ -540,6 +559,8 @@ def groups( for record in records: if (model and record.model.name != model) or (user and record.user != user): continue + if not _matches_rl_attempt(record, rl_runs, rl_attempt): + continue by_group.setdefault(record.group_id, []).append(record) groups: list[dict] = [] for group_id, members in by_group.items(): @@ -1157,6 +1178,8 @@ async def api_runs(request: Request) -> JSONResponse: group=params.get("group") or None, version=params.get("version") or None, accelerator=params.get("accelerator") or None, + rl_runs=tuple(filter(None, (params.get("rl_run"), params.get("rl_native_run")))), + rl_attempt=params.get("rl_attempt") or None, limit=_parse_limit(params.get("limit")), ) return JSONResponse(rows) @@ -1318,6 +1341,8 @@ async def api_groups(request: Request) -> JSONResponse: status=params.get("status") or None, version=params.get("version") or None, accelerator=params.get("accelerator") or None, + rl_runs=tuple(filter(None, (params.get("rl_run"), params.get("rl_native_run")))), + rl_attempt=params.get("rl_attempt") or None, limit=_parse_limit(params.get("limit")), ) return JSONResponse(groups) diff --git a/infra/marina/apps/evaldash/journeys/conftest.py b/infra/marina/apps/evaldash/journeys/conftest.py index 4b6dbd80343..76ed3716098 100644 --- a/infra/marina/apps/evaldash/journeys/conftest.py +++ b/infra/marina/apps/evaldash/journeys/conftest.py @@ -19,6 +19,7 @@ import pytest from evaldash import app as evaldash_app from evaldash import fixtures +from evalrecords.records import RLAttemptRef, read_record, write_record from marina.db import DatabaseSpec, engine_for APP = "evaldash" @@ -30,7 +31,17 @@ def seeded_records(marina_database: DatabaseSpec) -> Iterator[str]: """Fixture records on disk, reconciled into the app's schema; yields the records prefix.""" prefix = RECORDS_PREFIX - fixtures.build_fixtures(prefix) + records = fixtures.build_fixtures(prefix) + for path, run_id, attempt_id in zip( + records[:4], + ("native/fixture", "logical-fixture", "unrelated", "logical-fixture"), + ("wanted", "wanted", "wanted", "earlier"), + strict=True, + ): + record = read_record(path) + write_record( + record.model_copy(update={"rl_attempt": RLAttemptRef(run_id=run_id, attempt_id=attempt_id, step=0)}), prefix + ) fixtures.build_native_fixtures(prefix) engine = engine_for(marina_database, APP) try: diff --git a/infra/marina/apps/evaldash/journeys/test_runs.py b/infra/marina/apps/evaldash/journeys/test_runs.py index 53bef10e2cf..3775675cbd4 100644 --- a/infra/marina/apps/evaldash/journeys/test_runs.py +++ b/infra/marina/apps/evaldash/journeys/test_runs.py @@ -5,7 +5,7 @@ import re from typing import Any, cast -from urllib.parse import quote, unquote_plus +from urllib.parse import quote, unquote_plus, urlencode import pytest from marina.journeys import Journey @@ -30,6 +30,19 @@ def test_the_run_log_lists_launches_and_one_run_opens(journey: Journey) -> None: journey.sees("Metrics").shoot("run-detail") assert journey.page.url == journey.url(f"/runs/{newest}") + params = urlencode({"rl_run": "logical-fixture", "rl_native_run": "native/fixture", "rl_attempt": "wanted"}) + matched = cast(list[dict[str, Any]], journey.api(f"{API}/runs?{params}")) + assert {row["rl_run_id"] for row in matched} == {"logical-fixture", "native/fixture"} + assert len(matched) == 2 and all(row["rl_attempt_id"] == "wanted" and row["rl_step"] == 0 for row in matched) + [group] = cast(list[dict[str, Any]], journey.api(f"{API}/groups?{params}")) + assert {item["run_id"] for item in group["evals"]} == {row["run_id"] for row in matched} + journey.visit(f"/runs?view=runs&{params}") + expect(journey.page.get_by_role("link", name="detail →")).to_have_count(2) + journey.visit("/runs/snowball-2026.07.20-mmlu") + link = journey.page.get_by_role("link", name="RL attempt wanted") + expect(link).to_have_attribute("href", re.compile(r"/#run=native%2Ffixture&attempt=wanted$")) + expect(journey.page.get_by_text("checkpoint step 0", exact=False)).to_be_visible() + def test_the_shell_bar_carries_the_app_and_its_own_navigation(journey: Journey) -> None: journey.visit("/runs") diff --git a/infra/marina/apps/evaldash/web/src/constants.ts b/infra/marina/apps/evaldash/web/src/constants.ts index 7223dc2756c..9be0d9ba7fa 100644 --- a/infra/marina/apps/evaldash/web/src/constants.ts +++ b/infra/marina/apps/evaldash/web/src/constants.ts @@ -1,6 +1,7 @@ // Most models the Compare surface scores at once. The panel picker and the compare page // share this so they never disagree on how many models are sendable. export const MAX_COMPARE = 4 +export const RL_PROGRESS_URL = 'https://applets.marina.oa.dev/a/6c971887-1e22-45b1-9dcb-dd775829df57/' // Run properties a panel or comparison request can be filtered on. Mirrors metrics.RUN_FACETS; the // server rejects nothing it does not recognize, it simply ignores it, so drift is inert. diff --git a/infra/marina/apps/evaldash/web/src/pages/RunDetailPage.vue b/infra/marina/apps/evaldash/web/src/pages/RunDetailPage.vue index 001ea56ac0e..9e1793d9d51 100644 --- a/infra/marina/apps/evaldash/web/src/pages/RunDetailPage.vue +++ b/infra/marina/apps/evaldash/web/src/pages/RunDetailPage.vue @@ -3,6 +3,7 @@ import { computed, onMounted, ref, watch } from 'vue' import { RouterLink } from 'vue-router' import { useApi } from '@/composables/useApi' import { onViewRefresh } from '@/composables/useRefresh' +import { RL_PROGRESS_URL } from '@/constants' import { formatDuration, formatInterval, @@ -25,6 +26,10 @@ import GroupLinks from '@/components/runs/GroupLinks.vue' const props = defineProps<{ runId: string }>() const { data, loading, error, refresh } = useApi(() => `api/runs/${props.runId}`) +const rlAttemptUrl = computed(() => { + const attempt = data.value?.rl_attempt + return attempt ? `${RL_PROGRESS_URL}#${new URLSearchParams({ run: attempt.run_id, attempt: attempt.attempt_id })}` : null +}) onMounted(refresh) watch(() => props.runId, refresh) @@ -155,6 +160,10 @@ async function copyPath() { {{ data.user }}

{{ data.description }}

+

+ RL attempt {{ data.rl_attempt.attempt_id }} + · checkpoint step {{ data.rl_attempt.step }} +

diff --git a/infra/marina/apps/evaldash/web/src/pages/RunsPage.vue b/infra/marina/apps/evaldash/web/src/pages/RunsPage.vue index ff54fc119c2..b1a0ed33d4f 100644 --- a/infra/marina/apps/evaldash/web/src/pages/RunsPage.vue +++ b/infra/marina/apps/evaldash/web/src/pages/RunsPage.vue @@ -53,6 +53,9 @@ const limit = computed({ }, }) const group = computed(() => queryValue('group')) +const rlRun = computed(() => queryValue('rl_run')) +const rlNativeRun = computed(() => queryValue('rl_native_run')) +const rlAttempt = computed(() => queryValue('rl_attempt')) type View = 'launches' | 'runs' const view = computed({ get: () => queryValue('view') === 'runs' || group.value ? 'runs' : 'launches', @@ -65,6 +68,9 @@ function requestParams(): URLSearchParams { for (const [key, value] of Object.entries(selected.value)) { if (value) params.set(key, value) } + if (rlRun.value) params.set('rl_run', rlRun.value) + if (rlNativeRun.value) params.set('rl_native_run', rlNativeRun.value) + if (rlAttempt.value) params.set('rl_attempt', rlAttempt.value) params.set('limit', String(limit.value)) return params } diff --git a/infra/marina/apps/evaldash/web/src/types/api.ts b/infra/marina/apps/evaldash/web/src/types/api.ts index 0897f8555e3..a89cba3bb74 100644 --- a/infra/marina/apps/evaldash/web/src/types/api.ts +++ b/infra/marina/apps/evaldash/web/src/types/api.ts @@ -298,6 +298,7 @@ export interface RunMetricRow { // the run-detail endpoint computes it (the rolled-up primary metric) and attaches it to the response. export interface EvalRecord { run_id: string + rl_attempt?: { run_id: string; attempt_id: string; step?: number | null } | null group_id: string version: string | null description: string | null diff --git a/infra/marina/apps/rl_progress/README.md b/infra/marina/apps/rl_progress/README.md index 8c043ff113e..b146d7e71b3 100644 --- a/infra/marina/apps/rl_progress/README.md +++ b/infra/marina/apps/rl_progress/README.md @@ -13,10 +13,20 @@ A run-only link (`#run=`) selects its latest attempt. Add run URL; the Grafana link uses the recorded native execution window. The Model column can filter by the recorded model. The issue number links to GitHub, and the opt-out is shown in the attempt details. Linked EvalDash evaluations open the recorded run IDs. The detail view includes per-step family, AAII-category and difficulty means and scored/attempted answer counts. +The attempt's EvalDash filter finds evaluations that enter the catalog after publication. +Terminal publication looks up catalog records for the exact run and attempt. +Re-publication adds newly discovered links to the existing row. The attempt details link to a grader report when one was published. It shows training and evaluation success rates and verifier coverage by task and subset, with failure counts and grading latency by subset. +Preset progress shows each control set's global score on its own evaluation data. +The comparable line uses shared-task differences from the saved control link reports. +The line breaks where a link is unavailable or the protocol changes. The global series +keeps each scored point and marks changes in evaluation data or protocol. Experiments +with a recorded base revision appear with those controls. The plot shows the run's own +score and a comparable point when the recorded gate supplies a matching difference. + Malformed records are skipped individually and named in a visible note. ## Data contract @@ -24,8 +34,10 @@ Malformed records are skipped individually and named in a visible note. The app's release migration creates its `rl_runs` table in the application schema. Each `(run_id, attempt_id)` identifies one updatable JSON record. The index groups native attempts of the same model, preset, user and composed comparison configuration. Repeat -publication refreshes that attempt's record. Null model, issue, EvalDash links, gate, gate result and -grader report fields preserve their stored values. A terminal record takes precedence over a +publication refreshes that attempt's record. Null provenance fields, issue, gate, gate result and +grader report fields preserve their stored values. EvalDash links accumulate by ID. +History publishers write format 2. The API returns format 1 to format-1 +publishers and retains the stored history metadata. A terminal record takes precedence over a running update for the same attempt. Native failures and failed training or evaluation invariants set `status: failed` and name `failed_facts`. @@ -60,12 +72,19 @@ Check cold-loaded run and attempt hash links, refresh after repeat publication, and the detail dialog's scrolling body, close control, Escape, and backdrop dismissal. Stop the local stack with Ctrl-C. -The `Marin - Release RL Progress` workflow runs manually from main, with inspection as its default. The `rl-progress` CI job runs the packaged API and `marina journey rl_progress` browser owner. +The `Marin - Release RL Progress` workflow runs on main pushes that change the +app. Its manual dispatch defaults to inspection. The `rl-progress` CI job runs +the packaged API and `marina journey rl_progress` browser owner. -Deploy a Marina runtime containing `finestore.rl.rl_progress` before releasing the app package. +Release the run index runtime with format-1 `AttemptSummary` support before +releasing the history app package. Confirm both the history app package and +the runtime support format 2 before using the history publisher. The +history app package accepts format-1 publisher writes and preserves saved +history. Republishing an indexed attempt adds its native ID for older +EvalDash backlinks. For production, follow [Marina's release procedure](../../README.md). Inspect the -current private revision, then release with its exact `--base-version`. Merging -source does not publish it. Verify the deployed assets, selected revision and all +current private revision, then release with its exact `--base-version`. Verify +the deployed assets, selected revision and all stored records after release. Do not change access mode or rewrite historical results as part of a frontend update. diff --git a/infra/marina/apps/rl_progress/dist/app.js b/infra/marina/apps/rl_progress/dist/app.js index a2fdbd58800..06103c50d23 100644 --- a/infra/marina/apps/rl_progress/dist/app.js +++ b/infra/marina/apps/rl_progress/dist/app.js @@ -1,3 +1,5 @@ +import { showProgress } from './progress.js'; + const $ = (id) => document.getElementById(id); let runs = []; const selectedAttempts = new Map(); @@ -9,11 +11,12 @@ function element(tag, text, attrs = {}) { return node; } const series = (run) => run.series ?? run.label; +const savedPreset = (run) => run.preset ?? run.series; const grafanaLink = (run) => run.grafana_url && /^https:\/\/grafana\.oa\.dev\//.test(run.grafana_url) ? element('a', 'Grafana ↗', { href: run.grafana_url, target: '_blank', rel: 'noopener noreferrer' }) : null; const number = (value, digits = 4) => Number.isFinite(value) ? value.toFixed(digits) : '—'; const percent = (value) => value == null ? 'unavailable' : `${number(value, 2)}%`; const comparison = (row) => `${row.metric}: ${number(row.control)} → ${number(row.run)}, Δ ${percent(row.delta_percent)}, noise ±${percent(row.noise_percent)}${row.passes == null ? '' : row.passes ? ' · PASS' : ' · FAIL'}`; -const invariant = (row) => `r${row.replicate} ${row.name}: ${row.value} ${row.comparator ?? '(comparator unknown)'} ${row.limit} · ${row.holds ? 'PASS' : 'FAIL'}`; +const invariant = (row) => `${row.replicate == null ? 'Group' : `r${row.replicate}`} ${row.name}: ${row.value} ${row.comparator ?? '(comparator unknown)'} ${row.limit} · ${row.holds ? 'PASS' : 'FAIL'}`; const hours = (run) => run.elapsed_seconds == null ? null : run.elapsed_seconds / 3600; const attemptTime = (run) => Date.parse(run.started_at ?? run.run_date ?? run.completed_at) || 0; function groupedRuns(records = runs) { @@ -31,8 +34,13 @@ function visibleRuns(groups) { function route(run) { return '#' + new URLSearchParams({ run: run.run_id, attempt: run.attempt_id }); } function selectedFromHash() { const params = new URLSearchParams(location.hash.slice(1)); - const attempts = groupedRuns().get(params.get('run')) ?? []; - return params.has('attempt') ? attempts.find((run) => run.attempt_id === params.get('attempt')) ?? null : attempts[0] ?? null; + const runId = params.get('run'); + if (!runId) return null; + const attempts = groupedRuns().get(runId) ?? []; + const aliases = runs.filter((run) => run.native_run_id === runId); + const attemptId = params.get('attempt'); + if (attemptId != null) return [...attempts, ...aliases].find((run) => run.attempt_id === attemptId) ?? null; + return attempts[0] ?? aliases.sort((a, b) => attemptTime(b) - attemptTime(a))[0] ?? null; } function addField(list, title, value) { @@ -51,12 +59,16 @@ function showDetails(run) { for (const id of run.evaldash_run_ids ?? []) { links.append(element('a', `EvalDash ${id} ↗`, { href: `https://marina.oa.dev/evaldash/runs/${encodeURIComponent(id)}`, target: '_blank', rel: 'noopener noreferrer' })); } + const evaluations = new URLSearchParams({ rl_run: run.run_id, rl_attempt: run.attempt_id, view: 'runs' }); + if (run.native_run_id && run.native_run_id !== run.run_id) evaluations.set('rl_native_run', run.native_run_id); + links.append(element('a', 'All EvalDash evaluations of this attempt', { href: `https://marina.oa.dev/evaldash/runs?${evaluations}` })); if (run.has_grader_report) links.append(element('a', 'Grader stats', { href: './graders.html?' + route(run).slice(1) })); links.append(element('a', 'Link to this run', { href: route(run) })); body.append(links); const fields = element('dl', null, { class: 'detail-grid' }); const facts = [ ['Model', run.model], ['Preset', run.preset], ['Preset revision', run.preset_revision], + ['Base version', run.base_preset_revision], ['Evaluation set', run.evaluation_data_identity], ['User', run.user], ['Branch', run.branch], ['Uncommitted changes', run.dirty == null ? null : run.dirty ? 'Yes' : 'No'], ['PR', run.pr_number], ['Cluster', run.cluster], ['Issue', run.issue], ['Series', series(run)], ['Run ID', run.run_id], ['Attempt ID', run.attempt_id], ['Iris job', run.iris_job_id], @@ -100,6 +112,17 @@ function render() { const model = $('model-filter').value; const matching = model ? runs.filter((run) => run.model === model) : runs; const groups = groupedRuns(matching), selected = visibleRuns(groups); + const preset = $('progress-preset'), previous = preset.value; + const choices = new Map(matching.filter((run) => run.model && savedPreset(run) && run.evaluations?.length) + .map((run) => [JSON.stringify([run.model, savedPreset(run)]), `${run.model} · ${savedPreset(run)}`])); + preset.replaceChildren(...[...choices].sort((a, b) => a[1].localeCompare(b[1])) + .map(([value, label]) => element('option', label, { value }))); + if (choices.has(previous)) preset.value = previous; + $('progress-panel').hidden = !choices.size; + const history = matching.filter((run) => JSON.stringify([run.model, savedPreset(run)]) === preset.value); + const reference = history.find((run) => run.control_preset && run.control_preset !== savedPreset(run)); + const controls = reference ? matching.filter((run) => run.model === reference.model && savedPreset(run) === reference.control_preset) : []; + showProgress($('progress-charts'), history, controls, route); $('count').textContent = `${selected.length} runs · ${matching.length} recorded attempts`; $('attempts').replaceChildren(...[...selected].sort((a, b) => attemptTime(b) - attemptTime(a)).map((run) => { const tr = element('tr'); @@ -118,6 +141,7 @@ function render() { const objectives = element('td'), constraints = element('td'), verdict = element('td'); if (report) { for (const row of report.comparisons) { + if (row.role === 'slice') continue; const cell = row.role === 'objective' ? objectives : constraints; cell.append(element('p', comparison(row), { class: row.passes === false ? 'warning' : '' })); } @@ -130,7 +154,9 @@ function render() { constraints.textContent = '—'; verdict.textContent = '—'; } - tr.append(name, element('td', run.model ?? 'Not recorded'), objectives, constraints, verdict); + const evalCount = (run.evaldash_run_ids ?? []).length; + tr.append(name, element('td', run.model ?? 'Not recorded'), objectives, constraints, verdict, + element('td', evalCount ? String(evalCount) : '—')); return tr; })); } @@ -152,6 +178,7 @@ async function refresh() { } $('refresh').onclick = refresh; $('model-filter').onchange = render; +$('progress-preset').onchange = render; function closeDetails() { if (location.hash.startsWith('#run=')) history.replaceState(null, '', location.pathname + location.search); $('run-detail').close(); diff --git a/infra/marina/apps/rl_progress/dist/index.html b/infra/marina/apps/rl_progress/dist/index.html index 6124db860bd..66ce1220b17 100644 --- a/infra/marina/apps/rl_progress/dist/index.html +++ b/infra/marina/apps/rl_progress/dist/index.html @@ -13,7 +13,12 @@
-

Recorded runs

Select an attempt; latest first. Native timestamps use UTC.
Run / attemptModelObjectives · control → runGuardsVerdict
+ +

Recorded runs

Select an attempt; latest first. Native timestamps use UTC.
Run / attemptModelObjectives · control → runGuardsVerdictEvalDash
RUN DETAILS

diff --git a/infra/marina/apps/rl_progress/dist/progress.js b/infra/marina/apps/rl_progress/dist/progress.js new file mode 100644 index 00000000000..740339615ff --- /dev/null +++ b/infra/marina/apps/rl_progress/dist/progress.js @@ -0,0 +1,198 @@ +const SVG = 'http://www.w3.org/2000/svg'; +const controlPath = /\/control\/[^/]+-([a-f0-9]{7,40})-r\d+(?:-retry\d+)?\/([^/]+)\/?$/; +const evaluationMetric = /^([^@]+)@(\d+)\/(.+)$/; +const comparableVerdicts = new Set(['pass', 'fail']); +const score = (value) => `${(100 * value).toFixed(1)}%`; +const time = (run) => run.completed_at ?? run.started_at ?? run.run_date ?? ''; +const sameCommit = (a, b) => a && b && (a.startsWith(b) || b.startsWith(a)); + +function metrics(run) { + const scores = new Map(); + for (const row of run.evaluations ?? []) { + const match = row.metric.match(evaluationMetric); + if (!match || !Number.isFinite(row.run)) continue; + const [, evaluation, step, statistic] = match; + const key = `${evaluation}/${statistic}`; + if (!scores.has(key) || Number(step) > scores.get(key).step) scores.set(key, { value: row.run, step: Number(step) }); + } + return scores; +} + +function controlSets(runs) { + const sets = new Map(); + for (const run of runs) { + const match = run.artifact_uri?.match(controlPath); + if (!match) continue; + const [, commit, version] = match; + const revision = run.preset_revision ?? version; + const key = `${revision}/${commit}`; + if (!sets.has(key)) sets.set(key, { revision, commit, rows: [] }); + sets.get(key).rows.push(run); + } + return [...sets.values()].flatMap((set) => { + const report = set.rows.find((run) => run.gate_result?.attempt_ids.includes(run.attempt_id))?.gate_result; + const latestByOutput = new Map(); + for (const run of [...set.rows].sort((a, b) => time(b).localeCompare(time(a)))) { + if (run.status !== 'succeeded' || latestByOutput.has(run.artifact_uri)) continue; + if (report?.attempt_ids.length && !report.attempt_ids.includes(run.attempt_id)) continue; + if (!report && (run.dirty || (run.branch && run.branch !== 'main' && !sameCommit(run.source_revision, set.commit)))) continue; + latestByOutput.set(run.artifact_uri, run); + } + const rows = [...latestByOutput.values()]; + if (!rows.length) return []; + const [latest] = rows; + return [{ ...set, rows, report, time: time(latest), data: latest.evaluation_data_identity, + protocol: latest.evaluation_protocol_identity }]; + }).sort((a, b) => a.time.localeCompare(b.time)); +} + +function comparison(report, metric) { + if (!comparableVerdicts.has(report?.verdict)) return null; + const row = report.comparisons.find((item) => item.metric === metric); + if (!row) return null; + if (Number.isFinite(row.delta)) return { delta: row.delta, tolerance: row.tolerance }; + return null; +} + +function controlPoints(sets, scores, metric) { + const points = sets.flatMap((set) => { + const values = set.rows.map((run) => scores.get(run).get(metric)?.value).filter(Number.isFinite); + if (!values.length) return []; + return [{ ...set, global: values.reduce((total, value) => total + value, 0) / values.length, + min: Math.min(...values), max: Math.max(...values) }]; + }); + for (const [index, point] of points.entries()) { + const previous = points[index - 1]; + if (!previous) { point.segment = 0; continue; } + const protocolChanged = (point.protocol && previous.protocol && point.protocol !== previous.protocol) + || point.report?.reason === 'evaluation protocol differs'; + const dataChanged = point.data && previous.data && point.data !== previous.data; + point.marker = protocolChanged ? 'Protocol changed' : dataChanged ? 'Evaluation set changed' : null; + const shared = point.report?.invariants.some((fact) => fact.name === `${metric.split('/')[0]}/shared_tasks` && fact.holds); + if (shared && !protocolChanged && point.report.control_revision === previous.revision + && sameCommit(point.report.control_commit, previous.commit)) { + point.link = comparison(point.report, metric); + } + point.segment = previous.segment + (point.link ? 0 : 1); + } + for (let index = points.length - 1; index >= 0; index--) { + const next = points[index + 1]; + points[index].chained = next?.link ? next.chained - next.link.delta : points[index].global; + } + return points; +} + +function branchPoints(runs, scores, controls, metric) { + const groups = new Set(); + return runs.flatMap((run) => { + const global = scores.get(run).get(metric)?.value; + if (!Number.isFinite(global) || controlPath.test(run.artifact_uri ?? '')) return []; + const report = run.gate_result; + const matching = controls.filter((control) => control.revision === run.base_preset_revision); + const base = matching.find((control) => sameCommit(report?.control_commit, control.commit)) ?? matching.at(-1); + const gateControl = controls.find((control) => report?.control_revision === control.revision + && sameCommit(report.control_commit, control.commit)); + const group = report?.attempt_ids.length > 1 ? JSON.stringify([...report.attempt_ids].sort()) : null; + const delta = base && gateControl?.segment === base.segment && !groups.has(group) ? comparison(report, metric) : null; + if (delta && group) groups.add(group); + return [{ run, global, time: base?.time ?? time(run), chained: delta ? gateControl.chained + delta.delta : null, + tolerance: delta?.tolerance, replicateCount: delta && group ? report.attempt_ids.length : 1 }]; + }).sort((a, b) => time(a.run).localeCompare(time(b.run))); +} + +function svg(tag, attributes, label) { + const node = document.createElementNS(SVG, tag); + for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, value); + if (label != null) node.textContent = label; + return node; +} + +function plot(metric, controls, branches, route) { + const chart = svg('svg', { viewBox: '0 0 680 200', role: 'group', 'aria-label': metric, class: 'progress-chart' }); + const values = [...controls.flatMap((row) => [row.min, row.max, row.chained]), + ...branches.flatMap((row) => [row.global, row.chained, row.chained == null ? null : row.chained + (row.tolerance ?? 0), + row.chained == null ? null : row.chained - (row.tolerance ?? 0)])].filter(Number.isFinite); + const low = Math.min(...values), high = Math.max(...values), padding = Math.max(.025, (high - low) * .12); + const y = (value) => 160 - 130 * (value - low + padding) / (high - low + 2 * padding); + const times = [...new Set([...controls, ...branches].map((row) => row.time))].sort(); + const positions = new Map(times.map((value, index) => [value, index])); + const x = (at) => times.length === 1 ? 346 : 68 + 555 * positions.get(at) / (times.length - 1); + const line = (index, a, end, b, className, label) => { + const node = svg('line', { x1: x(index), y1: y(a), x2: x(end), y2: y(b), class: className }); + if (label) node.append(svg('title', {}, label)); + chart.append(node); + }; + for (const value of new Set([low, (low + high) / 2, high])) { + chart.append(svg('line', { x1: 55, x2: 650, y1: y(value), y2: y(value), class: 'history-grid' }), + svg('text', { x: 50, y: y(value) + 3, 'text-anchor': 'end' }, score(value))); + } + for (const [index, point] of controls.entries()) { + const previous = controls[index - 1]; + if (previous) line(previous.time, previous.global, point.time, point.global, 'history-global'); + if (point.link) line(previous.time, previous.chained, point.time, point.chained, 'history-chain', + Number.isFinite(point.link.tolerance) ? `Shared-task tolerance ±${score(point.link.tolerance)}` : null); + if (point.marker) { + const marker = svg('line', { x1: x(point.time), y1: 20, x2: x(point.time), y2: 165, class: 'history-marker', + 'aria-label': point.marker }); + marker.append(svg('title', {}, `${point.marker}${point.data ? ` · ${point.data}` : ''}`)); + chart.append(marker, svg('text', { x: x(point.time) - 4, y: 17, 'text-anchor': 'end' }, point.marker)); + } + line(point.time, point.min, point.time, point.max, 'history-global', `Replicate range ${score(point.min)}–${score(point.max)}`); + const markers = [[point.global, 'global']]; + if (point.link || controls[index + 1]?.link) markers.push([point.chained, 'chain']); + for (const [value, style] of markers) { + const dot = svg('circle', { cx: x(point.time), cy: y(value), r: 3.5, class: `history-${style}` }); + dot.append(svg('title', {}, `${point.revision} · ${style === 'chain' ? 'Comparable' : 'Global'} ${score(value)}`)); + chart.append(dot); + } + if (index === 0 || index === controls.length - 1 || controls.length <= 5) { + chart.append(svg('text', { x: x(point.time), y: 181, 'text-anchor': 'middle' }, point.revision)); + } + } + let previousMain; + for (const point of branches) { + const value = point.chained ?? point.global; + const onMain = !controls.length && point.run.branch === 'main' && !point.run.dirty; + if (onMain) { + if (previousMain) line(previousMain.time, previousMain.value, point.time, value, 'history-global'); + previousMain = { time: point.time, value }; + } + if (point.chained != null && Number.isFinite(point.tolerance)) { + line(point.time, value - point.tolerance, point.time, value + point.tolerance, 'history-branch'); + } + const detail = point.replicateCount > 1 ? ` · ${point.replicateCount} replicate mean` : ''; + const link = svg('a', { href: route(point.run), 'aria-label': `${point.run.label} · ${score(value)}${detail}` }); + link.append(svg('circle', { cx: x(point.time), cy: y(value), r: 4.5, class: onMain ? 'history-global' : 'history-branch' }), + svg('title', {}, `${point.run.branch ?? point.run.label} · ${score(value)} · ${point.run.base_preset_revision ?? 'Base unavailable'}`)); + if (point.chained != null && point.chained !== point.global) { + const dot = svg('circle', { cx: x(point.time), cy: y(point.global), r: 3, class: 'history-global' }); + dot.append(svg('title', {}, `Experiment global ${score(point.global)}`)); + link.append(dot); + } + chart.append(link); + } + return chart; +} + +export function showProgress(container, runs, reference, route) { + const scores = new Map([...runs, ...reference].map((run) => [run, metrics(run)])); + const selected = [...new Set([...scores.values()].flatMap((values) => [...values.keys()]))] + .filter((key) => /^([^/]+)\/(family_mean|family\/[^/]+\/mean|mean)$/.test(key)); + const metricsToShow = selected.filter((key) => !/^[^/]+\/mean$/.test(key) + || !selected.includes(key.replace(/\/mean$/, '/family_mean'))); + const controls = controlSets([...runs, ...reference]); + const initialOnly = runs.some((run) => run.planned_updates === 0) + && runs.every((run) => run.planned_updates == null || run.planned_updates === 0); + container.replaceChildren(); + for (const metric of metricsToShow.sort((a, b) => a.split('/').length - b.split('/').length || a.localeCompare(b))) { + const points = controlPoints(controls, scores, metric); + const branches = branchPoints(runs, scores, points, metric); + if (!points.length && !branches.length) continue; + const figure = document.createElement('figure'); + const label = document.createElement('figcaption'); + label.textContent = metric.replaceAll('/', ' · ').replaceAll('_', ' '); + if (initialOnly) label.textContent += ' · initializer inference'; + figure.append(label, plot(metric, points, branches, route)); + container.append(figure); + } +} diff --git a/infra/marina/apps/rl_progress/dist/style.css b/infra/marina/apps/rl_progress/dist/style.css index 45f6b86ac62..6e9cd1c8617 100644 --- a/infra/marina/apps/rl_progress/dist/style.css +++ b/infra/marina/apps/rl_progress/dist/style.css @@ -1,3 +1,29 @@ :root{--ink:#17181c;--paper:#fcfbf8;--panel:#fff;--edge:#e2ded2;--muted:#6d6a60;--mark:#1f5c4a;--warn:#8a3324;font:15px/1.55 system-ui,-apple-system,sans-serif;color:var(--ink);background:var(--paper)}*{box-sizing:border-box}body{margin:0}main{max-width:1250px;margin:auto;padding:38px 30px}header,.panel-heading,.toolbar,.dialog-heading{display:flex;align-items:center;justify-content:space-between;gap:16px}header{align-items:flex-start;margin-bottom:25px}h1{font-size:32px;letter-spacing:-1px;line-height:1.2;margin:9px 0}h2{font-size:20px;font-weight:600;margin:5px 0 10px}p{margin:8px 0}.eyebrow{font-size:11px;font-weight:650;letter-spacing:1.5px;color:var(--muted)}header p,.note,.panel-heading>span{color:var(--muted);font-size:13px}.toolbar{justify-content:flex-start;margin:0 0 20px}.panel{padding:24px;border:1px solid var(--edge);border-radius:6px;background:var(--panel);margin-bottom:20px}.table-scroll{overflow:auto}table{border-collapse:collapse;width:100%;font-size:13px}th,td{padding:12px 16px 12px 0;border-bottom:1px solid var(--edge);text-align:left;vertical-align:top}th{text-transform:uppercase;letter-spacing:.6px;font-size:10px;color:var(--muted)}td:first-child{min-width:270px}td button{border:0;padding:0;text-align:left;color:var(--mark);background:none}.warning{color:var(--warn)}button,select{font:inherit;color:inherit;padding:7px 10px;border:1px solid var(--edge);background:var(--panel);border-radius:4px}button,a,select{cursor:pointer}button:hover,a:hover{color:var(--mark)}:focus-visible{outline:2px solid var(--mark);outline-offset:3px}dialog{width:min(880px,94vw);max-height:90vh;border:1px solid var(--edge);border-radius:8px;padding:0;overflow:hidden;background:var(--panel);color:var(--ink)}dialog[open]{display:flex;flex-direction:column}.dialog-heading{flex-shrink:0;padding:18px 26px;border-bottom:1px solid var(--edge)}.dialog-scroll{min-height:0;overflow-y:auto;overscroll-behavior:contain;padding:20px 26px}dialog::backdrop{background:#13171a88}.detail-grid{display:grid;grid-template-columns:150px 1fr;gap:10px 20px;font-size:13px}.detail-grid dt{color:var(--muted)}.detail-grid dd{margin:0;overflow-wrap:anywhere}.links{display:flex;flex-wrap:wrap;gap:14px;margin:18px 0}.links a{color:var(--mark)}.evidence{font-size:13px;padding-left:22px}.evidence li{margin:9px 0}#error{color:var(--warn);padding:15px;border:1px solid var(--warn);margin-bottom:20px}@media(max-width:700px){main{padding:22px 14px}header h1{font-size:26px}.panel{padding:17px}.panel-heading{align-items:flex-start;flex-direction:column;gap:0}.toolbar{flex-wrap:wrap}.detail-grid{grid-template-columns:1fr;gap:3px}.detail-grid dd{margin-bottom:10px}.dialog-heading{padding:14px 19px}.dialog-scroll{padding:16px 19px}} #attempts select{display:block;max-width:26rem;margin:.5rem 0}#warnings{white-space:pre-line;margin:1rem 0} + +.progress-legend { + color: var(--muted); + display: flex; + flex-wrap: wrap; + gap: 1rem; + font-size: 13px; +} +.progress-legend span { color: var(--series-color); } +#progress-charts { + display: grid; + gap: 1rem; + grid-template-columns: repeat(auto-fit, minmax(min(380px, 100%), 1fr)); +} +#progress-charts figure { border-top: 1px solid var(--edge); margin: .75rem 0 0; padding-top: .75rem; } +#progress-charts figure:first-child { grid-column: 1 / -1; max-width: 780px; width: 100%; } +#progress-charts figcaption { font-weight: 600; } +.progress-chart { display: block; max-width: 100%; } +.progress-chart text { fill: var(--muted); font: 11px system-ui, sans-serif; } +.progress-chart line { fill: none; stroke: var(--series-color, var(--edge)); } +.progress-chart circle { fill: var(--series-color); } +.history-chain { --series-color: var(--mark); stroke-width: 2.75; } +.history-global { --series-color: #606577; stroke-width: 1.25; } +.history-branch { --series-color: #7c3d69; stroke-width: 1.5; } +.history-marker { --series-color: var(--warn); stroke-dasharray: 3 4; } +.progress-chart a:hover circle, .progress-chart a:focus-visible circle { stroke: var(--ink); stroke-width: 2; } diff --git a/infra/marina/apps/rl_progress/journeys/test_rl_progress_journey.py b/infra/marina/apps/rl_progress/journeys/test_rl_progress_journey.py index 347e8e68ce5..dbab1f13a70 100644 --- a/infra/marina/apps/rl_progress/journeys/test_rl_progress_journey.py +++ b/infra/marina/apps/rl_progress/journeys/test_rl_progress_journey.py @@ -14,7 +14,9 @@ def test_stored_attempts_keep_links_breakdowns_and_refresh(journey: Journey) -> None: api = f"{journey.origin}/a/{APPLET_ID}/api/runs" record = progress_record() | { + "format_version": 2, "run_id": "journey/run", + "native_run_id": "native/journey/run", "label": "Learning fixture", "model": "snowball", "evaldash_run_ids": ["first-evaluation", "second-evaluation"], @@ -46,6 +48,10 @@ def publish(value): } second.pop("issue") publish(second) + publish( + progress_record() + | {"run_id": record["native_run_id"], "attempt_id": "legacy-native", "label": "Earlier native attempt"} + ) route = urlencode({"run": record["run_id"], "attempt": record["attempt_id"]}) journey.page.goto(f"{journey.origin}/a/{APPLET_ID}/#{route}", wait_until="domcontentloaded") dialog = journey.page.get_by_role("dialog") @@ -58,6 +64,20 @@ def publish(value): expect(dialog.get_by_role("link", name=f"EvalDash {evaluation_id}")).to_have_attribute( "href", f"https://marina.oa.dev/evaldash/runs/{evaluation_id}" ) + filters = urlencode( + [ + ("rl_run", record["run_id"]), + ("rl_attempt", record["attempt_id"]), + ("view", "runs"), + ("rl_native_run", record["native_run_id"]), + ] + ) + expect(dialog.get_by_role("link", name="All EvalDash evaluations of this attempt")).to_have_attribute( + "href", f"https://marina.oa.dev/evaldash/runs?{filters}" + ) + native_route = urlencode({"run": record["native_run_id"], "attempt": record["attempt_id"]}) + journey.page.goto(f"{journey.origin}/a/{APPLET_ID}/#{native_route}", wait_until="domcontentloaded") + expect(dialog.get_by_text("Learning fixture", exact=True)).to_be_visible() expect(journey.page.get_by_role("cell", name="snowball", exact=True)).to_be_visible() for metric, value in (("family/small", "0.2500"), ("aai_category/coding", "0.3750"), ("difficulty/hard", "0.5000")): expect(dialog.get_by_text(f"eval_lite_100@25/{metric}/mean: {value}", exact=False)).to_be_visible() @@ -104,9 +124,9 @@ def publish(value): journey.page.reload(wait_until="domcontentloaded") expect(dialog).to_be_visible() expect(dialog).to_contain_text("family/small/mean: 0.6250") - expect(journey.page.locator("#attempts > tr")).to_have_count(1) + expect(journey.page.locator("#attempts > tr")).to_have_count(2) response = journey.page.request.get(api) - assert response.ok and len(response.json()["runs"]) == 2 + assert response.ok and len(response.json()["runs"]) == 3 journey.page.keyboard.press("Escape") publish(record | {"run_id": "journey/mochi", "label": "Mochi fixture", "model": "mochi"}) journey.click("Refresh") @@ -117,3 +137,104 @@ def publish(value): model_filter.select_option("snowball") expect(journey.page.get_by_role("button", name="Updated learning fixture")).to_be_visible() expect(journey.page.get_by_role("button", name="Mochi fixture")).to_have_count(0) + + +def test_progress_anchors_experiments_and_keeps_the_global_protocol_point(journey: Journey) -> None: + api = f"{journey.origin}/a/{APPLET_ID}/api/runs" + overall, family = "eval_lite/family_mean", "eval_lite/family/small/mean" + revisions = [f"2026.11.{day}" for day in (1, 2, 3, 4)] + commits = [letter * 10 for letter in "abcd"] + + def attempt(name, revision, day, raw): + return progress_record() | { + "format_version": 2, + "run_id": name, + "attempt_id": name, + "label": name, + "model": "snowball", + "preset": "learning-medium", + "preset_revision": revision, + "started_at": f"2026-11-0{day}T00:00:00Z", + "completed_at": f"2026-11-0{day}T01:00:00Z", + "gate_result": None, + "evaluations": [ + Comparison( + metric=metric.replace("eval_lite/", "eval_lite@25/"), role="slice", run=raw, n_run=1, n_control=0 + ).model_dump(mode="json") + for metric in (overall, family) + ], + } + + def link(run, base, delta, *, overlap=True): + return progress_record()["gate_result"] | { + "attempt_ids": [run], + "control_commit": commits[base], + "control_revision": revisions[base], + "invariants": [ + { + "name": "eval_lite/shared_tasks", + "value": 18 if overlap else 15, + "limit": 18, + "comparator": ">=", + "holds": overlap, + "replicate": None, + }, + ], + "comparisons": [ + Comparison(metric=metric, role="slice", delta=delta, n_run=1, n_control=1).model_dump(mode="json") + for metric in (overall, family) + ], + "verdict": "pass" if overlap else "invalid", + } + + for i, (revision, raw) in enumerate(zip(revisions, (0.5, 0.4, 0.7, 0.75), strict=True)): + name = f"control-{i}" + record = attempt(name, revision, i + 1, raw) | { + "artifact_uri": f"s3://example/control/learning-medium-{commits[i]}-r0/{revision}", + "evaluation_data_identity": f"panel@{revisions[min(i, 2)]}", + "evaluation_protocol_identity": "protocol-a" if i < 2 else "protocol-b", + "gate_result": link(name, i - 1, 0.1, overlap=i != 3) if i else None, + } + response = journey.page.request.post(api, data=record) + assert response.ok, response.text() + + retry = attempt("control-0-retry", revisions[0], 1, 0.7) | { + "artifact_uri": f"s3://example/control/learning-medium-{commits[0]}-r0-retry1/{revisions[0]}", + "branch": "control-proof", + "dirty": False, + "source_revision": commits[0], + "evaluation_data_identity": f"panel@{revisions[0]}", + "evaluation_protocol_identity": "protocol-a", + } + feature_control = attempt("feature-control", "dev", 2, 0.95) | { + "artifact_uri": "s3://example/control/learning-medium-fffaaaa000-r0/dev", + "branch": "feature", + } + unmatched = attempt("unknown-base", "dev", 6, 0.8) | {"branch": "older-branch"} + for record in (retry, feature_control, unmatched): + response = journey.page.request.post(api, data=record) + assert response.ok, response.text() + + branch = attempt("branch-at-first-preset", "dev", 4, 0.55) | { + "branch": "experiment", + "base_preset_revision": revisions[0], + "gate_result": link("branch-at-first-preset", 1, -0.15), + } + response = journey.page.request.post(api, data=branch) + assert response.ok, response.text() + + journey.page.goto(f"{journey.origin}/a/{APPLET_ID}/", wait_until="domcontentloaded") + journey.page.get_by_role("combobox", name="Preset", exact=True).select_option(label="snowball · learning-medium") + chart = journey.page.get_by_role("group", name=overall, exact=True) + expect(chart.locator("line.history-chain")).to_have_count(1) + expect(chart.locator("line[aria-label='Evaluation set changed']")).to_have_count(1) + expect(chart.locator("line[aria-label='Protocol changed']")).to_have_count(1) + expect(chart.locator("circle.history-global > title").last).to_contain_text("Experiment global 55.0%") + expect(chart.locator("circle.history-global > title").first).to_contain_text("Global 60.0%") + expect(chart.locator("circle.history-global > title").nth(2)).to_contain_text("Global 70.0%") + expect(chart.locator("circle.history-global > title").nth(3)).to_contain_text("Global 75.0%") + expect(chart.locator("line.history-global > title").first).to_contain_text("50.0%\u201370.0%") + expect(chart.get_by_role("link", name="unknown-base · 80.0%")).to_be_visible() + expect(journey.page.get_by_role("group", name=family, exact=True).locator("line.history-chain")).to_have_count(1) + chart.get_by_role("link", name="branch-at-first-preset · 25.0%").locator("circle").first.click() + expect(journey.page.get_by_role("dialog")).to_contain_text(revisions[0]) diff --git a/infra/marina/apps/rl_progress/server/app.py b/infra/marina/apps/rl_progress/server/app.py index a2bb66972a1..3116bd70447 100644 --- a/infra/marina/apps/rl_progress/server/app.py +++ b/infra/marina/apps/rl_progress/server/app.py @@ -7,17 +7,32 @@ from typing import Any from fastapi import FastAPI, HTTPException -from finestore.rl.rl_progress import AttemptSummary +from finestore.rl.rl_progress import AttemptSummary, ComparisonRole from pydantic import ValidationError from sqlalchemy import text from sqlalchemy.engine import Connection from sqlalchemy.exc import ProgrammingError -_RETAINED_FIELDS = ("issue", "gate", "gate_result", "model", "evaldash_run_ids", "grader_report") +_HISTORY_FIELDS = ( + "native_run_id", + "base_preset_revision", + "control_preset", + "evaluation_data_identity", + "evaluation_protocol_identity", +) +_RETAINED_FIELDS = ( + "issue", + "model", + "grader_report", + *(field for field in _HISTORY_FIELDS if field in AttemptSummary.model_fields), +) _RETAINED_VALUES = ", ".join( f"'{key}', COALESCE(NULLIF(EXCLUDED.record -> '{key}', 'null'::jsonb), rl_runs.record -> '{key}', 'null'::jsonb)" for key in _RETAINED_FIELDS ) +_KEEP_HISTORY_GATE = """EXCLUDED.record ->> 'format_version' = '1' + AND rl_runs.record ->> 'format_version' = '2' + AND jsonb_typeof(rl_runs.record -> 'gate_result') = 'object'""" _UPSERT = text( f"""INSERT INTO rl_runs (run_id, attempt_id, record) VALUES (:run_id, :attempt_id, CAST(:record AS jsonb)) @@ -25,7 +40,30 @@ SET record = CASE WHEN EXCLUDED.record ->> 'status' = 'running' AND rl_runs.record ->> 'status' IN ('succeeded', 'failed') THEN rl_runs.record - ELSE EXCLUDED.record || jsonb_build_object({_RETAINED_VALUES}) + ELSE EXCLUDED.record || jsonb_build_object( + {_RETAINED_VALUES}, + 'gate', CASE WHEN {_KEEP_HISTORY_GATE} THEN rl_runs.record -> 'gate' + ELSE COALESCE(NULLIF(EXCLUDED.record -> 'gate', 'null'::jsonb), rl_runs.record -> 'gate') + END, + 'gate_result', CASE WHEN {_KEEP_HISTORY_GATE} THEN rl_runs.record -> 'gate_result' + ELSE COALESCE(NULLIF(EXCLUDED.record -> 'gate_result', 'null'::jsonb), rl_runs.record -> 'gate_result') + END, + 'format_version', CASE WHEN '2' IN (EXCLUDED.record ->> 'format_version', rl_runs.record ->> 'format_version') + THEN 2 ELSE 1 END, + 'evaldash_run_ids', ( + SELECT jsonb_agg(link ORDER BY first_seen) + FROM ( + SELECT link, min(position) AS first_seen + FROM jsonb_array_elements( + CASE WHEN jsonb_typeof(rl_runs.record -> 'evaldash_run_ids') = 'array' + THEN rl_runs.record -> 'evaldash_run_ids' ELSE '[]'::jsonb END + || COALESCE(NULLIF(EXCLUDED.record -> 'evaldash_run_ids', 'null'::jsonb), '[]'::jsonb) + ) WITH ORDINALITY AS links(link, position) + WHERE jsonb_typeof(link) = 'string' AND link <> '""'::jsonb + GROUP BY link + ) saved_links + ) + ) END RETURNING record""" ) @@ -95,19 +133,23 @@ def publish(record: dict[str, Any]) -> dict: {"run_id": summary.run_id, "attempt_id": summary.attempt_id, "record": summary.model_dump_json()}, ).scalar_one() repaired = dict(stored) - for field in _RETAINED_FIELDS: - if incoming[field] is None: + retained_fields = (*_RETAINED_FIELDS, "gate", "gate_result") + legacy_gate = incoming["format_version"] == 1 and repaired.get("format_version") == 2 + for field in retained_fields: + if incoming.get(field) is None or (legacy_gate and field == "gate_result"): try: - json.dumps(repaired[field], allow_nan=False) + json.dumps(repaired.get(field), allow_nan=False) except ValueError: - repaired[field] = None + repaired[field] = incoming.get(field) try: summary = AttemptSummary.model_validate_json(json.dumps(repaired, allow_nan=False), strict=True) except ValidationError as error: invalid = {item["loc"][0] for item in error.errors() if item["loc"]} - for field in _RETAINED_FIELDS: - if field in invalid and incoming[field] is None: - repaired[field] = None + for field in retained_fields: + if field in invalid and ( + incoming.get(field) is None or (legacy_gate and field == "gate_result") + ): + repaired[field] = incoming.get(field) summary = AttemptSummary.model_validate_json(json.dumps(repaired, allow_nan=False), strict=True) normalized = summary.model_dump(mode="json") if normalized != stored: @@ -122,6 +164,19 @@ def publish(record: dict[str, Any]) -> dict: "record": summary.model_dump_json(), }, ) + if incoming["format_version"] == 1: + legacy = {key: value for key, value in normalized.items() if key not in _HISTORY_FIELDS} + legacy["format_version"] = 1 + if legacy_gate and (gate := legacy.get("gate_result")) is not None: + legacy["gate_result"] = { + key: value + for key, value in gate.items() + if key not in {"control_commit", "control_revision"} + } | { + "comparisons": [row for row in gate["comparisons"] if row["role"] != ComparisonRole.SLICE], + "invariants": [fact for fact in gate["invariants"] if fact["replicate"] is not None], + } + return legacy return normalized except ProgrammingError as error: details = error.orig.args[0] diff --git a/infra/marina/src/marina/client.py b/infra/marina/src/marina/client.py index 822b412ddf3..083b721c2f4 100644 --- a/infra/marina/src/marina/client.py +++ b/infra/marina/src/marina/client.py @@ -68,6 +68,7 @@ def marina_request( params: dict[str, object] | None = None, session: requests.Session | None = None, token_provider: TokenProvider | None = None, + timeout: float = DEFAULT_TIMEOUT, ) -> object | None: """Call Marina, optionally reusing a caller-owned transport and token provider.""" service_url = service_url.rstrip("/") @@ -85,7 +86,7 @@ def marina_request( json=json_body, data=payload, headers=headers, - timeout=DEFAULT_TIMEOUT, + timeout=timeout, ) if response.status_code >= 400: detail = ( diff --git a/infra/marina/tests/rl_progress_fixtures.py b/infra/marina/tests/rl_progress_fixtures.py index edeb8a0cd1e..69c5b152a2f 100644 --- a/infra/marina/tests/rl_progress_fixtures.py +++ b/infra/marina/tests/rl_progress_fixtures.py @@ -35,6 +35,8 @@ def rl_progress_client(tmp_path, monkeypatch): ) def request(origin, method, path, *, json_body=None, **kwargs): + if method == "GET" and path == "/evaldash/api/runs": + return [] response = client.request(method, path, json=json_body) response.raise_for_status() return response.json() diff --git a/infra/marina/tests/test_rl_progress.py b/infra/marina/tests/test_rl_progress.py index 152b83d5eaf..c41ea5a5885 100644 --- a/infra/marina/tests/test_rl_progress.py +++ b/infra/marina/tests/test_rl_progress.py @@ -72,6 +72,24 @@ def publish(record): else: missing_issue[field] = None assert publish(missing_issue) == changed + history = changed | { + "format_version": 2, + "native_run_id": "native/test/control", + "base_preset_revision": "2026.11.01", + "gate_result": ( + changed["gate_result"] + | { + "control_commit": "abcdef0123", + "control_revision": "2026.11.01", + "comparisons": [ + *changed["gate_result"]["comparisons"], + changed["gate_result"]["comparisons"][0] | {"metric": "eval/family/small/mean", "role": "slice"}, + ], + } + ), + } + assert publish(history) == history + assert publish(changed) == changed unknown = record | { "run_id": "test/unknown", "attempt_id": "unknown", @@ -144,7 +162,7 @@ def publish(record): ) payload = client.get(f"/a/{APPLET_ID}/api/runs").json() rows = {row["attempt_id"]: row for row in payload["runs"]} - assert rows["native-first"] == _projection(changed) + assert rows["native-first"] == _projection(history) assert rows["native-second"] == _projection(failed) assert rows["unknown"] == _projection(legacy | {"issue": None}) assert len(rows) == 3 diff --git a/lib/evalrecords/src/evalrecords/records.py b/lib/evalrecords/src/evalrecords/records.py index c3c2c4d6525..382346c5740 100644 --- a/lib/evalrecords/src/evalrecords/records.py +++ b/lib/evalrecords/src/evalrecords/records.py @@ -20,7 +20,7 @@ from enum import StrEnum from typing import Annotated, Any, Literal, TypedDict -from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator +from pydantic import AliasChoices, BaseModel, ConfigDict, Field, NonNegativeInt, model_validator from rigging.filesystem.factory import open_url, url_to_fs from rigging.filesystem.storage_path import prefix_join @@ -650,6 +650,16 @@ class RepeatAggregate(BaseModel): source_coverage: TaskCoverage | None = None +class RLAttemptRef(BaseModel): + """The RL attempt that produced the evaluated model.""" + + model_config = ConfigDict(frozen=True) + + run_id: str + attempt_id: str + step: NonNegativeInt | None = Field(default=None, exclude_if=lambda value: value is None) + + class EvalRunRecord(BaseModel): """The full account of one eval run, serialized to ``record.json``. @@ -679,6 +689,7 @@ class EvalRunRecord(BaseModel): """A free-text note on why the launch was run (``--description``), e.g. ``Trying out a new sweep after fixing RL``. Shared by every record in a group and surfaced on the launch in the dashboard.""" model: ModelRef + rl_attempt: RLAttemptRef | None = Field(default=None, exclude_if=lambda value: value is None) judge: HostedJudgeRef | None = None evaluation: EvalRef = Field(alias="eval") hardware: HardwareRef diff --git a/lib/finestore/src/finestore/rl/rl_progress.py b/lib/finestore/src/finestore/rl/rl_progress.py index 3c1c5b35eb9..ab093d8c11f 100644 --- a/lib/finestore/src/finestore/rl/rl_progress.py +++ b/lib/finestore/src/finestore/rl/rl_progress.py @@ -49,7 +49,7 @@ class Invariant(BaseModel): limit: bool | int | float comparator: Literal["<=", ">=", "=="] | None = None holds: bool - replicate: int = 0 + replicate: int | None = 0 class Comparison(BaseModel): @@ -86,6 +86,8 @@ class GateResult(BaseModel): reason: str | None attempt_ids: list[Identity] replicates: Annotated[StrictInt, Field(gt=0)] + control_commit: Identity | None = Field(default=None, exclude_if=lambda value: value is None) + control_revision: Identity | None = Field(default=None, exclude_if=lambda value: value is None) class GradingLatency(TypedDict): @@ -152,14 +154,19 @@ def wandb_tags(self) -> list[str]: class AttemptSummary(BaseModel): model_config = ConfigDict(strict=True, extra="forbid") - format_version: Literal[1] = 1 + format_version: Literal[1, 2] = 1 run_id: Identity + native_run_id: Identity | None = Field(default=None, exclude_if=lambda value: value is None) attempt_id: Identity label: Identity series: str | None = None model: Identity | None = None preset: Identity | None = None preset_revision: Identity | None = None + base_preset_revision: Identity | None = Field(default=None, exclude_if=lambda value: value is None) + control_preset: Identity | None = Field(default=None, exclude_if=lambda value: value is None) + evaluation_data_identity: Identity | None = Field(default=None, exclude_if=lambda value: value is None) + evaluation_protocol_identity: Identity | None = Field(default=None, exclude_if=lambda value: value is None) user: Identity | None = None branch: str | None = None dirty: bool | None = None diff --git a/lib/finestore/src/finestore/rl/run_records.py b/lib/finestore/src/finestore/rl/run_records.py index ebbbb6865af..315ba89429a 100644 --- a/lib/finestore/src/finestore/rl/run_records.py +++ b/lib/finestore/src/finestore/rl/run_records.py @@ -96,6 +96,7 @@ class AttemptRecord(BaseModel): result: LaunchResult | None = None issue: int | None = None index: RunIndexIdentity | None = None + base_preset_revision: str | None = None interruption: Literal["coordinator_terminated"] | None = None elapsed_excluding_eval_seconds: Annotated[FiniteFloat, Field(ge=0)] | None = None diff --git a/lib/marin/src/marin/evaluation/runner.py b/lib/marin/src/marin/evaluation/runner.py index 35a7b92b43a..075c0bc4e43 100644 --- a/lib/marin/src/marin/evaluation/runner.py +++ b/lib/marin/src/marin/evaluation/runner.py @@ -28,6 +28,7 @@ ModelConfigRef, ModelRef, Provenance, + RLAttemptRef, RunStatus, ServingParams, TaskCoverage, @@ -263,6 +264,7 @@ class EvaluationBatch: egress_allow: tuple[str, ...] = () """Egress rules the orchestrator job and its children need beyond the cluster allowlist.""" source_model_config: ModelConfigRef | None = None + rl_attempt: RLAttemptRef | None = None @dataclass(frozen=True) @@ -322,6 +324,7 @@ def _record( user=batch.user, version=batch.version, description=batch.description, + rl_attempt=batch.rl_attempt, model=ModelRef( name=batch.model.name, location=batch.model.location, diff --git a/lib/marin/src/marin/rl/cli.py b/lib/marin/src/marin/rl/cli.py index 795f4f84048..0fb6d08bc86 100644 --- a/lib/marin/src/marin/rl/cli.py +++ b/lib/marin/src/marin/rl/cli.py @@ -36,8 +36,10 @@ _COORDINATOR_DISK = "64GB" _COORDINATOR_GRAPH_ENV = "MARIN_RL_COORDINATOR_GRAPH" RUN_INDEX_ENV = "MARIN_RL_RUN_INDEX" +BASE_PRESET_REVISION_ENV = "MARIN_RL_BASE_PRESET_REVISION" _COORDINATOR_ENV_VARS = ( RUN_INDEX_ENV, + BASE_PRESET_REVISION_ENV, "DAYTONA_API_KEY", "DAYTONA_RL_API_KEY", "DAYTONA_EVAL_API_KEY", diff --git a/tests/evaluation/test_evaluation.py b/tests/evaluation/test_evaluation.py index 58df63948e7..c9c0328e1ce 100644 --- a/tests/evaluation/test_evaluation.py +++ b/tests/evaluation/test_evaluation.py @@ -30,6 +30,8 @@ read_record, record_path, ) +from finestore.rl.rl_progress import RunIndexIdentity +from finestore.rl.run_records import AttemptRecord, write_attempt from iris.cluster.constraints import CLUSTER_CONSTRAINT_KEY, Constraint, ConstraintOp from iris.resources.state import JobState, TaskState from iris.rpc import job_pb2 @@ -53,6 +55,8 @@ run_with_inference_recovery, ) from marin.evaluation.serving_config import inference_config_for_model +from marin.execution.artifact import RECORD_FILENAME, ArtifactRecord, result_type_name +from marin.execution.lazy import ArtifactStep, StepContext from marin.execution.step_status import StatusFile from marin.inference.config import ( EffectiveServing, @@ -67,6 +71,7 @@ RemoteInferenceStartupError, ) from marin.inference.types import InferenceBackendState, OpenAIEndpoint, RunningModel +from marin.rl.skyrl import SkyRLPolicyModel, SkyRLRun from prometheus_client.parser import text_string_to_metric_families from rigging.filesystem.cluster_config import marin_temp_bucket from rigging.filesystem.step_status import STATUS_FAILED, STATUS_SUCCESS @@ -90,6 +95,7 @@ EvalStepConfig, run_eval_pipeline_step, ) +from experiments.post_training.skyrl_evaluation import evaluate_model # Stand-in agent limits the fake driver reports back. They match neither Harbor's defaults nor any # model in these tests, so an assertion on them can only be satisfied by the preflight result. @@ -875,7 +881,7 @@ def launch(batch: EvaluationBatch, _client: object): @pytest.mark.parametrize( ("version", "retry_limit", "reuse_completed"), - [("test", 1, True), ("dev", 1, False), ("test", 2, False)], + [("2026.07.24", 1, True), ("dev", 1, False), ("2026.07.24", 2, False)], ) def test_pipeline_retry_preserves_completed_evaluations(tmp_path, monkeypatch, version, retry_limit, reuse_completed): completed: list[str] = [] @@ -911,16 +917,57 @@ def launch(batch, _client): monkeypatch.setattr("experiments.evaluation.pipeline.launch_group", launch) monkeypatch.setattr("marin.evaluation.runner.record_rollout_run", lambda _record: None) _patch_inference_runtime(monkeypatch, lambda _config: nullcontext(_remote_session())) - config = EvalStepConfig( - model=models()["qwen3-8b"], - evals=resolve_evaluations("smoke"), - limit=1, - max_concurrent=1, - artifact_path=str(tmp_path / "pipeline"), + policy_root = tmp_path / "trained" + policy_root.mkdir() + result = SkyRLRun( + path=str(policy_root), + hf_model_uri=str(policy_root / "hf"), + global_step=0, + tokenizer_uri="fixture/tokenizer", + tokenizer_revision=None, + checkpoint_root=str(policy_root / "checkpoints"), + draft_checkpoint_root=None, + terminal_manifest_uri=str(policy_root / "terminal.json"), + iris_job_id="/fixture/policy", + run_id="native-policy", + attempt_id="trained-attempt", + ) + artifact = ArtifactRecord(result_type=result_type_name(SkyRLRun), result=result.result_payload()) + (policy_root / RECORD_FILENAME).write_text(artifact.model_dump_json()) + index = RunIndexIdentity( + run_id="logical-policy", + model="snowball", + preset="train-long", + preset_revision="2026.07.24", + user="tester", + branch="fixture", + source_revision="fixture", + dirty=False, + ) + write_attempt( + str(policy_root / "exports"), AttemptRecord(run_id="native-policy", attempt_id="trained-attempt", index=index) + ) + serving = replace( + models()["qwen3-8b"], location="", revision=None, identity=None, tokenizer=None, tokenizer_revision=None + ) + source = ArtifactStep.adopt("fixture/policy", "2026.07.24", str(policy_root), kind=SkyRLRun) + step = evaluate_model( + SkyRLPolicyModel(source), + serving, + resolve_evaluations("smoke"), + version=version, accelerator=None, submission_cluster="marin", federated_cluster=None, - version=version, + ) + config = replace( + step.build_config( + StepContext.for_run( + str(tmp_path / "pipeline"), str(tmp_path), deps=step.deps, runtime_args=step.runtime_args + ) + ), + limit=1, + max_concurrent=1, ) with pytest.raises(RuntimeError, match="1 step"): @@ -930,6 +977,9 @@ def launch(batch, _client): assert len(completed) == (1 if reuse_completed else 2) assert (attempts[0] == attempts[1]) == reuse_completed assert len(result.run_ids) == 2 + for run_id in result.run_ids: + saved = read_record(record_path(result.records_prefix, run_id)) + assert saved.rl_attempt.model_dump() == {"run_id": "logical-policy", "attempt_id": "trained-attempt", "step": 0} def test_launch_group_resolves_declared_secrets_outside_the_pickled_batch(tmp_path, monkeypatch): diff --git a/tests/rl/test_skyrl.py b/tests/rl/test_skyrl.py index d768fea8723..7d9edde6c03 100644 --- a/tests/rl/test_skyrl.py +++ b/tests/rl/test_skyrl.py @@ -30,7 +30,6 @@ ) from finestore.store import DataStore from iris.rpc import controller_pb2, job_pb2 -from marin.evaluation.model_config import ModelConfig from marin.execution.artifact import ( RECORD_FILENAME, Artifact, @@ -78,8 +77,6 @@ from rigging.filesystem.step_status import STATUS_SUCCESS from skyrlrecipe.locality import RoleTopologyMode -from experiments.post_training.skyrl_evaluation import SKYRL_POLICY_LOCATION, resolve_skyrl_model - def _model_step() -> ArtifactStep[LevanterCheckpoint]: return ArtifactStep.adopt( @@ -1435,27 +1432,11 @@ def test_finished_policy_resolves_terminal_export_as_model_input(tmp_path, token tokenizer, "tokenizer-commit" if tokenizer else None, ) - evaluation = ModelConfig(name="finished", location=SKYRL_POLICY_LOCATION, tokenizer="declared/tokenizer") - evaluated = resolve_skyrl_model(context, source, evaluation) - assert (evaluated.location, evaluated.tokenizer, evaluated.tokenizer_revision) == ( - str(root / "policy"), - tokenizer or str(root / "policy"), - "tokenizer-commit" if tokenizer else None, - ) + identity = f"tests/finished@2026.10.26:{source.fingerprint()}" + assert resolved.identity == identity fingerprint = StepContext.for_fingerprint({}, model.deps()) policy_identity = model.resolve(fingerprint) - evaluation_identity = resolve_skyrl_model(fingerprint, source, evaluation) - assert (evaluation_identity.location, evaluation_identity.tokenizer, evaluation_identity.tokenizer_revision) == ( - policy_identity.uri, - policy_identity.tokenizer_uri or policy_identity.uri, - policy_identity.tokenizer_revision, - ) - assert evaluated.identity == evaluation_identity.identity == f"tests/finished@2026.10.26:{source.fingerprint()}" - assert evaluation_identity.location == f"tests/finished@2026.10.26:{source.fingerprint()}/policy" - other = ArtifactStep.adopt("tests/other-policy", "2026.10.27", str(root), kind=SkyRLRun) - other_model = resolve_skyrl_model(StepContext.for_fingerprint({}, (other,)), other, evaluation) - assert other_model.identity == f"tests/other-policy@2026.10.27:{other.fingerprint()}" - assert other_model.location == f"tests/other-policy@2026.10.27:{other.fingerprint()}/policy" + assert (policy_identity.uri, policy_identity.identity) == (f"{identity}/policy", identity) def test_reject_forced_socket_transport_blocks_multi_node_overrides() -> None: diff --git a/vendor/skyrl/cloud/iris/tests/test_task_spec_dataset.py b/vendor/skyrl/cloud/iris/tests/test_task_spec_dataset.py index 8218024065c..885b62064e2 100644 --- a/vendor/skyrl/cloud/iris/tests/test_task_spec_dataset.py +++ b/vendor/skyrl/cloud/iris/tests/test_task_spec_dataset.py @@ -14,10 +14,13 @@ from shellbox.backends.shellsim.machine import ShellSimMachineFactory from shellbox.machine import Backend, ExecutionRequirements, Machine, MachineSpec from skyrl_gym.rollout_specs import is_shell_harness +from skyrl_gym.verification import VerificationResult from skyrl_train.config.utils import get_default_config -from skyrl_train.dataset.tasks import SourceTaskDataset +from skyrl_train.dataset.tasks import SourceTaskDataset, TaskDataset, write_tasks from skyrl_train.dataset.harbor_import import HARBOR_TRIAL_SESSION +from skyrl_train.grader_reporting import GraderStats, write_grader_report from skyrl_train.task_inputs import TaskInput, task_messages +from skyrl_train.trajectory_runners.types import TrajectoryBatch from taskcompendium.convert.structure_closure import structure_closure_task from taskcompendium.models import ( CommandSemantics, @@ -45,17 +48,20 @@ async def create(self, spec: MachineSpec) -> Machine: raise AssertionError(f"Admission must not acquire a machine: {spec}") -def _load(tmp_path: Path, tasks, **task_spec_overrides) -> list[TaskInput]: - path = tmp_path / "tasks.parquet" - pq.write_table(pa.Table.from_pylist([{"task_spec": task.model_dump_json()} for task in tasks]), path) - tokenizer = PreTrainedTokenizerFast( +def _tokenizer(): + return PreTrainedTokenizerFast( tokenizer_object=Tokenizer(models.WordLevel({"[UNK]": 0}, unk_token="[UNK]")), unk_token="[UNK]", chat_template="{% for message in messages %}{{ message.content }} {% endfor %}", ) + + +def _load(tmp_path: Path, tasks, **task_spec_overrides) -> list[TaskInput]: + path = tmp_path / "tasks.parquet" + pq.write_table(pa.Table.from_pylist([{"task_spec": task.model_dump_json()} for task in tasks]), path) configs = OmegaConf.to_container(get_default_config().environment.task_sessions, resolve=True) configs["task_spec"].update(task_spec_overrides) - dataset = SourceTaskDataset([str(path)], tokenizer, 128, num_workers=1, environment_configs=configs) + dataset = SourceTaskDataset([str(path)], _tokenizer(), 128, num_workers=1, environment_configs=configs) return [row["input"] for row in dataset.collate_fn(list(dataset))] @@ -96,6 +102,31 @@ def test_dataset_harness_binding_keeps_harbor_and_assistant_prefix_execution(tmp assert is_shell_harness(loaded[1].harness) assert loaded[2].harness == ASSISTANT_PREFIX_HARNESS + packed = [] + for name in ("one", "two"): + task = loaded[0].task.model_copy( + update={ + "id": name, + "source": ( + loaded[0].task.source.model_copy( + update={ + "dataset": f"tasktrove://pack%2Fdataset/shared%2Fsource/category/{name}", + } + ) + ), + } + ) + packed.append(loaded[0].model_copy(update={"task": task})) + path = tmp_path / "packed-rollouts.parquet" + write_tasks(path, iter(packed)) + dataset = TaskDataset([str(path)], _tokenizer(), 128, num_workers=1) + metadata = [row["input"].metadata for row in dataset.collate_fn(list(dataset))] + stats = GraderStats() + stats.add(TrajectoryBatch(rewards=[1.0, 1.0], verification_results=[VerificationResult.verified(1.0)] * 2), metadata) + write_grader_report(str(tmp_path), "0", {"evaluation": stats.summary()["subsets"]}) + [subset] = json.loads((tmp_path / "grader_report.json").read_text())["evaluation"]["0"] + assert (subset["subset_id"], subset["attempted"]) == ("pack/dataset/shared/source", 2) + def test_canonical_rows_lower_at_load_and_admit_image_and_package_graders(tmp_path: Path): image = text_task("image-task", source="nvidia/Nemotron-RL-Ultra-Training-Blends").model_copy( diff --git a/vendor/skyrl/skyrl-train/skyrl_train/dataset/tasks.py b/vendor/skyrl/skyrl-train/skyrl_train/dataset/tasks.py index 05380c0a439..54c6197e5a4 100644 --- a/vendor/skyrl/skyrl-train/skyrl_train/dataset/tasks.py +++ b/vendor/skyrl/skyrl-train/skyrl_train/dataset/tasks.py @@ -8,6 +8,7 @@ from pathlib import Path from tempfile import TemporaryDirectory from typing import Any +from urllib.parse import unquote, urlsplit import pyarrow as pa import pyarrow.parquet as pq @@ -47,10 +48,25 @@ PARQUET_BATCH_SIZE = 1024 +def _source_stratum(dataset: str, labels: Mapping[str, str]) -> str: + if dataset.startswith("tasktrove://"): + uri = urlsplit(dataset) + source = uri.path.lstrip("/").partition("/")[0] + if uri.netloc and source: + return f"{unquote(uri.netloc)}/{unquote(source)}" + return labels.get("subset_id") or dataset + + def task_evaluation_identity(task: dict, selection: SelectionManifest | None) -> TaskEvaluationIdentity: digest = canonical_sha256(task) if selection is None: - return TaskEvaluationIdentity(task_digest=digest, strata=TaskStrata(agentic="agentic" in task.get("tags", ()))) + return TaskEvaluationIdentity( + task_digest=digest, + strata=TaskStrata( + source=_source_stratum(task["source"]["dataset"], task.get("labels", {})), + agentic="agentic" in task.get("tags", ()), + ), + ) identity = selection.identity(task["id"]) if identity.task_digest != digest: raise ValueError(f"evaluation task content differs from selection manifest: {task['id']}") @@ -109,6 +125,12 @@ def collate_fn(self, rows) -> list[dict]: if ultra is not None and "blend" in ultra and "agent" in ultra else () ) + stored_identity = extras.get(TASK_EVALUATION_IDENTITY) + identity = TaskEvaluationIdentity.model_validate_json(stored_identity) if stored_identity else None + subset = ( + identity.strata.source if identity is not None + else _source_stratum(lowered.task.source.dataset, lowered.task.labels) + ) inputs.append( { "uid": uid, @@ -121,12 +143,8 @@ def collate_fn(self, rows) -> list[dict]: teacher_route=extras.get("teacher_route"), metric_tags=metric_tags, task_id=lowered.task.id, - subset_id=lowered.task.labels.get("subset_id") or lowered.task.source.dataset, - evaluation_identity=( - TaskEvaluationIdentity.model_validate_json(extras[TASK_EVALUATION_IDENTITY]) - if extras.get(TASK_EVALUATION_IDENTITY) is not None - else None - ), + subset_id=subset, + evaluation_identity=identity, ), group_grader=task_group_grader(lowered), ), diff --git a/vendor/skyrl/skyrl-train/tests/cpu/test_evaluation_score_order.py b/vendor/skyrl/skyrl-train/tests/cpu/test_evaluation_score_order.py index 6b8662b5340..fd58dfbd510 100644 --- a/vendor/skyrl/skyrl-train/tests/cpu/test_evaluation_score_order.py +++ b/vendor/skyrl/skyrl-train/tests/cpu/test_evaluation_score_order.py @@ -65,9 +65,18 @@ def test_final_profiles_build_primary_and_additional_datasets_without_periodic_e else: write_tasks(path, [lowered_task(task)]) write_selection_panel( - path.parent, [task], path.parent.name, "1", - lambda _: {"family": path.parent.name, "source": "declared-source", - "aai_category": "general", "topic": "algebra", "difficulty": "hard", "agentic": True}, + path.parent, + [task], + path.parent.name, + "1", + lambda _: { + "family": path.parent.name, + "source": "declared-source", + "aai_category": "general", + "topic": "algebra", + "difficulty": "hard", + "agentic": True, + }, ) config.data.val_data = [str(primary)] config.data.task_cache_dir = str(tmp_path / "task-cache") @@ -120,6 +129,7 @@ def test_final_profiles_build_primary_and_additional_datasets_without_periodic_e ("named", "named", "declared-source", "general", "algebra", "hard"), ] assert all(item.data_source != "declared-source" for item in identities) + assert all(item.subset_id == "declared-source" for item in identities) assert all(item.evaluation_identity.strata.agentic for item in identities) assert all(item.evaluation_identity.task_digest == digest for item in identities) assert OmegaConf.to_container(config, resolve=True) == original_config @@ -159,9 +169,7 @@ def test_final_profiles_build_primary_and_additional_datasets_without_periodic_e pq.write_table(pa.table({"task_spec": [changed.model_dump_json()]}), primary) with pytest.raises(ValueError, match="task content differs from selection manifest"): experiment.get_eval_dataset([str(primary)]) - mismatched = original.set_column( - original.schema.get_field_index("family"), "family", pa.array(["wrong-family"]) - ) + mismatched = original.set_column(original.schema.get_field_index("family"), "family", pa.array(["wrong-family"])) membership_path = primary.parent / "validation.parquet" membership = pq.read_table(membership_path) changed_task = json.loads(membership["task_spec"][0].as_py()) @@ -209,9 +217,7 @@ async def test_evaluation_collector_keeps_task_id_and_scoring_metadata(tmp_path) task = text_task("validation-task") row = task_input(lowered_task(task), metric_class="script", data_source="validation") identity = TaskEvaluationIdentity(strata=TaskStrata(family="math", source="fixture")) - row = replace( - row, metadata=replace(row.metadata, evaluation_identity=identity, task_id=task.id, subset_id="math") - ) + row = replace(row, metadata=replace(row.metadata, evaluation_identity=identity, task_id=task.id, subset_id="math")) loader = StatefulDataLoader([{"input": row}], collate_fn=list) tokenizer = SimpleNamespace(eos_token_id=2, decode=lambda _tokens: "answer") projection = WholeTaskProjection(config.generator, tokenizer) @@ -247,8 +253,7 @@ async def run(request): assert set(report["evaluation"]) == {"0", "named/0"} assert report["evaluation"]["named/0"][0]["subset_id"] == "math" assert { - key: [(row["task_id"], row["success_rate"]) for row in rows] - for key, rows in report["evaluation_tasks"].items() + key: [(row["task_id"], row["success_rate"]) for row in rows] for key, rows in report["evaluation_tasks"].items() } == {"0": [(task.id, 1.0)], "named/0": [(task.id, 1.0)]}