feat: consolidate eval cli (#3471)

## Summary

Migrates the eval CLI from verifiers into the prime-rl ecosystem: `uv
run eval` is prime-rl's entrypoint for evaluating any model on any
environment, standalone or as the online evals of a training run.

Why:

- consolidation of features: adaptive concurrency, the local dashboard,
resume from the trace stream, live rollouts
- easier code sharing between the CLI entrypoints (`rl`, `sft`, `eval`)
- direct access to the pre-installed environments (`prime-envs`
submodule)
- one workspace for post-training: training and evals

Important:

- the verifiers eval CLI stays for a transition period as the quick
in-process path, renamed `uv run vf-eval` so prime-rl owns `eval`
(PrimeIntellect-ai/verifiers#2610 removes it later); env servers and
their streamed traces (PrimeIntellect-ai/verifiers#2512, merged; the
submodule points at verifiers `main`) are consumed here only
- evals run through env servers, for scalability; the launcher (`eval`,
`sft`, `rl`) owns them
- `--resume` continues an interrupted run from its trace stream: landed
episodes rejoin the epoch, only the owed rollouts run;
`num_examples`/`group_size` may change, the model, sampling and env
config may not
- multi-env capable (`[[source]]` blocks); the single-env command
shorthands are preserved
- adaptive concurrency only against local deployments (it reads vLLM
`/metrics`); against an API, concurrency is pinned via `min_inflight =
max_inflight` (the default pins 128)
- prime-rl's core dependencies are plain CPU; install them and the
environments with `uv sync --all-packages`
- Prime runs and traces integrate through the single monitor abstraction
(`--monitors.prime`, `--monitors.wandb`, the file monitor)

Examples:

```bash
uv run eval gsm8k                                            # default model on Prime Inference
uv run eval gsm8k -n 32 -r 4 -m openai/gpt-5.6-luna           # 32 tasks × 4 rollouts, another model
uv run eval terminal-bench-2 --env.taskset.tasks '["fix-git"]' --env.agent.harness.id bash -n 1 -r 2
uv run eval @ configs/debug/eval/single-turn.toml            # gsm8k, null harness
uv run eval @ configs/debug/eval/multi-turn.toml             # 16 terminal-bench-2 tasks, bash harness
uv run eval @ configs/debug/eval/multi-env.toml              # terminal-bench-2 under bash and rlm side by side
uv run eval @ configs/debug/eval/aime2026.toml               # AIME 2026, avg@16
uv run eval @ configs/debug/eval/tb2.toml                    # Terminal-Bench 2, avg@4
uv run eval @ configs/debug/eval/resume.toml --run.name x    # then: --resume
uv run eval gsm8k --monitors.prime                           # stream the evaluation to the platform
```

## Breaking

- `uv run evals` is `uv run eval` (`EvalsConfig` → `EvalConfig`); config
shape: `[eval.client]` → `[client]`, `[eval.concurrency]` →
`[concurrency]`, `[[eval.source]]` → `[[source]]`,
`eval.num_examples`/`eval.group_size` → top level. `[online]` is gone:
online evals are spawned by `sft`.
- `eval` has no `[ckpt]` block; `--resume` is a switch that reads the
run's trace stream.
- SFT online evals: no public entrypoint (`uv run sft` with an `[eval]`
block spawns it); `logs/attempt_N/evals.log` → `eval.log`, `evals.json`
→ `eval.json`, W&B label `online-eval`; `EvalsEvalConfig` →
`SFTOnlineEvalConfig`.
- `ratio` is accepted on training sources only, `interval` on online
eval sources only; a standalone eval's `[[source]]` takes neither.
- `orchestrator.env_server_base_port` and the eval entrypoint's
`env_server_base_port` are removed: launcher-managed env servers bind an
OS-assigned port and publish it
(`configs/attempt_N/resolved/envs/<split>/<name>.address`);
`serve.address` pins one. `uv run env-server` without `serve.address`
binds an OS-assigned port (`address_file` publishes it).
- `configs/evals/swe.toml` is removed (`uv run eval swebench-verified
--env.agent.harness.id bash`).

## Verification

- Unit: `uv run pytest tests/unit` green (configs, orchestrator, eval,
monitors incl. the live reader).
- Debug configs: single-turn, multi-turn, multi-env and aime2026 run to
completion against Prime Inference. Resume: single-env and multi-env
runs interrupted with SIGTERM and resumed hold exactly examples ×
group_size unique episodes with the plan and epoch metrics over the full
set; resuming with a larger `group_size` runs only the extra rollouts;
resuming with another model is refused.
- Core install (`uv sync` without extras) runs `uv run eval`; an SFT run
with online evals starts one env server per source.
- Live streaming, on the final code: gsm8k 16 single-turn episodes,
terminal-bench-2 fix-git with bash (13-14 turns, the pending preview
alternating with committed turns in the live files), kuhn-poker 4
two-seat episodes (8 traces), a 5-step reverse-text RL run (768 train
episodes with token ids, logprobs and masks); no assembly mismatch.
- Platform: `--monitors.prime` on a two-rollout fix-git eval opened the
evaluation 9 s after launch, streamed both rollouts and closed it; the
dashboard linked to it throughout.
- Dashboard behaviour checked in headless Chromium: live rows and viewer
follow, handover in place, metrics pane per env, filter menus, platform
button states.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking CLI and config renames affect existing scripts; env-server
address discovery replaces fixed ports across `rl`, `sft`, and `eval`
launch paths.
> 
> **Overview**
> **Replaces `uv run evals` with `uv run eval`** as the standalone
evaluation entrypoint, sharing the orchestrator eval pipeline
(per-source env servers, adaptive or pinned concurrency, file/W&B/Prime
monitors). Config is **flattened** (`[[source]]`, `[client]`,
`[concurrency]` at top level); **`--resume`** continues from the trace
stream instead of a `[ckpt]` cursor; SFT **online eval** is renamed and
typed as `SFTOnlineEvalConfig` (no public `[online]` block).
> 
> **Env server wiring changes:** fixed `env_server_base_port` ranges are
removed—launcher-managed servers bind **OS-assigned loopback ports** and
publish addresses via **`address_file`** /
`configs/.../envs/<split>/<name>.address`. Training **`ratio`** and
online-eval **`interval`** are scoped to the right source types only.
> 
> **Docs and examples** add `docs/eval.md`, per-example `eval.toml`
files, and `configs/debug/eval/*` smokes; **`configs/evals/swe.toml` is
deleted**. CI adds a **gsm8k eval** integration test on VM runners.
> 
> **Dashboard** gains live rollout APIs and eval-centric metrics
(plan-driven progress, platform links, eval run status), renames
**`evals.log` → `eval.log`**, and tightens static asset revalidation.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
82f2f0eda7628c874be6dcfcda700cab26fd4442. 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>
This commit is contained in:
Mika Senghaas
2026-09-16 11:04:24 -07:00
committed by GitHub
co-authored by Claude Fable 5.1
parent 0d372c1fd6
commit c394c2e1bd
86 changed files with 4689 additions and 1848 deletions
+3
View File
@@ -87,6 +87,9 @@ jobs:
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py"
- test: gsm8k_eval
runner: vm
pytest_args: "tests/integration/test_gsm8k_eval.py"
steps:
- name: Install Git
run: |
+2 -1
View File
@@ -212,7 +212,8 @@ Check out the [docs](docs) directory for in-depth guides on how to use prime-rl.
- [**Overview**](docs/overview.md) - Architecture, install, and a copy-pasteable end-to-end RL run
- [**Configuration**](docs/configuration.md) - TOML composition, CLI overrides, env vars, validation
- [**Training**](docs/training.md) - RL, SFT, evals, checkpointing, observability, rules of thumb
- [**Training**](docs/training.md) - RL, SFT, checkpointing, observability, rules of thumb
- [**Eval**](docs/eval.md) - Standalone evals against any inference server, online evals, resume, platform upload
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA
+8 -6
View File
@@ -10,14 +10,16 @@ Configurations for running prime-rl.
`minimax-m2.5` (swe), `nemotron-3-super` (swe), `deepseek-v4-flash` (sft + a standalone
vLLM serving pre-flight). For the tutorialized equivalents, see
[`examples/advanced/`](../examples/advanced).
- **`evals/`** — standalone eval configs, run with `uv run evals @ configs/evals/swe.toml`.
- **`ci/`** — integration and nightly configs used by CI.
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
(two reverse-text train sources + one eval source, one env server per source). Not
guaranteed functional or up to date.
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), `multi-env/`
(two reverse-text train sources + one eval source, one env server per source), and
`eval/` (`uv run eval` smokes against Prime Inference, one per shape: `single-turn`
(gsm8k), `multi-turn` (terminal-bench-2 fix-git in sandboxes against a local vLLM deployment with the adaptive band), `resume`, `multi-env`).
Not guaranteed functional or up to date.
```bash
uv run rl @ configs/basic/<env>/rl.toml
uv run sft @ configs/basic/<env>/sft.toml # where present
uv run rl @ configs/basic/<env>/rl.toml
uv run sft @ configs/basic/<env>/sft.toml # where present
uv run eval @ configs/debug/eval/<shape>.toml
```
+12
View File
@@ -0,0 +1,12 @@
# CI eval smoke: gsm8k with the null harness in a local subprocess runtime against
# Prime Inference — the eval path end to end without a GPU or sandbox.
num_examples = 4
dashboard = false
[sampling]
max_completion_tokens = 8192
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+16
View File
@@ -0,0 +1,16 @@
# AIME 2026 at avg@16: every problem 16 times with the null harness (one chat
# completion per rollout) against Prime Inference. The math tasksets forbid the
# agent any network, and only the sandboxed runtimes enforce that policy, so the
# rollouts run in prime sandboxes (PRIME_API_KEY) rather than as subprocesses.
# Competition math needs room to reason, so the completion budget is generous.
#
# uv run eval @ configs/debug/eval/aime2026.toml
group_size = 16
[sampling]
max_completion_tokens = 32768
[[source]]
env.taskset.id = "aime26"
env.agent.harness.id = "null"
+20
View File
@@ -0,0 +1,20 @@
# Multi env: 16 terminal-bench-2 tasks under two harnesses, bash and rlm, in prime
# sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout each with
# a ten-minute budget, against Prime Inference on the default model. One env server
# per source; the sources share the taskset, so each carries its own name.
#
# uv run eval @ configs/debug/eval/multi-env.toml
num_examples = 16
[[source]]
name = "tb2-bash"
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 600
[[source]]
name = "tb2-rlm"
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "rlm"
env.agent.timeout.rollout = 600
+12
View File
@@ -0,0 +1,12 @@
# Single env, multi turn: 16 terminal-bench-2 tasks with the bash harness in
# prime sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout
# each, against Prime Inference on the default model.
#
# uv run eval @ configs/debug/eval/multi-turn.toml
num_examples = 16
[[source]]
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
+23
View File
@@ -0,0 +1,23 @@
# Single env, resume: gsm8k with a low pinned concurrency so the run can be
# interrupted partway. Relaunch with the same --run.name and --resume: the landed
# episodes are restored from the trace stream and only the owed rollouts run.
# Resuming a finished run restores everything and exits.
#
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug
# <Ctrl-C partway>
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug --resume
num_examples = 8
group_size = 2
[concurrency]
min_inflight = 2
max_inflight = 2
[sampling]
max_completion_tokens = 8192
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+15
View File
@@ -0,0 +1,15 @@
# Single env, single turn: gsm8k with the null harness (one chat completion per
# task, no sandbox) against Prime Inference.
#
# uv run eval @ configs/debug/eval/single-turn.toml
num_examples = 8
group_size = 2
[sampling]
max_completion_tokens = 8192
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+13
View File
@@ -0,0 +1,13 @@
# Terminal-Bench 2 at avg@4: every task 4 times with the bash harness in prime
# sandboxes (PRIME_API_KEY authenticates sandbox creation) against Prime Inference.
#
# uv run eval @ configs/debug/eval/tb2.toml
group_size = 4
[[source]]
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
env.agent.retries.max_retries = 2
env.agent.retries.include = ["ProviderError", "SandboxError"]
+1 -1
View File
@@ -1,6 +1,6 @@
# Minimal multi-env debug run: two reverse-text train sources + one eval source.
# The launcher spawns one env server per source at its derived address
# (tcp://127.0.0.1:5000-5002); the orchestrator connects to each.
# (each on an OS-assigned loopback port it publishes); the orchestrator connects to each.
max_steps = 10
seq_len = 2048
-32
View File
@@ -1,32 +0,0 @@
# Standalone SWE evals: SWE-bench Verified + Terminal-Bench 2, one epoch each,
# against DeepSeek V4 Flash on Prime Inference.
#
# export PRIME_API_KEY=<your Prime Inference key>
# uv run evals @ configs/evals/swe.toml
#
# The tasksets run in prime sandboxes (the default runtime), so the key also
# authenticates sandbox creation. External API endpoints expose no vLLM
# /metrics, so adaptive concurrency has no load signal - the band must be
# pinned (min_inflight = max_inflight) or the evals process refuses to start.
model = "deepseek/deepseek-v4-flash"
[eval.client]
base_url = "https://api.pinference.ai/api/v1"
api_key_var = "PRIME_API_KEY"
[eval.concurrency]
min_inflight = 32
max_inflight = 32
[[eval.source]]
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
[[eval.source]]
name = "terminal-bench-2"
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
+1 -1
+1 -1
View File
@@ -171,7 +171,7 @@ env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
`ratio` is a training-source field: it defaults to `1` (equal weight per env), and values are relative weights normalized to probabilities across envs. Eval sources of a training run carry `interval` instead, the step interval at which they fire (inherited from the group-level `interval` when unset); a standalone eval has neither.
Everything environment lives under the `env` block (verifiers' `[env]` shape): `env.taskset` configures the v1 taskset, and each agent is a field on the env — `env.agent.harness` selects how the single-agent env's tasks are run, and per-run caps are per-agent (`env.agent.max_turns`, `env.agent.timeout`, `env.agent.max_output_tokens`). A multi-agent env declares its own seats (`env.<role>.*`).
+115
View File
@@ -0,0 +1,115 @@
# Eval
This page covers `uv run eval` — evaluating a model in one or more environments. For the online evals of a training run, see [Training](training.md#online-evals).
> **AI agents working in this repo:** the equivalent runbook is at [`skills/eval/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/eval/SKILL.md).
## Table of Contents
- [Launch](#launch)
- [Configuration](#configuration)
- [Resume](#resume)
- [Monitors](#monitors)
- [File](#file)
- [Prime](#prime)
- [Metrics](#metrics)
`uv run eval` runs one epoch of every configured source and exits. It reuses the orchestrator's eval pipeline: env servers are spawned per source, episodes are admitted under the concurrency controller, and every episode streams into the run's trace stream and metrics.
## Launch
By default the model is served by Prime Inference; authenticate with `PRIME_API_KEY` or `prime login`:
```bash
uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Inference
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
```
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
```bash
uv run inference --vllm.model Qwen/Qwen3-4B
uv run eval gsm8k -n 32 -r 4 -m Qwen/Qwen3-4B --client.base_url http://localhost:8000/v1
```
Single-source shorthands: `<taskset-id>` names the run's only source, `--env.<field> <value>` sets a field of that source's env block (`--env.agent.harness.id bash`, `--env.taskset.tasks '["fix-git"]'`), `-n`/`-r` set `num_examples`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). The shorthands cannot be combined with a TOML that defines `[[source]]` blocks. `uv run eval -h` lists them.
Against a local vLLM deployment, set `min_inflight < max_inflight` in `[concurrency]` to dynamically adjust the number of concurrent episodes for maximum throughput. An external API exposes no vLLM `/metrics` to adapt to, so pin the concurrency there (`-c N`, i.e. `min_inflight = max_inflight`).
## Configuration
Multi-source runs use a TOML (`EvalConfig` in `packages/prime-rl-configs/src/prime_rl/configs/eval.py`). The eval block is flattened to the top level — `[[source]]`, `[client]`, `[concurrency]`, `[sampling]`, `num_examples`, `group_size` — and each source takes the same `env` block as `[[orchestrator.eval.source]]`:
```toml
model = "Qwen/Qwen3-4B"
num_examples = 32
group_size = 4
[client]
base_url = "http://localhost:8000/v1"
[concurrency] # adaptive against a local vLLM deployment
min_inflight = 8
max_inflight = 256
[sampling]
max_completion_tokens = 2048
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "bash"
[[source]]
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
Per-source `num_examples`, `group_size` and `sampling` override the top-level defaults. Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
## Resume
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: the episodes that landed rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch) and only the rollouts still owed run. Errored episodes and the ones the interruption cut off run again.
```bash
uv run eval @ eval.toml --run.name my-eval
# <interrupted>
uv run eval @ eval.toml --run.name my-eval --resume
```
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
A landed episode counts toward the task with its `task.key`, so `num_examples` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The model, the sampling and each source's env must match the config the landed episodes were measured with (kept beside them in `monitors/file/eval.json`); a resume that changes them stops with the differing config paths. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
## Monitors
Monitors receive the run's metrics and episodes through one abstraction. The file monitor is on by default; `--monitors.wandb` logs the run to Weights & Biases; `--monitors.prime` streams it to the Prime platform.
### File
The file monitor writes the run's metrics and trace stream under `output_dir / run.name / monitors/file/` and feeds the local [dashboard](training.md#dashboard). Env servers stream every rollout to the eval process as it happens: the trace's header when it is minted, then one delta per committed turn (the new messages and the model call behind them), per phase change (boot, setup, agent, finalize, scoring), and a preview of each model request's uncommitted messages, so a tool result shows the moment the model is asked about it rather than with the reply. The file monitor appends those deltas to `monitors/file/traces/live/<trace_id>.jsonl` and deletes the file when the episode lands in the finished trace stream, so that directory is exactly the live set and finished traces stay where they always were. The dashboard's traces tab shows live rollouts in the episode table itself: a pulsing dot in the `#` cell marks the row, a phase badge says where the rollout is (boot, setup, running, finalize, scoring), the `dispatched → arrived` column shows the dispatch time with the elapsed time in brackets, and the turn, token and branch counts grow as deltas land. The status filter toggles live and completed rows, and a live row opens in the trace viewer, which follows the rollout turn by turn (the transcript stays pinned to the newest turn until you scroll up; folded entries stay folded; the pending messages of the request in flight render dimmed with an `awaiting model` chip). The table and an open live trace poll once a second and transfer nothing while the rollout is unchanged. The progress line in `eval.log` counts the live rollouts by phase (`2 inflight episodes ... - boot 1 · running 1`). Read a live trace from a shell with `uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`. The same stream exists for RL runs, covering train and online-eval rollouts alike.
The dashboard's metrics tab reads the trace stream directly. It shows one env at a time; the filter menu picks the env and whether errored episodes join the distributions. A block bar has one cell per expected episode: landed episodes (errored ones in red; click one to open it), live rollouts as pulsing outlines (click one to follow it), and the rest empty, with the percentage beside it. The expected count is what the eval runner wrote to `monitors/file/plan.json` when it counted the epoch's tasks. Below the bar, a summary row gives the headline numbers: avg@k and pass@k, the error and truncation rates (yellow past 10%, red past 50%), mean turns and branches in one tile, mean episode time and tokens, and the total cost when the run has costs; hover a tile for its distribution. The env's own rewards and metrics follow, a beeswarm pane each, resizable like the training charts. The usage section is one pane splitting each episode's tokens into input and output, and the timing section is the same pane over the phases of a rollout (boot, setup, model, harness, finalize, scoring, and `other` for wall time no phase accounts for): an icicle bar shows the mean split, one strip per episode below shows the split per rollout, and a legend sits above. Hovering a phase highlights it across the pane; the strips show 40 episodes by default and all of them on `show all`. A metric every episode shares appears as a chip instead of a pane, and a metric with only a few distinct values, such as a binary reward, as a counted dot plot with the count and share of each value. Every dot is an episode (or a task): hover it for its value and click it to open the trace; hover the pane's background for the summary (min, p10, median, p90, max), with a faint boxplot behind the dots. Errored episodes stay out of the distributions until the filter includes them, where they read red.
### Prime
`--monitors.prime` streams each source's epoch as an evaluation on the Prime platform:
```bash
uv run eval gsm8k -n 32 -r 4 -c 8 --monitors.prime
```
The monitor opens one platform evaluation per env when its epoch starts, streams every episode to it as it lands, and closes it with the epoch's aggregates. The run leaves its platform identity in `monitors/prime/run.json` (the training run's id and URL, or one entry per eval epoch), and the dashboard's top bar shows a `view on platform` link from the moment the evaluation opens: a direct link for a training run or a single evaluation, a menu when a run has several.
## Metrics
Eval metrics mirror the training rollout hierarchy under the `eval/<env>` scope:
| Metric | Reading |
|---|---|
| `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>/has_error/mean` | share of rollouts that raised |
| `eval/<env>/all/seq_len/mean` | mean episode length in tokens |
Task-specific env metrics (e.g. `correct_answer`, `format`) appear under the same prefix. The console summary line per source (`Evaluated <env> ... Reward 0.8125`) reports the epoch mean.
+1
View File
@@ -7,6 +7,7 @@
"overview",
"configuration",
"training",
"eval",
"inference",
"scaling",
"algorithms",
+9 -8
View File
@@ -1,6 +1,6 @@
# Training
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md).
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md). For standalone evals, see [Eval](eval.md).
> **AI agents working in this repo:** the equivalent runbooks are at [`skills/training/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/skills/training) — top-level routing in [`skills/training/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/SKILL.md), launch details in [`skills/training/start-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/start-run/SKILL.md), and check-in / restart procedures in [`skills/training/monitor-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/monitor-run/SKILL.md).
@@ -37,7 +37,8 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at a derived loopback address); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
## RL Trainer
@@ -201,17 +202,17 @@ num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
The launcher starts the inference server, one env server per eval source, and an online-eval process next to the trainer (it logs to `logs/attempt_<n>/eval.log`). NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the online-eval process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
#### Multi-Node Trainer and Inference Pool
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and evals process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and online-eval process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2 # trainer nodes
num_infer_nodes = 1 # inference pool + evals
num_infer_nodes = 1 # inference pool + online evals
[inference.vllm]
tensor_parallel_size = 8
@@ -220,7 +221,7 @@ tensor_parallel_size = 8
job_name = "my-run"
```
The shared script passes the trainer rank-0 hostname directly to the evals process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, evals never sees a final broadcast, so the job remains active until walltime. Trainer and evals log to one shared W&B run. The trainer creates it, and evals finalizes it.
The shared script passes the trainer rank-0 hostname directly to the online-eval process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, online-eval never sees a final broadcast, so the job remains active until walltime. Trainer and online-eval log to one shared W&B run. The trainer creates it, and online-eval finalizes it.
### SFT-Specific Knobs
@@ -331,7 +332,7 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
├── orchestrator.log # single instance, single file
├── evals.log # SFT online-eval process
├── eval.log # `uv run eval` process, or the SFT online-eval process
├── inference.log # symlink → inference/node_0.log on multi-node
├── trainer/
│ ├── node_*.log # per-node trainer stdout (multi-node only)
@@ -347,7 +348,7 @@ Env logs are the first place to look for env-side errors (most user code lives t
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
```bash
tail -F <run_dir>/logs/latest/{trainer,orchestrator,evals,inference}.log
tail -F <run_dir>/logs/latest/{trainer,orchestrator,eval,inference}.log
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
```
+1 -2
View File
@@ -19,7 +19,7 @@ All advanced configs submit through SLURM (the `rl` entrypoint writes the sbatch
Walk-throughs for the core environments (baseline eval → optional SFT warmup → RL → eval), each with its own README:
- [`reverse-text/`](basic/reverse-text/README.md) — smallest end-to-end loop (single-turn, 0.6B)
- [`reverse-text/`](basic/reverse-text/README.md) — smallest end-to-end loop (single-turn, 0.6B): `eval.toml` → `sft.toml` → `rl.toml`
- [`alphabet-sort/`](basic/alphabet-sort/README.md) — multi-turn, user simulator, LoRA
- [`wiki-search/`](basic/wiki-search/README.md) — multi-turn tool calling, LoRA
- [`wordle/`](basic/wordle/README.md) — multi-turn (~6-turn games)
@@ -35,5 +35,4 @@ Examples that don't follow the basic eval → SFT → RL walk-through pattern:
## Related config folders
- Frontier-model configs without launch walkthroughs (`minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`) live in [`configs/advanced/`](../configs/advanced).
- Standalone eval configs live in [`configs/evals/`](../configs/evals).
- Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
+2 -16
View File
@@ -39,14 +39,7 @@ uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507
Evaluate the base model:
```bash
# Run this in the other terminal
uv run eval alphabet-sort --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
-n 20 \
-r 3 \
--sampling.max-tokens 768 \
--args '{"min_turns": 3, "max_turns": 3, "min_names_per_turn": 1, "max_names_per_turn": 4, "task": {"similarity_power": 8, "power_per_turn": false}}' \
--no-push
uv run eval @ examples/basic/alphabet-sort/eval.toml
```
We got an **average reward of ~0.26** across 20×3 rollouts. The model achieves **0% perfect attempts** (no rollouts score 1.0) and **0% perfect examples** (no examples have all 3 rollouts at 1.0). The model shows high variance and struggles on most examples, with the high similarity power (8) heavily penalizing even small errors, and the scores aren't different for most attempts.
@@ -113,14 +106,7 @@ uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruc
```bash
# Run this in the other terminal
uv run eval alphabet-sort --harness.id null \
-m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL \
--client.base-url http://localhost:8000/v1 \
-n 20 \
-r 3 \
--sampling.max-tokens 768 \
--args '{"min_turns": 3, "max_turns": 3, "min_names_per_turn": 1, "max_names_per_turn": 4, "task": {"similarity_power": 8, "power_per_turn": false}}' \
--no-push
uv run eval @ examples/basic/alphabet-sort/eval.toml -m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
```
Way better! Our model now gets an **average reward of ~0.81** with **73% perfect attempts** (44/60 rollouts score 1.0) and **65% perfect examples** (13/20 examples have all 3 rollouts at 1.0).
+24
View File
@@ -0,0 +1,24 @@
# Evaluate a model on alphabet-sort against a local inference server
# (`uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507`).
# Override the model with `-m` to evaluate a trained checkpoint.
#
# uv run eval @ examples/basic/alphabet-sort/eval.toml
model = "Qwen/Qwen3-4B-Instruct-2507"
num_examples = 20
group_size = 3
[client]
base_url = "http://localhost:8000/v1"
[sampling]
max_completion_tokens = 768
[[source]]
name = "alphabet-sort"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+4 -5
View File
@@ -27,7 +27,7 @@ uv run inference --vllm.model Qwen/Qwen3-0.6B
```bash
# Run this in the other terminal
uv run eval reverse-text --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval @ examples/basic/reverse-text/eval.toml
```
This is of course just a quick vibe check and no full-fledged evaluation, but we can see that the model struggles with this task. In this specific instance, we got an **average reward of ~0.05** across the 20x3 rollouts. Let's do some training!
@@ -94,7 +94,7 @@ uv run inference --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
```bash
# Run this in the other terminal
uv run eval reverse-text --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval @ examples/basic/reverse-text/eval.toml -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
```
Way better! Now we get an **average reward of ~0.8**.
@@ -197,10 +197,9 @@ kubectl exec -it my-exp-inference-0 -- bash
uv run inference --vllm.model /data/outputs/weights_hf/step_20
# Back in trainer pod, run evaluation
uv run eval reverse-text --harness.id null \
uv run eval @ examples/basic/reverse-text/eval.toml \
-m /data/outputs/weights_hf/step_20 \
--client.base-url $INFERENCE_URL \
-n 20 -r 3 --sampling.max-tokens 1024 --no-push
--client.base-url $INFERENCE_URL
```
### Clean Up
+21
View File
@@ -0,0 +1,21 @@
# Evaluate a model on reverse-text against a local inference server
# (`uv run inference --vllm.model Qwen/Qwen3-0.6B`). Override the model
# with `-m` to evaluate a trained checkpoint.
#
# uv run eval @ examples/basic/reverse-text/eval.toml
model = "Qwen/Qwen3-0.6B"
num_examples = 20
group_size = 3
[client]
base_url = "http://localhost:8000/v1"
[sampling]
max_completion_tokens = 1024
[[source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+2 -14
View File
@@ -77,13 +77,7 @@ Evaluate the base model:
```bash
# Run this in the other terminal
uv run eval wiki-search --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
-n 20 \
-r 3 \
--sampling.max-tokens 512 \
--no-push
uv run eval @ examples/basic/wiki-search/eval.toml
```
## RL Training
@@ -116,13 +110,7 @@ uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSe
```bash
# Run this in the other terminal
uv run eval wiki-search --harness.id null \
-m <user>/Qwen3-4B-Instruct-WikiSearch-RL \
--client.base-url http://localhost:8000/v1 \
-n 20 \
-r 3 \
--sampling.max-tokens 512 \
--no-push
uv run eval @ examples/basic/wiki-search/eval.toml -m <user>/Qwen3-4B-Instruct-WikiSearch-RL
```
## Taskset Configuration
+21
View File
@@ -0,0 +1,21 @@
# Evaluate a model on wiki-search against a local inference server
# (`uv run inference --vllm.model Qwen/Qwen3-4B-Instruct-2507 --vllm.tool-call-parser hermes`).
# Override the model with `-m` to evaluate a trained checkpoint.
#
# uv run eval @ examples/basic/wiki-search/eval.toml
model = "Qwen/Qwen3-4B-Instruct-2507"
num_examples = 20
group_size = 3
[client]
base_url = "http://localhost:8000/v1"
[sampling]
max_completion_tokens = 512
[[source]]
name = "wiki-search"
env.taskset.id = "wiki-search"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+2 -2
View File
@@ -29,7 +29,7 @@ Then, use the `eval` entrypoint to evaluate the model in the `wordle` environmen
```bash
# Run this in the other terminal
uv run eval wordle --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval @ examples/basic/wordle/eval.toml
```
We got an **average reward of ~0.2** across the 20x3 rollouts. From the summary, we can see that the most of the reward is coming from format and partial rewards. In fact, the model does not guess the correct word within any game, leading to a win rate of **0%**. Looking at some samples, it is evident repeatedly submitting guesses in the wrong format and is not able to revise its strategy from the environment feedback. Let's do some SFT warmup to get the model to learn the format of the environment.
@@ -97,7 +97,7 @@ uv run inference --vllm.model PrimeIntellect/Qwen3-1.7B-Wordle-RL
```bash
# Run this in the other terminal
uv run eval wordle --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval @ examples/basic/wordle/eval.toml -m PrimeIntellect/Qwen3-1.7B-Wordle-RL
```
Way better! Our model now wins **~60%** and gets an average reward of **~1.5**.
+21
View File
@@ -0,0 +1,21 @@
# Evaluate a model on wordle against a local inference server
# (`uv run inference --vllm.model Qwen/Qwen3-1.7B`). Override the model
# with `-m` to evaluate a trained checkpoint.
#
# uv run eval @ examples/basic/wordle/eval.toml
model = "Qwen/Qwen3-1.7B"
num_examples = 20
group_size = 3
[client]
base_url = "http://localhost:8000/v1"
[sampling]
max_completion_tokens = 1024
[[source]]
name = "wordle"
env.taskset.id = "wordle"
env.player.harness.id = "null"
env.player.runtime.type = "subprocess"
@@ -9,8 +9,8 @@ from prime_rl.utils.config import BaseConfig, default_output_dir
class EnvServerConfig(BaseConfig):
"""``uv run env-server``: what to serve (``[env]``) and how it's hosted (``[serve]``).
The ``rl`` launcher writes one of these per train/eval source, with ``serve.address``
set to the source's derived address."""
The launchers write one of these per train/eval source they manage, with
``address_file`` set: the server binds an OS-assigned port and publishes it there."""
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
"""The environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
@@ -18,6 +18,11 @@ class EnvServerConfig(BaseConfig):
serve: vf.ServeConfig = vf.ServeConfig()
"""How it's served: the worker pool, the bind address, each worker's episode bound."""
address_file: Path | None = None
"""Publish the bound address to this file once serving. Set by the launchers for the
servers they spawn, so the address never has to be agreed on up front (``serve.address``
unset binds an OS-assigned port)."""
log: LogConfig = LogConfig()
output_dir: Path = Field(default_factory=default_output_dir)
@@ -0,0 +1,155 @@
import uuid
from pathlib import Path
from pydantic import AliasChoices, Field, model_validator
from prime_rl.configs.monitors import EvalMonitorsConfig, MonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig, RunConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.utils.config import default_output_dir
class ServedEvalConfig(EvalSourcesConfig):
"""Eval sources run against a live inference server: the server's client and the
adaptive concurrency band."""
client: ClientConfig = ClientConfig()
"""Client of the inference server evals run against."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight episode concurrency, sized by the same controller as
``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it."""
@property
def env_addresses(self) -> dict[tuple[str, str], str | None]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: an explicit ``serve.address``
is an externally managed server; None means the launcher spawns the server and the
eval learns its address from the file it publishes."""
return {("eval", source.resolved_name): source.serve.address for source in self.source}
PRIME_INFERENCE_URL = "https://api.pinference.ai/api/v1"
class EvalConfig(ServedEvalConfig):
"""``uv run eval``: evaluate the configured sources once against a live inference
server, then exit. Every source's env server is spawned by the eval process unless
the source sets ``serve.address``. Defaults to Prime Inference (``PRIME_API_KEY`` or
``prime login``) with the concurrency pinned at 128."""
model: str = Field("deepseek/deepseek-v4.1-flash", validation_alias=AliasChoices("model", "m"))
"""Model id — the ``model`` field of every eval request and the startup model check."""
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
"""Client of the inference server. Defaults to Prime Inference."""
concurrency: ConcurrencyConfig = ConcurrencyConfig(min_inflight=128, max_inflight=128)
"""In-flight episodes, pinned at 128 (``-c N`` repins). External APIs expose no vLLM
``/metrics`` to adapt to; against a vLLM server set ``min_inflight < max_inflight`` to
let the band adapt to KV usage like the orchestrator's."""
num_examples: int = Field(-1, validation_alias=AliasChoices("num_examples", "n"))
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "r"))
"""Default rollouts per example. Can be overridden per env."""
run: RunConfig = Field(default_factory=RunConfig)
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory that groups related runs. Each run writes its artifacts (traces, logs,
checkpoints) to ``output_dir / run.name``. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
clean: bool = False
"""Delete the run directory (``output_dir / run.name``) before starting. Required to
overwrite a run directory that contains artifacts from a previous run when not resuming."""
dry_run: bool = False
"""Resolve and write the config, then exit without evaluating."""
dashboard: bool = True
"""Start (or reuse) the local dashboard daemon and print its URL."""
resume: bool = False
"""Continue the interrupted run named by ``run.name`` from its trace stream: the
landed episodes rejoin the epoch and only the rollouts still owed run. The model,
sampling and env config must match the interrupted run; ``num_examples`` and
``group_size`` may change."""
log: LogConfig = LogConfig()
monitors: EvalMonitorsConfig = EvalMonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
@property
def run_dir(self) -> Path:
assert self.run.dir is not None # resolved at construction
return self.output_dir / self.run.dir
@model_validator(mode="after")
def auto_setup_run_identity(self):
"""Auto-generate the run name (``<envs>--<model>--<short-id>``) when unset and
default the run directory, W&B run name and platform evaluation name to it."""
if self.run.name is None:
envs = "+".join(dict.fromkeys(source.resolved_name for source in self.source))
model = self.model.split("/")[-1]
self.run.name = f"{envs}--{model}--{uuid.uuid4().hex[:8]}".lower()
if self.run.dir is None:
self.run.dir = self.run.name
if self.monitors.wandb is not None and self.monitors.wandb.name is None:
self.monitors.wandb.name = self.run.name
if self.monitors.prime is not None and self.monitors.prime.name is None:
self.monitors.prime.name = self.run.name
return self
class SFTOnlineEvalConfig(ScheduledEvalConfig, ServedEvalConfig):
"""The ``[eval]`` block of the ``sft`` entrypoint, and the config of the online-eval
process the launcher spawns from it: interval-driven eval sources against the inference
server that receives the trainer's weight broadcasts. The process watches the
broadcasts directory, moves the inference server onto each broadcast, and runs the
due sources against the updated weights. The launcher fills the run-level fields
(``model``, ``weight_broadcast``, ``broadcasts_dir``, ``max_steps``, ``resume_step``,
``output_dir``, ``log``, ``monitors``) from the resolved SFT config."""
cancel_on_new_checkpoint: bool = True
"""Cancel unfinished episodes when a newer trainer checkpoint is ready. Disable to
finish every triggered eval epoch before loading later weights. The trainer can idle
while it waits for slow evals."""
model: str | None = None
"""Name the inference server serves the model under. The name stays fixed across
weight updates (weights are swapped in place), so per-step results are told apart by
``eval/{env}/policy_version``."""
weight_broadcast: WeightBroadcastConfig | None = None
"""Weight transport. None reloads weights from the filesystem broadcasts."""
broadcasts_dir: Path | None = None
"""Directory to watch for ``step_{n}`` weight broadcasts. Defaults to
``<output_dir>/broadcasts``."""
max_steps: int | None = None
"""Trainer step at which the run ends. The final checkpoint always fires every eval
env, and the process exits after processing it. If None, runs until terminated."""
resume_step: int | None = None
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
skipped; set ``retrigger_on_resume`` to re-fire interval-aligned evals at this step."""
output_dir: Path = Field(default_factory=default_output_dir)
"""The run directory, shared with the trainer. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
@model_validator(mode="after")
def auto_setup_broadcasts_dir(self):
if self.broadcasts_dir is None:
self.broadcasts_dir = self.output_dir / "broadcasts"
return self
@@ -1,141 +0,0 @@
from pathlib import Path
from pydantic import Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig, ResumeConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.utils.config import BaseConfig, default_output_dir
class EvalsEvalConfig(EvalConfig):
"""Evals against a live inference server. Extends the orchestrator ``EvalConfig``
(sources, sampling, intervals) with the client of the inference deployment and
evals-side knobs."""
client: ClientConfig = ClientConfig()
"""Client of the inference server evals run against. Auto-wired from the
``[inference]`` block when the launcher manages the server."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the eval source at position ``i`` is
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
keep it instead, without shifting the other sources' ports."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
cancel_on_new_checkpoint: bool = True
"""For online evals, cancel unfinished episodes when a newer trainer checkpoint is ready.
Disable to finish every triggered eval epoch before loading later weights. The trainer can
idle while it waits for slow evals."""
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: sources with an explicit
``serve.address`` are externally managed; the evals process spawns an env server at
the derived address for every other source."""
return {
("eval", source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, source in enumerate(self.source)
}
class OnlineConfig(BaseConfig):
"""Broadcast-driven online evals: watch a broadcasts directory for new weight
broadcasts and evaluate each eligible one. Without this block the evals process runs
every eval source once against the weights the inference server currently serves,
then exits."""
broadcasts_dir: Path | None = None
"""Directory to watch for ``step_{n}`` weight broadcasts. Defaults to
``<output_dir>/broadcasts``."""
max_steps: int | None = None
"""Trainer step at which the run ends. The final checkpoint always fires every
eval env, and the evals process exits after processing it. If None, the evals process
runs until terminated."""
resume_step: int | None = None
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
this step."""
class CheckpointConfig(BaseConfig):
"""Checkpoint progress for an interruptible standalone eval run."""
interval: int = Field(1, ge=1)
"""Save after the task cursor advances by N completed groups."""
class EvalsConfig(BaseConfig):
"""``uv run evals``: run the configured evals against a live inference server.
Standalone (no ``[online]``), one epoch of every eval source runs against the
served weights and the evals process exits. With ``[online]``, the evals process watches a
broadcasts directory for new weight broadcasts, updates the inference server through
the configured transport, and runs the configured evals against the updated weights.
The ``sft`` launcher writes this config; filesystem mode also works standalone against
any trainer that writes ``broadcasts/step_{n}`` directories with ``STABLE`` markers."""
model: str = "Qwen/Qwen3-0.6B"
"""Name the inference server serves the model under — the ``model`` field of every
eval request and the startup model check. Auto-filled from ``model.name`` by the
``sft`` launcher; the name stays fixed across weight updates (weights are
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
eval: EvalsEvalConfig
"""Eval sources, sampling, intervals, concurrency, and the inference client."""
online: OnlineConfig | None = None
"""Checkpoint watching (``[online]``). None runs the evals once and exits."""
weight_broadcast: WeightBroadcastConfig | None = None
"""Weight transport for online evals. The ``sft`` launcher fills this from its
resolved trainer transport. None uses filesystem reloads."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer for online evals. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
ckpt: CheckpointConfig | None = None
"""Checkpoint standalone eval progress. Checkpoint steps are task cursor positions."""
resume: ResumeConfig | None = None
"""Resume a standalone eval run from a cursor checkpoint. A bare block loads the latest checkpoint."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
@model_validator(mode="after")
def auto_setup_broadcasts_dir(self):
if self.online is not None and self.online.broadcasts_dir is None:
self.online.broadcasts_dir = self.output_dir / "broadcasts"
return self
@model_validator(mode="after")
def validate_skip_first_step_is_online_only(self):
"""``skip_first_step`` gates the base-model eval between checkpoints; a
standalone run has only that one epoch, so skipping it would exit
successfully without evaluating anything."""
if self.online is None and self.eval.skip_first_step:
raise ValueError(
"eval.skip_first_step only applies to online evals - a standalone run "
"would skip its only eval epoch. Remove it or add an [online] block."
)
return self
@model_validator(mode="after")
def validate_checkpointing_is_standalone_only(self):
if self.online is not None and (self.ckpt is not None or self.resume is not None):
raise ValueError(
"evals ckpt/resume only supports standalone evals - online evals are coordinated "
"with the trainer's live weight-broadcast lifecycle"
)
return self
@@ -43,11 +43,16 @@ class FileMonitorConfig(BaseConfig):
not the records, so this only trades record size against overlay precision."""
class PrimeMonitorConfig(BaseConfig):
class PrimeTrainMonitorConfig(BaseConfig):
name: str | None = None
"""Run name shown on the platform. Inherits ``run.name`` when unset."""
class PrimeEvalMonitorConfig(BaseConfig):
name: str | None = None
"""Evaluation name shown on the platform. Inherits ``run.name`` when unset."""
class MonitorsConfig(BaseConfig):
wandb: WandbMonitorConfig | None = None
"""Log metrics to Weights & Biases. Off by default; enable with ``--monitors.wandb``."""
@@ -56,6 +61,11 @@ class MonitorsConfig(BaseConfig):
"""Log metrics and episode traces to the run's output directory. On by default; disable with ``--no-monitors.file``."""
class OrchestratorMonitorsConfig(MonitorsConfig):
prime: PrimeMonitorConfig | None = None
class TrainMonitorsConfig(MonitorsConfig):
prime: PrimeTrainMonitorConfig | None = None
"""Log metrics and episodes to the Prime Intellect platform. If None, disabled."""
class EvalMonitorsConfig(MonitorsConfig):
prime: PrimeEvalMonitorConfig | None = None
"""Upload every eval source's finished epoch as an evaluation on the Prime Intellect platform. If None, disabled."""
@@ -10,7 +10,7 @@ from prime_rl.configs.algorithm import (
AlgoConfig,
GRPOAlgoConfig,
)
from prime_rl.configs.monitors import OrchestratorMonitorsConfig
from prime_rl.configs.monitors import TrainMonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
BaseWeightBroadcastConfig,
@@ -161,14 +161,11 @@ class EnvConfig(BaseConfig):
"""The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
serve: vf.ServeConfig = vf.ServeConfig()
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config with an unset ``address`` filled in as the derived ``tcp://127.0.0.1:<env_server_base_port + index>``. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config; an unset ``address`` means the spawned server binds an OS-assigned port and publishes it for the orchestrator. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
name: str | None = None
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
ratio: float = Field(1.0, gt=0)
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
@model_validator(mode="before")
@classmethod
def _resolve_env(cls, data):
@@ -269,6 +266,9 @@ class TrainSourceConfig(EnvConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
ratio: float = Field(1.0, gt=0)
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
group_size: int = Field(1, ge=1)
"""Rollouts generated per example for GRPO group-relative advantages.
Inherits from ``orchestrator.group_size`` when unset."""
@@ -293,6 +293,10 @@ class EvalSourceConfig(EnvConfig):
group_size: int = Field(1, ge=1)
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8)."""
class OnlineEvalSourceConfig(EvalSourceConfig):
"""An eval source of a training run: evaluated on a step interval."""
interval: int = Field(100, ge=1)
"""Per-env eval interval. If unset, inherits from the group-level eval interval."""
@@ -328,7 +332,9 @@ class TrainConfig(BaseConfig):
return self
class EvalConfig(BaseConfig):
class EvalSourcesConfig(BaseConfig):
"""Eval sources and the group-level defaults they inherit."""
source: list[EvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources."""
@@ -341,6 +347,49 @@ class EvalConfig(BaseConfig):
group_size: int = Field(1, ge=1)
"""Default rollouts per example. Can be overridden per env."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_examples and
group_size (the worker ``pool`` is configured per env, default elastic)."""
group_sampling = self.sampling.model_dump()
for source in self.source:
if "sampling" not in source.model_fields_set:
source.sampling = EvalSamplingConfig(**group_sampling)
else:
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
source.sampling = EvalSamplingConfig(**merged)
if "num_examples" not in source.model_fields_set:
source.num_examples = self.num_examples
if "group_size" not in source.model_fields_set:
source.group_size = self.group_size
return self
@model_validator(mode="after")
def validate_non_empty_sources(self):
if not self.source:
raise ValueError(
"At least one eval source is required. Add a source block "
"(e.g. [[source]] or [[orchestrator.eval.source]]) or drop the eval block entirely to disable eval."
)
return self
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [source.resolved_name for source in self.source]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(
f"Duplicate evaluation environment names: {set(duplicates)}. Each env must have a unique name."
)
return self
class ScheduledEvalConfig(EvalSourcesConfig):
"""Eval sources evaluated on a step interval next to training."""
source: list[OnlineEvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources, each with its own step interval."""
interval: int = Field(100, ge=1)
"""Step interval at which to evaluate the model."""
@@ -354,43 +403,22 @@ class EvalConfig(BaseConfig):
exit where all evals already completed."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
group_sampling = self.sampling.model_dump()
def resolve_env_intervals(self):
"""Per-env intervals inherit the group-level interval."""
for source in self.source:
if "sampling" not in source.model_fields_set:
source.sampling = EvalSamplingConfig(**group_sampling)
else:
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
source.sampling = EvalSamplingConfig(**merged)
if "num_examples" not in source.model_fields_set:
source.num_examples = self.num_examples
if "group_size" not in source.model_fields_set:
source.group_size = self.group_size
if "interval" not in source.model_fields_set:
source.interval = self.interval
return self
@model_validator(mode="after")
def validate_non_empty_sources(self):
if not self.source:
raise ValueError(
"EvalConfig must define at least one source. Either drop the "
"[orchestrator.eval] block entirely (to disable eval) or "
"add a [[orchestrator.eval.source]] block."
)
return self
@property
def intervals(self) -> dict[str, int]:
"""Step interval per eval env, by resolved name."""
return {source.resolved_name: source.interval for source in self.source}
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [source.resolved_name for source in self.source]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(
f"Duplicate evaluation environment names: {set(duplicates)}. Each env must have a unique name."
)
return self
class RLOnlineEvalConfig(ScheduledEvalConfig):
"""The ``[orchestrator.eval]`` block: online evals against the orchestrator's
inference pool, on the policy the train rollouts see."""
class CheckpointConfig(BaseConfig):
@@ -510,7 +538,7 @@ class OrchestratorConfig(BaseConfig):
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. RL/OPD roll out through the renderer
client; SFT uses it to backfill tokens for its chat-completions teacher."""
eval: EvalConfig | None = None
eval: RLOnlineEvalConfig | None = None
"""Evaluation configuration."""
log: LogConfig = LogConfig()
@@ -518,7 +546,7 @@ class OrchestratorConfig(BaseConfig):
env_vars: EnvVars = {}
"""Extra environment variables for the orchestrator process(es). Merged on top of the launcher defaults."""
monitors: OrchestratorMonitorsConfig = OrchestratorMonitorsConfig()
monitors: TrainMonitorsConfig = TrainMonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
collect_inference_metrics: bool = True
@@ -545,9 +573,6 @@ class OrchestratorConfig(BaseConfig):
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the source at position ``i`` (train, then eval) is served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address`` keep it instead, without shifting the other sources' ports (indices stay positional). Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
batch_size: int | None = Field(None, ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
@@ -770,15 +795,9 @@ class OrchestratorConfig(BaseConfig):
return sources
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each source's env server lives, keyed by ``(split, resolved_name)``:
the source's own ``serve.address`` when set (an externally managed server), else
``tcp://127.0.0.1:<port>`` with ports from ``env_server_base_port`` in
``env_sources`` order. The launcher binds env servers at exactly these addresses
and the orchestrator connects to them, so both sides agree from the config
alone."""
return {
(split, source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, (split, source) in enumerate(self.env_sources)
}
def env_addresses(self) -> dict[tuple[str, str], str | None]:
"""Where each source's env server lives, keyed by ``(split, resolved_name)``: the
source's own ``serve.address`` when set (an externally managed server), else None —
the launcher spawns the server, which binds an OS-assigned port and publishes it
to the source's address file for the orchestrator to pick up."""
return {(split, source.resolved_name): source.serve.address for split, source in self.env_sources}
@@ -7,7 +7,7 @@ from pydantic import Field, model_validator
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig
from prime_rl.configs.monitors import FileMonitorConfig, PrimeTrainMonitorConfig
from prime_rl.configs.orchestrator import (
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
)
@@ -102,7 +102,7 @@ class SharedMonitorsConfig(BaseConfig):
file: FileMonitorConfig | None = None
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/monitors/file/metrics.jsonl`` on both trainer and orchestrator."""
prime: PrimeMonitorConfig | None = None
prime: PrimeTrainMonitorConfig | None = None
"""Prime platform monitor. Propagated to the orchestrator only — the trainer has no platform integration."""
@@ -8,7 +8,7 @@ from pydantic import AliasChoices, Field, model_validator
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
from renderers.base import MODEL_RENDERER_MAP
from prime_rl.configs.evals import EvalsEvalConfig
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
@@ -203,7 +203,7 @@ class SFTConfig(BaseConfig):
val: SFTValConfig | None = None
"""Validation configuration. If None, no validation runs."""
eval: EvalsEvalConfig | None = None
eval: SFTOnlineEvalConfig | None = None
"""Online evaluation configuration: rollout-based evals against a live inference
server that receives the trainer's weight broadcasts. If None, no online evals run."""
@@ -437,7 +437,7 @@ class SFTConfig(BaseConfig):
"Online evals are configured without an [inference] block - the launcher will not "
f"start an inference server. Make sure one is running at eval.client.base_url "
f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', "
"otherwise the evals process will hang waiting for it. If a router fronts the "
"otherwise the online-eval process will hang waiting for it. If a router fronts the "
"deployment, set eval.client.admin_base_url to the engine URLs - admin ops "
"(pause/update_weights/resume) must bypass the router.",
stacklevel=2,
+2 -1
View File
@@ -24,6 +24,7 @@ dependencies = [
"openai>=1.106.1",
"orjson>=3.11.0",
"psutil>=7.0.0",
"prometheus-client>=0.20.0",
"pyzstd>=0.16.2",
"rich>=14.0.0",
"setproctitle>=1.3.0",
@@ -42,7 +43,7 @@ sft = "prime_rl.entrypoints.sft:main"
inference = "prime_rl.entrypoints.inference:main"
trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
evals = "prime_rl.entrypoints.evals:main"
eval = "prime_rl.entrypoints.eval:main"
env-server = "prime_rl.entrypoints.env_server:main"
dashboard = "prime_rl.entrypoints.dashboard:main"
+2 -2
View File
@@ -63,9 +63,9 @@ env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text` or `--orchestrator.eval.source.0.env.taskset.id reverse-text`.
Source lists are set in TOML. The CLI has no list-index paths (`--orchestrator.eval.source.0.env.taskset.id` does not parse); a whole list can be passed as JSON (`--orchestrator.eval.source '[{"env": {"taskset": {"id": "reverse-text"}}}]'`), which replaces the list wholesale.
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server), e.g. `--eval.source.0.env.taskset.id reverse-text`.
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server). The `eval` entrypoint flattens it further: `[[source]]`, `[client]`, `[concurrency]`, `num_examples`, `group_size` at the top level, plus the single-source shorthands `uv run eval <taskset-id> --env.<field> <value> -n N -r N -c N -m MODEL` (see the `eval` skill).
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
+20 -136
View File
@@ -5,164 +5,48 @@ description: Find, start, use, and stop the local run dashboard for metrics, con
# Run dashboard
`uv sync --extra dashboard && uv run dashboard [output_dir ...]` (default
`outputs/`, or `$PRL_OUTPUT_DIR` if set) serves a web UI at `http://localhost:7788`. It only reads run
dirs — safe against live runs — and installs anywhere (cluster head node,
laptop against a mounted outputs dir): GPU dependencies live behind the
`gpu` extra.
`uv sync --extra dashboard && uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR`) serves a web UI at `http://localhost:7788`. It only reads run dirs, so it is safe against live runs and installs anywhere: GPU dependencies live behind the `gpu` extra.
The Config and Logs views default to `latest (attempt <n>)`. Select an attempt
to inspect the immutable config or log files from an earlier launch. The Config
view shows a copyable launch command above the launch TOML or resolved JSON.
What is not obvious from the UI:
The trace viewer has separate **Transcript**, **Timeline**, **Replay**, and
**Semantic** views. Timeline is a wall-clock Gantt of physical prefix branches.
Replay renders the selected agent branch as a terminal session with play/pause,
seek, restart, and speed controls. It preserves recorded model-call and
tool-result delays. Since the trace schema records a complete model-call span
but no per-token timestamps, response text is paced evenly across that measured
span and labeled as inferred; events without timestamps remain ordered and are
labeled untimed. Semantic projects Verifiers `MessageNode.semantic_parents` as a
top-to-bottom causal graph of model calls, including subagent calls, returns,
compactions, and custom edge types. Calls occupy compact causal ranks within
bounded agent lanes: the root stays centered, concurrent children fan out
symmetrically, and child slots are reused after return, so graph width reflects
peak agent concurrency rather than total subagents. Compaction starts a visibly
separate context segment. For display only, a missing continuation is recovered
when the physical parent chain proves a completed tool round-trip; fragments
that still cannot be placed are shown explicitly as unlinked instead of being
presented as contexts. Hover or click an agent or context label to see its
latest and peak prompt lengths first, followed by cumulative token processing
and cost. Exact timing remains available on model-call hover and in Timeline.
Traces without semantic parents keep the other views and disable Semantic.
- Config and Logs default to `latest (attempt <n>)`; select an attempt to inspect an earlier launch. The Config view shows a copyable launch command.
- Trace viewer views: **Transcript**, **Timeline** (wall-clock Gantt of prefix branches), **Replay** (the branch as a terminal session; response text is paced evenly across the recorded model-call span and labelled inferred; default 8×; **Skip inference** collapses model calls but keeps tool delays; **T** toggles thinking, never advertise Ctrl+T) and **Semantic** (`semantic_parents` as a causal graph of model calls; width reflects peak agent concurrency; unplaceable fragments show as unlinked). Traces without semantic parents disable Semantic.
- Live rollouts appear in the traces table with a pulsing dot and a phase badge, and open in the viewer, which follows them (pinned to the newest turn until you scroll up; the request in flight's uncommitted messages render dimmed as `awaiting model`). They come from `monitors/file/traces/live/*.jsonl`, polled once a second.
- For an eval run the metrics tab shows one env at a time (filter → env, `include errors`): a block progress bar (one cell per expected episode, from `monitors/file/plan.json`), summary tiles (avg@k, pass@k, error and truncation rate coloured >10% yellow / >50% red, turns / branches, episode time, tokens, cost), env metrics as dot plots or beeswarms (hover a dot for its episode, click to open it; hover the background for the quantiles), and usage / timing composition panes (icicle of the mean split over per-episode strips; `other` is wall time no phase accounts for; hover a part to dim the rest; 40 strips by default, `show all` for every one).
- `view on platform` in the top bar links to the run on the Prime platform when `--monitors.prime` was on (`monitors/prime/run.json`); an eval's evaluation opens at epoch start, so the link is live from the first episode.
- An eval reads `completed` once its stream is sealed by a clean exit; a crashed or interrupted one reads `stopped` after its files go quiet.
Replay defaults to 8× so long coding-agent model waits remain watchable; select
1× for exact wall time or up to 32× for faster review. In-flight calls display
their measured progress and recorded output-token usage even when they produce
only tool calls. Enable **Skip inference** to collapse model calls to immediate
responses while preserving the recorded command-to-tool-output delays. This is
distinct from the speed control, which scales every delay uniformly. Recorded
model thinking is shown by default. Toggle **Thinking** in the replay controls
or press **T** while Replay is open to hide or show it without changing playback
timing. Do not advertise Ctrl+T: browsers reserve it for a new tab before the
page can handle the keypress. Use **Top** or the **Home** key to scroll to the
beginning without pausing the replay. Use **Live** or **End** to resume
following newly rendered output. Prompt-context nodes that were committed at
response time are placed at the linked call's start so their serialization
timestamp does not create a false blank wait before the replay.
Every dashboard instance serves the dirs it was started with plus every dir in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`). Launchers register their output dir on every start and, in interactive sessions, auto-start a dashboard only when none is live; `--no-dashboard` opts a run out, non-interactive launches never spawn one. `--isolated` serves only the given dirs and ignores the registry.
Every dashboard instance serves the dirs it was started with **plus** every dir
in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`, re-read
live). Launchers (`rl`, `sft`) register their output dir on every
start and, in interactive sessions, auto-start a dashboard only when none is
live — an already-running one absorbs the new dir automatically, whatever port
it is on. `--no-dashboard` opts a run out; non-interactive launches (CI, nohup)
register their dir but never spawn.
## Finding, stopping, restarting
## Isolated mode
`--isolated` serves only the given dirs: no registry read or write, no
discovery claim, and launchers ignore the instance. Use it for focused views
(demos, debugging one run dir) or to keep a scratch dir out of the registry.
## Finding the live dashboard
The live port can differ from 7788 (a taken port bumps to the next free one),
so read the discovery file:
The port can differ from 7788 (a taken port bumps to the next free one), so read the discovery file and hand the researcher its `url`; launcher logs also end with a `Dashboard · <url>` banner.
```bash
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
curl -sf $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/runs > /dev/null && echo live
ps aux | grep PRL::Dashboard # process title
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<port>"}
kill $(jq -r .pid ~/.cache/prime-rl/dashboard/daemon.json) # stop; the next launch (or `uv run dashboard`) restarts it
```
Hand the researcher the `url` from `daemon.json`. Launcher logs also print it:
startup ends with a `Dashboard · <url>` banner. The auto-started instance logs
to `~/.cache/prime-rl/dashboard/daemon.log`.
## Stopping / restarting
```bash
kill $(jq -r .pid ~/.cache/prime-rl/dashboard/daemon.json) # the discovered instance
pkill -f PRL::Dashboard # every dashboard on the host
```
A clean exit releases `daemon.json`; a stale file from a dead process is taken
over by the next start. Killing a dashboard never affects runs (it only reads),
and killing a run never takes the dashboard down (it runs in its own session).
Restart by launching any run, or directly: `uv run dashboard`.
Killing a dashboard never affects runs and killing a run never takes the dashboard down. The daemon serves the code of the checkout that started it (`readlink /proc/<pid>/cwd`): after switching branches or worktrees, kill it so the next launch restarts it on the current code. Its log is `~/.cache/prime-rl/dashboard/daemon.log`.
## Point the open dashboard
Use `POST /api/view` to show relevant run data in every connected dashboard
tab:
`POST /api/view` shows run data in every connected tab. `run` is required; the other fields leave unspecified state alone. For trace evidence pass `step`, `kind` and `subset` together and address the episode by its stable `id` (`subset: "effective"` narrows the traces tab to the cohort shipped at that step); `highlight` entries are `{node, quote, reason, field?}`. On `409`, tell the user to open the returned `url`.
```bash
curl -sS -X POST $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/view \
-H 'content-type: application/json' -d '{
"run": "demo-rl", "tab": "traces",
"step": 0, "kind": "train", "subset": "effective",
"episode": "ep-s00-reverse-text-0",
"highlight": [{"node": 3, "quote": "hint: reverse the words", "reason": "tool result the policy conditioned on"}]
}'
-H 'content-type: application/json' -d '{"run": "demo-rl", "tab": "traces", "step": 0, "kind": "train", "subset": "effective",
"episode": "ep-s00-reverse-text-0", "highlight": [{"node": 3, "quote": "hint: reverse the words", "reason": "the tool result the policy conditioned on"}]}'
```
`run` is required; other fields are optional and leave unspecified UI state
unchanged. For trace evidence, supply `step`, `kind`, and `subset` together and
address the episode by stable `id`. The traces tab opens on the whole stream;
`subset: "effective"` switches it to the cohort that shipped at one step. Use
optional `trace` and `branch` indices
for multi-agent traces and `highlight` entries shaped as `{node, quote,
reason, field?}`. On `409`, tell the user to open the returned `url`; the stored
command applies when the tab connects.
## Reports, only when asked
## Write a report only when asked
Create a report only when the user explicitly asks for one. Otherwise answer
normally; use `/api/view` when showing trace evidence would help.
Write requested reports to `<run>/reports/<slug>.md`, then POST `{"run": ...,
"tab": "report", "report": "<slug>"}`. Use Markdown with a frontmatter
`title` and one-line JSON citation definitions:
Write a requested report to `<run>/reports/<slug>.md`, then POST `{"run": ..., "tab": "report", "report": "<slug>"}`. Markdown with a frontmatter `title` (rendered as the H1, do not repeat it) and one-line JSON citations:
```markdown
---
title: Why does reward dip at step 4?
---
The dip is provider errors, not policy regression [^err].
[^err]: {"step": 4, "kind": "train", "subset": "all", "episode": "ep-...", "node": 0, "quote": "engine overloaded", "note": "The failed call that emptied this step's batch."}
```
The frontmatter `title` is rendered as the report H1; do not repeat it with a
Markdown `#` heading. The inline renderer supports only HTTP(S) and anchor
links. Relative Markdown links render as literal text, so identify local source
files with inline code paths or link to a supported HTTP endpoint.
Each citation requires `step`, `kind`, `subset`, `episode`, `quote`, and `note`.
Use the top-level rollout record `id` returned by the dashboard episode-list
API—not a nested `traces[*].id`, and never `line`. Copy a short, distinctive
quote exactly; matching is case-sensitive and whitespace-insensitive. Keep
`note` to 1–2 sentences explaining why the quote supports the claim.
Cite major empirical, comparative, and diagnostic conclusions, but not routine
explanation. Use exact trace citations for trajectory-level claims. For
aggregate statistics, identify the run and source file; do not imply that one
example trajectory proves the aggregate.
Use adjacent markers (`[^a] [^b]`) only when one claim genuinely depends on
distinct passages, such as a comparison or corroboration. Use one citation
when one passage is sufficient.
Optional fields are `run`, `trace`, `branch`, `node`, `field`, `prefix`, and
`suffix`. Use `field: "content"` or `"reasoning"` only to disambiguate message
parts. Use verbatim adjacent `prefix`/`suffix` only when a quote repeats.
Ambiguous or mismatched citations remain broken and do not navigate.
Use Markdown; raw HTML is escaped.
Before handoff, reload the report and verify through the dashboard API that
every referenced citation resolves uniquely to its episode, node, and quote.
Confirm zero broken citations, one rendered title, and no unsupported relative
links.
A citation needs `step`, `kind`, `subset`, `episode` (the top-level record `id`, never `line` or a `traces[*].id`), an exact short `quote` (case-sensitive, whitespace-insensitive) and a one-sentence `note`; optional `trace`, `branch`, `node`, `field`, `prefix`, `suffix` disambiguate. Cite empirical and diagnostic claims, not routine explanation; one citation per passage. Only HTTP(S) and anchor links render. Before handing over, verify through the API that every citation resolves.
+75
View File
@@ -0,0 +1,75 @@
---
name: eval
description: Launch and monitor prime-rl evals — the `uv run eval` entrypoint, its config and CLI shorthands, run directory, resume, logs and metrics. Use when asked to evaluate a model or checkpoint on an environment, smoke-test an environment, or check on an eval run.
---
# Eval
`uv run eval` evaluates a model in one or more environments and exits after one epoch per source. It reuses the orchestrator's eval pipeline: one env server per source, a concurrency band, every episode through the monitors, and a trace stream that `--resume` continues from. Online evals of training runs are the `training` skill.
## Start an eval
The user launches runs; hand over the command unless told otherwise. Always cap smokes (`-n`, `-r`).
```bash
uv run eval gsm8k -n 32 -r 4 # Prime Inference
uv run eval gsm8k -n 32 -r 4 -c 8 --env.agent.harness.id bash # pin concurrency; set a field of the env block
uv run eval gsm8k -n 32 -r 4 -m Qwen/Qwen3-4B --client.base_url http://localhost:8000/v1 # a local `uv run inference` server
uv run eval @ eval.toml --run.name my-eval # multi-source TOML
uv run eval @ eval.toml --run.name my-eval --resume # continue an interrupted run
uv run eval @ eval.toml --dry-run # resolve and write the config, exit
uv run eval @ eval.toml --monitors.prime # stream each source's epoch to the platform
```
- Config: `EvalConfig` (`packages/prime-rl-configs/src/prime_rl/configs/eval.py`); `uv run eval -h` lists the fields.
- Entrypoint: `src/prime_rl/entrypoints/eval.py`; implementation `src/prime_rl/eval/eval.py`, shared engine `src/prime_rl/eval/runner.py`.
- Shorthands (single-source runs): `<taskset-id>`, `--env.<field> <value>`, `-n` `num_examples`, `-r` `group_size`, `-m` `model`, `-c N` pins `concurrency.min_inflight = max_inflight = N`. They cannot be combined with a TOML that defines `[[source]]` blocks.
- Concurrency: an API exposes no vLLM `/metrics`, so run pinned there; against `uv run inference` set `min_inflight < max_inflight` in `[concurrency]` to adapt to KV usage.
- Env servers: spawned per source on OS-assigned ports (published to `configs/attempt_N/resolved/envs/eval/<name>.address`) unless the source sets `serve.address`.
- Ready-made configs: `configs/debug/eval/*.toml`, one per shape (single turn, multi turn, resume, multi env, aime2026, tb2).
Minimal multi-source TOML (the eval block is flattened to the top level; per-source `num_examples`, `group_size`, `sampling` override the top level):
```toml
model = "Qwen/Qwen3-4B"
num_examples = 32
group_size = 4
[client]
base_url = "http://localhost:8000/v1"
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "bash"
[[source]]
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
## Monitor an eval
Run dir: `output_dir / run.name` (auto `<envs>--<model>--<short-id>`; `ls -t outputs | head -1` finds the latest). The console stays quiet while the eval runs; everything is in the files and the dashboard (`dashboard` skill).
```
{run_dir}/
├── configs/latest/ # command.txt, the launch TOML, resolved/eval.json
├── logs/latest/
│ ├── eval.log # the eval process
│ └── envs/eval/{name}.log # one log per env server
└── monitors/file/ # metrics.jsonl, the trace stream, traces/live/ (one file per live trace), plan.json
```
```bash
tail -F {run_dir}/logs/latest/eval.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/eval.log {run_dir}/logs/latest/envs/eval/*.log
grep SUCCESS {run_dir}/logs/latest/eval.log # one "Evaluated <env> ... Reward 0.xxxx" line per source
uv run python -m prime_rl.monitors.file.traces {run_dir} [<trace_id>] # live rollouts by phase, or one assembled live trace
```
The progress line in `eval.log` counts live rollouts by phase (`- boot 1 · running 3`). A rollout stuck in `boot` for minutes is waiting on its sandbox; one in `running` with a frozen turn count is waiting on a model call or tool.
Metrics live under `eval/<env>/all/<agent>/…` (`reward/mean`, `is_truncated/mean` — raise `sampling.max_completion_tokens` when high, `has_error/mean`, the taskset's own metrics). Validate a result by reading a few traces in the dashboard rather than trusting the mean alone.
Stop a run with SIGINT/SIGTERM to the eval PID (`ps aux | grep PRL::Eval`); `--resume` restores the landed episodes from the trace stream and runs only the rollouts still owed (`num_examples`/`group_size` may change, the model, sampling and env config may not). Env servers are children of the eval process and exit with it.
+1 -1
View File
@@ -10,4 +10,4 @@ Two phases — start the run, then watch it.
- **Start a run** — see `start-run/SKILL.md` for the `rl`, `sft`, and `inference` entrypoints and how to launch them (single-node, SLURM, dry-run).
- **Monitor a run** — see `monitor-run/SKILL.md` for the runbook: how to find the output dir, what to tail, which metrics to watch, and how to restart safely.
Both subskills assume the `configs` skill for config-loading mechanics.
Both subskills assume the `configs` skill for config-loading mechanics. Standalone evals (`uv run eval`) are the `eval` skill; online evals of a training run are configured in `start-run` and read in `monitor-run`.
+6 -2
View File
@@ -82,7 +82,7 @@ Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`
{run_dir}/logs/latest/
├── trainer.log # rank 0 stdout
├── orchestrator.log # orchestrator stdout
├── evals.log # SFT online-eval evals stdout
├── eval.log # SFT online-eval process (also the `uv run eval` process — see the `eval` skill)
├── inference.log # vLLM stdout
├── trainer/
│ ├── node_*.log # per-node (multi-node only)
@@ -100,10 +100,14 @@ Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough
Scan for problems:
```bash
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evals,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,eval,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
```
### Live rollouts
`{run_dir}/monitors/file/traces/live/<trace_id>.jsonl` holds the env server's streamed deltas of one live rollout (train or eval) and disappears when its episode lands in the stream, so the directory is the live set. `uv run python -m prime_rl.monitors.file.traces {run_dir}` prints one row per live trace with `stage` (pending/boot/setup/running/finalize/scoring/done/error), turns, tokens, elapsed and the latest message; with a trace id it prints the assembled trace. The dashboard's traces tab shows them in the episode table (tinted, phase badge, growing counts; filter status → in flight) and opens them in the viewer.
### Metrics
All metrics print to the console log (and W&B when configured).
+3 -39
View File
@@ -1,6 +1,6 @@
---
name: start-run
description: How to launch prime-rl training runs — the `rl`, `sft`, `inference`, and `evals` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
description: How to launch prime-rl training runs — the `rl`, `sft`, and `inference` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint. Standalone evals are the `eval` skill.
---
# Start a run
@@ -95,43 +95,6 @@ curl http://localhost:8000/v1/chat/completions \
- Entrypoint: `src/prime_rl/entrypoints/inference.py`
- SLURM: single-node, multi-node, and disaggregated deployments
## `evals` — multi-env evals
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. Add `[ckpt]` (`interval` counts completed task groups in the eval-source order) to make the run interruptible, then use `--resume`, `--resume.step N`, or `--resume.dir path/to/checkpoints/step_N`; for standalone evals, checkpoint step N means resume from task cursor N. Checkpoints store only the cursor, not generated episode records; partially completed groups and groups beyond the durable cursor are retried. Resume loads without `[ckpt]` but does not save new checkpoints. Checkpoint/resume is rejected with `[online]` because that process is coupled to the trainer's live broadcast handshake. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. By default a newer checkpoint cancels unfinished episodes from the prior eval. Set `eval.cancel_on_new_checkpoint = false` to drain every epoch. The trainer can idle while it waits for slow evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
```bash
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
uv run evals @ eval.toml
```
Minimal standalone `eval.toml`:
```toml
model = "Qwen/Qwen3-4B"
[eval.client]
base_url = "http://localhost:8000/v1"
[eval.concurrency] # adaptive; same controller as [orchestrator.concurrency]
min_inflight = 8
max_inflight = 128
[[eval.source]]
num_examples = 32 # always cap eval size for smokes
group_size = 4
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # optional: make a standalone eval resumable
interval = 10 # completed task groups between cursor saves
```
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/latest/envs/eval/{name}.log`.
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `configs/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
## Exporting checkpoints
Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`). Convert to HF safetensors with `uv run python tools/convert_dcp_to_bf16.py <run_dir>/checkpoints/step_{n}` (writes `<ckpt_dir>/weights`, serveable via `uv run inference --vllm.model <dir>`; model config auto-read from the run’s `configs/latest/resolved/trainer.json`/`sft.json`; multi-rank via `torchrun --nproc-per-node N`; full fine-tunes only, LoRA rejected). Quantize a bf16 HF dir to blockwise FP8 with `tools/convert_bf16_to_fp8.py <dir>` (vLLM-native format), or straight from a checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (rank-parallel, writes only `<ckpt_dir>/weights-FP8`, no bf16 on disk); dequantize fp8-only releases with `tools/convert_fp8_to_bf16.py <dir>`. Caveat: on SM120 GPUs (RTX PRO 6000) vLLM 0.26 picks `CutlassFp8BlockScaledMMKernel` for blockwise-fp8 checkpoints and it silently degrades outputs — serve with `VLLM_DISABLED_KERNELS=CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel` to fall back to the Triton kernel.
@@ -143,7 +106,8 @@ Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`).
| `rl` | Full RL pipeline | Production RL training |
| `sft` | Supervised fine-tuning | SFT and hard-distill |
| `inference` | vLLM server | Standalone serving / debugging |
| `evals` | Multi-env evals | Standalone evals / SFT online evals |
Standalone evals (`uv run eval`) are covered by the `eval` skill.
## Key paths
+155 -17
View File
@@ -28,9 +28,10 @@ from prime_rl.entrypoints.dashboard import DAEMON_FILE, DIRS_FILE, STATE_DIR, re
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
from prime_rl.monitors.file.traces.chunks import open_chunk
from prime_rl.monitors.file.traces.index import summarize_episode
from prime_rl.monitors.file.traces.live import LiveFolds, live_etag, live_path, live_rows, stage
from prime_rl.monitors.file.traces.update import branch_node_paths, fold_trace_updates
from prime_rl.utils.config import default_output_dir
from prime_rl.utils.pathing import get_file_monitor_dir
from prime_rl.utils.pathing import get_eval_plan_path, get_file_monitor_dir, get_platform_run_path
from prime_rl.utils.process import set_proc_title
try:
@@ -42,7 +43,7 @@ except ModuleNotFoundError as error: # the dashboard ships as an extra
raise SystemExit("the dashboard needs the 'dashboard' extra - install with `uv sync --extra dashboard`") from error
STATIC_DIR = Path(__file__).parent / "static"
MASTER_LOGS = {"trainer.log", "orchestrator.log", "inference.log", "evals.log"}
MASTER_LOGS = {"trainer.log", "orchestrator.log", "inference.log", "eval.log"}
MAX_LOG_CHUNK = 2_000_000
app = FastAPI()
@@ -75,6 +76,8 @@ def _lru_put(cache: OrderedDict, key, value) -> None:
# Append-only file caches keyed by absolute path: line-start offsets and per-episode summaries.
_offsets_cache: OrderedDict[Path, tuple[int, bytes, list[int]]] = OrderedDict()
_summaries_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
_series_keys: dict[tuple[Path, str | None], tuple[int, set[str]]] = {}
"""Per stream and kind filter: how many summaries were scanned for series keys, and the keys."""
_annotations_cache: OrderedDict[Path, tuple[tuple, dict[str, dict], dict[Path, int]]] = OrderedDict()
_index_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
_rows_cache: OrderedDict[Path, tuple] = OrderedDict() # key, rows, entered, by_trace, consumed, last row
@@ -239,7 +242,7 @@ def main_config(run_dir: Path) -> tuple[str, dict]:
return "sft", read_json(configs / "sft.json")
if (configs / "orchestrator.json").exists() or (configs / "trainer.json").exists():
return "rl", read_json(configs / "orchestrator.json") or read_json(configs / "trainer.json")
if (configs / "eval.json").exists(): # verifiers `uv run eval` run dir
if (configs / "eval.json").exists():
return "eval", read_json(configs / "eval.json")
return "other", {}
@@ -258,6 +261,40 @@ def step_numbers(run_dir: Path) -> list[int]:
return sorted({step for _, step in effective_steps(run_dir)})
def eval_env(config: dict) -> str | None:
"""The taskset(s) of an eval run: the ``[[source]]`` list, else a single ``[env]``."""
sources = config.get("source") or []
if sources:
return "+".join(((s.get("env") or {}).get("taskset") or {}).get("id") or "?" for s in sources)
return ((config.get("env") or {}).get("taskset") or {}).get("id")
def source_total_episodes(source: dict) -> int | None:
"""What one ``[[source]]`` will produce, from its config alone: ``num_examples = -1``
means the whole taskset, unknown up front unless the source names its tasks."""
tasks = ((source.get("env") or {}).get("taskset") or {}).get("tasks")
count = source.get("num_examples") or -1
if count < 0 and not tasks:
return None
return (count if count >= 0 else len(tasks)) * (source.get("group_size") or 1)
def eval_totals(config: dict) -> dict[str, int | None]:
"""Expected episodes per eval env (a source's name, else its taskset id)."""
return {
s.get("name") or ((s.get("env") or {}).get("taskset") or {}).get("id") or "?": source_total_episodes(s)
for s in config.get("source") or []
}
def eval_total_episodes(config: dict) -> int | None:
sources = config.get("source") or []
if sources:
totals = [source_total_episodes(s) for s in sources]
return None if any(t is None for t in totals) else sum(totals) or None
return (config.get("num_tasks") or 0) * (config.get("num_rollouts") or 0) or None
def run_meta(run_dir: Path) -> dict:
configs = run_dir / "configs"
run_type, config = main_config(run_dir)
@@ -278,18 +315,43 @@ def run_meta(run_dir: Path) -> dict:
started = orjson.loads(f.readline()).get("time")
except orjson.JSONDecodeError:
started = None
# Liveness reads every artifact the processes touch: an eval ships its metrics at
# epoch end and its first episode can take minutes, but its log ticks every few
# seconds. The launch itself is the start until a metrics row says otherwise.
stream = traces_file(run_dir)
if updated is None and stream is not None: # eval runs have no metrics
updated = stream.stat().st_mtime
started = configs.stat().st_mtime if configs.is_dir() else None
touched = []
for path in (run_dir / "logs" / "latest").glob("*.log"):
try:
touched.append(path.stat().st_mtime)
except FileNotFoundError:
continue # rotated away between the listing and the stat
if stream is not None:
touched.append(stream.stat().st_mtime)
if touched:
updated = max(touched + ([updated] if updated is not None else []))
# An eval writes its only metrics row at the end of the epoch, so its start is the
# launch, not that row; a training run's first row follows its launch closely.
if (started is None or run_type == "eval") and resolved.is_dir():
started = resolved.stat().st_mtime
# An eval has no step horizon; it is complete when its file monitor finalized, which
# only a clean exit does: the stream's live chunk is sealed and nothing plain is left.
finished = run_type == "eval" and stream is not None and stream.is_dir() and not any(stream.glob("*.jsonl"))
plan_path = get_eval_plan_path(run_dir)
eval_plan = orjson.loads(plan_path.read_bytes()) if plan_path.is_file() else {}
platform_path = get_platform_run_path(run_dir)
platform = orjson.loads(platform_path.read_bytes()) if platform_path.is_file() else None
return {
"name": run_dir.name,
"type": run_type,
"finished": finished,
"eval_plan": eval_plan,
"platform": platform,
"model": model_name(config),
"dataset": (config.get("data") or {}).get("name"),
"has_validation": run_type == "sft" and config.get("val") is not None,
"env": ((config.get("env") or {}).get("taskset") or {}).get("id"),
"total_episodes": (config.get("num_tasks") or 0) * (config.get("num_rollouts") or 0) or None,
"env": eval_env(config),
"total_episodes": eval_total_episodes(config),
"eval_totals": eval_totals(config),
"max_steps": config.get("max_steps"),
"train_envs": envs("train"),
"eval_envs": envs("eval"),
@@ -329,8 +391,7 @@ def log_component(rel: Path) -> tuple[str, str]:
"trainer.log": ("trainer", "trainer"),
"orchestrator.log": ("orch", "orchestrator"),
"inference.log": ("infer", "inference"),
"evals.log": ("evals", "evals"),
"eval.log": ("evals", "eval"),
"eval.log": ("eval", "eval"),
}.get(parts[0], ("other", parts[0]))
if parts[0] == "trainer":
if parts[1] == "torchrun": # trainer/torchrun/<rdzv>/attempt_0/<rank>/std{out,err}.log
@@ -377,7 +438,7 @@ def list_logfiles(run: str, attempt: str = "latest") -> dict:
add(path, component, label)
# Include unscoped env logs from runs created before attempt-scoped eval logging.
for path in sorted((run_dir / "logs" / "envs").rglob("*.log")):
add(path, f"env:{path.stem}", f"{path.stem} (evals)")
add(path, f"env:{path.stem}", f"{path.stem} (eval)")
return {"attempt": attempt_num, "attempts": attempts, "files": files}
@@ -408,7 +469,7 @@ def read_log(run: str, file: str, start: int | None = None, end: int | None = No
# ------------------------------------------------------------------------- configs
CONFIG_ORDER = ["rl", "sft", "eval", "evals", "orchestrator", "trainer", "inference"]
CONFIG_ORDER = ["rl", "sft", "eval", "orchestrator", "trainer", "inference"]
def config_rank(name: str) -> tuple[int, str]:
@@ -529,8 +590,7 @@ def _file_size(path: Path) -> int:
def traces_file(run_dir: Path) -> Path | None:
"""The run's episode stream: the chunk directory the file monitor writes, browsed
through its index, or the single ``traces.jsonl`` a verifiers ``uv run eval`` run
writes at the run root."""
through its index, or a bare ``traces.jsonl`` at the run root."""
stream = get_trace_stream(run_dir)
if _file_size(get_index_path(stream)) > 0:
return stream
@@ -1687,6 +1747,51 @@ def rendered_token_text(trace: dict, model: str | None) -> dict:
}
_live_folds = LiveFolds()
"""The dashboard's incremental folds of every run's live files."""
@app.get("/api/runs/{run}/live")
def live_traces(run: str, etag: str | None = None) -> dict:
"""The run's in-flight traces, folded from the env servers' streamed deltas
(``monitors/file/traces/live/<trace_id>.jsonl``): one row per live trace with its
phase, turns, tokens, cost, elapsed time and last message. A trace whose file is
gone has finished and sits in the stream. ``etag`` is the fingerprint the client
last saw: an unchanged live set answers a poll with ``{unchanged}``."""
run_dir = get_run_dir(run)
current = live_etag(run_dir)
if etag is not None and etag == current:
return {"unchanged": True}
return {"time": time.time(), "etag": current, "rows": live_rows(run_dir, _live_folds)}
@app.get("/api/runs/{run}/live/{trace_id}")
def live_trace(run: str, trace_id: str, etag: str | None = None) -> dict:
"""One in-flight trace assembled from its deltas, shaped like a stream record (an
episode with this one trace) so the trace viewer renders it as it grows. ``etag``
is the file size the client last folded: nothing appended means ``{unchanged}``."""
path = live_path(get_run_dir(run), trace_id)
try:
size = path.stat().st_size # before the read: a delta landing in between shows up next poll
except FileNotFoundError:
raise HTTPException(404, "live trace not found - its episode finished or never streamed")
if etag is not None and etag == str(size):
return {"unchanged": True}
folded = _live_folds.read(path)
if folded is None:
raise HTTPException(404, "live trace not found - its episode finished or never streamed")
dispatch, trace = folded
return {
"id": None,
"etag": str(size),
"kind": dispatch.get("kind"),
"env": {"name": dispatch.get("env")},
"group": {"id": dispatch.get("group")},
"live": {**dispatch, "stage": stage(trace)},
"traces": [trace],
}
@app.get("/api/runs/{run}/episodes/series")
def episode_series(run: str, kind: str | None = None, etag: str | None = None, after: int = 0) -> dict:
"""Per-episode series over the stream (x = arrival order): reward, shape, and the
@@ -1698,15 +1803,37 @@ def episode_series(run: str, kind: str | None = None, etag: str | None = None, a
if etag is not None and etag == current_etag:
return {"unchanged": True, "etag": current_etag}
summaries = [s for s in episode_summaries(path) if not kind or s.get("kind") == kind]
keys: set[str] = set()
for s in summaries:
# the key set only grows: rescan the summaries past the ones already scanned
with _lock:
scanned, keys = _series_keys.get((path, kind)) or (0, set())
if scanned > len(summaries):
scanned, keys = 0, set()
for s in summaries[scanned:]:
keys.update(
k
for k in ("reward", "advantage", "cost", "turns", "branches", "input_tokens", "output_tokens")
for k in (
"env",
"group",
"line",
"ok",
"num_errors",
"truncated",
"stop_condition",
"duration",
"reward",
"advantage",
"cost",
"turns",
"branches",
"input_tokens",
"output_tokens",
)
if s.get(k) is not None
)
for group in ("rewards", "metrics", "timing"):
keys.update(f"{group}/{name}" for name in s.get(group) or {})
with _lock:
_series_keys[(path, kind)] = (len(summaries), keys)
def value(s: dict, key: str):
group, _, name = key.partition("/")
@@ -1982,6 +2109,17 @@ def get_episode_timeline(run: str, line: int) -> dict:
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
@app.middleware("http")
async def revalidate_static(request, call_next):
"""The page and its assets change with the checkout the daemon runs; a reload must
revalidate them (an ETag answers 304 when unchanged) instead of trusting a heuristic
freshness from ``Last-Modified``."""
response = await call_next(request)
if request.url.path == "/" or request.url.path.startswith("/static/"):
response.headers["Cache-Control"] = "no-cache"
return response
@app.get("/")
def index() -> FileResponse:
return FileResponse(STATIC_DIR / "index.html")
File diff suppressed because it is too large Load Diff
+38 -3
View File
@@ -28,6 +28,11 @@
</nav>
<label class="toggle" title="apply agent view commands as they arrive"><input type="checkbox" id="follow-toggle" checked><span class="dot"></span>follow</label>
<label class="toggle" title="poll for updates"><input type="checkbox" id="live-toggle" checked><span class="dot"></span>live</label>
<div id="platform-wrap" class="dd-wrap" hidden>
<a id="platform-link" class="btn platform" target="_blank" rel="noopener">view on platform<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 17L17 7M9 7h8v8"></path></svg></a>
<button id="platform-btn" class="btn dd-btn platform" hidden>view on platform</button>
<div class="dd-menu" id="platform-menu" hidden></div>
</div>
</header>
<div id="run-overview"></div>
@@ -35,6 +40,19 @@
<main>
<section id="tab-metrics">
<div class="controls">
<div id="metrics-filter-wrap" class="dd-wrap" hidden>
<button id="metrics-filter-btn" class="btn dd-btn" title="filter">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
</button>
<div class="dd-menu dd-filters" id="metrics-filter-menu" hidden>
<div class="dd-sec">filter</div>
<label class="dd-row" id="metrics-env-row"><span class="t-label">env</span>
<select id="metrics-env"></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="metrics-errors"><span class="dot"></span>include errors</label>
</div>
</div>
<div class="seg" id="metrics-mode">
<button data-mode="overview" class="active">Overview</button>
<button data-mode="all">All</button>
@@ -51,6 +69,7 @@
<button id="metrics-expand" class="btn">expand</button>
</div>
<div id="metrics-body"></div>
<div id="swarm-tip" hidden></div>
</section>
<section id="tab-config" hidden>
@@ -91,6 +110,12 @@
</button>
<div class="dd-menu dd-filters" id="trace-filter-menu" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row"><span class="t-label">status</span>
<div class="seg toggle-seg" id="trace-status-filter">
<button data-status="live" class="on" title="live rollouts, streamed by their env servers">live</button>
<button data-status="done" class="on" title="episodes in the finished stream">completed</button>
</div>
</div>
<div class="dd-row"><span class="t-label">kind</span>
<div class="seg toggle-seg" id="trace-kinds">
<button data-kind="train" class="on">train</button>
@@ -130,9 +155,13 @@
</div>
<div id="episode-table-wrap">
<table id="episode-table">
<colgroup>
<col class="c-line"><col class="c-phase"><col class="c-span"><col class="c-kind"><col class="c-env"><col class="c-group">
<col class="c-tok"><col class="c-turns"><col class="c-branches"><col class="c-stop"><col class="c-reward">
</colgroup>
<thead><tr>
<th>#</th><th>arrived</th><th>took</th><th>kind</th><th>env</th><th>group</th><th>reward</th>
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>status</th>
<th>#</th><th>phase</th><th title="when the rollout was dispatched, when its episode arrived, and how long that took (or has taken so far)">dispatched → arrived</th><th>kind</th><th>env</th><th>group</th>
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>reward</th>
</tr></thead>
<tbody></tbody>
</table>
@@ -179,7 +208,7 @@
<aside id="tm-left">
<div class="tm-head tm-stephead" id="tm-stephead">
<button id="tm-step-prev" class="btn tm-nav" title="previous step">‹</button>
<span id="tm-step-label"></span>
<span id="tm-step-label"></span><span id="tm-live-label" class="muted"></span>
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
</div>
<div class="tm-head tm-ctlrow">
@@ -190,6 +219,12 @@
</button>
<div class="dd-menu dd-filters" id="tm-filter-menu" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row"><span class="t-label">status</span>
<div class="seg toggle-seg" id="tm-status-filter">
<button data-status="live" class="on" title="live rollouts, streamed by their env servers">live</button>
<button data-status="done" class="on" title="episodes in the finished stream">completed</button>
</div>
</div>
<div class="dd-row"><span class="t-label">kind</span>
<div class="seg toggle-seg" id="tm-kinds">
<button data-kind="train" class="on">train</button>
+117 -6
View File
@@ -90,6 +90,15 @@ body {
#tabs button:hover { color: var(--grey-6); }
#tabs button.active { color: var(--accent); border-bottom-color: var(--accent); }
#topbar .toggle { margin-left: auto; }
#topbar .toggle + .toggle { margin-left: 0; }
#platform-wrap { margin-left: 14px; }
/* looks like the run and compare pickers; the arrow says it leaves the page */
#platform-wrap .platform { display: inline-flex; align-items: center; gap: 8px; text-decoration: none; cursor: pointer; }
#platform-wrap .platform:hover { color: var(--accent); border-color: var(--accent); }
#platform-wrap .platform.disabled { color: var(--grey-4); border-color: var(--grey-3); cursor: default; }
#platform-menu { left: auto; right: 0; min-width: 180px; }
#platform-menu .dd-opt { display: block; color: var(--grey-5); text-decoration: none; }
#platform-menu .dd-opt:hover { color: var(--grey-6); }
select, .search, .btn {
background: transparent;
@@ -336,9 +345,85 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
text-overflow: ellipsis;
}
.stat-value { font-size: 20px; color: var(--grey-6); margin: 6px 0 0; }
.eval-progress { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
.ep-bar { flex: 1; height: 6px; background: var(--grey-2); border: 1px solid var(--hairline); }
.ep-fill { height: 100%; background: var(--accent); }
/* eval progress: one cell per expected episode */
.eval-progress { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; }
.ep-head { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
.ep-row { display: flex; align-items: center; gap: 12px; }
.ep-row .ep-blocks { flex: 1; }
.ep-pct { font-size: 13px; color: var(--grey-6); min-width: 4ch; text-align: right; }
.ep-head .name { font-size: 14px; color: var(--grey-6); }
.ep-blocks { display: flex; gap: 2px; height: 28px; }
.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: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; }
/* distributions: a beeswarm per metric, a faint boxplot behind it, stats on hover */
#tab-metrics { position: relative; }
.swarm-card .chart-head { cursor: default; }
.swarm-host { height: var(--pane-h, 150px); margin-top: 6px; }
.swarm { display: block; }
.swarm .sw-bg { fill: transparent; }
.swarm circle { fill: var(--accent); fill-opacity: 0.7; cursor: pointer; }
.swarm circle.err { fill: var(--negative); }
.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; }
.sw-box rect { fill: var(--hairline-faint); stroke: var(--grey-3); stroke-width: 1; }
.sw-box line { stroke: var(--grey-3); stroke-width: 1; }
.sw-box .median { stroke: var(--grey-4); stroke-width: 1.5; }
/* timing pane: breadcrumb, icicle of the zoomed node, per-episode strips, tree legend */
/* eval metrics sections: flat, a muted heading each */
.eval-sec { margin-bottom: 18px; }
.eval-sec-title { text-transform: uppercase; font-size: 10px; letter-spacing: 0.08em; color: var(--grey-4); border-bottom: 1px solid var(--hairline); padding-bottom: 4px; margin-bottom: 10px; }
.phase-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; margin-right: 6px; vertical-align: middle; }
.timing-pane .chart-head { cursor: default; }
.tm-crumbs { font-size: 12px; color: var(--grey-5); }
.tm-crumb.current { color: var(--grey-6); }
.tm-legend { display: flex; flex-wrap: wrap; gap: 4px 18px; margin: 4px 0 14px; font-size: 11px; color: var(--grey-5); }
.tm-icicle svg { display: block; margin-bottom: 14px; }
.tm-seg text { fill: #111; font-size: 10px; pointer-events: none; }
.tm-strip-seg { cursor: pointer; }
.tm-row-hit { fill: transparent; cursor: pointer; }
.tm-line.dim { opacity: 0.3; }
.tm-strip-seg.dim { opacity: 0.2; }
.tm-strip-seg:hover { filter: brightness(1.25); }
.tm-line.err { fill: var(--negative); }
.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 */
.sum-grid { margin-bottom: 4px; display: grid; grid-template-columns: none; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); gap: 12px; }
.sum-tile { cursor: default; padding: 14px 16px; min-height: 96px; display: flex; flex-direction: column; justify-content: center; }
.sum-tile .stat-label, .sum-tile .stat-value { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.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); }
.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); }
.tm-strips.scroll { max-height: 560px; overflow-y: auto; }
.tm-node { white-space: nowrap; cursor: default; }
.tm-node:hover { color: var(--grey-6); }
/* constants as chips; counted dot plots for few-valued metrics */
.const-row { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; }
.const-chip { font-size: 12px; color: var(--grey-6); background: var(--grey-2); border: 1px solid var(--hairline); padding: 4px 10px; }
.const-chip .k { color: var(--grey-4); font-size: 10px; text-transform: uppercase; letter-spacing: 0.05em; margin-right: 8px; }
.dp-count { fill: var(--grey-5); font-size: 10px; }
#swarm-tip {
position: absolute;
z-index: 50;
pointer-events: none;
background: var(--grey-1);
border: 1px solid var(--grey-3);
padding: 6px 8px;
min-width: 160px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
font-size: 11px;
}
#swarm-tip .tip-head { color: var(--accent); margin-bottom: 4px; }
#swarm-tip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
#swarm-tip .tip-row span:first-child { color: var(--grey-4); }
.ep-label {
font-size: 10px;
letter-spacing: var(--track-caps);
@@ -633,7 +718,7 @@ mark.hit {
.sb-cell.eval:hover::after { background: var(--grey-6); }
#trace-filter-menu {
right: 0;
min-width: 240px;
min-width: 320px;
display: flex;
flex-direction: column;
gap: 8px;
@@ -643,7 +728,21 @@ mark.hit {
#episode-table-wrap { flex: 1; overflow: auto; border: 1px solid var(--hairline); background: var(--grey-1); min-height: 0; }
#episode-table .vpad td { padding: 0; border: 0; }
#episode-table { width: 100%; border-collapse: collapse; font-size: 11.5px; }
/* fixed columns: a poll that swaps rows in or out never reflows the table. The sized
columns hold mono text whose width follows the font, not the window, so they are
measured in characters; env and stop take what is left, and below the minimum the
wrap scrolls sideways instead of crushing them. */
#episode-table { width: 100%; min-width: 190ch; border-collapse: collapse; font-size: 11.5px; table-layout: fixed; }
#episode-table col.c-line { width: 7.5ch; }
#episode-table col.c-phase { width: 11.5ch; }
#episode-table col.c-span { width: 50ch; }
#episode-table col.c-kind { width: 8.5ch; }
#episode-table col.c-group { width: 13.5ch; }
#episode-table col.c-tok { width: 25ch; }
#episode-table col.c-turns { width: 9ch; }
#episode-table col.c-branches { width: 12.5ch; }
#episode-table col.c-reward { width: 10.5ch; }
#episode-table td, #episode-table th { overflow: hidden; text-overflow: ellipsis; }
#episode-table th {
text-align: left;
font: 400 10px var(--font-mono);
@@ -1102,6 +1201,7 @@ mark.hit {
/* numbered collapsible message entries */
details.entry { border: 1px solid var(--hairline); margin-bottom: 8px; }
details.entry.pending { opacity: 0.55; border-style: dashed; }
details.entry.semantic-origin {
border-color: var(--accent);
outline: 1px solid rgba(182, 255, 60, 0.55);
@@ -1523,7 +1623,7 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
/* filter & sort popover */
.dd-filters { min-width: 210px; display: flex; flex-direction: column; gap: 6px; }
.dd-filters { min-width: 320px; display: flex; flex-direction: column; gap: 6px; }
.dd-sec {
text-transform: uppercase;
font-size: 10px;
@@ -1534,6 +1634,7 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
margin-top: 2px;
}
.dd-filters .dd-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin: 0; }
.dd-filters .seg button { padding: 0 9px; }
/* controls sit right, sized to their content, so the label reads as the row's subject */
.dd-filters .dd-row select, .dd-filters .dd-row .dd-select, .dd-filters .dd-row .seg { margin-left: auto; }
.dd-filters .dd-row .dd-btn { justify-content: space-between; gap: 8px; }
@@ -1589,3 +1690,13 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
background: var(--grey-2);
border-bottom: 1px solid var(--hairline);
}
/* in-flight rollouts share the episode table; the phase badge and a pulsing dot in
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.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); }
#tm-live-label { margin-left: 8px; }
#log-comp-menu .file-item.sub { padding-left: 22px; }
#episode-table .day { margin-right: 8px; }
+19 -1
View File
@@ -1,5 +1,8 @@
import os
import queue
import threading
from functools import partial
from pathlib import Path
from verifiers.v1 import pool_serve_kwargs
from verifiers.v1.runtimes import set_base_sandbox_labels
@@ -17,15 +20,30 @@ def setup_worker(log_level: str | None, json_logging: bool, sandbox_labels: list
set_base_sandbox_labels(sandbox_labels)
def publish_address(addresses: queue.SimpleQueue, path: Path) -> None:
"""Write the bound address once serve_env reports it (it blocks in the server loop
afterwards). Atomic, so a waiting client never reads a partial line."""
address = addresses.get()
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".address.tmp")
tmp.write_text(address)
tmp.replace(path)
@clean_exit
def run_server(config: EnvServerConfig):
run_name = os.environ.get("PRL_RUN_NAME")
sandbox_labels = [run_name] if run_name else []
addresses: queue.SimpleQueue | None = None
if config.address_file is not None:
addresses = queue.SimpleQueue()
threading.Thread(target=publish_address, args=(addresses, config.address_file), daemon=True).start()
# ``serve.pool`` (static or elastic) sizes the server. serve_env applies the worker
# setup in this process and in every spawned worker.
serve_env(
**pool_serve_kwargs(config.serve.pool),
address=config.serve.address,
address=config.serve.address or "tcp://127.0.0.1:0",
address_queue=addresses,
log_setup=partial(setup_worker, config.log.level, config.log.json_logging, sandbox_labels),
config_data=env_config_data(config.env),
max_concurrent=config.serve.max_concurrent,
+203
View File
@@ -0,0 +1,203 @@
"""Launcher for ``uv run eval``: one epoch of every configured eval source.
Defers heavy ML imports until after the config is parsed, so ``eval --help``
short-circuits. The implementation lives in ``prime_rl.eval.eval``.
"""
import asyncio
import json
import os
import re
import signal
import sys
import tomllib
import uuid
from pathlib import Path
from subprocess import Popen
from typing import Any
from prime_rl.configs.eval import EvalConfig
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes, set_proc_title
USAGE = """\
usage: uv run eval [<taskset-id>] [--env.<field> <value> ...] [-n N] [-r N] [-c N] [-m MODEL] [options]
uv run eval @ eval.toml [options] multi-source runs ([[source]] blocks)
uv run eval @ eval.toml --run.name <name> --resume resume an interrupted run
Shorthands for a single-source run:
<taskset-id> the taskset of the run's only source
--env.<field> <value> a field of that source's env block (e.g. --env.agent.harness.id bash)
-c N pin the concurrency band (concurrency.min_inflight = max_inflight = N)
"""
NUMBER = re.compile(r"-?\d+(\.\d+)?")
def set_nested(target: dict[str, Any], keys: list[str], value: Any) -> None:
for key in keys[:-1]:
target = target.setdefault(key, {})
target[keys[-1]] = value
def parse_value(raw: str) -> Any:
"""A JSON list/object stays structured; every other value is left to pydantic."""
return json.loads(raw) if raw.startswith(("[", "{")) else raw
def expand_shorthands(argv: list[str]) -> list[str]:
"""Rewrite the single-source shorthands into flags ``EvalConfig`` parses.
``<taskset-id>`` and ``--env.<path> <value>`` describe the run's only source and fold
into one JSON ``--source`` flag (pydantic-config has no list-index paths, so
``--source.0.env...`` cannot address it). ``-c N`` pins the concurrency band.
Everything else passes through untouched.
"""
out: list[str] = []
source: dict[str, Any] = {}
rest = list(argv)
if rest and not rest[0].startswith(("-", "@")):
set_nested(source, ["env", "taskset", "id"], rest.pop(0))
i = 0
while i < len(rest):
arg = rest[i]
flag, has_value, value = arg.partition("=")
if not has_value and (flag.startswith("--env.") or flag == "-c"):
if i + 1 >= len(rest) or (rest[i + 1].startswith("-") and not NUMBER.fullmatch(rest[i + 1])):
raise SystemExit(f"{flag} needs a value")
i += 1
value = rest[i]
if flag.startswith("--env."):
set_nested(source, [key.replace("-", "_") for key in flag[2:].split(".")], parse_value(value))
elif flag == "-c":
out += ["--concurrency.min_inflight", value, "--concurrency.max_inflight", value]
else:
out.append(arg)
i += 1
if source:
if any(toml_defines_source(path) for path in root_config_files(argv)):
raise SystemExit(
"The <taskset-id> / --env.* shorthands describe a single source and cannot be combined "
"with a config file that defines [[source]] blocks - use one or the other"
)
out += ["--source", json.dumps([source])]
return out
def root_config_files(argv: list[str]) -> list[Path]:
"""Root ``@ file`` references (a ``--flag @ file`` is a nested reference)."""
return [
Path(argv[i + 1])
for i, arg in enumerate(argv[:-1])
if arg == "@" and (i == 0 or not argv[i - 1].startswith("--"))
]
def toml_defines_source(path: Path) -> bool:
if path.suffix != ".toml" or not path.is_file():
return False
with path.open("rb") as f:
return "source" in tomllib.load(f)
def main():
set_proc_title("Eval")
argv = sys.argv[1:]
if not argv or any(arg in ("-h", "--help") for arg in argv):
print(USAGE)
sys.argv = [sys.argv[0], "--help"]
cli(EvalConfig)
return
# The typed parse sees the expanded flags; the launch artifacts keep the command as typed.
sys.argv = [sys.argv[0], *expand_shorthands(argv)]
config = cli(EvalConfig)
sys.argv = [sys.argv[0], *argv]
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import (
format_config_message,
format_log_message,
prepare_attempt_dirs,
validate_run_dir,
write_env_server_config,
write_launch_artifacts,
)
# The run identity is runtime-only: $PRL_RUN_ID / $PRL_RUN_NAME are stamped on
# every episode and inherited by the env servers.
os.environ.setdefault("PRL_RUN_ID", uuid.uuid4().hex)
assert config.run.name is not None # resolved at construction
os.environ["PRL_RUN_NAME"] = config.run.name
clean = config.clean and not os.environ.get("NEVER_CLEAN")
validate_run_dir(config.run_dir, output_dir=config.output_dir, resuming=config.resume, clean=clean)
config.run_dir.mkdir(parents=True, exist_ok=True)
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
log_file = log_dir / "eval.log"
logger = setup_logger(config.log.level, json_logging=config.log.json_logging, log_file=log_file)
logger.info("Starting eval")
write_launch_artifacts(config_dir, "eval")
(config_dir / "eval.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
components: list[tuple[str, Path | str]] = [("Eval", config_dir / "eval.json")]
# One env server per source without an explicit `serve.address`, like the rl launcher's:
# `env-server @ <path>` binds an OS-assigned port and publishes it to the source's
# address file, where the eval picks it up.
env_servers = [source for source in config.source if source.serve.address is None]
env_names = [source.resolved_name for source in env_servers]
if env_servers:
components.append(("Envs", f"{config_dir}/envs/eval/*.json"))
for source in env_servers:
components.append(
(f" {source.resolved_name}", write_env_server_config(config_dir, "eval", source, config.log))
)
if config.dry_run:
logger.info(f"Configs:\n{format_config_message(config_dir, 'eval', components)}")
logger.success("Dry run complete. To start the eval, remove --dry-run from your command.")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
from prime_rl.eval.eval import run_eval
processes: list[Popen] = []
for source in env_servers:
name = source.resolved_name
logger.info(f"Starting {name} server")
env_server_log = log_dir / "envs" / "eval" / f"{name}.log"
env_server_log.parent.mkdir(parents=True, exist_ok=True)
with open(env_server_log, "w") as log_file_handle:
processes.append(
Popen(
["env-server", "@", (config_dir / "envs" / "eval" / f"{name}.json").as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS},
stdout=log_file_handle,
stderr=log_file_handle,
)
)
logger.info(f"Configs:\n{format_config_message(config_dir, 'eval', components)}")
logger.info(format_log_message(log_dir, eval=True, env_names={"eval": env_names}))
def sigterm_handler(signum, frame):
logger.warning("Received SIGTERM, terminating all processes...")
cleanup_processes(processes)
sys.exit(1)
signal.signal(signal.SIGTERM, sigterm_handler)
log_dashboard_url(logger, dashboard_url)
# Like the rl/sft launchers, the console stays quiet while the eval runs: results
# live in the dashboard and the log file, only errors surface here.
setup_logger(config.log.level, json_logging=config.log.json_logging, log_file=log_file, console_level="ERROR")
try:
asyncio.run(run_eval(config))
finally:
cleanup_processes(processes)
setup_logger(config.log.level, json_logging=config.log.json_logging, log_file=log_file).success("Eval finished!")
if __name__ == "__main__":
main()
-34
View File
@@ -1,34 +0,0 @@
"""Lightweight launcher for the online evals.
Defers heavy ML imports until after ``cli()`` parses CLI args, so
``evals --help`` short-circuits in ``cli()``. The actual implementation
lives in ``prime_rl.evals.evals``.
"""
import asyncio
import json
import os
from prime_rl.configs.evals import EvalsConfig
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Evals")
config = cli(EvalsConfig)
from prime_rl.utils.pathing import prepare_attempt_dirs, write_launch_artifacts
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
os.environ["PRL_LOG_DIR"] = str(log_dir)
write_launch_artifacts(config_dir, "evals")
(config_dir / "evals.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
from prime_rl.evals.evals import run_evals
asyncio.run(run_evals(config))
if __name__ == "__main__":
main()
+48 -43
View File
@@ -20,6 +20,7 @@ from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import (
clean_future_steps,
format_config_message,
format_log_message,
get_ckpt_dir,
get_launcher_dir,
@@ -27,6 +28,7 @@ from prime_rl.utils.pathing import (
prepare_attempt_dirs,
resolve_latest_ckpt_step,
validate_run_dir,
write_env_server_config,
write_launch_artifacts,
)
from prime_rl.utils.process import (
@@ -50,23 +52,18 @@ INFERENCE_CONFIG = "inference.json"
ENVS_DIR = "envs"
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig, str]]:
"""``(split, source, address)`` for every launcher-managed train/eval source. The
launcher runs one env server per source at its deterministic address; the
orchestrator connects there. A source with ``serve.address`` set is externally
managed — its server runs elsewhere and only the orchestrator connects to it — so
the launcher neither writes its TOML nor spawns a server for it."""
addresses = config.orchestrator.env_addresses
return [
(split, source, addresses[(split, source.resolved_name)])
for split, source in config.orchestrator.env_sources
if source.serve.address is None
]
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig]]:
"""``(split, source)`` for every launcher-managed train/eval source. The launcher
runs one env server per source; each binds an OS-assigned port and publishes it to
its address file, where the orchestrator picks it up. A source with ``serve.address``
set is externally managed — its server runs elsewhere and only the orchestrator
connects to it — so the launcher neither writes its TOML nor spawns a server for it."""
return [(split, source) for split, source in config.orchestrator.env_sources if source.serve.address is None]
def env_server_names(config: RLConfig, split: str) -> list[str]:
"""Names of the launcher-managed env servers for one split."""
return [source.resolved_name for source_split, source, _ in env_servers(config) if source_split == split]
return [source.resolved_name for source_split, source in env_servers(config) if source_split == split]
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
@@ -76,6 +73,19 @@ def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None =
json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2)
def rl_config_components(config: RLConfig, config_dir: Path) -> list[tuple[str, Path | str]]:
"""The resolved per-component configs ``write_subconfigs`` leaves in ``config_dir``."""
components: list[tuple[str, Path | str]] = [
("Orchestrator", config_dir / ORCHESTRATOR_CONFIG),
("Trainer", config_dir / TRAINER_CONFIG),
]
if config.inference is not None:
components.append(("Inference", config_dir / INFERENCE_CONFIG))
if env_servers(config):
components.append(("Envs", f"{config_dir}/{ENVS_DIR}/*/*.json"))
return components
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
"""Write resolved subconfigs to disk as TOML files."""
output_dir.mkdir(parents=True, exist_ok=True)
@@ -96,21 +106,11 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
with open(output_dir / INFERENCE_CONFIG, "w") as f:
json.dump(inference_dict, f, indent=2)
# One EnvServerConfig TOML per launcher-managed source: `env-server @ <path>` binds
# at the source's deterministic address, where the orchestrator connects. The source's
# env/serve blocks carry over; its other knobs (sampling, algo, name, ...) are
# orchestrator-side.
for split, source, address in env_servers(config):
env_dir = output_dir / ENVS_DIR / split
env_dir.mkdir(parents=True, exist_ok=True)
source_dict = dump_resolved_config(source)
env_server_dict = {
"env": source_dict["env"],
"serve": {**source_dict.get("serve", {}), "address": address},
"log": {"level": config.orchestrator.log.vf_level, "json_logging": config.orchestrator.log.json_logging},
}
with open(env_dir / f"{source.resolved_name}.json", "w") as f:
json.dump(env_server_dict, f, indent=2)
# One EnvServerConfig per launcher-managed source: `env-server @ <path>` binds an
# OS-assigned port and publishes it to the source's address file, where the
# orchestrator picks it up.
for split, source in env_servers(config):
write_env_server_config(output_dir, split, source, config.orchestrator.log)
def rl_local(config: RLConfig):
@@ -124,12 +124,21 @@ def rl_local(config: RLConfig):
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_artifacts(config_dir, "rl")
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', rl_config_components(config, config_dir))}")
if config.dry_run:
logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.")
return
logger.info(
format_log_message(
log_dir=log_dir,
trainer=True,
orchestrator=True,
inference=config.inference is not None,
env_names={split: env_server_names(config, split) for split in ("train", "eval")},
)
)
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs from deployment config
@@ -153,7 +162,6 @@ def rl_local(config: RLConfig):
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
start_command = sys.argv
logger.info("Starting RL run")
logger.debug(f"RL start command: {' '.join(start_command)}")
# Build shared W&B env vars for subprocesses. Shared mode is always on for
@@ -248,10 +256,10 @@ def rl_local(config: RLConfig):
"otherwise rollouts will hang."
)
# Start one env server per source. The orchestrator connects to each source's
# deterministic address, polling until the server is up, so the servers and the
# Start one env server per source. The orchestrator waits for each server's
# published address and polls until it answers, so the servers and the
# orchestrator start in parallel.
for split, source, address in env_servers(config):
for split, source in env_servers(config):
name = source.resolved_name
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
logger.info(f"Starting {name} server")
@@ -523,8 +531,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
env_names={"train": train_env_names, "eval": eval_env_names},
**modelexpress_vars,
)
else:
@@ -564,8 +571,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
trainer_env_vars=trainer_env_vars,
orchestrator_env_vars=orchestrator_env_vars,
inference_env_vars=inference_env_vars,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
env_names={"train": train_env_names, "eval": eval_env_names},
**modelexpress_vars,
)
@@ -586,7 +592,7 @@ def rl_slurm(config: RLConfig):
if config.deployment.type == "single_node":
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean"})
logger.info(f"Wrote config to {config_dir / RL_CONFIG}")
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', [('RL', config_dir / RL_CONFIG)])}")
train_env_names = env_server_names(config, "train")
eval_env_names = env_server_names(config, "eval")
@@ -596,12 +602,11 @@ def rl_slurm(config: RLConfig):
trainer=True,
orchestrator=True,
inference=True,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
env_names={"train": train_env_names, "eval": eval_env_names},
)
else:
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', rl_config_components(config, config_dir))}")
train_env_names = env_server_names(config, "train")
eval_env_names = env_server_names(config, "eval")
@@ -612,8 +617,7 @@ def rl_slurm(config: RLConfig):
trainer=True,
orchestrator=has_infer,
inference=has_infer,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
env_names={"train": train_env_names, "eval": eval_env_names},
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
)
@@ -661,6 +665,7 @@ def rl(config: RLConfig):
# step is stale. When training from scratch, every existing step directory is
# stale — without this, a fresh run in a dirty run dir would pick up rollouts
# from a previous run and the orchestrator would see a negative async level.
get_logger().info("Starting RL run")
resume_step: int | None = None
if resuming:
if config.resume.dir is not None:
+76 -71
View File
@@ -8,8 +8,8 @@ from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from prime_rl.configs.evals import EvalsConfig, OnlineConfig
from prime_rl.configs.orchestrator import EvalSourceConfig
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.orchestrator import OnlineEvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.shared import LogConfig
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
@@ -17,6 +17,7 @@ from prime_rl.utils.config import cli, dump_resolved_config, find_package_resour
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import (
clean_future_steps,
format_config_message,
format_log_message,
get_broadcast_dir,
get_ckpt_dir,
@@ -25,6 +26,7 @@ from prime_rl.utils.pathing import (
prepare_attempt_dirs,
resolve_latest_ckpt_step,
validate_run_dir,
write_env_server_config,
write_launch_artifacts,
)
from prime_rl.utils.process import (
@@ -42,23 +44,17 @@ SFT_CONFIG = "sft.json"
SFT_SBATCH = "sft.sbatch"
INFERENCE_CONFIG = "inference.json"
EVALS_CONFIG = "evals.json"
ONLINE_EVAL_CONFIG = "eval.json"
ENVS_DIR = "envs"
def eval_env_servers(config: SFTConfig) -> list[tuple[EvalSourceConfig, str]]:
"""``(source, address)`` for every launcher-managed eval source. A source with
``serve.address`` set is externally managed — the launcher neither writes its
config nor spawns a server for it."""
def eval_env_servers(config: SFTConfig) -> list[OnlineEvalSourceConfig]:
"""Every launcher-managed eval source. A source with ``serve.address`` set is
externally managed — the launcher neither writes its config nor spawns a server for it."""
if config.eval is None:
return []
addresses = config.eval.env_addresses
return [
(source, addresses[("eval", source.resolved_name)])
for source in config.eval.source
if source.serve.address is None
]
return [source for source in config.eval.source if source.serve.address is None]
def get_ckpt_base(config: SFTConfig) -> Path:
@@ -76,28 +72,37 @@ def resolve_resume_step(config: SFTConfig) -> int | None:
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
def build_evals_config(config: SFTConfig) -> EvalsConfig:
"""Derive the evals subconfig from the resolved SFT config. The launcher
spawns the env servers itself, so each source's derived address is stamped in,
marking it externally managed for the evals process."""
def build_online_eval_config(config: SFTConfig) -> SFTOnlineEvalConfig:
"""The online-eval process's config: the resolved ``[eval]`` block with the run-level
fields filled from the SFT config. The launcher spawns the env servers itself; the
online-eval process finds each one through the address it publishes in the shared
config attempt."""
assert config.eval is not None
eval_config = config.eval.model_copy(deep=True)
addresses = config.eval.env_addresses
for source in eval_config.source:
source.serve.address = addresses[("eval", source.resolved_name)]
return EvalsConfig(
run_fields = dict(
model=config.model.name,
eval=eval_config,
weight_broadcast=config.weight_broadcast,
online=OnlineConfig(
broadcasts_dir=get_broadcast_dir(config.run_dir),
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
),
broadcasts_dir=get_broadcast_dir(config.run_dir),
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
output_dir=config.run_dir,
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
monitors=config.monitors,
)
return SFTOnlineEvalConfig(**{**eval_config.model_dump(exclude=set(run_fields)), **run_fields})
def sft_config_components(config: SFTConfig, config_dir: Path) -> list[tuple[str, Path | str]]:
"""The resolved configs a launch leaves in ``config_dir``: the SFT config and, with
online evals, the inference, online-eval and env-server configs."""
components: list[tuple[str, Path | str]] = [("SFT", config_dir / SFT_CONFIG)]
if config.eval is not None:
if config.inference is not None:
components.append(("Inference", config_dir / INFERENCE_CONFIG))
components.append(("Eval", config_dir / ONLINE_EVAL_CONFIG))
if eval_env_servers(config):
components.append(("Envs", f"{config_dir}/{ENVS_DIR}/eval/*.json"))
return components
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
@@ -108,7 +113,7 @@ def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None
def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: bool = False) -> None:
"""Write the inference, evals, and env-server configs for online evals."""
"""Write the inference, online-eval, and env-server configs for online evals."""
config_dir.mkdir(parents=True, exist_ok=True)
if config.inference is not None:
@@ -121,22 +126,14 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
with open(config_dir / INFERENCE_CONFIG, "w") as f:
json.dump(inference_dict, f, indent=2)
with open(config_dir / EVALS_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_evals_config(config)), f, indent=2)
with open(config_dir / ONLINE_EVAL_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_online_eval_config(config)), f, indent=2)
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>`
# binds at the source's deterministic address, where the evals process connects.
for source, address in eval_env_servers(config):
env_dir = config_dir / ENVS_DIR / "eval"
env_dir.mkdir(parents=True, exist_ok=True)
source_dict = dump_resolved_config(source)
env_server_dict = {
"env": source_dict["env"],
"serve": {**(source_dict.get("serve") or {}), "address": address},
"log": {"level": config.log.vf_level, "json_logging": config.log.json_logging},
}
with open(env_dir / f"{source.resolved_name}.json", "w") as f:
json.dump(env_server_dict, f, indent=2)
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>` binds an
# OS-assigned port and publishes it to the source's address file, where the
# online-eval process picks it up.
for source in eval_env_servers(config):
write_env_server_config(config_dir, "eval", source, config.log)
def write_slurm_script(
@@ -191,12 +188,12 @@ def write_slurm_script(
"dp_per_node": config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
"enable_expert_parallel": config.inference.vllm.enable_expert_parallel,
"inference_env_vars": inference_env_vars,
"evals_env_vars": {
"online_eval_env_vars": {
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
},
"eval_env_names": [source.resolved_name for source, _ in eval_env_servers(config)],
"eval_env_names": [source.resolved_name for source in eval_env_servers(config)],
}
script = template.render(
**config.slurm.template_vars,
@@ -236,6 +233,7 @@ def sft_slurm(config: SFTConfig):
online_eval = config.deployment.type == "multi_node" and config.eval is not None
logger.info("Starting SFT run")
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_artifacts(config_dir, "sft")
config_path = config_dir / SFT_CONFIG
@@ -249,9 +247,8 @@ def sft_slurm(config: SFTConfig):
# inference pool runs on its dedicated nodes in the same allocation.
exclude = exclude | {"inference"}
write_config(config, config_path, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
# Trainer and evals processes log to a single shared W&B run.
# Trainer and online-eval processes log to a single shared W&B run.
prl_run_id: str | None = None
if online_eval and config.monitors.wandb is not None:
prl_run_id = os.environ["PRL_RUN_ID"]
@@ -259,7 +256,7 @@ def sft_slurm(config: SFTConfig):
launcher_dir = get_launcher_dir(config.run_dir)
if online_eval:
write_eval_subconfigs(config, config_dir, strip_router=True)
logger.info(f"Wrote eval subconfigs to {config_dir}")
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
script_path = launcher_dir / SFT_SBATCH
write_slurm_script(config, config_path, log_dir, script_path, prl_run_id)
logger.info(f"Wrote SLURM script to {script_path}")
@@ -269,9 +266,9 @@ def sft_slurm(config: SFTConfig):
log_dir=log_dir,
trainer=True,
num_train_nodes=num_nodes,
evals=online_eval,
eval=online_eval,
inference=online_eval,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)] if online_eval else None,
env_names={"eval": [source.resolved_name for source in eval_env_servers(config)]} if online_eval else None,
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
)
@@ -297,20 +294,28 @@ def sft_local(config: SFTConfig):
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
logger.info("Starting SFT run")
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_artifacts(config_dir, "sft")
config_path = config_dir / SFT_CONFIG
write_config(config, config_path)
logger.info(f"Wrote config to {config_path}")
if config.eval is not None:
write_eval_subconfigs(config, config_dir)
logger.info(f"Wrote eval subconfigs to {config_dir}")
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
if config.dry_run:
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
return
logger.info(
format_log_message(
log_dir=log_dir,
trainer=True,
eval=config.eval is not None,
inference=config.inference is not None,
env_names={"eval": [source.resolved_name for source in eval_env_servers(config)]},
)
)
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
@@ -329,17 +334,17 @@ def sft_local(config: SFTConfig):
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
# Trainer and evals log to a single shared W&B run whose id ($WANDB_RUN_ID)
# Trainer and online-eval log to a single shared W&B run whose id ($WANDB_RUN_ID)
# equals $PRL_RUN_ID, one label per process.
wandb_shared_env: dict[str, str] = {}
if config.eval is not None:
# The trainer creates the run; the evals process (which drains its final evals
# after the trainer exits) finalizes it.
# The trainer creates the run; the online-eval process (which drains its final
# evals after the trainer exits) finalizes it.
wandb_shared_env = {
"WANDB_SHARED_MODE": "1",
"WANDB_RUN_ID": os.environ["PRL_RUN_ID"],
"WANDB_SHARED_PRIMARY": "trainer",
"WANDB_SHARED_FINISHER": "evals",
"WANDB_SHARED_FINISHER": "online-eval",
"WANDB_PROGRAM": "uv run sft",
"WANDB_ARGS": json.dumps(sys.argv),
}
@@ -388,9 +393,9 @@ def sft_local(config: SFTConfig):
log_path=log_dir / "inference.log",
)
# Start one env server per eval source. The evals process connects to each source's
# deterministic address, polling until the server is up.
for source, address in eval_env_servers(config):
# Start one env server per eval source. The online-eval process waits for each
# server's published address and polls until it answers.
for source in eval_env_servers(config):
name = source.resolved_name
logger.info(f"Starting {name} server")
start_process(
@@ -401,10 +406,10 @@ def sft_local(config: SFTConfig):
)
if config.eval is not None:
logger.info("Starting evals")
logger.info("Starting online evals")
start_process(
"evals",
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
"online-eval",
[sys.executable, "-m", "prime_rl.eval.online", "@", (config_dir / ONLINE_EVAL_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
@@ -414,9 +419,9 @@ def sft_local(config: SFTConfig):
"PRL_ATTEMPT_LOG_DIR": str(log_dir),
"PRL_LOG_DIR": str(log_dir),
**wandb_shared_env,
"WANDB_SHARED_LABEL": "evals",
"WANDB_SHARED_LABEL": "online-eval",
},
log_path=log_dir / "evals.log",
log_path=log_dir / "eval.log",
)
from prime_rl.utils.utils import get_free_port
@@ -455,11 +460,11 @@ def sft_local(config: SFTConfig):
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Wait for the trainer (and the evals process, which drains its final evals after
# the trainer's last checkpoint) while surfacing any process failure.
# Wait for the trainer (and the online-eval process, which drains its final evals
# after the trainer's last checkpoint) while surfacing any process failure.
terminal_events = [stop_events["trainer"]]
if "evals" in stop_events:
terminal_events.append(stop_events["evals"])
if "online-eval" in stop_events:
terminal_events.append(stop_events["online-eval"])
while True:
pending = [event for event in terminal_events if not event.is_set()]
if error_queue:
@@ -497,12 +502,12 @@ def sft_local(config: SFTConfig):
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
"""Remove eval artifacts a previous run left behind: weight broadcasts and rollout
trace dirs — everything on a fresh start, steps past the resume step on resume.
Without this the evals process would replay stale broadcasts (and then skip the
Without this the online-eval process would replay stale broadcasts (and then skip the
re-trained ones at the same steps), and the append-only trace files would mix two
policies' rollouts under one step."""
logger = setup_logger(config.log.level or "info")
if os.environ.get("NEVER_CLEAN"):
logger.warning("NEVER_CLEAN is set - keeping stale weight broadcasts; the evals process may replay them")
logger.warning("NEVER_CLEAN is set - keeping stale weight broadcasts; the online-eval process may replay them")
return
resume_step = resolve_resume_step(config)
clean_future_steps(config.run_dir, resume_step if resume_step is not None else -1)
+68
View File
@@ -0,0 +1,68 @@
"""Evals: one epoch of every configured eval source against the weights the inference
server currently serves.
Every episode streams through the monitors as it arrives; a finished epoch also goes to
the platform when ``monitors.prime`` is set. An interrupted run resumes with
``--resume`` from its trace stream: the landed episodes rejoin the epoch and only the
rollouts still owed run (``prime_rl.eval.resume``)."""
from __future__ import annotations
from prime_rl import monitors
from prime_rl.configs.eval import EvalConfig
from prime_rl.eval import resume
from prime_rl.eval.runner import EvalRunner
from prime_rl.utils.config import dump_resolved_config
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import clean_exit
class Eval:
def __init__(self, config: EvalConfig) -> None:
self.config = config
self.runner = EvalRunner(config, run_dir=config.run_dir)
async def run(self) -> None:
config = self.config
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(
producer="eval",
wandb=config.monitors.wandb,
prime=config.monitors.prime,
file=config.monitors.file,
output_dir=config.run_dir,
run_config=config,
eval_env_names=[source.resolved_name for source in config.source],
overview_flavor="eval",
)
resume.stamp_config(config.run_dir, dump_resolved_config(config))
await self.runner.setup()
restored: list = []
if config.resume:
restored, owed, groups = resume.plan(landed, self.runner.eval_envs)
self.runner.eval_source.restore(owed, groups)
get_logger().info(
f"Resuming from the trace stream: {len(restored)} episodes restored, "
f"{sum(sum(counts.values()) for counts in owed.values())} rollouts owed"
)
await self.runner.start()
fired = self.runner.eval_source.trigger(0)
await self.runner.run_epoch(fired, 0, restored=restored)
await self.runner.drain()
@clean_exit
async def run_eval(config: EvalConfig) -> None:
evaluation = Eval(config)
try:
await evaluation.run()
# Finalize only on a clean exit — a crashed run must not mark itself completed.
await monitors.finalize()
finally:
await evaluation.runner.stop()
+223
View File
@@ -0,0 +1,223 @@
"""Online evals: evaluate the trainer's weight broadcasts as they appear.
Spawned by the ``sft`` launcher (``python -m prime_rl.eval.online @ eval.json``)
next to the trainer. The process watches a broadcasts directory for offered weight broadcasts through a
``WeightReceiver`` (announced by their ``.sender_ready`` marker), moves the inference
server onto each of them, and runs the due eval sources against the updated weights,
sequentially per broadcast so every epoch measures exactly one policy version. Every
offered broadcast must be received, even when no eval is due — the trainer blocks inside
the handshake until the receiver acknowledges. By default, a newer checkpoint cancels
unfinished episodes from the prior version; ``cancel_on_new_checkpoint = false`` drains
every epoch instead."""
from __future__ import annotations
import asyncio
import json
import os
from prime_rl import monitors
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
from prime_rl.eval.runner import POLL_INTERVAL_S, EvalRunner
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, prepare_attempt_dirs
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.utils import clean_exit
# Budget for the trainer's startup broadcast: it is always coming, but only
# after the trainer has finished loading the model.
STARTUP_BROADCAST_TIMEOUT_S = 1200
class OnlineEval:
def __init__(self, config: SFTOnlineEvalConfig) -> None:
assert config.model is not None, "the sft launcher fills eval.model"
self.config = config
self.runner = EvalRunner(config, run_dir=config.output_dir)
# The last weight-broadcast step already handled (evaluated or skipped).
self.last_step = config.resume_step or 0
self.receiver: WeightReceiver | None = None
async def run(self) -> None:
config = self.config
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
producer="online-eval",
wandb=config.monitors.wandb,
file=config.monitors.file,
output_dir=config.output_dir,
run_config=config,
eval_env_names=[source.resolved_name for source in config.source],
overview_flavor="sft",
)
await self.runner.setup(skip_first_step=config.skip_first_step, is_resumed=config.resume_step is not None)
assert config.broadcasts_dir is not None # resolved by the config validator
# A hand-written config may omit the transport; broadcasts are then plain
# filesystem checkpoints.
weight_broadcast = config.weight_broadcast or FileSystemWeightBroadcastConfig()
get_logger().info(f"Initializing weight broadcast ({weight_broadcast})")
self.receiver = setup_weight_receiver(
config.broadcasts_dir,
weight_broadcast,
admin_plane=self.runner.admin_plane,
model_name=config.model,
)
await self.receiver.initialize()
await self.runner.start()
await self.watch()
await self.runner.drain()
get_logger().success("Online evals finished!")
async def watch(self) -> None:
"""Evaluate each eligible weight broadcast as it appears."""
config = self.config
assert self.receiver is not None
assert config.broadcasts_dir is not None
# Rendezvous with the trainer's startup broadcast (v0 fresh, the checkpoint step
# on resume) — always, for every transport: an in-memory trainer blocks inside
# its startup broadcast until this receive, and for filesystem it guarantees the
# served weights match the trainer's incoming policy.
startup_step = config.resume_step or 0
await self.receiver.sync_startup(startup_step, timeout=STARTUP_BROADCAST_TIMEOUT_S)
self.runner.policy.version = startup_step
if config.resume_step is None:
# The first trigger fires every env (policy v0) unless ``skip_first_step``.
await self.maybe_run_eval(step=0)
elif config.retrigger_on_resume:
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
# evals); the startup rendezvous above already loaded its weights. The
# final broadcast force-fires every env, exactly like the watch loop below.
is_final = config.max_steps is not None and config.resume_step >= config.max_steps
await self.maybe_run_eval(step=config.resume_step, force=is_final)
get_logger().info(f"Watching {config.broadcasts_dir} for new weight broadcasts (max_steps={config.max_steps})")
while True:
steps = get_all_ckpt_steps(config.broadcasts_dir)
published = {step: self.receiver.is_published(step) for step in steps}
newest_published = max((step for step in steps if published[step]), default=None)
# Also walk eval-due steps that are no longer on disk: broadcast cleaning
# (the trainer keeps only the newest broadcast) can delete a step before
# this scan sees it, and a vanished step would otherwise be skipped
# without a trace.
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_published)):
if step <= self.last_step:
continue
if step not in published:
get_logger().warning(
f"Weight broadcast for eval step {step} was deleted before it could be "
"evaluated (broadcast cleaning outpaced the evals process) - skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
if not published[step]:
# The trainer writes broadcasts in ascending order, so a marker-less
# step below a published one is an abandoned partial write (e.g. a
# crash mid-save), not one in progress — skip it instead of wedging.
if newest_published is None or newest_published < step:
break # still being written — later steps can't be ready either
get_logger().warning(
f"Weight broadcast step {step} is not marked published but newer "
"broadcasts are - treating it as abandoned and skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
is_final = config.max_steps is not None and step >= config.max_steps
await self.maybe_run_eval(step=step, reload_weights=True, force=is_final)
if config.max_steps is not None and self.last_step >= config.max_steps:
break
await asyncio.sleep(POLL_INTERVAL_S)
def next_published_step(self, step: int) -> int | None:
"""Return the first newer checkpoint offered by the trainer."""
assert self.config.broadcasts_dir is not None
assert self.receiver is not None
return next(
(
candidate
for candidate in get_all_ckpt_steps(self.config.broadcasts_dir)
if candidate > step and self.receiver.is_published(candidate)
),
None,
)
def deleted_due_steps(self, steps: list[int], newest_published: int | None) -> set[int]:
"""Eval-due steps up to the newest published broadcast that are missing from
the broadcasts dir — the trainer wrote them (it broadcasts at every due step),
so their absence means broadcast cleaning removed them before they were
evaluated."""
if newest_published is None:
return set()
due = {
step
for interval in self.runner.eval_source.intervals.values()
for step in range(interval, newest_published + 1, interval)
}
return due - set(steps)
async def maybe_run_eval(self, step: int, *, reload_weights: bool = False, force: bool = False) -> None:
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
reloading the inference weights first. No-op when no env is due — except
that a live transport's broadcast must always be received (the trainer
is blocked inside it), eval or no eval."""
runner = self.runner
if reload_weights:
assert self.receiver is not None
broadcast_dir = self.receiver.step_dir(step)
if not self.receiver.is_published(step):
get_logger().warning(f"No published weight broadcast for step {step} ({broadcast_dir}) - skipping eval")
self.last_step = max(self.last_step, step)
return
# Trigger before the reload: the dispatcher only schedules eval in PREFER_EVAL,
# so nothing dispatches until ``run_epoch`` switches modes below.
fired = runner.eval_source.trigger(step, force=force)
self.last_step = max(self.last_step, step)
if reload_weights:
# Every offered version must be received: the trainer blocks inside
# the handshake, so a failed receive fails the run loudly.
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
await runner.dispatcher.on_version_pending(step)
await self.receiver.receive(step)
runner.policy.version = step
await runner.dispatcher.on_new_version(step)
else:
runner.policy.version = step
if not fired:
return
superseding_step = (lambda: self.next_published_step(step)) if self.config.cancel_on_new_checkpoint else None
await runner.run_epoch(fired, step, superseding_step=superseding_step)
@clean_exit
async def run_online_eval(config: SFTOnlineEvalConfig) -> None:
evaluation = OnlineEval(config)
try:
await evaluation.run()
# Finalize only on a clean exit — a crashed run must not mark the run completed.
await monitors.finalize()
finally:
await evaluation.runner.stop()
def main():
set_proc_title("OnlineEvals")
config = cli(SFTOnlineEvalConfig)
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
(config_dir / "eval.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
setup_logger(config.log.level, json_logging=config.log.json_logging)
asyncio.run(run_online_eval(config))
if __name__ == "__main__":
main()
+168
View File
@@ -0,0 +1,168 @@
"""Resume an interrupted eval from its trace stream.
The stream records what landed, so it is what a resume continues from. The run's ok
episodes are read back and rejoin the epoch as if they had just arrived - through the
monitors, so the rebuilt stream, the epoch's metrics and the platform upload cover the
whole epoch - and only the rollouts still owed run. Errored episodes and the in-flight
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``).
"""
from __future__ import annotations
from collections import Counter, defaultdict
from collections.abc import Iterator
from fnmatch import fnmatch
from pathlib import Path
import orjson
import verifiers.v1 as vf
from prime_rl.monitors.file.traces import get_trace_stream
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.*.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."""
def stamp_config(run_dir: Path, config: dict) -> None:
directory = get_file_monitor_dir(run_dir)
directory.mkdir(parents=True, exist_ok=True)
(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."""
for number in sorted(chunk_numbers(stream)):
with open_chunk(stream, number) as chunk:
for line in chunk:
try:
yield orjson.loads(line)
except orjson.JSONDecodeError:
return
def archives(run_dir: Path) -> list[Path]:
"""The file monitor directories of the run's earlier attempts, oldest first: a resume
renames the one it finds to ``monitors/file.attempt_N`` and starts a fresh one."""
monitors = get_file_monitor_dir(run_dir).parent
return sorted(monitors.glob("file.attempt_*"), key=lambda path: int(path.name.rsplit("_", 1)[1]))
def take_landed(run_dir: Path) -> list[dict]:
"""The ok eval episodes the run has landed, each once, from every attempt's stream.
The current file monitor directory joins the archives so the resumed attempt writes a
fresh stream, plan and metrics; nothing is deleted."""
current = get_file_monitor_dir(run_dir)
stream = get_trace_stream(run_dir).relative_to(current)
landed: dict[str, dict] = {}
for directory in [*archives(run_dir), current]:
if (directory / stream).is_dir():
for record in read_records(directory / stream):
if record.get("ok"):
landed.setdefault(record["id"], record)
if current.is_dir():
current.rename(current.with_name(f"file.attempt_{len(archives(run_dir)) + 1}"))
return list(landed.values())
def plan(
landed: list[dict], eval_envs: EvalEnvs
) -> tuple[list[vf.WireEpisode], dict[str, dict[str, int]], dict[str, dict[str, str]]]:
"""Match the landed episodes to the run's tasks: the episodes to keep, in stream
order, the rollouts still owed per env and task key, and the group id a task's kept
episodes carry, so the owed ones complete that group rather than open another."""
targets: dict[str, Counter[str]] = {}
for env in eval_envs:
targets[env.name] = Counter(task.key for task in env.examples)
for key in targets[env.name]:
targets[env.name][key] *= env.config.group_size
kept: list[vf.WireEpisode] = []
counts: dict[str, Counter[str]] = defaultdict(Counter)
groups: dict[str, dict[str, str]] = defaultdict(dict)
for record in landed:
env_name = record["env"].get("name") or record["env"]["id"]
key = record["task"]["key"]
if counts[env_name][key] >= targets.get(env_name, Counter())[key]:
continue
kept.append(vf.WireEpisode.model_validate(record))
counts[env_name][key] += 1
if (group := record.get("group") or {}).get("id"):
groups[env_name].setdefault(key, group["id"])
owed = {
env_name: {
key: target - counts[env_name][key]
for key, target in target_counts.items()
if target > counts[env_name][key]
}
for env_name, target_counts in targets.items()
}
return kept, owed, dict(groups)
+340
View File
@@ -0,0 +1,340 @@
"""EvalRunner: the eval engine shared by ``eval`` (one epoch against the served weights)
and ``online-eval`` (an epoch per weight broadcast).
Scheduling reuses the orchestrator pipeline unchanged: an eval-only ``Dispatcher``
admits episodes under the adaptive ``ConcurrencyController``, fed by the
``InferenceMetricsCollector``'s ``/metrics`` polls. Eval episodes are version-pinned
measurements and are never cancelled on load - a controller cut only blocks admission
until the pool drains.
Env servers belong to the launcher (``eval``, ``sft``), like the orchestrator's belong to
``rl``: a source without an explicit ``serve.address`` is found through the address file
its server publishes; one with an address is reached directly."""
from __future__ import annotations
import asyncio
import os
import time
import uuid
from collections.abc import Callable, Sequence
from pathlib import Path
import verifiers.v1 as vf
from prime_rl import monitors
from prime_rl.configs.eval import EvalConfig, SFTOnlineEvalConfig
from prime_rl.orchestrator import live
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.metrics import dispatch_failure_metrics
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
from prime_rl.orchestrator.utils import (
eval_work,
intercept_vf_logging,
set_default_executor,
)
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_config_dir
monkey_patch_oai_iterable_types()
monkey_patch_chat_completion_logprobs()
# How often ``run_epoch`` re-checks for a superseding checkpoint while it waits for episodes.
POLL_INTERVAL_S = 2.0
class EvalRunner:
def __init__(self, config: EvalConfig | SFTOnlineEvalConfig, *, run_dir: Path) -> None:
self.config = config
self.run_dir = run_dir
intercept_vf_logging(logger="verifiers.v1", level="WARN")
self.eval_triggered_at: dict[tuple[str, int], float] = {}
self.dispatcher_task: asyncio.Task | None = None
# Assigned in setup(); None-initialized so stop() can tear down a
# partially completed setup with plain attribute checks.
self.clients: InferenceClient | None = None
self.admin_plane: AdminPlane | None = None
self.dispatcher: Dispatcher | None = None
self.inference_metrics: InferenceMetricsCollector | None = None
self.periodic_logger: PeriodicLogger | None = None
async def setup(self, *, skip_first_step: bool = False, is_resumed: bool = False) -> None:
config = self.config
set_default_executor()
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
self.run_name = os.environ.get("PRL_RUN_NAME")
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
get_logger().info(f"Initializing inference pool (base_url={config.client.base_url}, model={config.model})")
self.clients = InferenceClient(config.client, model_name=config.model)
self.admin_plane = AdminPlane(config.client)
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.source, config.env_addresses, get_config_dir(self.run_dir))
await self.eval_envs.start()
get_logger().info(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
get_logger().info("Waiting for inference pool to be ready")
await self.admin_plane.wait_for_ready(config.model)
get_logger().info("Inference pool ready")
intervals = config.intervals if isinstance(config, SFTOnlineEvalConfig) else None
self.eval_source = EvalSource(
self.eval_envs, intervals=intervals, skip_first_step=skip_first_step, is_resumed=is_resumed
)
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
self.policy = Policy(version=0, model_name=config.model)
# Pessimistic per-episode token cost for the controller's starting cap,
# only used when the engine doesn't report its max context length.
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.source) or 8192
self.concurrency = ConcurrencyController(config.concurrency, fallback_cost=fallback_cost)
self.dispatcher = Dispatcher(
train_envs=None,
eval_envs=self.eval_envs,
train_source=None,
eval_source=self.eval_source,
policy_clients=self.clients,
policy=self.policy,
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
tasks_per_minute=None,
max_off_policy_steps=0,
run_id=self.run_id,
run_name=self.run_name,
on_episode_complete=self.concurrency.record_episode,
)
# No ``on_overload``: eval episodes are measurements and are never
# cancelled — a cut only blocks admission until the pool drains.
self.concurrency.bind(
set_limit=self.dispatcher.set_limit,
get_inflight=lambda: self.dispatcher.current_inflight,
)
# The collector always polls — it feeds the concurrency controller;
# metrics fan out to every registered monitor.
self.inference_metrics = InferenceMetricsCollector(
self.admin_plane.clients,
on_load=self.concurrency.observe,
)
# Fail fast when adaptivity has no signal: external API endpoints
# (e.g. Prime Inference) expose no vLLM /metrics, so without a probe
# hit the cap would silently sit at min_inflight forever. A pinned
# band (min_inflight = max_inflight) makes the controller inert and
# is the supported way to run against such endpoints.
if not await self.inference_metrics.probe():
concurrency = config.concurrency
if concurrency.min_inflight != concurrency.max_inflight:
urls = ", ".join(str(client.base_url) for client in self.admin_plane.clients)
raise ValueError(
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
"pin the concurrency with `-c N` (concurrency.min_inflight = max_inflight = N)."
)
get_logger().info(f"No engine metrics - running with concurrency pinned at {concurrency.min_inflight}")
await self.inference_metrics.start()
self.periodic_logger = PeriodicLogger(
name="Eval",
collect=self.collect_pipeline_view,
metric_keys=[
*list(self.dispatcher.gauges().keys()),
*list(self.concurrency.gauges().keys()),
*DispatcherMetrics.drain_keys(train_envs=set(), eval_envs={env.name for env in self.eval_envs}),
],
interval=config.log.interval,
wandb_enabled=wandb_enabled,
)
async def start(self) -> None:
self.dispatcher_task = asyncio.create_task(self.dispatcher.start(), name="dispatcher")
await self.periodic_logger.start()
async def run_epoch(
self,
fired: list[str],
step: int,
*,
restored: Sequence[vf.Episode] = (),
superseding_step: Callable[[], int | None] | None = None,
) -> None:
"""Run the epoch ``EvalSource.trigger`` queued for ``step`` in the fired envs and
finalize each env's batch as it completes. ``restored`` episodes of this epoch
landed before a resume and rejoin it first; when ``superseding_step`` returns a
newer checkpoint, the unfinished episodes of this epoch are cancelled so the
caller can move on to it."""
for env_name in fired:
await monitors.log_eval_plan(env_name, step, self.eval_sink.batch_size_for(env_name))
now = time.perf_counter()
for env_name in fired:
self.eval_triggered_at[(env_name, step)] = now
total_rollouts = sum(
request.rollouts or 0
for request in self.eval_source.queue
if request.step == step and request.env_name in fired
)
restored_part = f", {len(restored)} restored" if restored else ""
get_logger().info(
f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts{restored_part})"
)
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=f"eval was triggered at step {step}")
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
for episode in restored:
await self.land(episode, pending)
cancellation_task: asyncio.Task[int] | None = None
newer_step: int | None = None
while pending:
if (
cancellation_task is None
and superseding_step is not None
and (newer_step := superseding_step()) is not None
):
get_logger().warning(
f"Checkpoint {newer_step} is ready - cancelling unfinished eval episodes for step {step}"
)
cancellation_task = asyncio.create_task(
self.dispatcher.cancel_eval_step(step), name=f"cancel-eval-step-{step}"
)
try:
if superseding_step is not None:
item = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=POLL_INTERVAL_S)
else:
item = await self.dispatcher.out_q.get()
except asyncio.TimeoutError:
if cancellation_task is not None and cancellation_task.done():
cancellation_task.result()
continue
if isinstance(item, GroupCancellation):
eval_batch = self.eval_sink.cancel(item)
elif isinstance(item, DispatchFailure):
eval_batch = self.eval_sink.fail(item)
else:
stamp_arrival([item], "eval", eval_work(item).step)
await self.land(item, pending)
continue
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
pending.discard(eval_batch.env_name)
if cancellation_task is not None:
cancelled = await cancellation_task
get_logger().warning(
f"Cancelled {cancelled} unfinished eval episodes for step {step}; advancing to checkpoint {newer_step}"
)
async def land(self, episode: vf.Episode, pending: set[str]) -> None:
"""One episode of the epoch, arrived or restored: through the monitors and into
its env's batch, which is finalized once the epoch is complete."""
step = eval_work(episode).step
await monitors.log([episode], step, "eval", "all")
eval_batch = self.eval_sink.add(episode)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
pending.discard(eval_batch.env_name)
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
if not batch.episodes and not batch.failures and not batch.cancelled:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
return
if batch.episodes.effective:
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
await monitors.log_annotations(stamp_batch(batch.episodes.effective.vf_episodes, batch.step))
await monitors.log_eval_epoch(batch.env_name, batch.step, batch.episodes.vf_episodes)
episodes = batch.episodes
effective = episodes.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", episodes), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
total_attempts = len(episodes) + len(batch.failures) + batch.cancelled
metrics |= dispatch_failure_metrics(
batch.failures,
prefix=f"eval/{batch.env_name}/all",
total_attempts=total_attempts,
)
if batch.cancelled:
metrics[f"eval/{batch.env_name}/all/cancelled/count"] = float(batch.cancelled)
metrics[f"eval/{batch.env_name}/all/cancelled/mean"] = batch.cancelled / total_attempts
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
eff, full = effective.metrics, episodes.metrics
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
if batch.cancelled:
get_logger().warning(
f"Partially evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Error {full.has_error.mean():.1%} | "
f"Completed {len(episodes)}/{total_attempts} | Cancelled {batch.cancelled}/{total_attempts}"
)
return
get_logger().success(
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%}"
)
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
"""Pipeline view for the ``PeriodicLogger``: per-env epoch progress plus the
in-flight pool against the controller's current cap."""
disp_gauges = self.dispatcher.gauges()
disp_drain = self.dispatcher.metrics.drained(train_envs=set(), eval_envs={env.name for env in self.eval_envs})
parts = []
for env_name, _step, arrived, expected in sorted(self.eval_sink.batch_progress()):
parts.append(f"{env_name} {arrived}/{expected} ({arrived / expected:.1%})" if expected else env_name)
progress_part = " | ".join(parts) if parts else "Idle"
stages = live.stage_counts(list(self.dispatcher.inflight.values()))
body = (
f"{progress_part}; {self.dispatcher.inflight_eval_count} inflight episodes "
f"(cap {self.dispatcher.max_inflight}, signal {self.concurrency.signal})"
+ (f" - {stages}" if stages else "")
)
payload = {**disp_gauges, **disp_drain, **self.concurrency.gauges()}
return body, payload
async def drain(self) -> None:
"""Stop the background loggers so nothing logs after the monitors finalize."""
await self.periodic_logger.stop()
await self.inference_metrics.stop()
async def stop(self) -> None:
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
if self.periodic_logger is not None:
await self.periodic_logger.stop()
if self.inference_metrics is not None:
await self.inference_metrics.stop()
if self.dispatcher is not None:
await self.dispatcher.stop()
if self.clients is not None:
await self.clients.aclose()
if self.admin_plane is not None:
await self.admin_plane.aclose()
-66
View File
@@ -1,66 +0,0 @@
"""Checkpoint standalone eval progress cursor."""
from __future__ import annotations
import contextlib
import os
import pickle
import tempfile
import time
from pathlib import Path
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_ckpt_dir, get_step_path
class CheckpointManager:
def __init__(self, output_dir: Path) -> None:
self.ckpt_dir = get_ckpt_dir(output_dir)
def get_ckpt_path(self, step: int) -> Path:
return get_step_path(self.ckpt_dir, step) / "evals"
def latest_step(self) -> int:
steps = [
step for step in get_all_ckpt_steps(self.ckpt_dir) if (self.get_ckpt_path(step) / "progress.pt").is_file()
]
if not steps:
raise FileNotFoundError(f"No evals checkpoints found in {self.ckpt_dir}")
return steps[-1]
def save(self, eval_source: EvalSource) -> None:
cursor = eval_source.cursor
ckpt_path = self.get_ckpt_path(cursor)
ckpt_path.mkdir(parents=True, exist_ok=True)
start = time.perf_counter()
# Replace atomically so resume never observes a partially written pickle.
fd, tmp_name = tempfile.mkstemp(dir=ckpt_path, prefix="progress.pt.", suffix=".tmp")
try:
with os.fdopen(fd, "wb") as f:
pickle.dump(eval_source.state_dict(), f)
os.replace(tmp_name, ckpt_path / "progress.pt")
except BaseException:
with contextlib.suppress(OSError):
os.unlink(tmp_name)
raise
get_logger().debug(
f"Evals checkpoint saved to {ckpt_path} (cursor={cursor}) in {format_time(time.perf_counter() - start)}"
)
def load(
self,
step: int,
eval_source: EvalSource,
path: Path | None = None,
) -> None:
ckpt_path = path if path is not None else self.get_ckpt_path(step)
state_file = ckpt_path / "progress.pt"
if not state_file.is_file():
raise FileNotFoundError(f"Evals checkpoint not found at {state_file}")
get_logger().info(f"Loading evals checkpoint from {state_file}")
with open(state_file, "rb") as f:
state = pickle.load(f)
if state["cursor"] != step:
raise ValueError(f"Evals checkpoint contains cursor {state['cursor']}, expected step {step}")
eval_source.load_state_dict(state)
-605
View File
@@ -1,605 +0,0 @@
"""Evals: multi-env evals against a live inference server.
Standalone (no ``[online]``), it runs one epoch of every configured eval
source against the weights the inference server currently serves, then exits.
With ``[online]``, it watches a broadcasts directory for offered weight
broadcasts through a ``WeightReceiver`` (announced by their
``.sender_ready`` marker), moves the inference server onto each of them, and
runs the configured evals against the updated weights, sequentially per
broadcast so every epoch measures exactly one policy version. Every offered
broadcast must be received, even when no eval is due — the trainer blocks
inside the handshake until the receiver acknowledges.
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
fed by the ``InferenceMetricsCollector``'s ``/metrics`` polls. Eval episodes
are version-pinned measurements. By default, a newer online checkpoint cancels
unfinished episodes from the prior version; callers can disable this when they need
every epoch to drain.
Env servers: sources without an explicit ``serve.address`` get an env server
spawned by the evals process at their derived address; sources with one are
externally managed (e.g. spawned by the ``sft`` launcher, which stamps the
derived addresses into this config)."""
from __future__ import annotations
import asyncio
import json
import os
import time
import uuid
from pathlib import Path
from subprocess import Popen
from prime_rl import monitors
from prime_rl.configs.evals import EvalsConfig
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
from prime_rl.evals.ckpt import CheckpointManager
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.metrics import dispatch_failure_metrics
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
from prime_rl.orchestrator.utils import (
episode_group_id,
eval_work,
intercept_vf_logging,
set_default_executor,
)
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.config import dump_resolved_config
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import create_attempt_log_dir, get_all_ckpt_steps, get_config_dir
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
from prime_rl.utils.utils import clean_exit
monkey_patch_oai_iterable_types()
monkey_patch_chat_completion_logprobs()
# How often to re-scan the broadcasts directory for new weight broadcasts.
POLL_INTERVAL_S = 2.0
# Budget for the trainer's startup broadcast: it is always coming, but only
# after the trainer has finished loading the model.
STARTUP_BROADCAST_TIMEOUT_S = 1200
class Evals:
def __init__(self, config: EvalsConfig, log_dir: Path | None = None) -> None:
self.config = config
self.log_dir = log_dir or (
Path(os.environ["PRL_LOG_DIR"])
if "PRL_LOG_DIR" in os.environ
else create_attempt_log_dir(config.output_dir)
)
setup_logger(config.log.level, json_logging=config.log.json_logging)
intercept_vf_logging(logger="verifiers.v1", level="WARN")
mode = f"online (broadcasts_dir={config.online.broadcasts_dir})" if config.online is not None else "standalone"
get_logger().info(f"Starting evals ({mode})")
# The last weight-checkpoint step already handled (evaluated or skipped).
self.last_step = (config.online.resume_step if config.online is not None else None) or 0
self.eval_triggered_at: dict[tuple[str, int], float] = {}
self.ckpt_manager = CheckpointManager(config.output_dir)
self.last_saved_cursor = 0
self.env_server_procs: list[Popen] = []
self.dispatcher_task: asyncio.Task | None = None
# Assigned in setup(); None-initialized so stop() can tear down a
# partially completed setup with plain attribute checks.
self.clients: InferenceClient | None = None
self.admin_plane: AdminPlane | None = None
self.dispatcher: Dispatcher | None = None
self.inference_metrics: InferenceMetricsCollector | None = None
self.periodic_logger: PeriodicLogger | None = None
async def setup(self) -> None:
config = self.config
set_default_executor()
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
producer="evals",
wandb=config.monitors.wandb,
file=config.monitors.file,
output_dir=config.output_dir,
run_config=config,
eval_env_names=[source.resolved_name for source in config.eval.source],
overview_flavor="sft",
)
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
self.run_name = os.environ.get("PRL_RUN_NAME")
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
self.clients = InferenceClient(config.eval.client, model_name=config.model)
self.admin_plane = AdminPlane(config.eval.client)
self.spawn_env_servers()
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.eval.source, config.eval.env_addresses)
await self.eval_envs.start()
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
get_logger().info("Waiting for inference pool to be ready")
await self.admin_plane.wait_for_ready(config.model)
get_logger().success("Inference pool ready")
self.receiver: WeightReceiver | None = None
if config.online is not None:
assert config.online.broadcasts_dir is not None
# A hand-written online config may omit the transport; broadcasts
# are then plain filesystem checkpoints.
weight_broadcast = config.weight_broadcast or FileSystemWeightBroadcastConfig()
get_logger().info(f"Initializing weight broadcast ({weight_broadcast})")
self.receiver = setup_weight_receiver(
config.online.broadcasts_dir,
weight_broadcast,
admin_plane=self.admin_plane,
model_name=config.model,
)
await self.receiver.initialize()
is_resumed = config.online is not None and config.online.resume_step is not None
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=is_resumed)
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
if config.resume is not None:
if config.resume.dir is not None:
resume_step = config.resume.dir_step
resume_path = config.resume.dir / "evals"
else:
resume_step = config.resume.step or self.ckpt_manager.latest_step()
resume_path = None
self.ckpt_manager.load(
resume_step,
self.eval_source,
path=resume_path,
)
self.last_saved_cursor = self.eval_source.cursor
get_logger().info(f"Resuming evals from task cursor {self.eval_source.cursor}")
self.policy = Policy(version=0, model_name=config.model)
# Pessimistic per-episode token cost for the controller's starting cap,
# only used when the engine doesn't report its max context length.
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.eval.source) or 8192
self.concurrency = ConcurrencyController(config.eval.concurrency, fallback_cost=fallback_cost)
self.dispatcher = Dispatcher(
train_envs=None,
eval_envs=self.eval_envs,
train_source=None,
eval_source=self.eval_source,
policy_clients=self.clients,
policy=self.policy,
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.eval.concurrency.max_inflight,
tasks_per_minute=None,
max_off_policy_steps=0,
run_id=self.run_id,
run_name=self.run_name,
on_episode_complete=self.concurrency.record_episode,
)
# No ``on_overload``: eval episodes are measurements and are never
# cancelled — a cut only blocks admission until the pool drains.
self.concurrency.bind(
set_limit=self.dispatcher.set_limit,
get_inflight=lambda: self.dispatcher.current_inflight,
)
# The collector always polls — it feeds the concurrency controller;
# metrics fan out to every registered monitor.
self.inference_metrics = InferenceMetricsCollector(
self.admin_plane.clients,
on_load=self.concurrency.observe,
)
# Fail fast when adaptivity has no signal: external API endpoints
# (e.g. Prime Inference) expose no vLLM /metrics, so without a probe
# hit the cap would silently sit at min_inflight forever. A pinned
# band (min_inflight = max_inflight) makes the controller inert and
# is the supported way to run against such endpoints.
if not await self.inference_metrics.probe():
concurrency = config.eval.concurrency
if concurrency.min_inflight != concurrency.max_inflight:
urls = ", ".join(str(client.base_url) for client in self.admin_plane.clients)
raise ValueError(
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
"pin the concurrency by setting eval.concurrency.min_inflight = max_inflight."
)
get_logger().warning(f"No engine metrics - running with concurrency pinned at {concurrency.min_inflight}")
await self.inference_metrics.start()
self.periodic_logger = PeriodicLogger(
name="Evals",
collect=self.collect_pipeline_view,
metric_keys=[
*list(self.dispatcher.gauges().keys()),
*list(self.concurrency.gauges().keys()),
*DispatcherMetrics.drain_keys(train_envs=set(), eval_envs={env.name for env in self.eval_envs}),
],
interval=config.log.interval,
wandb_enabled=wandb_enabled,
)
def spawn_env_servers(self) -> None:
"""Spawn one env server per source without an explicit ``serve.address``,
at the source's derived address."""
config = self.config
addresses = config.eval.env_addresses
config_dir = get_config_dir(config.output_dir) / "envs" / "eval"
log_dir = self.log_dir / "envs" / "eval"
for source in config.eval.source:
if source.serve.address is not None:
continue
name = source.resolved_name
address = addresses[("eval", name)]
source_dict = dump_resolved_config(source)
server_config = {
"env": source_dict["env"],
"serve": {**(source_dict.get("serve") or {}), "address": address},
"log": {"level": config.log.vf_level, "json_logging": config.log.json_logging},
}
config_dir.mkdir(parents=True, exist_ok=True)
config_path = config_dir / f"{name}.json"
config_path.write_text(json.dumps(server_config, indent=2))
log_dir.mkdir(parents=True, exist_ok=True)
log_path = log_dir / f"{name}.log"
get_logger().info(f"Starting env server {name} at {address} (logs: {log_path})")
with open(log_path, "w") as log_file:
process = Popen(
["env-server", "@", config_path.as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS},
stdout=log_file,
stderr=log_file,
)
self.env_server_procs.append(process)
async def run(self) -> None:
await self.setup()
self.dispatcher_task = asyncio.create_task(self.dispatcher.start(), name="dispatcher")
await self.periodic_logger.start()
if self.config.online is None:
await self.maybe_run_evals(step=0)
else:
await self.watch()
self.maybe_save_checkpoint(force=True)
# The periodic logger and the collector log to the W&B run, so they
# must stop before finalize marks the run finished.
await self.periodic_logger.stop()
await self.inference_metrics.stop()
get_logger().success("Evals finished!")
async def watch(self) -> None:
"""Online mode: evaluate each eligible weight broadcast as it appears."""
config = self.config
assert config.online is not None
online = config.online
# Rendezvous with the trainer's startup broadcast (v0 fresh, the
# checkpoint step on resume) — always, for every transport: an
# in-memory trainer blocks inside its startup broadcast until this
# receive, and for filesystem it guarantees the served weights match
# the trainer's incoming policy.
assert self.receiver is not None
startup_step = online.resume_step or 0
await self.receiver.sync_startup(startup_step, timeout=STARTUP_BROADCAST_TIMEOUT_S)
self.policy.version = startup_step
if online.resume_step is None:
# The first trigger fires every env (policy v0) unless ``skip_first_step``.
await self.maybe_run_evals(step=0)
elif config.eval.retrigger_on_resume:
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
# evals); the startup rendezvous above already loaded its weights. The
# final broadcast force-fires every env, exactly like the watch loop below.
is_final = online.max_steps is not None and online.resume_step >= online.max_steps
await self.maybe_run_evals(step=online.resume_step, force=is_final)
get_logger().info(f"Watching {online.broadcasts_dir} for new weight broadcasts (max_steps={online.max_steps})")
while True:
assert online.broadcasts_dir is not None # resolved by the config validator
steps = get_all_ckpt_steps(online.broadcasts_dir)
published = {step: self.receiver.is_published(step) for step in steps}
newest_published = max((step for step in steps if published[step]), default=None)
# Also walk eval-due steps that are no longer on disk: broadcast cleaning
# (the trainer keeps only the newest broadcast) can delete a step before
# this scan sees it, and a vanished step would otherwise be skipped
# without a trace.
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_published)):
if step <= self.last_step:
continue
if step not in published:
get_logger().warning(
f"Weight broadcast for eval step {step} was deleted before it could be "
"evaluated (broadcast cleaning outpaced the evals process) - skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
if not published[step]:
# The trainer writes broadcasts in ascending order, so a marker-less
# step below a published one is an abandoned partial write (e.g. a
# crash mid-save), not one in progress — skip it instead of wedging.
if newest_published is None or newest_published < step:
break # still being written — later steps can't be ready either
get_logger().warning(
f"Weight broadcast step {step} is not marked published but newer "
"broadcasts are - treating it as abandoned and skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
is_final = online.max_steps is not None and step >= online.max_steps
await self.maybe_run_evals(step=step, reload_weights=True, force=is_final)
if online.max_steps is not None and self.last_step >= online.max_steps:
break
await asyncio.sleep(POLL_INTERVAL_S)
def next_published_step(self, step: int) -> int | None:
"""Return the first newer checkpoint offered by the trainer."""
assert self.config.online is not None
assert self.config.online.broadcasts_dir is not None
assert self.receiver is not None
return next(
(
candidate
for candidate in get_all_ckpt_steps(self.config.online.broadcasts_dir)
if candidate > step and self.receiver.is_published(candidate)
),
None,
)
def deleted_due_steps(self, steps: list[int], newest_published: int | None) -> set[int]:
"""Eval-due steps up to the newest published broadcast that are missing from
the broadcasts dir — the trainer wrote them (it broadcasts at every due step),
so their absence means broadcast cleaning removed them before they were
evaluated."""
if newest_published is None:
return set()
due = {
step
for interval in self.eval_source.intervals.values()
for step in range(interval, newest_published + 1, interval)
}
return due - set(steps)
async def maybe_run_evals(self, step: int, *, reload_weights: bool = False, force: bool = False) -> None:
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
reloading the inference weights first. No-op when no env is due — except
that a live transport's broadcast must always be received (the trainer
is blocked inside it), eval or no eval."""
if reload_weights:
assert self.receiver is not None
broadcast_dir = self.receiver.step_dir(step)
if not self.receiver.is_published(step):
get_logger().warning(f"No published weight broadcast for step {step} ({broadcast_dir}) - skipping eval")
self.last_step = max(self.last_step, step)
return
fired = self.eval_source.trigger(step, force=force)
self.last_step = max(self.last_step, step)
if reload_weights:
# Every offered version must be received: the trainer blocks inside
# the handshake, so a failed receive fails the run loudly.
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
await self.dispatcher.on_version_pending(step)
await self.receiver.receive(step)
self.policy.version = step
await self.dispatcher.on_new_version(step)
if not fired:
return
for env_name in fired:
task_count = self.eval_source.triggered_task_count(env_name, step)
self.eval_sink.set_batch_size(env_name, step, task_count * self.eval_sink.group_size_for(env_name))
now = time.perf_counter()
for env_name in fired:
self.eval_triggered_at[(env_name, step)] = now
total_rollouts = sum(
self.eval_envs.get(request.env_name).config.group_size
for request in self.eval_source.queue
if request.step == step and request.env_name in fired
)
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
# between the trigger above and the weight reload completing.
if not reload_weights:
self.policy.version = step
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=f"eval was triggered at step {step}")
await self.consume_epoch(fired, step)
async def consume_epoch(self, fired: list[str], step: int) -> None:
"""Consume one epoch, preempting it when a newer checkpoint is ready."""
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name, step) > 0}
cancellation_task: asyncio.Task[int] | None = None
superseding_step: int | None = None
online = self.config.online
while pending:
if (
cancellation_task is None
and online is not None
and self.config.eval.cancel_on_new_checkpoint
and (superseding_step := self.next_published_step(step)) is not None
):
get_logger().warning(
f"Checkpoint {superseding_step} is ready - cancelling unfinished eval episodes for step {step}"
)
cancellation_task = asyncio.create_task(
self.dispatcher.cancel_eval_step(step), name=f"cancel-eval-step-{step}"
)
try:
if online is not None and self.config.eval.cancel_on_new_checkpoint:
item = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=POLL_INTERVAL_S)
else:
item = await self.dispatcher.out_q.get()
except asyncio.TimeoutError:
if cancellation_task is not None and cancellation_task.done():
cancellation_task.result()
continue
if isinstance(item, GroupCancellation):
eval_batch = self.eval_sink.cancel(item)
group_completed = False
group_id = item.group_id
elif isinstance(item, DispatchFailure):
eval_batch = self.eval_sink.fail(item)
group_completed = not self.eval_sink.has_pending_group(item.group_id)
group_id = item.group_id
else:
item_step = eval_work(item).step
stamp_arrival([item], "eval", item_step)
await monitors.log([item], item_step, "eval", "all")
eval_batch = self.eval_sink.add(item)
group_id = episode_group_id(item)
group_completed = not self.eval_sink.has_pending_group(group_id)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
pending.discard(eval_batch.env_name)
if group_completed:
source_index = self.dispatcher.pop_source_index(group_id)
if self.config.online is not None:
continue
if source_index is None:
raise RuntimeError(f"Eval group {group_id} is missing its source cursor")
if self.eval_source.mark_completed(source_index):
self.maybe_save_checkpoint()
if cancellation_task is not None:
cancelled = await cancellation_task
get_logger().warning(
f"Cancelled {cancelled} unfinished eval episodes for step {step}; "
f"advancing to checkpoint {superseding_step}"
)
def maybe_save_checkpoint(self, *, force: bool = False) -> None:
if self.config.ckpt is None:
return
cursor = self.eval_source.cursor
if cursor <= 0 or cursor == self.last_saved_cursor:
return
if not force and cursor - self.last_saved_cursor < self.config.ckpt.interval:
return
self.ckpt_manager.save(self.eval_source)
self.last_saved_cursor = cursor
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
if not batch.episodes and not batch.failures and not batch.cancelled:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
return
if batch.episodes.effective:
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
await monitors.log_annotations(stamp_batch(batch.episodes.effective.vf_episodes, batch.step))
episodes = batch.episodes
effective = episodes.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", episodes), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
total_attempts = len(episodes) + len(batch.failures) + batch.cancelled
metrics |= dispatch_failure_metrics(
batch.failures,
prefix=f"eval/{batch.env_name}/all",
total_attempts=total_attempts,
)
if batch.cancelled:
metrics[f"eval/{batch.env_name}/all/cancelled/count"] = float(batch.cancelled)
metrics[f"eval/{batch.env_name}/all/cancelled/mean"] = batch.cancelled / total_attempts
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
eff, full = effective.metrics, episodes.metrics
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
if batch.cancelled:
get_logger().warning(
f"Partially evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Error {full.has_error.mean():.1%} | "
f"Completed {len(episodes)}/{total_attempts} | Cancelled {batch.cancelled}/{total_attempts}"
)
return
get_logger().success(
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%}"
)
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
"""Pipeline view for the ``PeriodicLogger``: per-env epoch progress plus the
in-flight pool against the controller's current cap."""
disp_gauges = self.dispatcher.gauges()
disp_drain = self.dispatcher.metrics.drained(train_envs=set(), eval_envs={env.name for env in self.eval_envs})
parts = []
for env_name, _step, arrived, expected, buffered in sorted(self.eval_sink.batch_progress()):
part = f"{env_name} {arrived}/{expected} ({arrived / expected:.1%})" if expected else env_name
if buffered:
part += f" (+{buffered} buffered)"
parts.append(part)
progress_part = " | ".join(parts) if parts else "Idle"
body = (
f"{progress_part}; {self.dispatcher.inflight_eval_count} inflight episodes "
f"(cap {self.dispatcher.max_inflight}, signal {self.concurrency.signal})"
)
payload = {**disp_gauges, **disp_drain, **self.concurrency.gauges()}
return body, payload
async def stop(self) -> None:
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
if self.periodic_logger is not None:
await self.periodic_logger.stop()
if self.inference_metrics is not None:
await self.inference_metrics.stop()
if self.dispatcher is not None:
await self.dispatcher.stop()
if self.clients is not None:
await self.clients.aclose()
if self.admin_plane is not None:
await self.admin_plane.aclose()
cleanup_processes(self.env_server_procs)
@clean_exit
async def run_evals(config: EvalsConfig, log_dir: Path | None = None) -> None:
evals = Evals(config, log_dir)
try:
await evals.run()
# Finalize only on a clean exit — a crashed evals must not mark the run completed.
await monitors.finalize()
finally:
await evals.stop()
def main() -> None:
from prime_rl.entrypoints.evals import main as entrypoint_main
entrypoint_main()
if __name__ == "__main__":
main()
+42 -7
View File
@@ -13,10 +13,15 @@ import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, overload
from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig, WandbMonitorConfig
from prime_rl.configs.monitors import (
FileMonitorConfig,
PrimeEvalMonitorConfig,
PrimeTrainMonitorConfig,
WandbMonitorConfig,
)
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.monitors.file import FileMonitor
from prime_rl.monitors.prime import PrimeMonitor
from prime_rl.monitors.prime import PrimeEvalMonitor, PrimeTrainMonitor
from prime_rl.monitors.wandb import WandbMonitor
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import format_time, get_logger
@@ -27,7 +32,8 @@ if TYPE_CHECKING:
__all__ = [
"Monitor",
"WandbMonitor",
"PrimeMonitor",
"PrimeTrainMonitor",
"PrimeEvalMonitor",
"FileMonitor",
"setup",
"get",
@@ -41,7 +47,7 @@ MONITORS: list[Monitor] = []
async def setup(
wandb: WandbMonitorConfig | None = None,
prime: PrimeMonitorConfig | None = None,
prime: PrimeTrainMonitorConfig | PrimeEvalMonitorConfig | None = None,
file: FileMonitorConfig | None = None,
*,
output_dir: Path,
@@ -49,7 +55,7 @@ async def setup(
run_config: BaseConfig | None = None,
train_env_names: list[str] | None = None,
eval_env_names: list[str] | None = None,
overview_flavor: Literal["rl", "sft"] = "rl",
overview_flavor: Literal["rl", "sft", "eval"] = "rl",
) -> None:
"""Construct, initialize, and register one monitor per non-None config.
@@ -63,8 +69,10 @@ async def setup(
return
monitors: list[tuple[str, Monitor, dict[str, Any]]] = []
if prime is not None:
monitors.append(("prime", PrimeMonitor(prime), dict(config=run_config)))
if isinstance(prime, PrimeTrainMonitorConfig):
monitors.append(("prime", PrimeTrainMonitor(prime), dict(config=run_config, output_dir=output_dir)))
elif isinstance(prime, PrimeEvalMonitorConfig):
monitors.append(("prime", PrimeEvalMonitor(prime), dict(config=run_config, output_dir=output_dir)))
if wandb is not None:
monitors.append(
(
@@ -131,6 +139,33 @@ async def log_annotations(updates: list[dict[str, Any]]) -> None:
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
async def log_eval_plan(env_name: str, step: int, expected: int) -> None:
"""Log an eval epoch's expected episode count to all registered monitors."""
for monitor in MONITORS:
try:
await monitor.log_eval_plan(env_name, step, expected)
except Exception as e:
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
async def log_live(events: list[dict[str, Any]]) -> None:
"""Log live-trace events to all registered monitors."""
for monitor in MONITORS:
try:
await monitor.log_live(events)
except Exception as e:
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
async def log_eval_epoch(env_name: str, step: int, episodes: list[vf.Episode]) -> None:
"""Log one finished eval epoch to all registered monitors."""
for monitor in MONITORS:
try:
await monitor.log_eval_epoch(env_name, step, episodes)
except Exception as e:
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
async def finalize() -> None:
"""Finalize the run on all registered monitors."""
for monitor in MONITORS:
+14
View File
@@ -57,5 +57,19 @@ class Monitor(ABC):
"""Log trace updates — post-hoc facts about traces this run already logged.
Monitors that only carry scalars ignore them."""
async def log_live(self, events: list[dict[str, Any]]) -> None:
"""Log the env servers' stream of in-flight traces: ``{"delta", "dispatch"}`` for
each delta as it arrived, ``{"done": trace_id}`` when a trace's episode finished.
Monitors that only carry finished work ignore it."""
async def log_eval_plan(self, env_name: str, step: int, expected: int) -> None:
"""Log how many episodes the eval epoch of ``env_name`` at ``step`` will produce,
known once its tasks are counted. Monitors that only carry results ignore it."""
async def log_eval_epoch(self, env_name: str, step: int, episodes: list[vf.Episode]) -> None:
"""Log one finished eval epoch: every episode ``env_name`` produced for ``step``,
errored ones included. Fires once per epoch, after the episodes streamed through
``log``. Monitors that carry episodes as they arrive ignore it."""
async def finalize(self) -> None:
"""Finalize run."""
+62 -1
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import json
import shutil
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, BinaryIO, TextIO
@@ -13,8 +14,9 @@ from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
from prime_rl.monitors.file.traces.chunks import ChunkedJsonl
from prime_rl.monitors.file.traces.index import index_row
from prime_rl.monitors.file.traces.live import get_live_dir, get_pending_dir
from prime_rl.monitors.file.traces.update import update_index_row
from prime_rl.utils.pathing import get_file_monitor_dir
from prime_rl.utils.pathing import get_eval_plan_path, get_file_monitor_dir
from prime_rl.utils.utils import sanitize
if TYPE_CHECKING:
@@ -37,6 +39,7 @@ class FileMonitor(Monitor):
self._logged = sum(1 for _ in index.open("rb")) if index.is_file() else 0
self.path = get_file_monitor_dir(output_dir) / self.config.path
self.path.parent.mkdir(parents=True, exist_ok=True)
self._live_cleared = False
# Line-buffered append so a concurrently-running dashboard can tail the file.
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
self._streams: dict[Path, tuple[ChunkedJsonl, BinaryIO]] = {}
@@ -56,6 +59,64 @@ class FileMonitor(Monitor):
row["producer"] = self.producer
self.file.write(json.dumps(row) + "\n")
async def log_eval_plan(self, env_name: str, step: int, expected: int) -> None:
"""Merge the epoch's expected count into ``plan.json`` (atomic replace)."""
path = get_eval_plan_path(self.output_dir)
plan = orjson.loads(path.read_bytes()) if path.is_file() else {}
plan.setdefault(env_name, {})[str(step)] = expected
tmp = path.with_suffix(".json.tmp")
tmp.write_bytes(orjson.dumps(plan))
tmp.replace(path)
async def log_live(self, events: list[dict[str, Any]]) -> None:
"""Append each delta to its trace's file under ``traces/live/`` (the first line
carrying the dispatch identity); a finished or discarded trace's file goes away.
A dispatched episode holds a placeholder under ``traces/live/pending/`` until its
first trace streams."""
live_dir = get_live_dir(self.output_dir)
pending_dir = get_pending_dir(self.output_dir)
# A previous attempt's live traces are stale: nothing streams into them again. Only
# the process that streams clears them - every process of a run shares this monitor.
clear = not self._live_cleared
self._live_cleared = True
def write() -> None:
if clear:
shutil.rmtree(live_dir, ignore_errors=True)
pending_dir.mkdir(parents=True, exist_ok=True)
appends: dict[Path, list[bytes]] = {}
for event in events:
if "done" in event:
appends.pop(live_dir / f"{event['done']}.jsonl", None)
(live_dir / f"{event['done']}.jsonl").unlink(missing_ok=True)
continue
if "pending" in event:
path = pending_dir / f"{event['pending']}.json"
tmp = path.with_suffix(".json.tmp")
tmp.write_bytes(orjson.dumps(event["dispatch"]))
tmp.replace(path)
continue
if "dispatched" in event:
(pending_dir / f"{event['dispatched']}.json").unlink(missing_ok=True)
continue
delta = event["delta"]
path = live_dir / f"{delta['trace']}.jsonl"
if delta.get("discard"):
appends.pop(path, None)
path.unlink(missing_ok=True)
continue
line = {**delta, "dispatch": event["dispatch"]} if "open" in delta else delta
# deltas key semantic links by node index (int)
appends.setdefault(path, []).append(
orjson.dumps(line, default=str, option=OPTS | orjson.OPT_NON_STR_KEYS)
)
# one open per file per batch: a trace's deltas of the last half second land together
for path, lines in appends.items():
with path.open("ab") as f:
f.write(b"".join(line + b"\n" for line in lines))
await asyncio.to_thread(write)
def _stream(self, directory: Path) -> tuple[ChunkedJsonl, BinaryIO]:
"""A stream and its index, opened on first use and kept open. Writers flush the
stream before the index: a row a reader sees points at a record it can read."""
@@ -0,0 +1,6 @@
"""``uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`` — the run's
live (in-flight) traces: a table of them, or one assembled from its deltas."""
from prime_rl.monitors.file.traces.live import main
main()
+23 -3
View File
@@ -21,8 +21,7 @@ def walk_timing(obj: dict, prefix: str, out: dict[str, float]) -> None:
def episode_kind(rec: dict) -> str:
"""The kind of work an episode did. The file monitor stamps it as the episode
lands; a stream written by another producer (a verifiers ``uv run eval`` run) is
read off its run info instead."""
lands; a record without the stamp is read off its run info instead."""
for trace in rec.get("traces") or []:
if (kind := (trace.get("info") or {}).get("kind")) in ("train", "eval"):
return kind
@@ -30,6 +29,21 @@ def episode_kind(rec: dict) -> str:
return (run.get("work") or {}).get("type") or run.get("type") or "eval"
TRUNCATING_STOPS = frozenset(
{"max_turns", "max_input_tokens", "max_output_tokens", "max_total_tokens", "compaction_failed"}
)
"""The stop conditions ``verifiers.v1.Trace.is_truncated`` counts as truncation."""
def trace_truncated(trace: dict) -> bool:
"""``Trace.is_truncated`` for a dumped trace: a framework limit stopped it, or its
last successful model call ran out of length."""
if trace.get("stop_condition") in TRUNCATING_STOPS:
return True
last = next((call for call in reversed(trace.get("calls") or []) if call.get("error") is None), None)
return bool(last and last.get("finish_reason") == "length")
def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
"""One index row: what the table, the filters, the chart and the sort need.
@@ -38,6 +52,7 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
rewards, advantages = [], []
input_tokens = output_tokens = turns = branches = 0
stop_condition = None
truncated = False
reward_parts: dict[str, list[float]] = {}
metric_parts: dict[str, list[float]] = {}
timing: dict[str, float] = {}
@@ -79,6 +94,7 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
if (node.get("message") or {}).get("role") == "assistant":
turns += 1
stop_condition = trace.get("stop_condition", stop_condition)
truncated = truncated or trace_truncated(trace)
if input_tokens == 0 and output_tokens == 0: # some eval traces carry no token arrays
for call in trace.get("calls") or []:
usage = call.get("usage") or {}
@@ -95,7 +111,9 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
"id": rec.get("id"),
"kind": episode_kind(rec),
"trace_ids": [trace_id for trace in rec.get("traces") or [] if (trace_id := trace.get("id"))],
"env": (rec.get("env") or {}).get("id") or (rec.get("env") or {}).get("name"),
# the env's name is the orchestrator's key for it (two sources can share a taskset
# id); a record without one falls back to the id
"env": (rec.get("env") or {}).get("name") or (rec.get("env") or {}).get("id"),
"group": (rec.get("group") or {}).get("id"),
"ok": rec.get("ok"),
"num_errors": len(rec.get("errors") or []),
@@ -106,8 +124,10 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
"turns": turns,
"branches": branches,
"stop_condition": stop_condition,
"truncated": truncated,
# 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"),
"arrival": (first_info.get("arrival") or {}).get("time"),
"duration": _episode_duration(first_info, timing),
}
+289
View File
@@ -0,0 +1,289 @@
"""Live traces: the in-flight rollouts, one file of deltas per trace.
Env servers stream every rollout as it happens (``verifiers.v1.serve.delta``): the
trace's header when it is minted, then each committed turn and each phase change. The
file monitor appends those deltas to ``traces/live/<trace_id>.jsonl`` — the first line
also carries the ``dispatch`` identity (kind, env, group, task, step) — and deletes the
file when the episode lands in the finished stream, so the directory only ever holds
in-flight work. Reading one live trace is folding one small file; ``ls`` lists what is
in flight; finished traces are untouched (the stream and its index).
uv run python -m prime_rl.monitors.file.traces <run_dir> # a table of live rollouts
uv run python -m prime_rl.monitors.file.traces <run_dir> <trace_id> # one assembled trace
"""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
import threading
import time
from pathlib import Path
from typing import Any
import orjson
from verifiers.v1.serve import EpisodeAssembly
from prime_rl.monitors.file.traces import get_trace_dir
STAGES = ("pending", "boot", "setup", "running", "finalize", "scoring", "done", "error")
SNIPPET_CHARS = 160
def get_live_dir(output_dir: Path) -> Path:
return get_trace_dir(output_dir) / "live"
def live_path(output_dir: Path, trace_id: str) -> Path:
return get_live_dir(output_dir) / f"{trace_id}.jsonl"
def get_pending_dir(output_dir: Path) -> Path:
"""Dispatched episodes whose first trace has not streamed yet, one JSON of dispatch
identity each; the file goes away once a trace streams or the episode ends."""
return get_live_dir(output_dir) / "pending"
def list_pending(output_dir: Path) -> list[dict[str, Any]]:
pending_dir = get_pending_dir(output_dir)
if not pending_dir.is_dir():
return []
rows = []
for path in pending_dir.glob("*.json"):
try:
rows.append(orjson.loads(path.read_bytes()))
except (FileNotFoundError, orjson.JSONDecodeError):
continue # gone or mid-write: it is not pending anymore, or not yet
return rows
def fold_lines(data: bytes, dispatch: dict[str, Any], assembly: EpisodeAssembly) -> tuple[int, dict[str, Any]]:
"""Apply the whole lines in ``data``; returns how many bytes were consumed (a line
torn by an append in progress waits for the next read) and the dispatch identity."""
end = data.rfind(b"\n") + 1
for line in data[:end].splitlines():
if not line.strip():
continue
delta = orjson.loads(line)
dispatch = delta.pop("dispatch", dispatch)
assembly.apply(delta) # KeyError("open") when a file lost its header line
return end, dispatch
def read_live(path: Path) -> tuple[dict[str, Any], dict[str, Any]] | None:
"""``(dispatch, trace)`` folded from one live file, None when the file vanished
(its episode finished), nothing has landed in it yet, or it does not fold."""
try:
data = path.read_bytes()
except FileNotFoundError:
return None
assembly = EpisodeAssembly()
try:
_, dispatch = fold_lines(data, {}, assembly)
except (orjson.JSONDecodeError, KeyError):
return None
if not assembly.traces:
return None
(trace,) = assembly.traces.values()
return dispatch, trace
class LiveFolds:
"""Incremental folds of a run's live files: a poll reads only the bytes a file gained
since the last one and applies them to the assembly it already holds. Kept per process
by a long-lived reader (the dashboard); the CLI folds from scratch."""
def __init__(self) -> None:
self._folds: dict[Path, tuple[int, dict[str, Any], EpisodeAssembly]] = {}
# the list and the single-trace endpoints serve from one cache on a thread pool:
# a delta must fold once, and a caller serializes a copy, never the growing fold
self._lock = threading.Lock()
def read(self, path: Path) -> tuple[dict[str, Any], dict[str, Any]] | None:
with self._lock:
try:
size = path.stat().st_size
except FileNotFoundError:
self._folds.pop(path, None)
return None
consumed, dispatch, assembly = self._folds.get(path) or (0, {}, EpisodeAssembly())
if size < consumed: # replaced by a new attempt's file
consumed, dispatch, assembly = 0, {}, EpisodeAssembly()
if size > consumed:
with path.open("rb") as f:
f.seek(consumed)
data = f.read()
try:
read, dispatch = fold_lines(data, dispatch, assembly)
except (orjson.JSONDecodeError, KeyError):
self._folds.pop(path, None)
return None
consumed += read
self._folds[path] = (consumed, dispatch, assembly)
if not assembly.traces:
return None
(trace,) = assembly.traces.values()
snapshot = orjson.dumps((dispatch, trace), option=orjson.OPT_NON_STR_KEYS)
return tuple(orjson.loads(snapshot))
def forget_missing(self, live_dir: Path) -> None:
present = set(live_dir.glob("*.jsonl")) if live_dir.is_dir() else set()
with self._lock:
for path in [path for path in self._folds if path not in present]:
del self._folds[path]
def list_live(output_dir: Path, folds: LiveFolds | None = None) -> list[tuple[dict[str, Any], dict[str, Any]]]:
"""Every in-flight trace with its dispatch identity, oldest dispatch first."""
live_dir = get_live_dir(output_dir)
if not live_dir.is_dir():
return []
if folds is not None:
folds.forget_missing(live_dir)
read = folds.read if folds is not None else read_live
folded = [read(path) for path in sorted(live_dir.glob("*.jsonl"))] # not the pending/ subdir
return sorted((item for item in folded if item is not None), key=lambda item: item[0].get("started") or 0)
def stage(trace: dict[str, Any]) -> str:
"""The phase a trace is in, read off its timing spans the way the rollout sets them."""
if trace.get("errors"):
return "error"
timing = trace.get("timing") or {}
if (timing.get("scoring") or {}).get("end"):
return "done"
for span, name in (
("scoring", "scoring"),
("finalize", "finalize"),
("agent", "running"),
("setup", "setup"),
("boot", "boot"),
):
if (timing.get(span) or {}).get("start"):
return name
return "pending"
def message_text(message: dict[str, Any]) -> str:
content = message.get("content")
if isinstance(content, str):
return content
if isinstance(content, list):
return " ".join(part.get("text", "") for part in content if isinstance(part, dict))
return ""
def trace_row(trace: dict[str, Any]) -> dict[str, Any]:
"""The live table's view of one trace: phase, turns, tokens, cost, last message."""
calls = trace.get("calls") or []
usage = [call.get("usage") or {} for call in calls]
# The newest node is usually a tool result; the assistant's latest words say more.
last = ""
for node in reversed(trace.get("nodes") or []):
message = node.get("message") or {}
if message.get("role") == "assistant" and (last := " ".join(message_text(message).split())):
break
costs = [u["cost"] for u in usage if u.get("cost") is not None]
nodes = trace.get("nodes") or []
parents = {node.get("parent") for node in nodes if node.get("parent") is not None}
return {
"trace": trace.get("id"),
"agent": (trace.get("agent") or {}).get("name", "agent"),
"stage": stage(trace),
"turns": len(calls),
"branches": sum(1 for index in range(len(nodes)) if index not in parents),
"input_tokens": sum(u.get("prompt_tokens") or 0 for u in usage),
"output_tokens": sum(u.get("completion_tokens") or 0 for u in usage),
"cost": sum(costs) if costs else None,
"stop_condition": trace.get("stop_condition"),
"errors": len(trace.get("errors") or []),
"pending": len(trace.get("pending") or []),
"last": last[:SNIPPET_CHARS],
}
def live_row(dispatch: dict[str, Any], trace: dict[str, Any]) -> dict[str, Any]:
started = dispatch.get("started")
return {**dispatch, "elapsed": time.time() - started if started else None, **trace_row(trace)}
def pending_row(dispatch: dict[str, Any]) -> dict[str, Any]:
started = dispatch.get("started")
return {
**dispatch,
"elapsed": time.time() - started if started else None,
"trace": None,
"agent": None,
"stage": "pending",
"turns": 0,
"branches": 0,
"input_tokens": 0,
"output_tokens": 0,
"cost": None,
"stop_condition": None,
"errors": 0,
"pending": 0,
"last": "",
}
def live_rows(output_dir: Path, folds: LiveFolds | None = None) -> list[dict[str, Any]]:
"""Every in-flight rollout: dispatched-but-not-yet-streaming placeholders and the
streaming traces, oldest dispatch first. A placeholder whose episode already streams
a trace is on its way out and is not listed twice."""
live = list_live(output_dir, folds)
streaming = {dispatch.get("id") for dispatch, _ in live}
rows = [pending_row(dispatch) for dispatch in list_pending(output_dir) if dispatch.get("id") not in streaming]
rows.extend(live_row(dispatch, trace) for dispatch, trace in live)
return sorted(rows, key=lambda row: row.get("started") or 0)
def live_etag(output_dir: Path) -> str:
"""A fingerprint of the live directory that changes whenever any in-flight rollout
does: the set of files and their sizes. Cheap enough to answer a poll a second."""
live_dir = get_live_dir(output_dir)
if not live_dir.is_dir():
return "0"
entries = []
for directory, pattern in ((live_dir, "*.jsonl"), (get_pending_dir(output_dir), "*.json")):
if not directory.is_dir():
continue
for entry in directory.glob(pattern):
try:
entries.append(f"{entry.name}:{entry.stat().st_size}")
except FileNotFoundError:
continue # unlinked between listing and stat: its episode finished
return hashlib.md5("\n".join(sorted(entries)).encode()).hexdigest()[:16]
def main() -> None:
parser = argparse.ArgumentParser(description="Read a run's live (in-flight) traces.")
parser.add_argument("run_dir", type=Path)
parser.add_argument("trace_id", nargs="?", help="print this trace assembled, as JSON")
args = parser.parse_args()
if args.trace_id:
folded = read_live(live_path(args.run_dir, args.trace_id))
if folded is None:
sys.exit(f"no live trace {args.trace_id} under {get_live_dir(args.run_dir)}")
dispatch, trace = folded
print(json.dumps({"dispatch": dispatch, "trace": trace}, indent=2, default=str))
return
rows = live_rows(args.run_dir)
if not rows:
print(f"no live traces under {get_live_dir(args.run_dir)}")
return
for row in rows:
elapsed = f"{row['elapsed']:.0f}s" if row.get("elapsed") is not None else "-"
dispatched = time.strftime("%H:%M:%S", time.localtime(row["started"])) if row.get("started") else "--:--:--"
print(
f"{dispatched} {(row['trace'] or '-')[:8]:8s} {row.get('kind', ''):5s} {row.get('env', ''):20s} {str(row.get('task', '')):24s} "
f"{row['stage']:9s} turns {row['turns']:3d} in {row['input_tokens']:>7d} out {row['output_tokens']:>7d} "
f"{elapsed:>6s} {row['last'][:60]}"
)
if __name__ == "__main__":
main()
+143 -4
View File
@@ -2,13 +2,17 @@ from __future__ import annotations
import asyncio
import os
from pathlib import Path
from typing import TYPE_CHECKING, Any
import orjson
import prime_runs as pr
from prime_cli.core.config import Config as PrimeConfig
from prime_rl.configs.monitors import PrimeMonitorConfig
from prime_rl.configs.monitors import PrimeEvalMonitorConfig, PrimeTrainMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.pathing import get_platform_run_path
from prime_rl.utils.utils import sanitize
if TYPE_CHECKING:
@@ -21,6 +25,21 @@ BASE_URL_VAR = "PRIME_API_BASE"
FINISH_TIMEOUT = 60.0
def write_platform_record(output_dir: Path, record: dict[str, Any]) -> None:
"""Leave the run's platform identity in the run directory for the dashboard's
"view on platform" link (atomic replace: a reader never sees a torn file)."""
path = get_platform_run_path(output_dir)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".json.tmp")
tmp.write_bytes(orjson.dumps(record, option=orjson.OPT_INDENT_2))
tmp.replace(path)
def read_platform_record(output_dir: Path) -> dict[str, Any] | None:
path = get_platform_run_path(output_dir)
return orjson.loads(path.read_bytes()) if path.is_file() else None
def _base_url() -> str | None:
"""$PRIME_API_BASE historically points at the RFT API root (``.../api/v1/rft``);
the SDK takes the platform base URL. Unset means the SDK resolves it."""
@@ -28,7 +47,7 @@ def _base_url() -> str | None:
return base.rstrip("/").removesuffix("/rft") if base else None
class PrimeMonitor(Monitor):
class PrimeTrainMonitor(Monitor):
"""Logs metrics and episodes to the Prime platform through ``prime_runs``.
The run handle owns what ``TrainRun`` used to do by hand: the RFT
@@ -42,10 +61,10 @@ class PrimeMonitor(Monitor):
and backpressure, so they never stall the loop.
"""
config: PrimeMonitorConfig
config: PrimeTrainMonitorConfig
run: pr.Run
async def init(self, config: BaseConfig | None = None) -> None:
async def init(self, config: BaseConfig | None = None, output_dir: Path | None = None) -> None:
init_kwargs: dict[str, Any]
if run_id := os.getenv("RUN_ID"):
# A managed launch pre-created the platform run and injected its id -
@@ -86,6 +105,8 @@ class PrimeMonitor(Monitor):
if self.run.url:
attached = " (attached via $RUN_ID)" if self.run.attached else ""
self.logger.info(f"Logging metrics and episodes to platform run {self.run.id} ({self.run.url}){attached}")
if output_dir is not None:
write_platform_record(output_dir, {"kind": "train", "id": self.run.id, "url": self.run.url})
else:
self.logger.info(f"Platform run disabled ({pr.MODE_ENV}=disabled)")
@@ -114,3 +135,121 @@ class PrimeMonitor(Monitor):
# then finalizes (idempotent on the platform side); an attached run's
# failure marking stays with the launcher.
await asyncio.to_thread(self.run.finish)
class PrimeEvalMonitor(Monitor):
"""Streams each eval epoch to the Prime platform through ``prime_runs``: one
evaluation per env and step, opened when the epoch starts (``log_eval_plan``), fed
every episode as it lands (``log_episodes``) and finished with the epoch's aggregates
(``log_eval_epoch``), so the platform page follows the run from its first episode.
Metrics are not forwarded; the evaluation is the epoch."""
config: PrimeEvalMonitorConfig
async def init(self, config: BaseConfig | None = None, output_dir: Path | None = None) -> None:
self.mode = os.getenv(pr.MODE_ENV) or "online"
# A configured monitor must work: the SDK looks the key up when an epoch opens,
# which is too late to find out there is none.
if self.mode == "online" and not (os.getenv("PRIME_API_KEY") or PrimeConfig().api_key):
raise RuntimeError("API key not found - set PRIME_API_KEY or run `prime login`")
self.model: str = config.model if config is not None else "unknown"
self.sources = {source.resolved_name: source for source in config.source} if config is not None else {}
self.run_id = os.getenv("PRL_RUN_ID")
self.output_dir = output_dir
# (env, step) -> its open evaluation; None once opening it failed, so the epoch's
# episodes do not retry the platform on every arrival
self.runs: dict[tuple[str, int], pr.Run | None] = {}
self._lock = asyncio.Lock()
if self.mode == "online":
self.logger.info("Streaming eval epochs to the Prime platform")
if output_dir is not None:
write_platform_record(output_dir, {"kind": "eval", "run_id": self.run_id, "evaluations": {}})
else:
self.logger.info(f"Platform evaluations disabled ({pr.MODE_ENV}=disabled)")
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
pass
def open(self, env_name: str, step: int, expected: int | None) -> pr.Run:
"""Open the platform evaluation of one epoch. Blocking: runs in a worker thread."""
source = self.sources[env_name]
name = self.config.name if len(self.sources) == 1 else f"{self.config.name}--{env_name}"
return pr.init(
kind="eval",
mode=self.mode,
base_url=_base_url(),
name=name,
environments=[source.env.taskset.id],
model=self.model,
framework="prime-rl",
finish_timeout=FINISH_TIMEOUT,
config={
"model": self.model,
"step": step,
"run_id": self.run_id,
"num_examples": expected // source.group_size if expected else None,
"rollouts_per_example": source.group_size,
},
)
async def run_for(self, env_name: str, step: int, expected: int | None = None) -> pr.Run | None:
"""The epoch's evaluation, opened on first use."""
key = (env_name, step)
async with self._lock:
if key in self.runs:
return self.runs[key]
try:
run = await asyncio.to_thread(self.open, env_name, step, expected)
except Exception as e:
self.logger.warning(f"Failed to open the {env_name} (Step {step}) evaluation: {type(e).__name__}: {e}")
self.runs[key] = None
return None
self.runs[key] = run
if run.url:
self.logger.info(f"Streaming {env_name} (Step {step}) evaluation - {run.url}")
if self.output_dir is not None:
record = read_platform_record(self.output_dir) or {
"kind": "eval",
"run_id": self.run_id,
"evaluations": {},
}
record["evaluations"][env_name] = {"step": step, "id": run.id, "url": run.url}
write_platform_record(self.output_dir, record)
return run
async def log_eval_plan(self, env_name: str, step: int, expected: int) -> None:
await self.run_for(env_name, step, expected)
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Every eval episode as it lands (the ``all`` subset is the arrival stream)."""
if kind != "eval" or subset != "all":
return
by_env: dict[str, list[vf.Episode]] = {}
for episode in episodes:
if episode.env.name is not None:
by_env.setdefault(episode.env.name, []).append(episode)
for env_name, batch in by_env.items():
run = await self.run_for(env_name, step)
if run is not None:
await asyncio.to_thread(run.log_episodes, batch) # a queue put, off the loop
async def log_eval_epoch(self, env_name: str, step: int, episodes: list[vf.Episode]) -> None:
run = await self.run_for(env_name, step)
if run is None:
return
try:
await asyncio.to_thread(run.finish, pr.metrics.from_episodes(episodes))
except Exception as e:
self.logger.warning(f"Failed to finish the {env_name} (Step {step}) evaluation: {type(e).__name__}: {e}")
return
self.logger.info(f"Uploaded {env_name} (Step {step}) evaluation - {run.url}")
async def finalize(self) -> None:
# An epoch the run did not finish leaves its evaluation open: close it as cancelled.
for (env_name, step), run in self.runs.items():
if run is None or run.finished:
continue
try:
await asyncio.to_thread(run.finish, status=pr.RunStatus.CANCELLED, error="interrupted")
except Exception as e:
self.logger.warning(f"Failed to close the {env_name} (Step {step}) evaluation: {type(e).__name__}: {e}")
+1 -1
View File
@@ -33,7 +33,7 @@ class WandbMonitor(Monitor):
config: BaseConfig | None = None,
train_env_names: list[str] | None = None,
eval_env_names: list[str] | None = None,
overview_flavor: Literal["rl", "sft"] = "rl",
overview_flavor: Literal["rl", "sft", "eval"] = "rl",
) -> None:
# W&B reads the start command off sys.argv; the launcher passes the original
# command to subprocesses via $WANDB_ARGS.
+7 -2
View File
@@ -149,8 +149,13 @@ def eval_section(name: str, env_pattern: str) -> ws.Section:
def build_sections(
train_envs: Sequence[str] = (), eval_envs: Sequence[str] = (), flavor: Literal["rl", "sft"] = "rl"
train_envs: Sequence[str] = (), eval_envs: Sequence[str] = (), flavor: Literal["rl", "sft", "eval"] = "rl"
) -> list[ws.Section]:
# A standalone eval run has no training signal: one section per eval env.
if flavor == "eval":
if eval_envs:
return [eval_section(f"eval/{env}", re.escape(env)) for env in eval_envs]
return [eval_section("eval", ".*")]
# SFT trains on a dataset, not rollouts: the train section is the loss/perplexity
# curves, eval sections are the same rollout-based ones as RL.
if flavor == "sft":
@@ -225,7 +230,7 @@ def ensure_overview_view(
name: str = OVERVIEW_NAME,
train_envs: Sequence[str] = (),
eval_envs: Sequence[str] = (),
flavor: Literal["rl", "sft"] = "rl",
flavor: Literal["rl", "sft", "eval"] = "rl",
) -> str | None:
"""Ensure an overview saved view exists for this run's env set. Reuses an existing overview built
for the same envs; when the env set is new, creates a fresh versioned view (``overview`` →
+2 -1
View File
@@ -2,7 +2,6 @@ from __future__ import annotations
from typing import TYPE_CHECKING
import torch
import verifiers.v1 as vf
from prime_rl.configs.algorithm import GRPOAlgoConfig
@@ -23,6 +22,8 @@ class GRPOAlgorithm(Algorithm):
self.length_penalty = config.length_penalty
async def score_group(self, episodes: list[vf.Episode]) -> None:
import torch # only the trainer-side extras ship torch; an eval process never scores a group
traces = [trace for _, trace in iter_trainable_traces(episodes)]
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
length_penalty = self.length_penalty
+2 -1
View File
@@ -1,6 +1,5 @@
from __future__ import annotations
import torch
import verifiers.v1 as vf
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
@@ -20,6 +19,8 @@ class MaxRLAlgorithm(Algorithm):
<= 0 carries no signal and gets zero advantages."""
async def score_group(self, episodes: list[vf.Episode]) -> None:
import torch # only the trainer-side extras ship torch; an eval process never scores a group
traces = [trace for _, trace in iter_trainable_traces(episodes)]
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
mean = rewards.mean()
+40 -12
View File
@@ -14,10 +14,38 @@ from renderers import RendererConfig
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
from verifiers.v1.configs.client import EvalClientConfig, TrainClientConfig
from prime_rl.configs.eval import PRIME_INFERENCE_URL
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.logger import get_logger
def resolve_api_key(api_key_var: str) -> str:
"""The API key named by ``api_key_var``; ``PRIME_API_KEY`` also falls back to the prime
CLI config (``prime login``), like the verifiers client does. ``"EMPTY"`` when unset."""
api_key = os.environ.get(api_key_var)
if not api_key and api_key_var == "PRIME_API_KEY":
from prime_cli.core.config import Config as PrimeConfig
api_key = PrimeConfig().api_key
return api_key or "EMPTY"
def resolve_headers(client_config: ClientConfig) -> dict[str, str]:
"""The static headers plus those read from the environment. A Prime Inference client
without a team header gets the team from ``$PRIME_TEAM_ID`` or the prime CLI config,
like the verifiers client: a team's internal models are served only under it."""
env_headers = {
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
}
headers = {**client_config.headers, **env_headers}
if client_config.base_url.startswith(PRIME_INFERENCE_URL) and "X-Prime-Team-ID" not in headers:
from prime_cli.core.config import Config as PrimeConfig
if team_id := os.environ.get("PRIME_TEAM_ID") or PrimeConfig().team_id:
headers["X-Prime-Team-ID"] = team_id
return headers
class PrefillScorer:
"""Prefill-scores token ids against a pool's endpoint, lazily resolving
a single OpenAI client from the pool's train client config."""
@@ -32,7 +60,7 @@ class PrefillScorer:
# for these chat-completions teacher configs.
self._client = AsyncOpenAI(
base_url=config.base_url,
api_key=os.environ.get(config.api_key_var) or "EMPTY",
api_key=resolve_api_key(config.api_key_var),
default_headers=config.headers or None,
)
return await prefill_logprobs(self._client, model, token_ids)
@@ -221,10 +249,7 @@ def setup_client(
"renderer": renderer_config,
"renderer_model_name": renderer_model_name,
}
env_headers = {
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
}
headers = {**client_config.headers, **env_headers}
headers = resolve_headers(client_config)
return config_cls(
base_url=client_config.base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra
)
@@ -240,12 +265,9 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
urls = client_config.admin_base_url if client_config.admin_base_url else [client_config.base_url]
def _setup_admin_client(base_url: str) -> httpx.AsyncClient:
env_headers = {
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
}
headers = {**client_config.headers, **env_headers}
api_key = os.getenv(client_config.api_key_var, "EMPTY")
if api_key and api_key != "EMPTY":
headers = resolve_headers(client_config)
api_key = resolve_api_key(client_config.api_key_var)
if api_key != "EMPTY":
headers["Authorization"] = f"Bearer {api_key}"
# Strip /v1 suffix since admin endpoints are at root level
@@ -270,7 +292,13 @@ async def maybe_check_has_model(
logger.debug(f"Checking if model {model_name} is in the inference pool")
results = await asyncio.gather(*[admin_client.get("/v1/models") for admin_client in admin_clients])
for admin_client, result in zip(admin_clients, results):
models = result.json()["data"]
body = result.json() if result.headers.get("content-type", "").startswith("application/json") else {}
if result.status_code != 200 or "data" not in body:
raise RuntimeError(
f"Listing the models of {admin_client.base_url} failed with status {result.status_code}: "
f"{result.text[:300]}"
)
models = body["data"]
if not any(model["id"] == model_name for model in models):
raise ValueError(f"Model {model_name} was not found in the inference pool on {admin_client.base_url}")
logger.debug(f"Model {model_name} was found in the inference pool")
+89 -26
View File
@@ -33,11 +33,13 @@ from collections import defaultdict
from collections.abc import Callable
from dataclasses import dataclass, field
from enum import Enum, auto
from typing import Literal
from typing import Any, Literal
import verifiers.v1 as vf
from aiolimiter import AsyncLimiter
from prime_rl import monitors
from prime_rl.orchestrator import live
from prime_rl.orchestrator.clients import InferenceClient
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
from prime_rl.orchestrator.eval_source import EvalSource
@@ -57,6 +59,10 @@ from prime_rl.orchestrator.utils import min_fresh_version
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
from prime_rl.utils.logger import get_logger
LIVE_INTERVAL_S = 0.5
LIVE_EVENT_CAP = 20_000
"""Buffered live events (deltas and bookkeeping) before the oldest deltas are dropped."""
class DispatcherMode(Enum):
"""Which kind of work the dispatcher schedules next."""
@@ -189,8 +195,10 @@ class Dispatcher:
self.min_burst = max((env.config.group_size for env in train_envs or ()), default=8)
self.inflight: dict[asyncio.Task, InflightEpisode] = {}
self.live_events: list[dict[str, Any]] = []
self.live_dropped = False
self.live_task: asyncio.Task | None = None
self.groups: dict[uuid.UUID, GroupState] = {}
self.source_indices_by_group: dict[str, int] = {}
# Bounded so the dispatcher backpressures on a slow sink (unbounded
# when no hard ceiling is configured — the dynamic cap still bounds
@@ -331,6 +339,7 @@ class Dispatcher:
async def start(self) -> None:
"""Single dispatch loop: schedule, wait, collect, repeat."""
self.task = asyncio.current_task()
self.live_task = asyncio.create_task(self.publish_live())
try:
while not self.stopped.is_set():
await self.fill_inflight()
@@ -356,10 +365,52 @@ class Dispatcher:
async def stop(self) -> None:
self.stopped.set()
await self.cancel_inflight_episodes()
if self.live_task is not None:
await safe_cancel(self.live_task)
self.live_task = None
await self.flush_live()
if self.task is not None:
await safe_cancel(self.task)
self.task = None
def retire(self, meta: InflightEpisode) -> None:
"""An episode left the in-flight set (finished, cancelled, dropped): its live
traces are over, and so is its pending placeholder if no trace ever streamed."""
if not meta.live:
self.live_events.append(live.dispatched_event(meta))
self.live_events.extend({"done": trace_id} for trace_id in meta.live)
def queue_live(self, event: dict[str, Any]) -> None:
"""Buffer a delta for the next flush. The buffer is bounded: past the cap the
oldest deltas go (the live view of those traces misses a turn), never the
bookkeeping events that create or remove files."""
self.live_events.append(event)
if len(self.live_events) > LIVE_EVENT_CAP:
kept = [e for e in self.live_events if "delta" not in e]
deltas = [e for e in self.live_events if "delta" in e]
dropped = len(deltas) - LIVE_EVENT_CAP // 2
self.live_events = kept + deltas[dropped:]
if not self.live_dropped:
self.live_dropped = True
get_logger().warning(f"Live trace buffer over {LIVE_EVENT_CAP} events - dropping the oldest deltas")
async def flush_live(self) -> None:
if not self.live_events:
return
events, self.live_events = self.live_events, []
try:
await monitors.log_live(events)
except asyncio.CancelledError:
# stop() cancels the publisher mid-write and flushes once more: nothing is lost
self.live_events = events + self.live_events
raise
async def publish_live(self) -> None:
"""Hand the streamed deltas to the monitors in batches, at most twice a second."""
while True:
await asyncio.sleep(LIVE_INTERVAL_S)
await self.flush_live()
async def on_version_pending(self, step: int) -> None:
"""Drop train groups past ``max_off_policy_steps``: a group dispatched at
v{k} ships at earliest in the batch currently collecting, at staleness
@@ -465,10 +516,8 @@ class Dispatcher:
fresh = self.next_fresh_group(kind, envs)
if fresh is None:
return False
gid = uuid.uuid4()
gid = fresh.group_id or uuid.uuid4()
self.groups[gid] = fresh
if fresh.source_index is not None:
self.source_indices_by_group[str(gid)] = fresh.source_index
return await self.schedule_group_episode(gid, fresh)
def next_fresh_group(self, kind: WorkKind, envs) -> GroupState | None:
@@ -486,22 +535,19 @@ class Dispatcher:
return None
env_name = request.env_name
group_size = envs.get(env_name).config.group_size
rollouts = request.rollouts if request.rollouts is not None else envs.get(env_name).config.group_size
return GroupState(
kind=kind,
env_name=env_name,
task=request.task,
step=request.step,
episodes_to_schedule=group_size,
target_episodes=group_size,
episodes_to_schedule=rollouts,
target_episodes=rollouts,
policy_version_at_start=self.policy.version,
source_index=request.source_index,
group_id=uuid.UUID(request.group_id) if request.group_id else None,
)
def pop_source_index(self, group_id: str) -> int | None:
return self.source_indices_by_group.pop(group_id, None)
async def schedule_group_episode(self, group_id: uuid.UUID, group: GroupState) -> bool:
"""Dispatch one ``run`` task for this group.
@@ -536,26 +582,37 @@ class Dispatcher:
group.episodes_to_schedule -= 1
await self.acquire()
self.admissions_in_window += 1
task = asyncio.create_task(
env.run(
client=client,
model_name=model_name,
cache_salt=cache_salt,
task_data=group.task.data.model_dump(mode="json"),
)
)
self.inflight[task] = InflightEpisode(
meta = InflightEpisode(
kind=group.kind,
env_name=group.env_name,
group_id=group_id,
task=group.task,
policy_version=group.policy_version_at_start,
step=group.step,
source_index=group.source_index,
client_config=client,
started_at=time.monotonic(),
)
def on_delta(delta: dict) -> None:
first = not meta.live
live.apply(meta, delta)
self.queue_live({"delta": delta, "dispatch": live.dispatch_info(meta)})
# after the delta, and only once a trace streams: a reader never sees the
# episode in neither place (a discard as the first delta streams nothing)
if first and meta.live:
self.live_events.append(live.dispatched_event(meta))
task = asyncio.create_task(
env.run(
client=client,
model_name=model_name,
cache_salt=cache_salt,
task_data=group.task.data.model_dump(mode="json"),
on_delta=on_delta,
)
)
self.inflight[task] = meta
self.live_events.append(live.pending_event(meta))
return True
async def acquire(self) -> None:
@@ -578,6 +635,7 @@ class Dispatcher:
meta = self.inflight.pop(task, None)
if meta is None:
return # already handled by drop_group / cancel_inflight_episodes
self.retire(meta)
self.release(refund_admission=True)
group = self.groups.get(meta.group_id)
@@ -688,6 +746,7 @@ class Dispatcher:
continue
del self.inflight[task]
self.release()
self.retire(meta)
claimed.append((task, meta))
inflight_cancelled = len(claimed)
@@ -718,7 +777,6 @@ class Dispatcher:
if claimed:
await safe_cancel_all([task for task, _ in claimed])
self.source_indices_by_group.pop(str(group_id), None)
return cancelled
async def cancel_inflight_episodes(self) -> None:
@@ -727,10 +785,10 @@ class Dispatcher:
for meta in self.inflight.values():
self.metrics.record_cancellation(kind=meta.kind, env_name=meta.env_name)
self.release()
self.retire(meta)
tasks = list(self.inflight.keys())
self.inflight.clear()
self.groups.clear()
self.source_indices_by_group.clear()
if tasks:
await safe_cancel_all(tasks)
@@ -746,6 +804,7 @@ class Dispatcher:
continue
self.inflight.pop(task, None)
self.release()
self.retire(meta)
self.metrics.record_cancellation(kind="train", env_name=meta.env_name)
cancelled += 1
train_tasks.append(task)
@@ -775,7 +834,11 @@ class Dispatcher:
cancelled += await self.drop_group(group_id, reason="superseded")
for request in queued:
count = self.eval_envs.get(request.env_name).config.group_size
count = (
request.rollouts
if request.rollouts is not None
else self.eval_envs.get(request.env_name).config.group_size
)
cancelled += count
self.metrics.record_cancellation(kind="eval", env_name=request.env_name, n=count)
await self.out_q.put(
+43 -11
View File
@@ -21,8 +21,9 @@ from __future__ import annotations
import asyncio
import time
from collections.abc import Iterator, Sequence
from collections.abc import Callable, Iterator, Sequence
from itertools import islice
from pathlib import Path
from typing import Generic, TypeVar
import verifiers.v1 as vf
@@ -32,6 +33,7 @@ from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSour
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
from prime_rl.orchestrator.generation_source import GenerationSource
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import env_address_file
# Max wait for the env server to answer health. Generous because the launcher spawns
# servers concurrently with the orchestrator, and a server imports its env package
@@ -39,13 +41,31 @@ from prime_rl.utils.logger import format_time, get_logger
ENV_SERVER_STARTUP_TIMEOUT = 600.0
async def wait_for_address(path: Path, timeout: float) -> str:
"""The address a launcher-managed env server published, polling for the file the
server writes once it has bound (it starts concurrently with this process)."""
deadline = time.monotonic() + timeout
while True:
try:
if address := path.read_text().strip():
return address
except FileNotFoundError:
pass
if time.monotonic() > deadline:
raise TimeoutError(f"env server never published its address to {path} within {timeout}s")
await asyncio.sleep(0.5)
class Env:
"""Client onto a v1 env server. The orchestrator owns the taskset (loaded once,
client-side); the server owns agent/harness execution."""
def __init__(self, config: EnvConfig, address: str):
def __init__(self, config: EnvConfig, address: str | None, address_file: Path):
self.config = config
self.address = address
self.address_file = address_file
"""Where a launcher-managed server publishes its address; read when ``address``
is None."""
self.sampling_args: dict = {}
self.num_tasks: int | None = 0
"""Task count; ``None`` means the taskset is infinite."""
@@ -68,8 +88,10 @@ class Env:
async def start(self) -> None:
"""Connect to the env server and load the taskset client-side."""
get_logger().debug(f"Connecting {self.name} to env server {self.address}")
t0 = time.perf_counter()
if self.address is None:
self.address = await wait_for_address(self.address_file, timeout=ENV_SERVER_STARTUP_TIMEOUT)
get_logger().debug(f"Connecting {self.name} to env server {self.address}")
self._env_client = EnvClient(address=self.address)
# The server may still be coming up (the launcher spawns it concurrently with
# the orchestrator), so poll until it answers.
@@ -98,14 +120,18 @@ class Env:
model_name: str,
cache_salt: str | None,
task_data: dict,
on_delta: Callable[[dict], None] | None = None,
) -> vf.WireEpisode:
"""Run and return one typed episode. A failed multi-trace episode marks
its otherwise-clean traces failed so partial episodes never train."""
its otherwise-clean traces failed so partial episodes never train.
``on_delta`` sees each delta of the env server's stream — a turn or a phase
change of one of the episode's traces — as it lands."""
episode = await self.env_client.run(
task_data=task_data,
client=client,
model=model_name,
sampling=self._sampling(cache_salt),
on_delta=on_delta,
)
for trace in episode.traces:
if not episode.ok and trace.ok:
@@ -123,11 +149,12 @@ class TrainEnv(Env):
def __init__(
self,
config: TrainSourceConfig,
address: str,
address: str | None,
address_file: Path,
generation_source: GenerationSource,
algorithm: Algorithm,
):
super().__init__(config, address)
super().__init__(config, address, address_file)
self.generation_source = generation_source
self.algorithm = algorithm
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
@@ -142,8 +169,8 @@ class TrainEnv(Env):
class EvalEnv(Env):
config: EvalSourceConfig
def __init__(self, config: EvalSourceConfig, address: str):
super().__init__(config, address)
def __init__(self, config: EvalSourceConfig, address: str | None, address_file: Path):
super().__init__(config, address, address_file)
self.sampling_args = config.sampling.to_sampling_args()
self.examples: list[vf.Task] = []
@@ -203,7 +230,8 @@ class TrainEnvs(Envs[TrainEnv]):
def __init__(
self,
configs: Sequence[TrainSourceConfig],
addresses: dict[tuple[str, str], str],
addresses: dict[tuple[str, str], str | None],
config_dir: Path,
*,
clients,
renderer_config=None,
@@ -215,6 +243,7 @@ class TrainEnvs(Envs[TrainEnv]):
env = TrainEnv(
config,
addresses[("train", config.resolved_name)],
env_address_file(config_dir, "train", config.resolved_name),
GenerationSource(config.algo.sampling, clients, renderer_config),
build_algorithm(config.algo, clients),
)
@@ -224,8 +253,11 @@ class TrainEnvs(Envs[TrainEnv]):
class EvalEnvs(Envs[EvalEnv]):
"""Collection of evaluation environments."""
def __init__(self, configs: Sequence[EvalSourceConfig], addresses: dict[tuple[str, str], str]):
def __init__(
self, configs: Sequence[EvalSourceConfig], addresses: dict[tuple[str, str], str | None], config_dir: Path
):
self._envs: dict[str, EvalEnv] = {}
for config in configs:
env = EvalEnv(config, addresses[("eval", config.resolved_name)])
name = config.resolved_name
env = EvalEnv(config, addresses[("eval", name)], env_address_file(config_dir, "eval", name))
self._envs[env.name] = env
+25 -132
View File
@@ -8,8 +8,7 @@ from typing import TYPE_CHECKING
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.metrics import EvalEpisodes
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, eval_work
from prime_rl.utils.logger import get_logger
from prime_rl.orchestrator.utils import episode_env_name, eval_work
if TYPE_CHECKING:
import verifiers.v1 as vf
@@ -20,61 +19,36 @@ class EvalSink:
def __init__(self, *, eval_envs: EvalEnvs) -> None:
self.eval_envs = eval_envs
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
self.pending_group_failures: dict[str, list[DispatchFailure]] = defaultdict(list)
self.pending_group_cancellations: dict[str, GroupCancellation] = {}
self.pending_batches: dict[tuple[str, int], list[vf.Episode]] = defaultdict(list)
self.pending_batch_failures: dict[tuple[str, int], list[DispatchFailure]] = defaultdict(list)
self.pending_batch_cancellations: dict[tuple[str, int], int] = defaultdict(int)
self.expected_batch_sizes: dict[tuple[str, int], int] = {}
def add(self, episode: vf.Episode) -> EvalBatch | None:
env_name = episode_env_name(episode)
group_id = episode_group_id(episode)
eval_step = eval_work(episode).step
bkey = (env_name, eval_step)
group = self.pending_groups[group_id]
group.append(episode)
if self._group_size(group_id) >= self.group_size_for(env_name):
self.process_group(group_id)
if self._batch_size(bkey) >= self.batch_size_for(env_name, eval_step):
return self.process_batch(bkey)
return None
key = (episode_env_name(episode), eval_work(episode).step)
self.pending_batches[key].append(episode)
return self._complete(key)
def fail(self, failure: DispatchFailure) -> EvalBatch | None:
"""Count a request failure toward its group and eval epoch without
manufacturing a verifier episode."""
"""Count a request failure toward its eval epoch without manufacturing a
verifier episode."""
if failure.kind != "eval":
raise ValueError(f"EvalSink cannot process a {failure.kind} dispatch failure")
group_id = failure.group_id
bkey = (failure.env_name, failure.step)
self.pending_group_failures[group_id].append(failure)
if self._group_size(group_id) >= self.group_size_for(failure.env_name):
self.process_group(group_id)
if self._batch_size(bkey) >= self.batch_size_for(failure.env_name, failure.step):
return self.process_batch(bkey)
return None
key = (failure.env_name, failure.step)
self.pending_batch_failures[key].append(failure)
return self._complete(key)
def cancel(self, cancellation: GroupCancellation) -> EvalBatch | None:
"""Count a dispatcher-cancelled group toward its superseded eval epoch."""
if cancellation.kind != "eval":
raise ValueError(f"EvalSink cannot process a {cancellation.kind} group cancellation")
group_id = cancellation.group_id
bkey = (cancellation.env_name, cancellation.step)
self.pending_group_cancellations[group_id] = cancellation
if self._group_size(group_id) >= self.group_size_for(cancellation.env_name):
self.process_group(group_id)
if self._batch_size(bkey) >= self.batch_size_for(cancellation.env_name, cancellation.step):
return self.process_batch(bkey)
return None
key = (cancellation.env_name, cancellation.step)
self.pending_batch_cancellations[key] += cancellation.count
return self._complete(key)
def _group_size(self, group_id: str) -> int:
cancellation = self.pending_group_cancellations.get(group_id)
return (
len(self.pending_groups[group_id])
+ len(self.pending_group_failures[group_id])
+ (cancellation.count if cancellation is not None else 0)
)
def _complete(self, key: tuple[str, int]) -> EvalBatch | None:
if self._batch_size(key) >= self.batch_size_for(key[0]):
return self.process_batch(key)
return None
def _batch_size(self, key: tuple[str, int]) -> int:
return (
@@ -86,106 +60,25 @@ class EvalSink:
def group_size_for(self, env_name: str) -> int:
return self.eval_envs.get(env_name).config.group_size
def set_batch_size(self, env_name: str, step: int, size: int) -> None:
self.expected_batch_sizes[(env_name, step)] = size
def batch_size_for(self, env_name: str, step: int | None = None) -> int:
if step is not None:
key = (env_name, step)
if key in self.expected_batch_sizes:
return self.expected_batch_sizes[key]
def batch_size_for(self, env_name: str) -> int:
"""Every rollout of an env's epoch: its examples times its group size."""
env = self.eval_envs.get(env_name)
return len(env.examples) * env.config.group_size
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
def batch_progress(self) -> list[tuple[str, int, int, int]]:
"""``(env, step, arrived, expected)`` per epoch in progress."""
keys = set(self.pending_batches) | set(self.pending_batch_failures) | set(self.pending_batch_cancellations)
batch_counts = {key: self._batch_size(key) for key in keys}
buffered: dict[tuple[str, int], int] = {}
group_ids = set(self.pending_groups) | set(self.pending_group_failures) | set(self.pending_group_cancellations)
for group_id in group_ids:
group = self.pending_groups[group_id]
failures = self.pending_group_failures[group_id]
cancellation = self.pending_group_cancellations.get(group_id)
if not group and not failures and cancellation is None:
continue
if group:
env_name = episode_env_name(group[0])
eval_step = eval_work(group[0]).step
elif failures:
env_name = failures[0].env_name
eval_step = failures[0].step
else:
env_name = cancellation.env_name
eval_step = cancellation.step
key = (env_name, eval_step)
buffered[key] = (
buffered.get(key, 0)
+ len(group)
+ len(failures)
+ (cancellation.count if cancellation is not None else 0)
)
return [
(
env_name,
eval_step,
batch_counts.get((env_name, eval_step), 0),
self.batch_size_for(env_name, eval_step),
buffered.get((env_name, eval_step), 0),
)
for env_name, eval_step in set(batch_counts) | set(buffered)
(env_name, step, self._batch_size((env_name, step)), self.batch_size_for(env_name))
for env_name, step in keys
]
def has_pending_group(self, group_id: str) -> bool:
return bool(
self.pending_groups.get(group_id)
or self.pending_group_failures.get(group_id)
or self.pending_group_cancellations.get(group_id)
)
def process_group(self, group_id: str) -> None:
group = self.pending_groups.pop(group_id, [])
failures = self.pending_group_failures.pop(group_id, [])
cancellation = self.pending_group_cancellations.pop(group_id, None)
if not group and not failures and cancellation is None:
return
if group:
env_name = episode_env_name(group[0])
eval_step = eval_work(group[0]).step
elif failures:
env_name = failures[0].env_name
eval_step = failures[0].step
else:
env_name = cancellation.env_name
eval_step = cancellation.step
key = (env_name, eval_step)
self.pending_batches[key].extend(group)
self.pending_batch_failures[key].extend(failures)
if cancellation is not None:
self.pending_batch_cancellations[key] += cancellation.count
traces = [trace for episode in group for trace in episode.traces]
survivors = [trace for trace in traces if not trace.has_error]
num_errored = len(traces) - len(survivors) + sum(not episode.ok for episode in group if not episode.traces)
rewards = [trace.reward for trace in survivors]
avg_reward = sum(rewards) / len(rewards) if rewards else 0.0
task_idx = next((trace.task.data.idx for trace in traces), None)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} "
f"eval_step={eval_step} | episodes={len(group)} dispatch_failures={len(failures)} "
f"cancelled={cancellation.count if cancellation is not None else 0} "
f"traces={len(traces)} (errored={num_errored + len(failures)}) | reward={avg_reward:.4f}"
)
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
env_name, step = key
episodes = self.pending_batches.pop(key, [])
failures = self.pending_batch_failures.pop(key, [])
cancelled = self.pending_batch_cancellations.pop(key, 0)
self.expected_batch_sizes.pop(key, None)
return EvalBatch(
env_name=env_name,
step=step,
episodes=EvalEpisodes(episodes, group_size=self.group_size_for(env_name)),
failures=failures,
cancelled=cancelled,
episodes=EvalEpisodes(self.pending_batches.pop(key, []), group_size=self.group_size_for(env_name)),
failures=self.pending_batch_failures.pop(key, []),
cancelled=self.pending_batch_cancellations.pop(key, 0),
)
+36 -51
View File
@@ -6,7 +6,7 @@ including startup. The dispatcher pulls via ``next_task()`` until
from __future__ import annotations
from collections import Counter, deque
from collections import deque
from itertools import zip_longest
from typing import TYPE_CHECKING
@@ -15,7 +15,6 @@ from prime_rl.orchestrator.types import TaskRequest
if TYPE_CHECKING:
import verifiers.v1 as vf
from prime_rl.configs.orchestrator import EvalConfig
from prime_rl.orchestrator.envs import EvalEnvs
@@ -25,42 +24,52 @@ class EvalSource:
def __init__(
self,
eval_envs: EvalEnvs,
eval_config: EvalConfig,
*,
intervals: dict[str, int] | None = None,
skip_first_step: bool = False,
is_resumed: bool = False,
) -> None:
self.eval_envs = eval_envs
self.eval_config = eval_config
"""``intervals`` is the step interval per env of a training run's online evals;
a standalone eval has none and fires every env on its one trigger."""
self.skip_first_step = skip_first_step
self.tasks_by_env: dict[str, list[vf.Task]] = {}
self.group_sizes: dict[str, int] = {}
self.intervals: dict[str, int] = {}
for env in eval_envs:
self.tasks_by_env[env.name] = list(env.examples)
self.intervals[env.name] = env.config.interval
self.group_sizes[env.name] = env.config.group_size
self.intervals[env.name] = intervals[env.name] if intervals is not None else 1
self.queue: deque[TaskRequest] = deque()
self.cursor = 0
self._next_index = 0
self._completed: set[int] = set()
self._triggered_task_counts: dict[tuple[str, int], int] = {}
self.owed: dict[str, dict[str, int]] | None = None
self.groups: dict[str, dict[str, str]] = {}
# A fresh run evaluates the base policy. Resumed runs apply interval
# rules to the loaded checkpoint and later policies.
self.first_trigger = not is_resumed
def restore(self, owed: dict[str, dict[str, int]], groups: dict[str, dict[str, str]]) -> None:
"""Rollouts the next trigger still owes per env and task key, the rest having
landed before a resume; a task without an entry is complete. ``groups`` is the
group id the landed rollouts of a task carry, which the owed ones join."""
self.owed = owed
self.groups = groups
def trigger(self, step: int, *, force: bool = False) -> list[str]:
"""Fire eligible envs for ``step`` and return their names. On resume
``first_trigger`` is False, so the startup/base eval doesn't re-run.
``force`` fires every env regardless of interval (e.g. the evals process's
final-checkpoint eval)."""
is_first, self.first_trigger = self.first_trigger, False
if is_first and self.eval_config.skip_first_step:
if is_first and self.skip_first_step:
return []
fired: list[str] = []
for name, interval in self.intervals.items():
if (is_first or force or step % interval == 0) and self.tasks_by_env[name]:
fired.append(name)
queued_counts: Counter[str] = Counter()
fired = [
name
for name, interval in self.intervals.items()
if (is_first or force or step % interval == 0) and self.tasks_by_env[name]
]
owed, self.owed = self.owed, None
# Round-robin across fired envs (A₁, B₁, A₂, B₂, …) so the
# dispatcher rotates at example granularity. ``try_schedule``'s
# continue-group branch still keeps each example's group_size
@@ -70,41 +79,17 @@ class EvalSource:
for env_name, task in zip(fired, round_tasks, strict=True):
if task is None:
continue
source_index = self._next_index
self._next_index += 1
if source_index < self.cursor:
continue
self.queue.append(TaskRequest(env_name=env_name, task=task, step=step, source_index=source_index))
queued_counts[env_name] += 1
for env_name, count in queued_counts.items():
self._triggered_task_counts[(env_name, step)] = count
return [name for name in fired if queued_counts[name]]
def triggered_task_count(self, env_name: str, step: int) -> int:
return self._triggered_task_counts.get((env_name, step), 0)
def mark_completed(self, source_index: int) -> bool:
"""Advance the durable cursor only across a fully completed prefix."""
if source_index < self.cursor:
return False
self._completed.add(source_index)
previous = self.cursor
while self.cursor in self._completed:
self._completed.remove(self.cursor)
self.cursor += 1
return self.cursor != previous
def state_dict(self) -> dict:
return {"cursor": self.cursor}
def load_state_dict(self, state_dict: dict) -> None:
if set(state_dict) != {"cursor"}:
raise ValueError("Eval source checkpoint must contain only a cursor")
cursor = state_dict["cursor"]
if type(cursor) is not int or cursor < 0:
raise ValueError(f"Eval source checkpoint cursor must be a non-negative integer, got {cursor!r}")
self.cursor = cursor
self._completed.clear()
rollouts = self.group_sizes[env_name]
if owed is not None:
# duplicate tasks share a key: each takes up to a group of what the key owes
rollouts = min(rollouts, owed[env_name].get(task.key, 0))
owed[env_name][task.key] = owed[env_name].get(task.key, 0) - rollouts
if rollouts > 0:
group_id = self.groups.get(env_name, {}).get(task.key)
self.queue.append(
TaskRequest(env_name=env_name, task=task, step=step, rollouts=rollouts, group_id=group_id)
)
return fired
def next_task(self) -> TaskRequest | None:
"""Pop the next eval task, or ``None`` when the queue is empty."""
+68
View File
@@ -0,0 +1,68 @@
"""The dispatcher's side of the live traces.
Env servers stream every in-flight rollout as deltas (``verifiers.v1.serve.delta``). The
dispatcher relays each delta to the monitors stamped with who dispatched it, and keeps
only what its own progress line needs: the phase and turn count of each live trace.
"""
from __future__ import annotations
import time
from typing import Any
from prime_rl.monitors.file.traces.live import STAGES, stage
from prime_rl.orchestrator.types import InflightEpisode, LiveTrace
def dispatch_info(meta: InflightEpisode) -> dict[str, Any]:
"""Who an in-flight episode is, stamped on the first line of each of its live traces
and on its pending placeholder."""
data = meta.task.data
name = getattr(data, "name", None)
return {
"id": meta.dispatch_id,
"kind": meta.kind,
"env": meta.env_name,
"group": str(meta.group_id),
"task": str(name) if name else f"idx={data.idx}",
"policy_version": meta.policy_version,
"step": meta.step,
"started": time.time() - (time.monotonic() - meta.started_at) if meta.started_at else None,
}
def pending_event(meta: InflightEpisode) -> dict[str, Any]:
"""The episode was dispatched; until a trace streams, this is all there is to show."""
return {"pending": meta.dispatch_id, "dispatch": dispatch_info(meta)}
def dispatched_event(meta: InflightEpisode) -> dict[str, Any]:
"""The episode is no longer pending: a trace streamed, or the episode left the in-flight set."""
return {"dispatched": meta.dispatch_id}
def apply(meta: InflightEpisode, delta: dict[str, Any]) -> None:
"""Fold one delta into the episode's phase/turn bookkeeping."""
trace_id = delta["trace"]
if delta.get("discard"):
meta.live.pop(trace_id, None)
return
trace = meta.live.setdefault(trace_id, LiveTrace())
trace.turns += len(delta.get("calls") or [])
changed = delta.get("set") or {}
if delta.get("errors"):
trace.stage = "error"
elif "timing" in changed:
trace.stage = stage({"timing": changed["timing"]})
def stage_counts(inflight: list[InflightEpisode]) -> str:
"""``boot 1 · running 3`` — the in-flight traces by phase, in lifecycle order; an
episode with no trace yet counts as pending."""
counts = dict.fromkeys(STAGES, 0)
for meta in inflight:
if not meta.live:
counts["pending"] += 1
for trace in meta.live.values():
counts[trace.stage] = counts.get(trace.stage, 0) + 1
return " · ".join(f"{name} {n}" for name, n in counts.items() if n)
+9 -4
View File
@@ -78,7 +78,7 @@ from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import get_broadcast_dir
from prime_rl.utils.pathing import get_broadcast_dir, get_config_dir
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
monkey_patch_oai_iterable_types()
@@ -231,14 +231,16 @@ class Orchestrator:
if config.heartbeat is not None:
self.heart = Heartbeat(config.heartbeat.url)
config_dir = get_config_dir(config.output_dir)
self.train_envs = TrainEnvs(
config.train.source,
config.env_addresses,
config_dir,
clients=self.clients,
renderer_config=config.renderer,
)
if config.eval is not None:
self.eval_envs = EvalEnvs(config.eval.source, config.env_addresses)
self.eval_envs = EvalEnvs(config.eval.source, config.env_addresses, config_dir)
if config.resume is not None:
if config.resume.dir is not None:
@@ -325,7 +327,8 @@ class Orchestrator:
self.eval_source: EvalSource | None = (
EvalSource(
self.eval_envs,
config.eval,
intervals=config.eval.intervals,
skip_first_step=config.eval.skip_first_step,
is_resumed=self.resume_step is not None,
)
if config.eval is not None and self.eval_envs is not None
@@ -821,6 +824,8 @@ class Orchestrator:
env_name: self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
for env_name in fired
}
for env_name, expected in census.items():
await monitors.log_eval_plan(env_name, step, expected)
get_logger().info(f"Starting evals in {', '.join(fired)} ({sum(census.values())} total rollouts)")
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
@@ -857,7 +862,7 @@ class Orchestrator:
train_batch_part += f" (+{train_buffered} buffered)"
eval_batch_part = ""
for env, _step, eb, exp, _ebuf in eval_batches:
for env, _step, eb, exp in eval_batches:
eval_pct = eb / exp if exp else 0.0
eval_batch_part += f" | {env} {eb}/{exp} ({eval_pct:.1%})"
+17 -4
View File
@@ -3,7 +3,7 @@
from __future__ import annotations
import uuid
from dataclasses import dataclass
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeAlias
from prime_rl.transports.batch import TrainingSample
@@ -81,7 +81,16 @@ class TaskRequest:
env_name: str
task: vf.Task
step: int
source_index: int | None = None
rollouts: int | None = None
"""Rollouts of the task this request asks for; None is the env's group size."""
group_id: str | None = None
"""The group these rollouts join (a resume completing a task's landed group); None mints one."""
@dataclass
class LiveTrace:
stage: str = "pending"
turns: int = 0
@dataclass
@@ -94,10 +103,14 @@ class InflightEpisode:
task: vf.Task
policy_version: int
step: int
source_index: int | None = None
client_config: vf.ClientConfig | None = None
started_at: float = 0.0
"""``time.monotonic()`` at dispatch; feeds episode-duration estimates."""
dispatch_id: str = field(default_factory=lambda: uuid.uuid4().hex)
"""Names the episode on the live view from dispatch until its first trace streams."""
live: dict[str, LiveTrace] = field(default_factory=dict)
"""The episode's in-flight traces by id, as far as the env server's stream has
told: which phase each is in and how many turns it has committed."""
@dataclass
@@ -113,7 +126,7 @@ class GroupState:
target_episodes: int
emitted: int = 0
policy_version_at_start: int = 0
source_index: int | None = None
group_id: uuid.UUID | None = None
@dataclass
@@ -542,7 +542,7 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
{%- if train_env_names or eval_env_names %}
# Launch one env server per source next to the orchestrator, which connects to each
# source at its deterministic loopback address (so this node), polling until they are
# source on this node; each publishes the loopback address it bound, polling until they are
# up — the servers and the orchestrator start in parallel.
# NOTE: keep this block free of single quotes. The whole srun body is one
# single-quoted bash -c string, so a stray quote closes it early and the rest of
+10 -10
View File
@@ -61,14 +61,14 @@ mkdir -p "$LAUNCHER_DIR"
rm -f "$TRAINER_DONE"{% if online_eval %} "$EVAL_DONE"{% endif %}
{% if prl_run_id %}
# Trainer and evals log to one shared W&B run. The trainer creates the run,
# and the evals process finalizes it after the final epoch.
# Trainer and online-eval log to one shared W&B run. The trainer creates the run,
# and the online-eval process finalizes it after the final epoch.
export PRL_RUN_ID={{ prl_run_id }}
export PRL_RUN_NAME={{ run_name }}
export WANDB_RUN_ID=$PRL_RUN_ID
export WANDB_SHARED_MODE=1
export WANDB_SHARED_PRIMARY=trainer
export WANDB_SHARED_FINISHER=evals
export WANDB_SHARED_FINISHER=online-eval
export WANDB_PROGRAM="uv run sft"
{% endif %}
@@ -194,20 +194,20 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
{%- endfor %}
{%- endif %}
# Evals drives inference through the router and sends admin operations
# Online evals drive inference through the router and send admin operations
# directly to each engine.
{%- for key, value in evals_env_vars.items() %}
{%- for key, value in online_eval_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
(
PRL_LOG_DIR=$LOG_DIR WANDB_SHARED_LABEL=evals uv run evals \
@ $CONFIG_DIR/evals.json \
--eval.client.base-url $INFER_URLS \
--eval.client.admin-base-url $ADMIN_URLS \
PRL_LOG_DIR=$LOG_DIR WANDB_SHARED_LABEL=online-eval uv run python -m prime_rl.eval.online \
@ $CONFIG_DIR/eval.json \
--client.base-url $INFER_URLS \
--client.admin-base-url $ADMIN_URLS \
{%- if use_nccl_broadcast %}
--weight-broadcast.host $MASTER_ADDR \
{%- endif %}
2>&1 | tee $LOG_DIR/evals.log
2>&1 | tee $LOG_DIR/eval.log
COMPONENT_CODE=$?
if [ "$COMPONENT_CODE" -eq 0 ]; then
touch "$EVAL_DONE" || exit $?
+17 -2
View File
@@ -2,6 +2,7 @@ import json as json_module
import logging
import sys
import traceback
from pathlib import Path
from typing import Any
# Global logger instance
@@ -101,7 +102,13 @@ def setup_logger(
log_level: str = "info",
tag: str | None = None,
json_logging: bool = False,
log_file: Path | None = None,
console_level: str | None = None,
):
"""Install the prime-rl logger: a console sink (colorized, or JSON lines with
``json_logging``) and, with ``log_file``, a plain-text file sink for processes that
no launcher redirects. ``console_level`` raises the console sink's threshold above
``log_level`` (the file keeps everything), e.g. to surface only errors while a run is in flight."""
global _LOGGER, _JSON_LOGGING
_JSON_LOGGING = json_logging
@@ -154,9 +161,17 @@ def setup_logger(
# Install console handler (enqueue=True only for JSON mode to avoid blocking in async contexts)
if json_logging:
logger.add(json_sink, level=log_level.upper(), enqueue=True)
logger.add(json_sink, level=(console_level or log_level).upper(), enqueue=True)
else:
logger.add(sys.stdout, format=format, level=log_level.upper(), colorize=True)
logger.add(sys.stdout, format=format, level=(console_level or log_level).upper(), colorize=True)
if log_file is not None:
# The console format carries raw ANSI codes; the file gets a plain layout.
logger.add(
log_file,
format="{time:HH:mm:ss} {level: >7} " + f"{tag_prefix}{{message}}",
level=log_level.upper(),
colorize=False,
)
# Disable critical logging
logger.critical = lambda _: None
+83 -17
View File
@@ -1,4 +1,5 @@
import asyncio
import json
import os
import shlex
import shutil
@@ -7,6 +8,9 @@ import tempfile
import time
from pathlib import Path
from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.shared import LogConfig
from prime_rl.utils.config import dump_resolved_config
from prime_rl.utils.logger import get_logger
@@ -83,15 +87,19 @@ def latest_log_dir(run_dir: Path) -> Path:
return get_log_dir(run_dir) / "latest"
def shorten(name: str, max_len: int) -> str:
"""A name cut to fit a label column, the same way in every launcher block."""
return name if len(name) <= max_len else name[: max_len - 3] + "..."
def format_log_message(
log_dir: Path,
trainer: bool = False,
orchestrator: bool = False,
evals: bool = False,
eval: bool = False,
inference: bool = False,
job_log: bool = False,
train_env_names: list[str] | None = None,
eval_env_names: list[str] | None = None,
env_names: dict[str, list[str]] | None = None,
num_train_nodes: int = 1,
num_infer_nodes: int = 0,
) -> str:
@@ -112,25 +120,26 @@ def format_log_message(
log_lines.append(f"{i2}{'All ranks:':<{col - 1}}tail -F {log_dir}/trainer/torchrun/*/*/*/*.log")
if orchestrator:
log_lines.append(f"{i1}{'Orchestrator:':<{col}}tail -F {log_dir}/orchestrator.log")
if evals:
log_lines.append(f"{i1}{'Evals:':<{col}}tail -F {log_dir}/evals.log")
if eval:
log_lines.append(f"{i1}{'Eval:':<{col}}tail -F {log_dir}/eval.log")
if inference:
log_lines.append(f"{i1}{'Inference:':<{col}}tail -F {log_dir}/inference.log")
if num_infer_nodes > 1:
log_lines.append(f"{i2}{'All nodes:':<{col - 1}}tail -F {log_dir}/inference/node_*.log")
if train_env_names or eval_env_names:
# Env servers, by split (``envs/<split>/<name>.log``); one split lists its envs
# directly, several list them under the split.
splits = {split: names for split, names in (env_names or {}).items() if names}
if splits:
env_log_dir = log_dir / "envs"
log_lines.append(f"{i1}{'Envs:':<{col}}tail -F {env_log_dir}/*/*.log")
if train_env_names:
log_lines.append(f"{i2}{'Train:':<{col - 1}}tail -F {env_log_dir}/train/*.log")
for name in train_env_names:
short = name if len(name) <= max_name else name[: max_name - 3] + "..."
log_lines.append(f"{i3}{f'{short}:':<{col - 2}}tail -F {env_log_dir}/train/{name}.log")
if eval_env_names:
log_lines.append(f"{i2}{'Eval:':<{col - 1}}tail -F {env_log_dir}/eval/*.log")
for name in eval_env_names:
short = name if len(name) <= max_name else name[: max_name - 3] + "..."
log_lines.append(f"{i3}{f'{short}:':<{col - 2}}tail -F {env_log_dir}/eval/{name}.log")
for split, names in splits.items():
indent, width = (i2, col - 1) if len(splits) == 1 else (i3, col - 2)
if len(splits) > 1:
log_lines.append(f"{i2}{f'{split.capitalize()}:':<{col - 1}}tail -F {env_log_dir}/{split}/*.log")
for name in names:
log_lines.append(
f"{indent}{f'{shorten(name, max_name)}:':<{width}}tail -F {env_log_dir}/{split}/{name}.log"
)
return "Logs:\n" + "\n".join(log_lines)
@@ -186,12 +195,57 @@ def write_launch_toml(config_dir: Path, name: str) -> None:
(config_dir.parent / f"{name}.toml").write_text("\n".join(texts))
def format_config_message(config_dir: Path, name: str, components: list[tuple[str, Path | str]]) -> str:
"""Where a launch's configs are: the command as typed, the launch TOML when one was
given, and each component's resolved config. Mirrors ``format_log_message``."""
col = 18
attempt_dir = config_dir.parent
lines = [f" {'Command:':<{col}}{attempt_dir / 'command.txt'}"]
launch_toml = attempt_dir / f"{name}.toml"
if launch_toml.is_file():
lines.append(f" {'Launch TOML:':<{col}}{launch_toml}")
# A label starting with a space is a sub-entry (an env server under its split), cut
# to the column like the Logs block cuts env names.
for label, path in components:
if label.startswith(" "):
label = " " + shorten(label[1:], col - 4)
lines.append(f" {f'{label}:':<{col}}{path}")
return "\n".join(lines)
def write_launch_artifacts(config_dir: Path, name: str) -> None:
"""Write the user command and launch TOML for a config attempt."""
write_launch_command(config_dir, name)
write_launch_toml(config_dir, name)
def env_address_file(config_dir: Path, split: str, name: str) -> Path:
"""Where a launcher-managed env server publishes the address it bound
(``envs/<split>/<name>.address``, next to its config). The server binds an
OS-assigned port, so two runs on one host never race for the same one; a client
waits for this file instead of assuming a port."""
return config_dir / "envs" / split / f"{name}.address"
def write_env_server_config(config_dir: Path, split: str, source: EnvConfig, log: LogConfig) -> Path:
"""Write the ``EnvServerConfig`` of a launcher-managed source
(``envs/<split>/<name>.json``) and return its path. The source's env and serve
blocks carry over; its other knobs (sampling, algo, name, ...) stay client-side. The
server publishes the OS-assigned port it binds to the address file next to it."""
env_dir = config_dir / "envs" / split
env_dir.mkdir(parents=True, exist_ok=True)
source_dict = dump_resolved_config(source)
server_config = {
"env": source_dict["env"],
"serve": source_dict.get("serve") or {},
"address_file": env_address_file(config_dir, split, source.resolved_name).as_posix(),
"log": {"level": log.vf_level, "json_logging": log.json_logging},
}
path = env_dir / f"{source.resolved_name}.json"
path.write_text(json.dumps(server_config, indent=2))
return path
def get_launcher_dir(output_dir: Path) -> Path:
return output_dir / "launcher"
@@ -208,6 +262,18 @@ def get_batch_dir(output_dir: Path) -> Path:
return output_dir / "batches"
def get_eval_plan_path(output_dir: Path) -> Path:
"""``{env: {step: expected episodes}}`` for every eval epoch the run has started."""
return get_file_monitor_dir(output_dir) / "plan.json"
def get_platform_run_path(output_dir: Path) -> Path:
"""What the prime monitor knows about the run on the platform: ``{"kind": "train",
"id", "url"}`` for a training run, ``{"kind": "eval", "run_id", "evaluations":
{env: {"step", "id", "url"}}}`` for an eval run, one entry per uploaded epoch."""
return output_dir / "monitors" / "prime" / "run.json"
def get_file_monitor_dir(output_dir: Path) -> Path:
"""Everything the file monitor dumps locally: the metrics, and the traces with
the annotations about them."""
@@ -215,7 +281,7 @@ def get_file_monitor_dir(output_dir: Path) -> Path:
def get_eval_dir(output_dir: Path) -> Path:
return output_dir / "evals"
return output_dir / "eval"
def get_broadcast_dir(output_dir: Path) -> Path:
+12 -7
View File
@@ -9,8 +9,6 @@ from contextlib import contextmanager
from pathlib import Path
from typing import Any, Callable
import torch
import torch.distributed as dist
import wandb
from prime_rl.utils.logger import get_logger
@@ -39,10 +37,17 @@ def import_object(dotted_path: str) -> Any:
return getattr(module, name)
def destroy_process_group() -> None:
dist = sys.modules.get("torch.distributed")
if dist is not None and dist.is_initialized():
dist.destroy_process_group()
def clean_exit(func: Callable) -> Callable:
"""
A decorator that ensures the a torch.distributed process group is properly
cleaned up after the decorated function runs or raises an exception.
cleaned up after the decorated function runs or raises an exception. Torch is
looked up lazily: a process that never imported it (eval) has no group.
"""
if asyncio.iscoroutinefunction(func):
@@ -60,8 +65,7 @@ def clean_exit(func: Callable) -> Callable:
# the event loop swallows it and the process hangs indefinitely.
sys.exit(1)
finally:
if dist.is_initialized():
dist.destroy_process_group()
destroy_process_group()
return async_wrapper
else:
@@ -78,8 +82,7 @@ def clean_exit(func: Callable) -> Callable:
# sys.exit raises SystemExit so the finally block still runs.
sys.exit(1)
finally:
if dist.is_initialized():
dist.destroy_process_group()
destroy_process_group()
return sync_wrapper
@@ -166,6 +169,8 @@ def get_free_port() -> int:
@contextmanager
def default_dtype(dtype):
import torch
prev = torch.get_default_dtype()
torch.set_default_dtype(dtype)
try:
+60
View File
@@ -0,0 +1,60 @@
import re
from pathlib import Path
from typing import Callable
import pytest
from tests.conftest import ProcessResult
from tests.utils import strip_escape_codes
pytestmark = [pytest.mark.slow]
RUN_NAME = "gsm8k-eval"
TIMEOUT = 900
@pytest.fixture(scope="module")
def run_dir(output_dir: Path) -> Path:
return output_dir / RUN_NAME
@pytest.fixture(scope="module")
def eval_process(run_process: Callable[..., ProcessResult], output_dir: Path) -> ProcessResult:
"""`uv run eval` of single-turn null-harness rollouts against Prime Inference (the
default client and model); needs `PRIME_API_KEY`, no GPU, no sandbox."""
cmd = [
"uv",
"run",
"eval",
"@",
"configs/ci/integration/gsm8k-eval.toml",
"--clean",
"--output-dir",
output_dir.as_posix(),
"--run.name",
RUN_NAME,
]
return run_process(cmd, timeout=TIMEOUT)
@pytest.fixture(scope="module")
def summary(eval_process: ProcessResult, run_dir: Path) -> re.Match:
log = run_dir / "logs" / "latest" / "eval.log"
if eval_process.returncode != 0:
print("=== Eval Outputs ===")
print(*log.read_text().splitlines()[-200:], sep="\n")
assert eval_process.returncode == 0, f"Process has non-zero return code ({eval_process})"
lines = strip_escape_codes(log.read_text()).splitlines()
pattern = r"Evaluated gsm8k .*Reward\s+(?P<reward>\d+\.\d+) \| Turns\s+(?P<turns>\d+\.\d+) \| Branches\s+(?P<branches>\d+\.\d+)"
matches = [m for m in (re.search(pattern, line) for line in lines if "SUCCESS" in line) if m]
assert len(matches) == 1, f"Expected one eval summary line, found {len(matches)}"
return matches[0]
def test_eval_reward(summary: re.Match):
assert float(summary["reward"]) >= 0.5
def test_rollouts_are_one_branch(summary: re.Match):
"""A linear rollout is exactly one branch."""
assert float(summary["branches"]) == 1.0
+60
View File
@@ -0,0 +1,60 @@
import json
import pytest
from prime_rl.entrypoints.eval import expand_shorthands
def test_expand_shorthands_folds_taskset_and_env_into_one_source() -> None:
argv = [
"gsm8k",
"-n",
"4",
"--env.agent.harness.id",
"bash",
"--env.agent.max-turns=5",
"--env.taskset.tasks",
'["fix-git"]',
"-c",
"8",
"--run.name",
"smoke",
]
expanded = expand_shorthands(argv)
source = json.loads(expanded[expanded.index("--source") + 1])
assert source == [
{
"env": {
"taskset": {"id": "gsm8k", "tasks": ["fix-git"]},
"agent": {"harness": {"id": "bash"}, "max_turns": "5"},
}
}
]
assert expanded[: expanded.index("--source")] == [
"-n",
"4",
"--concurrency.min_inflight",
"8",
"--concurrency.max_inflight",
"8",
"--run.name",
"smoke",
]
def test_expand_shorthands_passes_through_without_shorthands() -> None:
argv = ["@", "eval.toml", "--model", "x", "--resume"]
assert expand_shorthands(argv) == argv
def test_expand_shorthands_refuses_shorthand_next_to_source_toml(tmp_path) -> None:
toml = tmp_path / "eval.toml"
toml.write_text('[[source]]\nenv.taskset.id = "gsm8k"\n')
with pytest.raises(SystemExit, match="cannot be combined"):
expand_shorthands(["wordle", "@", toml.as_posix()])
def test_expand_shorthands_requires_a_value() -> None:
with pytest.raises(SystemExit, match="needs a value"):
expand_shorthands(["gsm8k", "--env.agent.harness.id"])
assert "--env.agent.max_turns" not in expand_shorthands(["gsm8k", "--env.agent.max-turns", "-1"])
+112
View File
@@ -0,0 +1,112 @@
from types import SimpleNamespace
import orjson
import pytest
from prime_rl.eval import resume
from prime_rl.monitors.file.traces import get_trace_stream
from prime_rl.monitors.file.traces.chunks import ChunkedJsonl
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.utils.pathing import get_file_monitor_dir
def _task(key: str) -> SimpleNamespace:
return SimpleNamespace(key=key, hash=key)
def _env(name: str, task_keys: list[str], *, group_size: int = 1) -> SimpleNamespace:
return SimpleNamespace(
name=name, examples=[_task(key) for key in task_keys], config=SimpleNamespace(group_size=group_size)
)
def _record(env: str, key: str, *, ok: bool = True, group: str | None = None) -> dict:
return {
"env": {"id": env, "name": env},
"task": {"type": "Task", "data": {"idx": 0}, "key": key, "hash": key},
"group": {"id": group or f"group-{key}"},
"ok": ok,
"traces": [],
}
def test_plan_keeps_landed_rollouts_up_to_the_target_and_owes_the_rest() -> None:
envs = [_env("math", ["m0", "m1", "m2"], group_size=2), _env("code", ["c0"])]
landed = [
_record("math", "m0"),
_record("math", "m0"),
_record("math", "m0"), # a third rollout of m0 exceeds group_size 2
_record("math", "m1"),
_record("math", "m9"), # no longer selected (num_examples shrank)
_record("code", "c0", ok=False), # errored: owed again
]
kept, owed, groups = resume.plan([record for record in landed if record["ok"]], envs)
assert [(episode.env.name, episode.task.key) for episode in kept] == [
("math", "m0"),
("math", "m0"),
("math", "m1"),
]
assert owed == {"math": {"m1": 1, "m2": 2}, "code": {"c0": 1}}
# the owed rollout of m1 completes the group its landed rollout opened
assert groups == {"math": {"m0": "group-m0", "m1": "group-m1"}}
def test_trigger_queues_only_owed_rollouts() -> None:
source = EvalSource([_env("math", ["m0", "m1", "m2"], group_size=2), _env("code", ["c0"])])
source.restore({"math": {"m1": 1, "m2": 2}, "code": {}}, {"math": {"m1": "group-m1"}})
assert source.trigger(0) == ["math", "code"]
assert [(request.env_name, request.task.key, request.rollouts, request.group_id) for request in source.queue] == [
("math", "m1", 1, "group-m1"),
("math", "m2", 2, 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)
for key in keys:
stream.append(orjson.dumps({**_record("math", key), "id": key}, option=orjson.OPT_APPEND_NEWLINE))
stream.close()
land("m0", "m1")
assert [record["id"] for record in resume.take_landed(tmp_path)] == ["m0", "m1"]
assert not get_file_monitor_dir(tmp_path).exists()
assert [path.name for path in resume.archives(tmp_path)] == ["file.attempt_1"]
# the resumed attempt re-logged one episode and landed a new one before it died
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"}
-93
View File
@@ -1,93 +0,0 @@
import pickle
from types import SimpleNamespace
import pytest
from prime_rl.evals.ckpt import CheckpointManager
from prime_rl.orchestrator.eval_source import EvalSource
def _task(key: str) -> SimpleNamespace:
return SimpleNamespace(key=key, hash=key)
def _env(name: str, task_keys: list[str], *, interval: int = 1) -> SimpleNamespace:
return SimpleNamespace(
name=name,
examples=[_task(key) for key in task_keys],
config=SimpleNamespace(interval=interval),
)
def _eval_config() -> SimpleNamespace:
return SimpleNamespace(skip_first_step=False)
def _queued_tasks(eval_source: EvalSource) -> list[tuple[str, str, int | None]]:
return [(request.env_name, request.task.key, request.source_index) for request in eval_source.queue]
def test_eval_source_cursor_advances_only_over_completed_prefix() -> None:
eval_source = EvalSource(
[_env("math", ["m0", "m1"]), _env("code", ["c0", "c1"])],
_eval_config(),
)
assert eval_source.trigger(0) == ["math", "code"]
assert _queued_tasks(eval_source) == [
("math", "m0", 0),
("code", "c0", 1),
("math", "m1", 2),
("code", "c1", 3),
]
assert eval_source.mark_completed(1) is False
assert eval_source.cursor == 0
assert eval_source.mark_completed(3) is False
assert eval_source.cursor == 0
assert eval_source.mark_completed(0) is True
assert eval_source.cursor == 2
assert eval_source.mark_completed(2) is True
assert eval_source.cursor == 4
def test_eval_checkpoint_saves_only_cursor_and_resume_skips_completed_prefix(tmp_path) -> None:
eval_envs = [_env("math", ["m0", "m1"]), _env("code", ["c0", "c1"])]
eval_source = EvalSource(eval_envs, _eval_config())
eval_source.load_state_dict({"cursor": 2})
assert eval_source.trigger(0) == ["math", "code"]
assert _queued_tasks(eval_source) == [
("math", "m1", 2),
("code", "c1", 3),
]
assert eval_source.triggered_task_count("math", 0) == 1
assert eval_source.triggered_task_count("code", 0) == 1
ckpt = CheckpointManager(tmp_path)
ckpt.save(eval_source)
with (ckpt.get_ckpt_path(2) / "progress.pt").open("rb") as f:
assert pickle.load(f) == {"cursor": 2}
assert ckpt.latest_step() == 2
restored_source = EvalSource(eval_envs, _eval_config())
ckpt.load(2, restored_source)
assert restored_source.state_dict() == {"cursor": 2}
def test_eval_checkpoint_rejects_step_cursor_mismatch(tmp_path) -> None:
eval_source = EvalSource([_env("math", ["m0"])], _eval_config())
eval_source.load_state_dict({"cursor": 1})
ckpt = CheckpointManager(tmp_path)
ckpt.save(eval_source)
restored_source = EvalSource([_env("math", ["m0"])], _eval_config())
with pytest.raises(ValueError, match="contains cursor 1, expected step 2"):
ckpt.load(2, restored_source, path=ckpt.get_ckpt_path(1))
+2 -2
View File
@@ -8,7 +8,7 @@ from pydantic import BaseModel, Field, ValidationError
from pydantic_config import ConfigFileError
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.configs.evals import EvalsConfig
from prime_rl.configs.eval import EvalConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.rl import RLConfig
@@ -25,7 +25,7 @@ CONFIG_CLASSES = [
OrchestratorConfig,
InferenceConfig,
EnvServerConfig,
EvalsConfig,
EvalConfig,
]
Generated
+26 -24
View File
@@ -17,27 +17,27 @@ exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for
exclude-newer-span = "P7D"
[options.exclude-newer-package]
deep-ep = false
deep-gemm = false
dion = false
fastokens = false
flash-attn-3 = false
harbor = "2026-08-11T00:00:00Z"
nixl-cu13 = false
prime = false
prime-evals = false
prime-kernels = false
prime-pydantic-config = false
prime-runs = false
prime-sandboxes = false
prime-traces = false
prime-tunnel = false
renderers = false
tokenspeed-mla = false
torchao = false
verifiers = false
vllm = false
verifiers = false
harbor = "2026-08-11T00:00:00Z"
prime-traces = false
prime-pydantic-config = false
vllm-router = false
dion = false
prime-runs = false
flash-attn-3 = false
prime-tunnel = false
fastokens = false
deep-gemm = false
prime-evals = false
torchao = false
tokenspeed-mla = false
nixl-cu13 = false
deep-ep = false
prime-sandboxes = false
renderers = false
prime-kernels = false
prime = false
[manifest]
members = [
@@ -5010,6 +5010,7 @@ dependencies = [
{ name = "prime-pydantic-config" },
{ name = "prime-rl-configs" },
{ name = "prime-runs", extra = ["train"] },
{ name = "prometheus-client" },
{ name = "psutil" },
{ name = "pyarrow" },
{ name = "pybase64" },
@@ -5177,6 +5178,7 @@ requires-dist = [
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.1" },
{ name = "prometheus-client", specifier = ">=0.20.0" },
{ name = "psutil", specifier = ">=7.0.0" },
{ name = "pyarrow", specifier = ">=21.0.0" },
{ name = "pybase64", specifier = ">=1.4.2" },
@@ -5249,15 +5251,15 @@ requires-dist = [
[[package]]
name = "prime-runs"
version = "0.1.1"
version = "0.1.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx" },
{ name = "prime-traces" },
]
sdist = { url = "https://files.pythonhosted.org/packages/85/db/3d5a9362f0d373d10145eaee3ac255cf227bf4164b36d04119b18e226607/prime_runs-0.1.1.tar.gz", hash = "sha256:0be97dcc95b3f1648ca25475efa45a5892fb12a775bf1f61728baec73a0088bb", size = 61110, upload-time = "2026-09-04T17:01:33.379Z" }
sdist = { url = "https://files.pythonhosted.org/packages/db/ee/0e9cf800aa6b3db148b01d26e0d6957074027f52323b348ad35594e41d1c/prime_runs-0.1.2.tar.gz", hash = "sha256:2cd4775aa3176f95abf3def78ba257b6b0579ba2606d24307c88495e5b1bb6f1", size = 62099, upload-time = "2026-09-09T00:28:45.621Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/84/52/3fa41ac5e3c8bfa8eb33520f86634ae56474228f85c59b16aa04875efd7d/prime_runs-0.1.1-py3-none-any.whl", hash = "sha256:d512753ff84159a1234d1ea93091857f0a59fba12ef7ab2f69bfb579deb5ce75", size = 43006, upload-time = "2026-09-04T17:01:31.821Z" },
{ url = "https://files.pythonhosted.org/packages/37/59/e48470b0b47d3fc261e31e13d1ed47177f0a71044234ae46b40b00063f1c/prime_runs-0.1.2-py3-none-any.whl", hash = "sha256:95ca0775317cf2733aa38a0a26b263174b992d5be63009a4cfeeff212924759b", size = 43333, upload-time = "2026-09-09T00:28:44.22Z" },
]
[package.optional-dependencies]
@@ -7828,14 +7830,14 @@ requires-dist = [
{ name = "loguru", specifier = ">=0.7.0" },
{ name = "math-verify", specifier = ">=0.8.0" },
{ name = "mcp", specifier = "==2.0.0" },
{ name = "modal", marker = "extra == 'modal'", specifier = ">=1.4.0" },
{ name = "modal", marker = "extra == 'modal'", specifier = ">=1.5.4" },
{ name = "msgpack", specifier = ">=1.1.2" },
{ name = "nltk", marker = "extra == 'ta'", specifier = ">=3.9.2" },
{ name = "numpy", specifier = ">=2.1.0" },
{ name = "openai", specifier = ">=2.54.0,<3.0.0" },
{ name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" },
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.3" },
{ name = "prime-runs", specifier = ">=0.1.1" },
{ name = "prime-runs", specifier = ">=0.1.2" },
{ name = "prime-sandboxes", specifier = ">=0.2.39" },
{ name = "prime-tunnel", specifier = ">=0.1.8" },
{ name = "pydantic", specifier = ">=2.12.3" },