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
Prev Previous commit
Next Next commit
[rl] Preserve history across mixed-version readers
  • Loading branch information
atqamar committed Nov 24, 2026
commit 469b600adc0e4ae2893a46d10d9bf8a472e8186a
25 changes: 14 additions & 11 deletions experiments/post_training/rl.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,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,
Expand Down Expand Up @@ -120,13 +120,15 @@ 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(
run_id=config.run_id,
attempt_id=config.attempt_id,
issue=issue,
index=index,
base_preset_revision=base_revision or None,
),
)
return run_skyrl(config, forward_env=forward_env)
Expand Down Expand Up @@ -448,6 +450,10 @@ def _base_preset_revision(module: str, model: str, preset: str, source_revision:
"""
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",
Expand Down Expand Up @@ -482,8 +488,8 @@ def _base_preset_revision(module: str, model: str, preset: str, source_revision:
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__)
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


Expand Down Expand Up @@ -617,18 +623,15 @@ def _submit_from_launcher(
raise click.UsageError("submit from python -m MODULE, or pass entry_module to rl.main")
submitted_at = datetime.now(UTC).isoformat()
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),
}
)
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,
Expand All @@ -643,7 +646,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": index.base_preset_revision,
"base_preset_revision": base_preset_revision,
"runs": submitted,
}
_print_status(result)
Expand Down
36 changes: 20 additions & 16 deletions experiments/post_training/rl_publication.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,10 @@ def _gate_result(report: gate.GateReport | None) -> GateResult | None:
verdict=report.verdict,
effect=report.effect,
reason=report.reason,
invariants=list(report.invariants),
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,
Expand Down Expand Up @@ -266,7 +269,7 @@ 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 index.base_preset_revision is None:
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)
Expand All @@ -280,7 +283,7 @@ def build_record(
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,
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,
Expand Down Expand Up @@ -436,7 +439,6 @@ def _with_evaldash_links(summary: AttemptSummary, service_url: str | None) -> At
try:
from marina import client # noqa: PLC0415

run_ids = list(dict.fromkeys((summary.run_id, summary.native_run_id or summary.run_id)))
rows = client.marina_request(
service_url or client.DEFAULT_MARINA_URL,
"GET",
Expand All @@ -449,21 +451,23 @@ def _with_evaldash_links(summary: AttemptSummary, service_url: str | None) -> At
},
timeout=4,
)
if not isinstance(rows, list):
raise ValueError("EvalDash did not return a run list")
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)
)
return summary.model_copy(update={"evaldash_run_ids": list(dict.fromkeys(links))}) if links else summary
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(
Expand Down
24 changes: 19 additions & 5 deletions experiments/post_training/rl_tests/test_rl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -846,11 +846,17 @@ def test_detached_ungated_launch_indexes_prepared_then_terminal_attempt(
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[-1] == "origin/main"
return "HEAD"
assert args == ["merge-base", source_ref, "origin/main"]
return historical_ref
return git_output(args, cwd, **kwargs)

monkeypatch.setattr(snowball, "git_output", historical_source)
Expand All @@ -866,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,
Expand All @@ -880,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,
Expand All @@ -898,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=(
Expand Down
18 changes: 15 additions & 3 deletions experiments/post_training/rl_tests/test_rl_publication.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import click
import pytest
from click.testing import CliRunner
from finestore.rl.rl_progress import AttemptSummary, RunIndexIdentity
from finestore.rl.rl_progress import AttemptSummary, Invariant, RunIndexIdentity, Verdict
from finestore.rl.run_records import (
AttemptRecord,
CheckpointReference,
Expand Down Expand Up @@ -346,6 +346,7 @@ def unavailable_readback(origin, method, path, *, json_body=None, **kwargs):
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,
Expand All @@ -356,7 +357,6 @@ def unavailable_readback(origin, method, path, *, json_body=None, **kwargs):
branch="fixture",
source_revision="fixture",
dirty=False,
base_preset_revision=preset.revision,
)
if index == 0
else None
Expand Down Expand Up @@ -400,6 +400,17 @@ def unavailable_catalog(origin, method, path, **kwargs):
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)
Expand Down Expand Up @@ -436,6 +447,7 @@ def wrong_returned_key(origin, method, path, *, json_body=None, **kwargs):
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()
Expand Down Expand Up @@ -653,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"]
Expand Down
20 changes: 8 additions & 12 deletions infra/marina/apps/evaldash/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +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 = _rl_attempt(record)
attempt = record.rl_attempt
return {
"run_id": record.run_id,
"group_id": record.group_id,
Expand All @@ -387,24 +387,20 @@ 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.get("run_id"),
"rl_attempt_id": attempt.get("attempt_id"),
"rl_step": attempt.get("step"),
"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 _rl_attempt(record: EvalRunRecord) -> dict:
return record.model_dump(include={"rl_attempt"}).get("rl_attempt") or {}


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 = _rl_attempt(record)
ref = record.rl_attempt
return (
bool(ref)
and (not run_ids or ref.get("run_id") in run_ids)
and (attempt_id is None or ref.get("attempt_id") == attempt_id)
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)
)


Expand Down
9 changes: 6 additions & 3 deletions infra/marina/apps/rl_progress/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,12 @@ 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 the shared runtime with format-2 `AttemptSummary` support before using
the history publisher. The app package continues to serve format-1 writes
during the runtime rollout.
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`. Verify
Expand Down
11 changes: 7 additions & 4 deletions infra/marina/apps/rl_progress/dist/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const grafanaLink = (run) => run.grafana_url && /^https:\/\/grafana\.oa\.dev\//.
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) {
Expand All @@ -35,9 +35,12 @@ function route(run) { return '#' + new URLSearchParams({ run: run.run_id, attemp
function selectedFromHash() {
const params = new URLSearchParams(location.hash.slice(1));
const runId = params.get('run');
const attempts = groupedRuns().get(runId) ?? runs.filter((run) => run.native_run_id === runId)
.sort((a, b) => attemptTime(b) - attemptTime(a));
return params.has('attempt') ? attempts.find((run) => run.attempt_id === params.get('attempt')) ?? null : attempts[0] ?? null;
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) {
Expand Down
2 changes: 1 addition & 1 deletion infra/marina/apps/rl_progress/dist/progress.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function controlSets(runs) {
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.branch && run.branch !== 'main') 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()];
Expand Down
Loading
Loading