Compare commits

...
Author SHA1 Message Date
minh hoangandGitHub 96fa737c35 fix(docker): keep the editable verifiers when installing the prime CLI (#3705)
## Summary

Published prime-rl images since #3635 (2026-09-22) ship the PyPI
`verifiers==0.2.0` wheel instead of the submodule editable, and the
orchestrator and env-server entrypoints fail at import as a result. This
installs the prime CLI with its verifiers requirement overridden so the
editable stays, and asserts that at build time.

## What's wrong

`Dockerfile.cuda` installs the prime CLI after the lockfile sync (`uv
pip install 'prime>=0.7'`). Every prime release since 0.6.30 (prime#879,
2026-08-31) pins `verifiers==0.2.0`, so that install uninstalls the
editable verifiers (0.3.x, pretend version `0.3.2.dev137`) and replaces
it with the 0.2.0 wheel. Observed on a pristine `v0.9.1.dev128` pod on
telus:

```
$ uv run --no-sync orchestrator --help
  File ".../prime_rl/configs/orchestrator.py", line 160, in EnvConfig
    env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
AttributeError: module 'verifiers.v1' has no attribute 'SingleAgentEnvConfig'

$ uv run --no-sync env-server --help
  File ".../prime_rl/entrypoints/env_server.py", line 9, in <module>
    from verifiers.v1.runtimes import set_base_sandbox_labels
ImportError: cannot import name 'set_base_sandbox_labels' from 'verifiers.v1.runtimes'
```

`uv pip check` on the image reports 107 incompatibilities, all `...
requires verifiers>=0.3.1, but 0.2.0 is installed`.

Runs that install a Hub env at pod start survive by accident: `prime env
install` pulls an env that requires `verifiers>=0.3.1`, which drags
verifiers 0.3.x from PyPI back in before the orchestrator imports it.
Runs on baked envs get no such repair. The nightly FFT configs are all
baked envs, and nightly FFT has failed every day since 9/24.

An older CLI is not an option: the last release without the pin (0.6.29)
needs a prime-sandboxes API that 0.3.0 removed, and prime-rl itself
requires `prime-sandboxes>=0.3.0`.

## Fix

- Install the CLI with `--overrides` on a one-line file containing
`verifiers`, so its `verifiers==0.2.0` requirement is ignored and the
editable is left alone. Everything else the CLI needs (prime-traces,
prime-sandboxes, openai, …) still installs as before.
- Assert in the same `RUN` that `verifiers` imports from
`/app/deps/verifiers`, so a regression fails the build rather than the
orchestrator.
- **This is a workaround, marked `FIXME(prime#940)` in the Dockerfile.**
The real fix is the prime CLI dropping verifiers as a dependency,
PrimeIntellect-ai/prime#940. Once that ships, remove the overrides file
and the `--overrides` flag here and in `scripts/docker-entrypoint.sh` on
#3686, which replays this step with the same override for the runtime
source overlay. Keep the import assertion.

## Verified

- The override was exercised on telus pods against the
`v0.9.1.dev127-4-gba81f7c5b-feat-runtime-source-overlay` image (whose
entrypoint runs the identical command after re-syncing the editables):
verifiers stays at `0.3.2.dev137` from `deps/verifiers`, `prime
--version` and `uv run --no-sync prime env install
primeintellect/wordle` work, `orchestrator --help` and `env-server
--help` start, `uv pip check` drops from 107 incompatibilities to 7 (six
pre-existing lockfile inconsistencies plus the intentional `prime
requires verifiers==0.2.0`). A full hosted run (reverse-text, 20 steps)
completed on that venv.
- This Dockerfile change itself: image build dispatched from this
branch, result below.

Build from this branch: dispatched, result pending.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes Docker venv composition for a dependency that prime-rl
entrypoints rely on; mitigated by a build-time import-path assertion,
but image builds and baked-env runs depend on the override staying
correct.
> 
> **Overview**
> Published CUDA images broke **orchestrator** and **env-server**
because installing `prime>=0.7` after `uv sync` pulled PyPI
`verifiers==0.2.0` over the repo’s editable under `deps/verifiers`
(0.3.x APIs).
> 
> The **prime CLI install step** in `Dockerfile.cuda` now writes a
one-line `uv pip install --overrides` file (`verifiers`) so the CLI’s
pinned verifiers requirement is ignored while other CLI deps still
install. A **build-time assert** checks `verifiers` resolves under
`/app/deps/verifiers`. Comments mark this as a temporary
**FIXME(prime#940)** until the CLI drops verifiers; the entrypoint
overlay in `scripts/docker-entrypoint.sh` is called out as needing the
same cleanup later.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
22c9bfd1c9907da4662665f225ca10c3cdf6a930. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-27 16:53:54 -07:00
35aa06fbfa feat(eval): allow any config override on resume (#3690)
## Summary

`uv run eval --resume` used to compare the resolved config against the
interrupted attempt's `eval.json`. It refused any change outside a short
allowlist, which left out the solver `model`, everything under
`source.*.env` (including where each judge is served) and
`tasks_per_minute`. So a paused eval couldn't move to a new endpoint
serving the same weights under another name, such as a self-hosted
router becoming a hosted API. The only way out was `--clean`.

This PR removes that validation (`RESUMABLE`, `config_diff`,
`check_config`, `previous_config`), so any field can be overridden on
resume. It's up to whoever resumes to keep the measurement consistent.
The resolved config is still written beside each attempt's episodes
(`stamp_config`), so every attempt records what it ran with.
`docs/eval.md` still says a resume that changes the model, sampling or
env stops with the differing paths. That's no longer true and needs a
follow-up.

## Test plan

- Removed the tests for the deleted functions. `pytest tests/unit/eval`
passes (7 tests).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Resume can now mix previously landed episodes with a different model,
sampling, or env configuration, which can invalidate eval comparability
if operators override carelessly.
> 
> **Overview**
> **`uv run eval --resume` no longer compares the new resolved config to
the interrupted attempt's stamped `eval.json`.** The allowlist-based
guard (`RESUMABLE`, `config_diff`, `check_config`, `previous_config`) is
removed, so fields like model, sampling, env/judge endpoints, and source
layout can all change when resuming instead of forcing `--clean`.
> 
> Resume still loads landed episodes from the trace stream and stamps
the current config per attempt via `stamp_config`; only the validation
step in `Eval.run` is dropped. Module docs now state that **any config
may be overridden** and consistency is the operator's responsibility.
> 
> Unit tests for config checking and `previous_config` lookup were
removed; remaining resume tests (`plan`, `take_landed`, trigger
integration) are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
06482534d862782e1a844ea9f8d5c3f5c37310ac. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 14:43:05 -07:00
718635b2ca feat: treat timed-out rollouts as their own outcome (#3702)
## Summary

Companion to PrimeIntellect-ai/verifiers#2693, which stops a rollout
whose stage deadline expires as `<stage>_timeout` with
`Trace.is_timeout` set (scored, not errored).

- Training keeps main's semantics: the dispatcher records a `Timeout`
error on a timed-out train trace, so it stays out of the batch and
counts under `has_error`. Eval keeps the timeout as a scored outcome.
- Metrics: `is_timeout` joins the trace rates
(`<scope>/{all,effective}/<agent>/is_timeout/mean`) next to
`is_truncated`; `EpisodeMetrics.is_timeout` over the full cohort feeds
the console summary lines (`... | Truncation 0.0% | Timeout 100.0%`) for
train, online eval and standalone eval.
- W&B overview and dashboard metric sections plot
`all/<agent>/is_timeout/mean`.
- Trace index rows carry `timeout` (the episode's `is_timeout` or any
trace's); the dashboard series expose it.
- Dashboard: yellow (`--timeout`) marks for timed-out episodes on the
overview tile (`timeout rate`), episode cells, swarm points,
timing/token strips, episode table rows (with a `timed out (<stop>)`
title), trace tabs and the timeline state; the trace meta panel shows
`is_timeout`.
- Dispatcher: a timed-out eval trace with zero turns stays a timeout
instead of being promoted to an `EmptyTrajectory` error; it is scored
and counted under `is_timeout`.
- Bumps `deps/verifiers` to verifiers `main` with #2693 merged.

## Breaking

- In evals, a rollout that hits its `timeout.rollout` (or
setup/finalize/scoring) budget no longer counts under `has_error`: it
lands `ok` with `stop_condition = "<stage>_timeout"`, is scored, and
enters the `effective` subset like a truncated rollout does. Training is
unchanged: a timed-out rollout is still an error (now typed `Timeout`,
with `is_timeout` set alongside).

## Verification

Ran off this branch with the verifiers companion on `PYTHONPATH`:

```
uv run eval gsm8k -n 4 -r 1 -c 4 -m alibaba/qwen3.5-flash --env.agent.harness.id null --env.agent.runtime.type subprocess --env.agent.timeout.rollout 2
```

Before the dispatcher change: `Error 100.0% | Truncation 0.0% | Timeout
0.0%`, every trace re-labelled `EmptyTrajectory`. After: `Error 0.0% |
Truncation 0.0% | Timeout 100.0%`, metrics `is_timeout/mean = 1.0`,
`stop_condition/agent_timeout = 1.0`, index rows `ok=true,
stop_condition=agent_timeout, timeout=true`. A control run with the
default budget lands `agent_completed`, `timeout=false`, `Timeout 0.0%`.

Dashboard driven headlessly with playwright against both runs: `timeout
rate` tile `100%` in `rgb(255, 209, 102)`, every episode cell/row class
`timeout`, rows titled `timed out (agent_timeout)`, trace meta
`is_timeout true` / `ok true`; the control run shows `0%` and no marks;
no page errors.

`tests/unit/orchestrator`, `tests/unit/eval` and
`tests/unit/test_dashboard_timeline.py` pass.


## Screenshots

Eval with `--env.agent.timeout.rollout 2`: the overview tile and episode
cells read yellow, the traces table marks each row's edge yellow, and
the trace viewer lists the timed-out episodes with `is_timeout true` /
`ok true`.


![overview](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/assets/is-timeout/timeout-2s-overview.png)

![traces](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/assets/is-timeout/timeout-2s-traces-table.png)
![trace
viewer](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/assets/is-timeout/timeout-2s-traces.png)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Eval cohort semantics change (timeouts move off `has_error` onto
`is_timeout`), and the dispatcher path that promotes empty trajectories
to errors now explicitly exempts timed-out eval traces—worth validating
against downstream dashboards and monitors that assumed timeouts were
errors.
> 
> **Overview**
> Rollouts that hit a stage deadline (`<stage>_timeout`) are now a
**distinct outcome** from errors and truncation, with **`is_timeout`**
tracked alongside **`is_truncated`** in orchestrator metrics, console
summaries, W&B/dashboard metric panels, and docs.
> 
> **Training vs eval:** On **train**, the dispatcher still drops
timed-out traces from the batch by attaching a **`Timeout`** error and
marking the trace **`ok=false`** (same exclusion as before, now typed).
On **eval**, timeouts stay **`ok`** and scored; zero-turn timeout traces
are no longer relabeled as **`EmptyTrajectory`** errors.
> 
> **Observability:** Trace index rows and eval series expose
**`timeout`**; the dashboard uses yellow styling for timeout rate,
episode cells, swarm dots, tables, timeline state, and trace meta
**`is_timeout`**. Eval success logs and standalone eval runner output
add a **Timeout** percentage next to truncation/error.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
83c0ce4c920aa0fb55eea97c251db18ec763053f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 13:12:08 -07:00
17 changed files with 100 additions and 124 deletions
+14 -2
View File
@@ -137,9 +137,21 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
# Needed for private environments hub auth
# Needed for private environments hub auth.
#
# FIXME(prime#940): workaround, remove once the prime CLI drops verifiers as
# a dependency (https://github.com/PrimeIntellect-ai/prime/pull/940). The CLI
# pins verifiers==0.2.0, which replaced the editable verifiers synced above
# with the PyPI wheel and left prime-rl's own entrypoints unable to import;
# the --overrides file ignores that one requirement. When removing it, drop
# the overrides file and the --overrides flag, keep the import assertion, and
# make the same change in scripts/docker-entrypoint.sh, which replays this
# step for the runtime source overlay.
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
VIRTUAL_ENV=/app/.venv uv pip install 'prime>=0.7'
printf 'verifiers\n' > /tmp/prime-cli-overrides.txt \
&& VIRTUAL_ENV=/app/.venv uv pip install --overrides /tmp/prime-cli-overrides.txt 'prime>=0.7' \
&& rm /tmp/prime-cli-overrides.txt \
&& /app/.venv/bin/python -c 'import pathlib, verifiers; assert pathlib.Path(verifiers.__file__).is_relative_to("/app/deps/verifiers"), verifiers.__file__'
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
+1 -1
+1
View File
@@ -115,6 +115,7 @@ Eval metrics mirror the training rollout hierarchy under the `eval/<env>` scope:
|---|---|
| `eval/<env>/all/<agent>/reward/mean` | mean reward over the epoch |
| `eval/<env>/all/<agent>/is_truncated/mean` | share of rollouts cut by the length limit |
| `eval/<env>/all/<agent>/is_timeout/mean` | share of rollouts stopped by a stage deadline (`<stage>_timeout`) |
| `eval/<env>/all/<agent>/has_error/mean` | share of rollouts that raised |
| `eval/<env>/all/seq_len/mean` | mean episode length in tokens |
+1
View File
@@ -118,6 +118,7 @@ Pulled from the console logs and mirrored to W&B.
- `reward/{all,env}/mean` — main signal. Should trend upward over hundreds of steps.
- `seq_len/{all,env}/mean` and `is_truncated/{all,env}/mean` — rollout length and truncation rate.
- `is_timeout/{all,env}/mean` — share of rollouts stopped by a stage deadline (`setup`/`agent`/`finalize`/`scoring` `_timeout`). Training counts a timed-out rollout as an error, so it stays out of the batch; eval scores it.
- `num_turns/{all,env}/mean` — for multi-turn envs.
- `empty_rollouts/{all,env}`, `errored_rollouts/{all,env}` — non-zero is fine in small numbers; sustained > 5% is a smell.
- `eval/{env}/{avg@k,pass@k}` — eval scores when `[orchestrator.eval]` is set.
+3
View File
@@ -823,6 +823,8 @@ def message_text(message: dict) -> str:
def timeline_status(trace: dict) -> str:
if not trace.get("is_completed"):
return "running"
if trace.get("is_timeout"):
return "timeout"
if not trace.get("ok") and (trace.get("errors") or trace.get("stop_condition") == "error"):
return "failed"
return "completed"
@@ -1822,6 +1824,7 @@ def episode_series(run: str, kind: str | None = None, etag: str | None = None, a
"ok",
"num_errors",
"truncated",
"timeout",
"stop_condition",
"duration",
"reward",
+40 -17
View File
@@ -423,7 +423,7 @@ function rowsChartHere() {
}
const COMMON_METRICS = ["effective/num_turns/mean", "effective/num_total_tokens/mean", "effective/num_branches/mean"];
const COMMON_REGEXES = ["effective/[^/]+/is_truncated/mean", "all/[^/]+/has_error/mean"];
const COMMON_REGEXES = ["effective/[^/]+/is_truncated/mean", "all/[^/]+/is_timeout/mean", "all/[^/]+/has_error/mean"];
const STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"];
const PERFORMANCE_METRICS = ["perf/mfu", "time/step", "time/wait_for_batch", "time/wait_for_policy"];
const SFT_TRAIN_METRICS = ["loss/mean", "loss/perplexity", "val/loss", "val/perplexity", "progress/epoch"];
@@ -628,11 +628,11 @@ function evalProgressHtml(env, idx, live) {
cells =
idx
.map((i) => {
const err = series.ok?.[i] === false;
const mark = outcomeClass(series, i);
const reward = series.reward?.[i];
return (
`<span class="ep-cell done${err ? " err" : ""}" data-line="${series.line?.[i]}" ` +
`title="#${series.line?.[i]} · reward ${reward != null ? fmtReward(reward) : "n/a"}${err ? " · error" : ""}"></span>`
`<span class="ep-cell done ${mark}" data-line="${series.line?.[i]}" ` +
`title="#${series.line?.[i]} · reward ${reward != null ? fmtReward(reward) : "n/a"}${mark === "err" ? " · error" : mark === "timeout" ? " · timeout" : ""}"></span>`
);
})
.join("") +
@@ -745,7 +745,7 @@ function dotPlotSvg(entry, W, H) {
const col = Math.floor(j / perCol), rowN = j % perCol;
const cx = x0 + col * (2 * r + 1);
const cy = top + plotH - r - rowN * (2 * r + 1);
return `<circle data-i="${i}" class="${p.err ? "err" : ""}" cx="${cx.toFixed(1)}" cy="${cy.toFixed(1)}" r="${r}"></circle>`;
return `<circle data-i="${i}" class="${markClass(p)}" cx="${cx.toFixed(1)}" cy="${cy.toFixed(1)}" r="${r}"></circle>`;
})
.join("");
const n = counts.get(v);
@@ -829,7 +829,7 @@ function swarmSvg(entry, W, H) {
stacks.set(column, k + 1);
const offset = Math.ceil(k / 2) * d * (k % 2 ? -1 : 1);
const y = Math.max(r, Math.min(plotH - r, mid + offset));
return `<circle data-i="${i}" class="${points[i].err ? "err" : ""}" cx="${px.toFixed(1)}" cy="${y.toFixed(1)}" r="${r}"></circle>`;
return `<circle data-i="${i}" class="${markClass(points[i])}" cx="${px.toFixed(1)}" cy="${y.toFixed(1)}" r="${r}"></circle>`;
});
// the x axis: a baseline under the plot, round-valued ticks with grid lines
const label = (v) => tickLabel(v, entry.fmt);
@@ -868,6 +868,16 @@ function drawSwarms() {
const SWARM_STAT_ROWS = ["min", "p10", "median", "p90", "max"];
/* an episode's outcome mark: a timeout reads yellow, an error red, a clean one unmarked */
function outcomeClass(series, i) {
if (series.timeout?.[i] === true) return "timeout";
return series.ok?.[i] === false ? "err" : "";
}
function markClass(point) {
return point.timeout ? "timeout" : point.err ? "err" : "";
}
function swarmTipHtml(entry, point) {
const row = (k, v) => `<div class="tip-row"><span>${esc(k)}</span><span>${v}</span></div>`;
if (point) {
@@ -875,6 +885,7 @@ function swarmTipHtml(entry, point) {
? [row("rollouts", point.n), row(entry.label, entry.fmt(point.v))]
: [row(entry.label, entry.fmt(point.v)), ...(point.reward != null ? [row("reward", fmtReward(point.reward))] : [])];
if (point.err) rows.push(row("errors", point.group ? "in a rollout" : "yes"));
if (point.timeout) rows.push(row("timeout", point.group ? "in a rollout" : "yes"));
rows.push(row("", point.group ? "click opens its first rollout" : "click opens the trace"));
return `<div class="tip-head">${point.group ? `task ${esc(point.group.slice(0, 8))}` : `episode #${point.line}`}</div>${rows.join("")}`;
}
@@ -907,15 +918,16 @@ function evalScoreEntries(idx, filter) {
const reward = series.reward?.[i] ?? (series.ok?.[i] === false ? 0 : null);
if (reward == null) continue;
const task = series.group?.[i] ?? String(i);
if (!byTask.has(task)) byTask.set(task, { group: task, line: series.line?.[i], rewards: [], err: false });
if (!byTask.has(task)) byTask.set(task, { group: task, line: series.line?.[i], rewards: [], err: false, timeout: false });
const t = byTask.get(task);
t.rewards.push(reward);
if (series.ok?.[i] === false) t.err = true;
if (series.timeout?.[i] === true) t.timeout = true;
}
const tasks = [...byTask.values()];
if (!tasks.length) return entries;
const k = Math.max(...tasks.map((t) => t.rewards.length));
const taskPoint = (t, v) => ({ v, group: t.group, line: t.line, n: t.rewards.length, err: t.err });
const taskPoint = (t, v) => ({ v, group: t.group, line: t.line, n: t.rewards.length, err: t.err, timeout: t.timeout });
if (!filter || filter.test("avg@k"))
entries.push(swarmEntry("avg@k", `avg@${k}`, tasks.map((t) => taskPoint(t, t.rewards.reduce((a, b) => a + b, 0) / t.rewards.length)), fmtReward));
if ((!filter || filter.test("pass@k")) && tasks.every((t) => t.rewards.every((r) => r === 0 || r === 1))) {
@@ -1015,7 +1027,7 @@ function timingPaneHtml(idx) {
if (total == null) return null;
const parts = leaves.map((p) => ({ name: p.split("/").pop(), v: series[`timing/${p}`]?.[i] ?? 0 }));
parts.push({ name: "other", v: Math.max(0, total - parts.reduce((a, p) => a + p.v, 0)) });
return { i, line: series.line?.[i], err: series.ok?.[i] === false, total, parts };
return { i, line: series.line?.[i], err: series.ok?.[i] === false, timeout: series.timeout?.[i] === true, total, parts };
})
.filter(Boolean)
.sort((a, b) => b.total - a.total);
@@ -1037,7 +1049,7 @@ function tokensPaneHtml(idx) {
.map((i) => {
const input = series.input_tokens?.[i] ?? 0, output = series.output_tokens?.[i] ?? 0;
if (!input && !output) return null;
return { i, line: series.line?.[i], err: series.ok?.[i] === false, total: input + output, parts: [{ name: "input", v: input }, { name: "output", v: output }] };
return { i, line: series.line?.[i], err: series.ok?.[i] === false, timeout: series.timeout?.[i] === true, total: input + output, parts: [{ name: "input", v: input }, { name: "output", v: output }] };
})
.filter(Boolean)
.sort((a, b) => b.total - a.total);
@@ -1113,7 +1125,7 @@ function drawComposition(pane, model, { kind, fmt, time, color }) {
const t = tip(
`<div class="tip-head">episode #${r.line} · ${fmt(r.total)}</div>` +
parts.map((p) => rowTip(p.name, `${fmt(p.v)} · ${Math.round((p.v / (r.total || 1)) * 100)}%`)).join("") +
`${r.err ? rowTip("errors", "yes") : ""}${rowTip("", "click opens the trace")}`
`${r.err ? rowTip("errors", "yes") : ""}${r.timeout ? rowTip("timeout", "yes") : ""}${rowTip("", "click opens the trace")}`
);
const segs = parts
.map((p) => {
@@ -1126,7 +1138,7 @@ function drawComposition(pane, model, { kind, fmt, time, color }) {
.join("");
return (
`<rect class="tm-row-hit" data-tip="${t}" data-row="${n}" data-line="${r.line}" x="0" y="${y - GAP / 2}" width="${W}" height="${SH + GAP}"></rect>` +
`<text class="hax tm-line${r.err ? " err" : ""}" data-row="${n}" x="${PAD_L - 6}" y="${y + SH - 1}" style="text-anchor:end">#${r.line}</text>${segs}`
`<text class="hax tm-line ${markClass(r)}" data-row="${n}" x="${PAD_L - 6}" y="${y + SH - 1}" style="text-anchor:end">#${r.line}</text>${segs}`
);
})
.join("");
@@ -1174,13 +1186,19 @@ function summaryTilesHtml(idx, all, scoreEntries) {
const rows = entry.rows ?? SWARM_STAT_ROWS.map((k) => [k, entry.fmt(entry.stats[k])]);
tile(entry.label, entry.headline, `<div class="tip-head">${esc(entry.label)} · ${fmtCompact(entry.stats.n)} tasks</div>${rows.map(([k, v]) => rowTip(k, v)).join("")}`, { cls: " score" });
}
// failure rates count every landed episode, the errors filter notwithstanding
// failure rates count every landed episode, the errors filter notwithstanding;
// the timeout rate reads yellow as soon as any episode timed out
if (all.length) {
const errored = all.filter((i) => series.ok?.[i] === false).length;
const truncated = all.filter((i) => (series.truncated?.[i] ?? TRUNCATING_STOPS.has(series.stop_condition?.[i])) === true).length;
for (const [label, n, what] of [["error rate", errored, "errored"], ["truncation rate", truncated, "truncated"]]) {
const timedOut = all.filter((i) => series.timeout?.[i] === true).length;
for (const [label, n, what, cls] of [
["error rate", errored, "errored", rateClass],
["truncation rate", truncated, "truncated", rateClass],
["timeout rate", timedOut, "timed out", (rate) => (rate > 0 ? " rate-timeout" : "")],
]) {
const rate = n / all.length;
tile(label, `${Math.round(rate * 100)}%`, `<div class="tip-head">${esc(label)}</div>${rowTip(what, `${n} of ${all.length} episodes`)}`, { cls: rateClass(rate) });
tile(label, `${Math.round(rate * 100)}%`, `<div class="tip-head">${esc(label)}</div>${rowTip(what, `${n} of ${all.length} episodes`)}`, { cls: cls(rate) });
}
}
const turns = distStats(idx.map((i) => series.turns?.[i]));
@@ -1236,6 +1254,7 @@ function renderEvalPane(body) {
line: series.line?.[i],
reward: series.reward?.[i],
err: series.ok?.[i] === false,
timeout: series.timeout?.[i] === true,
})),
fmt,
opts
@@ -4040,6 +4059,7 @@ function scopedErrorsHtml(scope, { failed, recovered }) {
}
function episodeRowClass(ep) {
if (ep.timeout) return "timeout";
if (!ep.ok) return "err";
return ep.num_errors ? "retried" : "";
}
@@ -4047,7 +4067,9 @@ function episodeRowClass(ep) {
function episodeRowTitle(ep) {
const n = ep.num_errors || 0;
const errors = `${n || 1} error${n === 1 ? "" : "s"}`;
if (!ep.ok) return errors;
const timeout = ep.timeout ? `timed out (${ep.stop_condition ?? "timeout"})` : "";
if (!ep.ok) return [timeout, errors].filter(Boolean).join(" · ");
if (timeout) return timeout;
return n ? `recovered from ${errors} in earlier attempts` : "";
}
@@ -4340,6 +4362,7 @@ function renderMeta(ep, trace, branches) {
parts.push(metaRow("stop_condition", trace.stop_condition));
parts.push(metaRow("is_completed", trace.is_completed));
parts.push(metaRow("is_truncated", traceTruncated(trace)));
parts.push(metaRow("is_timeout", !!trace.is_timeout));
parts.push(metaRow("ok", trace.ok));
const durations = [];
@@ -5532,7 +5555,7 @@ function renderEpisode() {
traceTabs.innerHTML =
traces.length > 1
? traces
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}${trace.ok ? "" : " err"}">${esc(trace.agent?.name || "agent")}</button>`)
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}${trace.is_timeout ? " timeout" : trace.ok ? "" : " err"}">${esc(trace.agent?.name || "agent")}</button>`)
.join("")
: "";
const branchTabs = $("#tm-branch-tabs");
+10
View File
@@ -15,6 +15,7 @@
--accent: #b6ff3c;
--negative: #ff4539;
--timeout: #ffd166;
--positive: #b6ff3c;
--infra: #4a9eff;
--risk: #ff6b4a;
@@ -358,6 +359,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
.ep-cell { flex: 1; min-width: 0; background: var(--grey-2); border: 1px solid var(--hairline); }
.ep-cell.done { background: var(--accent); border-color: var(--accent); cursor: pointer; }
.ep-cell.done.err { background: var(--negative); border-color: var(--negative); }
.ep-cell.done.timeout { background: var(--timeout); border-color: var(--timeout); }
.ep-cell.done:hover { filter: brightness(1.2); }
.ep-cell.live { border-color: var(--accent); background: rgba(182, 255, 60, 0.18); animation: live-pulse 1.6s ease-in-out infinite; cursor: pointer; }
@@ -369,6 +371,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
.swarm .sw-bg { fill: transparent; }
.swarm circle { fill: var(--accent); fill-opacity: 0.7; cursor: pointer; }
.swarm circle.err { fill: var(--negative); }
.swarm circle.timeout { fill: var(--timeout); }
.swarm circle:hover { fill-opacity: 1; stroke: var(--grey-6); stroke-width: 1; }
.sw-axis { stroke: var(--grey-3); stroke-width: 1; }
.sw-grid { stroke: var(--hairline-faint); stroke-width: 1; }
@@ -392,6 +395,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
.tm-strip-seg.dim { opacity: 0.2; }
.tm-strip-seg:hover { filter: brightness(1.25); }
.tm-line.err { fill: var(--negative); }
.tm-line.timeout { fill: var(--timeout); }
.comp-pane [data-part].dim { opacity: 0.2; }
.comp-pane .tm-node.dim { opacity: 0.35; }
/* the summary is one row whatever the count: the tiles share the width equally */
@@ -401,6 +405,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
.sum-tile .stat-value { font-size: clamp(16px, 1.7vw, 24px); margin-top: 8px; }
.sum-tile.rate-warn .stat-value { color: #ffd166; }
.sum-tile.rate-bad .stat-value { color: var(--negative); }
.sum-tile.rate-timeout .stat-value { color: var(--timeout); }
.tm-note { font-size: 10px; margin-top: 4px; }
.tm-more { color: var(--grey-5); cursor: pointer; text-decoration: underline dotted; text-underline-offset: 3px; }
.tm-more:hover { color: var(--grey-6); }
@@ -834,6 +839,8 @@ mark.hit {
.tm-item.active { background: var(--grey-2); border-color: var(--grey-3); color: var(--grey-6); }
.tm-item.err { background: rgba(255, 69, 57, 0.08); border-color: var(--negative); }
.tm-item.err:hover, .tm-item.err.active { background: rgba(255, 69, 57, 0.16); }
.tm-item.timeout { background: rgba(255, 209, 102, 0.08); border-color: var(--timeout); }
.tm-item.timeout:hover, .tm-item.timeout.active { background: rgba(255, 209, 102, 0.16); }
.tm-item.retried { border-left: 2px dotted var(--grey-4); }
.tm-item .tm-reward { margin-left: auto; }
.tm-nav { padding: 0 8px; height: 24px; }
@@ -936,6 +943,7 @@ mark.hit {
.tl-state { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
.tl-state.completed { color: var(--positive); }
.tl-state.failed { color: var(--negative); }
.tl-state.timeout { color: var(--timeout); }
.tl-state.running { color: var(--infra); }
.tl-tooltip {
position: fixed;
@@ -1212,6 +1220,7 @@ mark.hit {
.trace-recovered-item .trace-error-type { color: var(--grey-4); }
.trace-recovered-item .trace-error-tb > summary { border-top-color: var(--grey-3); }
.seg button.err, .seg button.err.active { color: var(--negative); }
.seg button.timeout, .seg button.timeout.active { color: var(--timeout); }
.trace-error-tb > summary {
display: flex;
align-items: center;
@@ -1731,6 +1740,7 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
place of their number set them apart */
.live-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); animation: live-pulse 2s ease-out infinite; }
#episode-table tr.err td:first-child { border-left: 2px solid var(--negative); }
#episode-table tr.timeout td:first-child { border-left: 2px solid var(--timeout); }
#episode-table tr.retried td:first-child { border-left: 2px dotted var(--grey-4); }
#episode-table tr.live.landing .live-dot { animation: none; opacity: 0.45; }
.badge.stage { font-size: 9px; padding: 2px 5px; line-height: 12px; border-radius: 3px; background: var(--hairline); border-color: transparent; color: var(--accent); }
-1
View File
@@ -27,7 +27,6 @@ class Eval:
landed: list[dict] = []
if config.resume:
# read and set aside before the monitors start: the resumed attempt writes a fresh stream
resume.check_config(resume.previous_config(config.run_dir), dump_resolved_config(config))
landed = resume.take_landed(config.run_dir)
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
+4 -65
View File
@@ -8,16 +8,14 @@ ones the interruption cut off are owed again.
A landed episode counts toward the task with its ``task.key``, so a resumed run may
select more or fewer examples or rollouts per example than the interrupted one: the
kept episodes are matched to the new selection and the rest is owed. What defines the
measurement itself - the model, the sampling, each source's env - must not change
(``check_config``).
kept episodes are matched to the new selection and the rest is owed. The resumed
config is not checked against the interrupted one: any of it may be overridden.
"""
from __future__ import annotations
from collections import Counter, defaultdict
from collections.abc import Iterator
from fnmatch import fnmatch
from pathlib import Path
import orjson
@@ -28,30 +26,10 @@ from prime_rl.monitors.file.traces.chunks import chunk_numbers, open_chunk
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.utils.pathing import get_file_monitor_dir
RESUMABLE = (
"resume",
"clean",
"dry_run",
"dashboard",
"num_examples",
"group_size",
"concurrency",
"client",
"log",
"monitors",
"source.*.num_examples",
"source.*.shuffle",
"source.*.group_size",
"source.*.serve",
)
"""Config paths a resumed run may change: how many rollouts to run and how to run them,
never what is measured."""
CONFIG_NAME = "eval.json"
"""The resolved config an attempt stamps into its file monitor directory once it is
running, beside the episodes it produces: a resume validates against the config those
episodes were measured with, never against an attempt that was rejected or dry."""
running, beside the episodes it produces, recording the config those episodes were
measured with."""
def stamp_config(run_dir: Path, config: dict) -> None:
@@ -60,45 +38,6 @@ def stamp_config(run_dir: Path, config: dict) -> None:
(directory / CONFIG_NAME).write_bytes(orjson.dumps(config, option=orjson.OPT_INDENT_2))
def previous_config(run_dir: Path) -> dict:
"""The config stamped beside the run's landed episodes: the current file monitor
directory's, else the newest archive's."""
for directory in [get_file_monitor_dir(run_dir), *reversed(archives(run_dir))]:
if (directory / CONFIG_NAME).is_file():
return orjson.loads((directory / CONFIG_NAME).read_bytes())
raise FileNotFoundError(f"Nothing to resume: {run_dir} holds no attempt that ran")
def config_diff(previous, current, prefix: str = "") -> list[str]:
"""Dotted paths at which two resolved configs differ (list items by index)."""
if isinstance(previous, dict) and isinstance(current, dict):
return [
path
for key in sorted(set(previous) | set(current))
for path in config_diff(previous.get(key), current.get(key), f"{prefix}.{key}" if prefix else key)
]
if isinstance(previous, list) and isinstance(current, list) and len(previous) == len(current):
return [
path
for index, (before, after) in enumerate(zip(previous, current, strict=True))
for path in config_diff(before, after, f"{prefix}.{index}")
]
return [] if previous == current else [prefix]
def check_config(previous: dict, current: dict) -> None:
changed = [
path
for path in config_diff(previous, current)
if not any(fnmatch(path, pattern) or fnmatch(path, f"{pattern}.*") for pattern in RESUMABLE)
]
if changed:
raise ValueError(
f"The run cannot resume with a different {', '.join(changed)} - the landed episodes would not "
"measure the same thing. Relaunch with --clean to start over."
)
def read_records(stream: Path) -> Iterator[dict]:
"""Every record of a trace stream, in order. A torn last line (the interrupted
process died mid-append) ends the stream."""
+2 -1
View File
@@ -303,7 +303,8 @@ class EvalRunner:
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%} | "
f"Timeout {full.is_timeout.mean():.1%}"
)
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
@@ -55,6 +55,7 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
turns = branches = 0
stop_condition = None
truncated = False
timeout = bool(rec.get("is_timeout"))
reward_parts: dict[str, list[float]] = {}
metric_parts: dict[str, list[float]] = {}
timing: dict[str, float] = {}
@@ -92,6 +93,7 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
turns += 1
stop_condition = trace.get("stop_condition", stop_condition)
truncated = truncated or trace_truncated(trace)
timeout = timeout or bool(trace.get("is_timeout"))
first_info = ((rec.get("traces") or [{}])[0].get("info")) or {}
return {
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
@@ -117,6 +119,7 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
"branches": branches,
"stop_condition": stop_condition,
"truncated": truncated,
"timeout": timeout,
# when the episode landed and how long it was alive: the stream's x axis,
# and the one duration worth sorting a stream by
"dispatch": (first_info.get("dispatch") or {}).get("time"),
+1
View File
@@ -40,6 +40,7 @@ COMMON_METRICS = [
COMMON_REGEXES = [
"all/[^/]+/has_error/mean",
"effective/[^/]+/is_truncated/mean",
"all/[^/]+/is_timeout/mean",
]
STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"]
+9 -2
View File
@@ -670,9 +670,16 @@ class Dispatcher:
episode.errors.append(vf.Error(type="EmptyEpisode", message="Episode returned with no traces"))
for trace in episode.traces:
if not trace.has_error and trace.num_turns == 0:
if trace.is_timeout and not trace.has_error and meta.kind == "train":
# Training keeps a timed-out rollout out of the batch: an error,
# like any other failure. Eval keeps it as a scored outcome.
trace.errors.append(vf.Error(type="Timeout", message=f"Trace stopped by {trace.stop_condition}"))
trace.ok = False
episode.ok = False
if not trace.has_error and not trace.is_timeout and trace.num_turns == 0:
# Empty trajectory: promote to an explicit error so the sink
# treats it like any other failure (``has_error`` reads ``ok``)
# treats it like any other failure (``has_error`` reads ``ok``).
# A timed-out eval trace with no turns stays a timeout: scored, no samples.
trace.errors.append(vf.Error(type="EmptyTrajectory", message="Trace returned with no trajectory steps"))
trace.ok = False
episode.ok = False
+5 -1
View File
@@ -197,7 +197,7 @@ class TraceMetrics(StatGroup):
"num_turns",
"num_branches",
)
RATES = ("is_truncated", "is_completed")
RATES = ("is_truncated", "is_timeout", "is_completed")
def stats(self) -> dict[str, Stat]:
return {
@@ -321,6 +321,10 @@ class EpisodeMetrics:
def is_truncated(self) -> Stat:
return Stat([float(record.trace.is_truncated) for record in self.records])
@property
def is_timeout(self) -> Stat:
return Stat([float(record.trace.is_timeout) for record in self.records])
@property
def has_error(self) -> Stat:
return Stat(
+4 -3
View File
@@ -883,7 +883,7 @@ class Orchestrator:
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max_off_policy_steps} | "
f"Error {episodes.metrics.has_error.mean():.1%} | Cancelled {episodes.metrics.cancelled.mean():.1%} | "
f"Truncation {eff.is_truncated.mean():.1%}"
f"Truncation {eff.is_truncated.mean():.1%} | Timeout {episodes.metrics.is_timeout.mean():.1%}"
)
if len(self.train_envs) <= 1:
get_logger().success(head)
@@ -904,7 +904,7 @@ class Orchestrator:
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max((episode_staleness(episode, step)[0] for episode in env_eff_pool), default=0)} | "
f"Error {pool.metrics.has_error.mean():.1%} | Cancelled {pool.metrics.cancelled.mean():.1%} | "
f"Truncation {env_eff.is_truncated.mean():.1%}"
f"Truncation {env_eff.is_truncated.mean():.1%} | Timeout {pool.metrics.is_timeout.mean():.1%}"
)
get_logger().success("\n\t\t ".join(lines))
@@ -952,7 +952,8 @@ class Orchestrator:
f"Evaluated {batch.env_name} | "
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%} | "
f"Timeout {full.is_timeout.mean():.1%}"
)
async def maybe_save_ckpt(self, step: int) -> float:
-31
View File
@@ -1,7 +1,6 @@
from types import SimpleNamespace
import orjson
import pytest
from prime_rl.eval import resume
from prime_rl.monitors.file.traces import get_trace_stream
@@ -64,28 +63,6 @@ def test_trigger_queues_only_owed_rollouts() -> None:
]
def test_check_config_allows_selection_changes_only() -> None:
previous = {
"model": "a",
"num_examples": 8,
"group_size": 2,
"sampling": {"temperature": 1.0},
"source": [{"env": {"taskset": {"id": "gsm8k"}}, "group_size": None, "serve": {"address": None}}],
}
resized = {
**previous,
"num_examples": 16,
"group_size": 4,
"source": [{"env": {"taskset": {"id": "gsm8k"}}, "group_size": 8, "serve": {"address": "tcp://x"}}],
}
resume.check_config(previous, resized)
with pytest.raises(ValueError, match="model, sampling.temperature"):
resume.check_config(previous, {**previous, "model": "b", "sampling": {"temperature": 0.5}})
with pytest.raises(ValueError, match="source"):
resume.check_config(previous, {**previous, "source": previous["source"] * 2})
def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
def land(*keys: str) -> None:
stream = ChunkedJsonl(get_trace_stream(tmp_path), max_bytes=1 << 20, compress=False)
@@ -102,11 +79,3 @@ def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
land("m0", "m2")
assert [record["id"] for record in resume.take_landed(tmp_path)] == ["m0", "m1", "m2"]
assert [path.name for path in resume.archives(tmp_path)] == ["file.attempt_1", "file.attempt_2"]
def test_previous_config_is_the_one_stamped_beside_the_results(tmp_path) -> None:
resume.stamp_config(tmp_path, {"model": "a"})
resume.take_landed(tmp_path) # the attempt that ran is archived; a rejected one never stamps
assert resume.previous_config(tmp_path) == {"model": "a"}
resume.stamp_config(tmp_path, {"model": "b"})
assert resume.previous_config(tmp_path) == {"model": "b"}
+2
View File
@@ -22,6 +22,7 @@ def mk(
num_turns: int = 1,
num_branches: int = 1,
is_truncated: bool = False,
is_timeout: bool = False,
is_completed: bool = True,
has_error: bool = False,
error_type: str = "error",
@@ -51,6 +52,7 @@ def mk(
num_turns=num_turns,
num_branches=num_branches,
is_truncated=is_truncated,
is_timeout=is_timeout,
is_completed=is_completed,
has_error=has_error,
last_error=SimpleNamespace(type=error_type) if has_error else None,