Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
[rl] Show comparable preset history and EvalDash links
  • Loading branch information
atqamar committed Nov 24, 2026
commit f1c17ddf280f36767d29b581256b86283e280ce2
3 changes: 3 additions & 0 deletions experiments/evaluation/launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
ModelConfigRef,
ModelRef,
PromptFormat,
RLAttemptRef,
RunStatus,
TaskEvidence,
list_records,
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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,
Expand Down
6 changes: 5 additions & 1 deletion experiments/evaluation/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -68,6 +68,7 @@ class EvalStepConfig:
federated_cluster: str | None
version: str
instances: int = 1
rl_attempt: RLAttemptRef | None = None


@dataclass(frozen=True)
Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand Down Expand Up @@ -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(
Expand Down
64 changes: 63 additions & 1 deletion experiments/post_training/rl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -431,6 +433,60 @@ 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 experiments.post_training.rl_presets import ModelPresets

module, model, preset = sys.argv[1:]
revisions = {value.by_name[preset].revision for value in vars(import_module(module)).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)
snapshot = subprocess.run(
[
"git",
"archive",
base,
"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, RuntimeError, subprocess.SubprocessError, tarfile.TarError) as error:
logger.debug("Main preset revision unavailable for %s (%s)", preset, type(error).__name__)
return None


class _PublicationWatch(BaseModel):
job: str
preset: str
Expand Down Expand Up @@ -560,7 +616,13 @@ 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"]
index = index.model_copy(
update={
"submitted_at": submitted_at,
"base_preset_revision": _base_preset_revision(module, index.model, index.preset, index.source_revision),
}
)
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
Expand Down
62 changes: 60 additions & 2 deletions experiments/post_training/rl_publication.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -51,6 +52,7 @@
from experiments.post_training.rl_measurements import (
InvalidComparison,
RunInputs,
evaluation_protocol,
evaluation_status,
read_run_inputs,
training_invariants,
Expand Down Expand Up @@ -188,12 +190,32 @@ def _gate_result(report: gate.GateReport | None) -> GateResult | None:
effect=report.effect,
reason=report.reason,
invariants=list(report.invariants),
comparisons=list(report.rows(ComparisonRole.OBJECTIVE, ComparisonRole.GUARD, ComparisonRole.REQUIREMENT)),
comparisons=[
row
for row in report.comparisons
if row.role in (ComparisonRole.OBJECTIVE, ComparisonRole.GUARD, ComparisonRole.REQUIREMENT)
or (row.role == ComparisonRole.SLICE and "/family/" in row.metric and row.metric.endswith("/mean"))
],
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]:
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,
Expand Down Expand Up @@ -238,14 +260,19 @@ def build_record(
if not provenance and index is None and terminal:
evidence.append("Recorded source provenance is unavailable.")
grader_report = _read_grader_report(launch, attempt_id, evidence) if terminal else None
evaluation_data, evaluation_protocol_id = _evaluation_identities(launch, evidence)
return AttemptSummary(
run_id=attempt.index_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=index.base_preset_revision if index is not None else None,
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,
Expand Down Expand Up @@ -394,6 +421,35 @@ def _link_issue(receipt: AttemptRecord, issue: int) -> int | None:
return assigned


def _evaldash_links(summary: AttemptSummary, native_id: str, service_url: str | None) -> list[str]:
try:
from marina import client # noqa: PLC0415

links = list(summary.evaldash_run_ids or ())
for run_id in dict.fromkeys((summary.run_id, native_id)):
rows = client.marina_request(
service_url or client.DEFAULT_MARINA_URL,
"GET",
"/evaldash/api/runs",
params={"rl_run": run_id, "rl_attempt": summary.attempt_id, "limit": 1000},
timeout=4,
)
if not isinstance(rows, list):
raise ValueError("EvalDash did not return a run list")
links.extend(
row["run_id"]
for row in rows
if isinstance(row, dict)
and row.get("rl_run_id") == run_id
and row.get("rl_attempt_id") == summary.attempt_id
and isinstance(row.get("run_id"), str)
)
return list(dict.fromkeys(links))
except (ImportError, OSError, ValueError, RuntimeError) as error:
logger.debug("EvalDash lookup unavailable for %s (%s)", summary.attempt_id, type(error).__name__)
return summary.evaldash_run_ids or []


def publish_runs(
outputs: Sequence[str],
preset: presets.Preset,
Expand Down Expand Up @@ -466,6 +522,8 @@ def publish_runs(
)
if issue is not None:
record = record.model_copy(update={"issue": _link_issue(receipt, issue)})
if record.status == "succeeded" and (links := _evaldash_links(record, receipt.run_id, service_url)):
record = record.model_copy(update={"evaldash_run_ids": links})
url = publish_result(record, service_url)
result.served_records.append(destination)
if selected_id == current_id:
Expand Down
17 changes: 15 additions & 2 deletions experiments/post_training/rl_tests/test_rl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -844,6 +845,15 @@ 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

def historical_source(args, cwd, **kwargs):
if args[0] == "merge-base":
assert args[-1] == "origin/main"
return "HEAD"
return git_output(args, cwd, **kwargs)

monkeypatch.setattr(snowball, "git_output", historical_source)
publications = []
unavailable = outcome == "interrupted"

Expand Down Expand Up @@ -917,7 +927,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
Expand Down Expand Up @@ -946,6 +958,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
Expand Down
22 changes: 19 additions & 3 deletions experiments/post_training/rl_tests/test_rl_publication.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,13 @@ def saved_gate(requirements=()):
interrupted = {"once": True}

def unavailable_readback(origin, method, path, *, json_body=None, **kwargs):
if method == "GET" and path == "/evaldash/api/runs":
run_id = kwargs["params"]["rl_run"]
return [
{"run_id": "linked-export", "rl_run_id": run_id, "rl_attempt_id": "native-0"},
{"run_id": "cached-export", "rl_run_id": run_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
Expand All @@ -334,6 +341,8 @@ def unavailable_readback(origin, method, path, *, json_body=None, **kwargs):
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"] == ["linked-export"]
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"))
Expand All @@ -348,6 +357,8 @@ def unavailable_readback(origin, method, path, *, json_body=None, **kwargs):
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 rows["native-0"]["evaldash_run_ids"] == ["linked-export"]
assert rows["native-0"]["evaluation_data_identity"].endswith("/full_validation.parquet")
assert repeated.urls[str(sources[0])].endswith(f"#run=tests%2Fpublication-0-{preset.revision}&attempt=native-0")

def wrong_returned_key(origin, method, path, *, json_body=None, **kwargs):
Expand All @@ -368,16 +379,21 @@ def wrong_returned_key(origin, method, path, *, json_body=None, **kwargs):
row.model_dump(mode="json")
for row in report.comparisons
if row.role in ("objective", "guard", "requirement")
or (row.role == "slice" and "/family/" in row.metric and row.metric.endswith("/mean"))
],
"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"),
("eval_lite/family/small/mean", "slice"),
("eval_lite/family/large/mean", "slice"),
}

run_ids = ("eval-initial-policy", "eval-terminal-policy")
Expand Down Expand Up @@ -414,7 +430,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"] == (["linked-export", *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"],
Expand Down Expand Up @@ -476,7 +492,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"] == ["linked-export", *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"):
Expand All @@ -489,7 +505,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"] == ["linked-export", *run_ids]
saved_evaluations = {}
for root in sources:
current_id, _ = read_stored_skyrl_attempts(str(root))
Expand Down
Loading