Compare commits

..
Author SHA1 Message Date
Mika SenghaasandGitHub d09bf96dbe feat: cancel superseded online eval episodes (#3402)
## Summary
- cancel queued and in-flight SFT eval episodes when the trainer offers
a newer checkpoint
- report scores from completed episodes and log the cancelled count and
fraction for each superseded checkpoint
- show the cancellation fraction in the local dashboard and W&B eval
sections
- allow `eval.cancel_on_new_checkpoint = false` to drain every epoch,
which can idle the trainer while slow evals finish
- document the online-eval behavior and configuration

## Verification
- `uv run ruff check
packages/prime-rl-configs/src/prime_rl/configs/evals.py
src/prime_rl/evals/evals.py src/prime_rl/monitors/wandb/overview.py
tests/unit/test_configs.py`
- `node --check src/prime_rl/dashboard/static/app.js`
- `uv run pytest tests/unit/test_configs.py -q` (122 passed)
- two-GPU SFT and online-eval run with NCCL broadcast (steps 0 and 1
reported partial scores with 6 of 8 episodes cancelled; step 2 completed
all 8 episodes; the launcher exited successfully)
- dashboard browser smoke test for the cancellation panel and run
metrics
- `PYTEST_OUTPUT_DIR=/tmp/prime-rl-eval-cancel-tests uv run pytest
tests/unit -m "not gpu" -q` (477 passed, 86 deselected; one unrelated
baseline Qwen3-VL fixture failure in
`tests/unit/orchestrator/test_qwen3_vl_e2e.py`)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes online eval scheduling and trainer–evals checkpoint handoff;
mis-cancellation could skew eval metrics or stall weight updates, but
behavior is configurable and scoped to online evals.
> 
> **Overview**
> Online SFT evals now **preempt unfinished epochs** when the trainer
publishes a newer checkpoint, so slow eval rollouts no longer block
loading the next weights. This is the default
(`eval.cancel_on_new_checkpoint = true`); set it to `false` to finish
every triggered epoch (the trainer may idle waiting).
> 
> The evals loop detects a superseding published step, calls
**`Dispatcher.cancel_eval_step`**, and **`EvalSink`** counts cancelled
groups toward partial epochs instead of treating `GroupCancellation` as
fatal. **`GroupCancellation`** carries the eval **`step`** and a
**`superseded`** reason. Weight reload hooks **`on_version_pending` /
`on_new_version`** run before consuming the epoch. Partial results still
log with **`eval/{env}/all/cancelled/count`** and **`cancelled/mean`**
(dashboard and W&B overview panels added).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
730dce804cc20fb3257c8c3a457bb22f95a82e94. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-26 11:32:01 -07:00
Mika SenghaasandGitHub 05967ffcd2 feat: preserve configs by attempt (#3405)
## Summary

- store launch TOML and resolved JSON files under `configs/attempt_<n>/`
- point `configs/latest` and `logs/latest` at the same launch attempt
- pin local and SLURM child processes to concrete attempt paths
- add config attempt selection to the dashboard
- default config and log selectors to `latest (attempt <n>)`
- keep the dashboard and checkpoint converter compatible with legacy
runs

## Breaking

- New runs no longer write configs to `configs/resolved/` or launch TOML
files directly under `configs/`. Update custom tooling to read
`configs/latest/resolved/` and `configs/latest/<entrypoint>.toml`. Use
`configs/attempt_<n>/` for a specific launch.

## Verification

Before this change, a resumed launch replaced the run-scoped config
files. After this change, both SFT and RL preserved attempt 1 and wrote
the resumed settings to attempt 2. Both `configs/latest` and
`logs/latest` resolved to `attempt_2`.

- SFT completed steps 1-5, then resumed from step 5 and completed steps
6-10
- RL completed steps 1-5, then resumed from step 5 and completed steps
6-10
- browser dashboard smoke passed for both resumed runs, including
attempt switching
- local, single-node SLURM, multi-node SLURM, and inference dry runs
produced matching attempt paths
- all generated SLURM scripts passed `bash -n`
- pathing unit tests passed: 11 tests
- Ruff checks and format checks passed

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes the on-disk run layout and all launch paths (local, SLURM,
evals); legacy fallbacks limit breakage, but custom tooling must move
from `configs/resolved/` to `configs/latest/resolved/`.
> 
> **Overview**
> Each launch now keeps its **launch TOML and resolved JSON** under
**`configs/attempt_<n>/`** (resolved files in **`resolved/`**), with
**`configs/latest`** aligned to the same attempt as **`logs/latest`**.
Resumes no longer overwrite prior launch configs.
> 
> Launchers allocate matching config and log attempts via
**`prepare_attempt_dirs`** / **`create_attempt_dirs`**, pin children
with **`PRL_ATTEMPT_CONFIG_DIR`** and **`PRL_ATTEMPT_LOG_DIR`**, and
SLURM templates receive concrete **`config_dir`** / **`log_dir`**
instead of shell attempt loops. **`evals`** writes attempt-scoped
configs like **`rl`** / **`sft`**.
> 
> The **dashboard** adds a config **attempt** selector and **`attempt`**
query params on config APIs; logs already supported attempts and now
default to **`latest (attempt <n>)`**. **`get_config_dir`** and
dashboard resolution keep **legacy** `configs/resolved/` runs working.
> 
> Docs, skills, **`convert_dcp_to_bf16`**, and tests/smoke cover the new
paths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
29cab3515b5c1b97eaa3aa53f9be3b947a11802c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-26 11:06:00 -07:00
30 changed files with 450 additions and 143 deletions
+2 -2
View File
@@ -247,8 +247,8 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
Then inspect the resolved config:
```bash
ls /tmp/reverse-dry/check/configs/resolved/
ls /tmp/reverse-dry/check/configs/latest/resolved/
# rl.json trainer.json orchestrator.json inference.json
```
Each per-process JSON reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/check/configs/resolved/trainer.json`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
Each per-process JSON reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/check/configs/latest/resolved/trainer.json`, etc.). Each launch also remains under `configs/attempt_<n>/`. This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
+8 -2
View File
@@ -81,7 +81,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| `--run.name <name>` | Run name, also the run directory name under `<output_dir>` (override the directory separately via `--run.dir`). Auto-generated as `<envs>--<model>--<short-id>` when unset, so every launch gets a fresh, readable run directory. Set an explicit name for a predictable path — required to resume the run later. |
| `--clean` | Wipe the run directory before starting. Useful when re-running a named run during iteration. |
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/latest/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
### Algorithms
@@ -198,7 +198,7 @@ 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 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 `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).
#### Multi-Node Trainer and Inference Pool
@@ -313,6 +313,12 @@ The exported directory loads directly into `uv run inference --vllm.model <dir>`
## Observability
### Config Files
Each launch writes its input TOML and resolved JSON files to
`<run_dir>/configs/attempt_<n>/`. Resumed runs keep the earlier configs.
`configs/latest` points to the current attempt.
### Log Files
The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>/` — every launch (fresh or resumed) gets its own numbered attempt directory, and `logs/latest` symlinks to the current one. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
@@ -27,6 +27,11 @@ class EvalsEvalConfig(EvalConfig):
"""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)``.
+1 -1
View File
@@ -25,7 +25,7 @@ Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max
```bash
uv run rl --help # all fields and defaults
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved configs (JSON) to /tmp/x/check/configs
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved JSON to /tmp/x/check/configs/latest
```
## Validators
+3
View File
@@ -11,6 +11,9 @@ dirs — safe against live runs — and installs anywhere (cluster head node,
laptop against a mounted outputs dir): 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.
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
+3 -3
View File
@@ -9,7 +9,7 @@ description: Monitor an ongoing prime-rl training run — find the output direct
### On launch
1. Find the run dir and read the resolved configs at `{run_dir}/configs/resolved/` (start with `rl.json`, or `orchestrator.json` on local runs). The launch TOML is copied verbatim to `{run_dir}/configs/rl.toml`. The run dir is `{output_dir}/{run_name}` — `run.name` auto-generates as `<envs>--<model>--<short-id>`, so if you only know the output dir, pick the most recently modified subdirectory (`ls -t {output_dir} | head -1`) or read `run.name` from the launch command.
1. Find the run dir and read the resolved configs at `{run_dir}/configs/latest/resolved/` (start with `rl.json`, or `orchestrator.json` on local runs). The launch TOML is copied verbatim to `{run_dir}/configs/latest/rl.toml`. The run dir is `{output_dir}/{run_name}` — `run.name` auto-generates as `<envs>--<model>--<short-id>`, so if you only know the output dir, pick the most recently modified subdirectory (`ls -t {output_dir} | head -1`) or read `run.name` from the launch command.
2. Confirm all processes are alive and the run is making progress.
3. Write the initial summary into `{run_dir}/STATUS.md`.
@@ -48,7 +48,7 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
### Where to find things
- `{run_dir}/configs/` — the launch TOML copied verbatim (`rl.toml`/`sft.toml`), plus `resolved/` with the per-component resolved configs, written as JSON so explicit None settings round-trip.
- `{run_dir}/configs/latest/` — the current attempt's launch TOML and `resolved/` JSON files. Each launch stays under `configs/attempt_<n>/`.
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
- `{run_dir}/rollouts/step_{n}/{train,eval}/` — saved episodes (see Episodes below).
@@ -56,7 +56,7 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
`uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR` if set; several dirs can be tracked at
once) serves a local web dashboard at `http://localhost:7788` with four views per run:
metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved config
metrics (the W&B overview sections, read from `metrics.jsonl`), per-attempt config
files, a rollout trace viewer with a per-token advantage/logprob view, and merged
component logs. It only reads the run dirs — safe to run against a live run.
`--port`/`--host` pick the bind address; a taken port automatically bumps to the next
+3 -3
View File
@@ -7,7 +7,7 @@ description: How to launch prime-rl training runs — the `rl`, `sft`, `inferenc
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory.
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory. Every launch writes configs under `configs/attempt_<n>/`; `configs/latest` points to the current attempt.
## Run directories
@@ -96,7 +96,7 @@ curl http://localhost:8000/v1/chat/completions \
## `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. 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. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
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. 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
@@ -130,7 +130,7 @@ env.agent.runtime.type = "subprocess"
## 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/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.
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.
## Summary
+3
View File
@@ -11,6 +11,9 @@ the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
skips the registry. See `skills/dashboard/SKILL.md` for discovery,
kill/restart commands, and the local view-command/report contract.
The Config and Logs views keep each launch attempt available. Both views open
at `latest (attempt <n>)` and let you select an earlier attempt.
GPU dependencies live behind the `gpu` extra, so this works anywhere — a
cluster head node, a laptop against a mounted outputs dir:
+28 -10
View File
@@ -208,10 +208,27 @@ def model_name(config: dict) -> str | None:
return model if isinstance(model, str) else (model or {}).get("name")
def resolved_config_dir(run_dir: Path) -> Path:
"""Where the resolved JSON dumps live: `configs/resolved/`, or `configs/` on
runs from before the launch-TOML split."""
def config_attempt_numbers(run_dir: Path) -> list[int]:
return [n for n, _ in numbered_dirs(run_dir / "configs", "attempt_")]
def config_attempt_dir(run_dir: Path, attempt: str = "latest") -> tuple[Path, int | None]:
"""Return one config attempt root, with a fallback for legacy run layouts."""
configs = run_dir / "configs"
attempts = config_attempt_numbers(run_dir)
if not attempts:
return configs, None
if attempt == "latest":
latest = (configs / "latest").resolve()
attempt_num = int(latest.name.removeprefix("attempt_")) if latest.is_dir() else attempts[-1]
else:
attempt_num = int(attempt)
return configs / f"attempt_{attempt_num}", attempt_num
def resolved_config_dir(run_dir: Path, attempt: str = "latest") -> Path:
"""Return resolved JSON dumps for one attempt or a legacy run."""
configs, _ = config_attempt_dir(run_dir, attempt)
resolved = configs / "resolved"
return resolved if resolved.is_dir() else configs
@@ -408,26 +425,27 @@ def config_rank(name: str) -> tuple[int, str]:
@app.get("/api/runs/{run}/configs")
def list_configs(run: str) -> dict:
def list_configs(run: str, attempt: str = "latest") -> dict:
"""Two views of a run's config: each launch TOML (verbatim, as the run was
started) and one "resolved" document concatenating every resolved JSON dump."""
run_dir = get_run_dir(run)
configs_dir = run_dir / "configs"
configs_dir, attempt_num = config_attempt_dir(run_dir, attempt)
files = sorted((p.name for p in configs_dir.glob("*.toml")), key=config_rank) if configs_dir.is_dir() else []
if any(resolved_config_dir(run_dir).rglob("*.json")):
if any(resolved_config_dir(run_dir, attempt).rglob("*.json")):
files.append("resolved")
return {"files": files}
return {"attempt": attempt_num, "attempts": config_attempt_numbers(run_dir), "files": files}
@app.get("/api/runs/{run}/config")
def read_config(run: str, file: str) -> dict:
def read_config(run: str, file: str, attempt: str = "latest") -> dict:
run_dir = get_run_dir(run)
if file == "resolved":
base = resolved_config_dir(run_dir)
base = resolved_config_dir(run_dir, attempt)
names = sorted((str(p.relative_to(base).with_suffix("")) for p in base.rglob("*.json")), key=config_rank)
doc = {name: read_json(base / f"{name}.json") for name in names}
return {"file": file, "content": orjson.dumps(doc).decode()}
path = safe_child(run_dir / "configs", file, suffix=".toml")
configs_dir, _ = config_attempt_dir(run_dir, attempt)
path = safe_child(configs_dir, file, suffix=".toml")
return {"file": file, "content": path.read_text()}
+57 -15
View File
@@ -31,7 +31,10 @@ const state = {
paneOrder: prefs.paneOrder ?? {},
},
compare: { runs: [], data: new Map() },
config: { loaded: false, files: [], file: null, fmt: "toml", cache: new Map() },
config: {
loaded: false, attempt: "latest", latestAttempt: null, attempts: [],
files: [], file: null, fmt: "toml", cache: new Map(),
},
logs: {
loaded: false, attempt: "latest", attempts: [], files: [], paneFile: {},
components: prefs.logComponents ? new Set(prefs.logComponents) : null,
@@ -188,8 +191,14 @@ async function selectRun(name, deferTab = false) {
evalEtag: null, evalCount: 0, evalCost: null,
};
if (state.meta?.type === "eval") fetchEvalSeries(); // populates the overview cost early
state.config = { loaded: false, files: [], file: null, fmt: state.config.fmt, cache: new Map() };
state.logs = { ...state.logs, loaded: false, attempt: "latest", files: [], paneFile: {}, maximized: null, buffers: new Map() };
state.config = {
loaded: false, attempt: "latest", latestAttempt: null, attempts: [],
files: [], file: null, fmt: state.config.fmt, cache: new Map(),
};
state.logs = {
...state.logs, loaded: false, attempt: "latest", latestAttempt: null,
files: [], paneFile: {}, maximized: null, buffers: new Map(),
};
state.traces = {
...state.traces,
loaded: false, fetching: false, steps: [], step: null, env: "", episodes: [], etag: null,
@@ -567,6 +576,7 @@ function buildSections(meta) {
{ regex: `eval/${envPattern}/effective/[^/]+/avg@.*` },
{ regex: `eval/${envPattern}/effective/[^/]+/reward/mean`, split: true },
{ regex: `eval/${envPattern}/all/[^/]+/reward/mean`, split: true },
{ regex: `eval/${envPattern}/all/cancelled/mean` },
...COMMON_METRICS.map((m) => ({ regex: `eval/${envPattern}/${m}` })),
...COMMON_REGEXES.map((r) => ({ regex: `eval/${envPattern}/${r}` })),
],
@@ -1221,15 +1231,19 @@ async function initMetrics() {
the network */
async function fetchConfigText(file) {
const cache = state.config.cache;
if (cache.has(file)) return cache.get(file);
const data = await api(`/api/runs/${encodeURIComponent(state.run)}/config?file=${encodeURIComponent(file)}`);
const key = `${state.config.attempt}:${file}`;
if (cache.has(key)) return cache.get(key);
const data = await api(
`/api/runs/${encodeURIComponent(state.run)}/config?file=${encodeURIComponent(file)}` +
`&attempt=${encodeURIComponent(state.config.attempt)}`
);
let text = data.content;
try {
text = JSON.stringify(JSON.parse(text), null, 2);
} catch {
/* show raw content if not valid JSON */
}
cache.set(file, text);
cache.set(key, text);
return text;
}
@@ -1431,13 +1445,28 @@ function renderConfigFormat() {
}
}
async function initConfig() {
state.config.loaded = true;
const data = await api(`/api/runs/${encodeURIComponent(state.run)}/configs`);
function renderConfigAttempts() {
const config = state.config;
const latest = config.latestAttempt == null ? "latest" : `latest (attempt ${config.latestAttempt})`;
$("#config-attempt-select").innerHTML =
`<option value="latest" ${config.attempt === "latest" ? "selected" : ""}>${latest}</option>` +
config.attempts
.map((a) => `<option value="${a}" ${String(a) === String(config.attempt) ? "selected" : ""}>attempt ${a}</option>`)
.join("");
syncDressedSelects();
}
async function loadConfigAttempt() {
const data = await api(
`/api/runs/${encodeURIComponent(state.run)}/configs?attempt=${encodeURIComponent(state.config.attempt)}`
);
state.config.latestAttempt = state.config.attempt === "latest" ? data.attempt : state.config.latestAttempt;
state.config.attempts = data.attempts;
state.config.files = data.files;
renderConfigAttempts();
if (!data.files.length) {
renderConfigFormat();
$("#config-view").innerHTML = emptyState("no configs", "this run has no configs/ directory");
$("#config-view").innerHTML = emptyState("no configs", "this attempt has no config files");
return;
}
if (!configFileFor(state.config.fmt)) state.config.fmt = configFileFor("toml") ? "toml" : "json";
@@ -1448,6 +1477,11 @@ async function initConfig() {
if (other) fetchConfigText(other); // warm the other side of the toggle
}
async function initConfig() {
state.config.loaded = true;
await loadConfigAttempt();
}
/* ------------------------------------------------------------------- logs */
const ANSI_RE = /\x1b\[[0-9;]*m/g;
@@ -1578,9 +1612,12 @@ function dressLogPaneSelects() {
function renderLogPanes() {
const logs = state.logs;
$("#attempt-select").innerHTML = logs.attempts
.map((a) => `<option value="${a}" ${String(a) === String(logs.attempt) ? "selected" : ""}>attempt ${a}</option>`)
.join("");
const latest = logs.latestAttempt == null ? "latest" : `latest (attempt ${logs.latestAttempt})`;
$("#attempt-select").innerHTML =
`<option value="latest" ${logs.attempt === "latest" ? "selected" : ""}>${latest}</option>` +
logs.attempts
.map((a) => `<option value="${a}" ${String(a) === String(logs.attempt) ? "selected" : ""}>attempt ${a}</option>`)
.join("");
renderLogCompMenu();
const container = $("#log-panes");
container.innerHTML = "";
@@ -1755,7 +1792,7 @@ async function loadLogfiles() {
const logs = state.logs;
const data = await api(`/api/runs/${encodeURIComponent(state.run)}/logfiles?attempt=${logs.attempt}`);
logs.attempts = data.attempts;
logs.attempt = data.attempt;
if (logs.attempt === "latest") logs.latestAttempt = data.attempt;
logs.files = data.files;
renderLogPanes();
dressLogPaneSelects();
@@ -3635,6 +3672,11 @@ $("#attempt-select").addEventListener("change", async (e) => {
await loadLogfiles();
await pollLogs();
});
$("#config-attempt-select").addEventListener("change", async (e) => {
state.config.attempt = e.target.value;
state.config.file = null;
await loadConfigAttempt();
});
$("#log-panes").addEventListener("change", async (e) => {
const select = e.target.closest(".lp-file");
if (!select) return;
@@ -4084,7 +4126,7 @@ document.addEventListener("visibilitychange", () => {
$("#config-search").value = prefs.configSearch ?? "";
$("#token-signal").value = prefs.tokenSignal === "rendered" ? "" : (prefs.tokenSignal ?? "");
$("#follow-toggle").checked = state.follow;
for (const sel of ["#run-select", "#trace-env", "#trace-sort", "#tm-env", "#tm-sort", "#attempt-select", "#token-signal", "#report-select"])
for (const sel of ["#run-select", "#trace-env", "#trace-sort", "#tm-env", "#tm-sort", "#config-attempt-select", "#attempt-select", "#token-signal", "#report-select"])
dressSelect($(sel));
syncTraceFilterControls();
setActive("#metrics-mode", "mode", state.metrics.mode);
+2
View File
@@ -55,6 +55,8 @@
<section id="tab-config" hidden>
<div class="controls">
<label class="t-label">attempt</label>
<select id="config-attempt-select"></select>
<div class="seg" id="config-format">
<button data-fmt="toml">TOML</button>
<button data-fmt="json">JSON</button>
+10 -3
View File
@@ -6,18 +6,25 @@ 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
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 write_launch_toml
from prime_rl.utils.pathing import prepare_attempt_dirs, write_launch_toml
write_launch_toml(config.output_dir, "evals")
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_toml(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))
+8 -6
View File
@@ -12,10 +12,10 @@ from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import (
format_log_message,
get_config_dir,
get_launcher_dir,
get_launcher_log_dir,
latest_log_dir,
prepare_attempt_dirs,
write_launch_toml,
)
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
@@ -57,7 +57,7 @@ def write_config(
return config_path
def write_slurm_script(config: InferenceConfig, config_path: Path, script_path: Path) -> None:
def write_slurm_script(config: InferenceConfig, config_path: Path, log_dir: Path, script_path: Path) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
@@ -76,6 +76,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
template_vars = dict(
**config.slurm.template_vars,
config_path=config_path,
config_dir=config_path.parent,
log_dir=log_dir,
output_dir=config.output_dir,
launcher_log_dir=get_launcher_log_dir(config.output_dir),
gpus_per_node=config.deployment.gpus_per_node,
@@ -133,17 +135,17 @@ def inference_slurm(config: InferenceConfig):
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
config_dir = get_config_dir(config.output_dir)
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
write_launch_toml(config_dir, "inference")
is_multi_node = config.deployment.type in ("multi_node", "disaggregated")
exclude = {"deployment", "slurm", "dry_run"} if is_multi_node else {"slurm", "dry_run"}
config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node)
logger.info(f"Wrote config to {config_path}")
script_path = get_launcher_dir(config.output_dir) / INFERENCE_SBATCH
write_slurm_script(config, config_path, script_path)
write_slurm_script(config, config_path, log_dir, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
log_dir = latest_log_dir(config.output_dir)
num_nodes = getattr(config.deployment, "num_nodes", 1)
log_message = format_log_message(log_dir=log_dir, inference=True, job_log=True, num_infer_nodes=num_nodes)
+11 -13
View File
@@ -20,13 +20,11 @@ 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,
create_attempt_log_dir,
format_log_message,
get_ckpt_dir,
get_config_dir,
get_launcher_dir,
get_launcher_log_dir,
latest_log_dir,
prepare_attempt_dirs,
resolve_latest_ckpt_step,
validate_run_dir,
write_launch_toml,
@@ -123,8 +121,8 @@ def rl_local(config: RLConfig):
json_logging=config.log.json_logging,
)
config_dir = get_config_dir(config.run_dir)
write_launch_toml(config.run_dir, "rl")
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_toml(config_dir, "rl")
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
@@ -179,9 +177,6 @@ def rl_local(config: RLConfig):
f"Update the base_url to use port {expected_port} to match the inference server."
)
# Per-attempt log dir: a resume never overwrites an earlier attempt's logs
log_dir = create_attempt_log_dir(config.run_dir)
# Start processes
processes: list[Popen] = []
monitor_threads: list[Thread] = []
@@ -420,7 +415,7 @@ def rl_local(config: RLConfig):
raise
def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) -> None:
def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script_path: Path) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
@@ -463,6 +458,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
script = template.render(
**config.slurm.template_vars,
config_path=config_dir / RL_CONFIG,
config_dir=config_dir,
log_dir=log_dir,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
@@ -476,6 +473,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
is_disaggregated=True,
run_name=config.run.name,
config_dir=config_dir,
log_dir=log_dir,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
@@ -519,6 +517,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
is_disaggregated=False,
run_name=config.run.name,
config_dir=config_dir, # TODO: should prob have each subconfig path separately
log_dir=log_dir,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
@@ -565,9 +564,8 @@ def rl_slurm(config: RLConfig):
config.log.level or os.environ.get("PRIME_LOG_LEVEL", "info"), json_logging=config.log.json_logging
)
config_dir = get_config_dir(config.run_dir)
write_launch_toml(config.run_dir, "rl")
log_dir = latest_log_dir(config.run_dir)
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_toml(config_dir, "rl")
if config.deployment.type == "single_node":
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean"})
@@ -604,7 +602,7 @@ def rl_slurm(config: RLConfig):
)
script_path = get_launcher_dir(config.run_dir) / RL_SBATCH
write_slurm_script(config, config_dir, script_path)
write_slurm_script(config, config_dir, log_dir, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
if config.dry_run:
+16 -13
View File
@@ -17,14 +17,12 @@ 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,
create_attempt_log_dir,
format_log_message,
get_broadcast_dir,
get_ckpt_dir,
get_config_dir,
get_launcher_dir,
get_launcher_log_dir,
latest_log_dir,
prepare_attempt_dirs,
resolve_latest_ckpt_step,
validate_run_dir,
write_launch_toml,
@@ -141,7 +139,9 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
json.dump(env_server_dict, f, indent=2)
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path, prl_run_id: str | None = None) -> None:
def write_slurm_script(
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str | None = None
) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
@@ -165,6 +165,8 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
script = template.render(
**config.slurm.template_vars,
config_path=config_path,
config_dir=config_path.parent,
log_dir=log_dir,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
@@ -199,7 +201,8 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
script = template.render(
**config.slurm.template_vars,
config_path=config_path,
config_dir=get_config_dir(config.run_dir),
config_dir=config_path.parent,
log_dir=log_dir,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
@@ -233,8 +236,8 @@ def sft_slurm(config: SFTConfig):
online_eval = config.deployment.type == "multi_node" and config.eval is not None
config_dir = get_config_dir(config.run_dir)
write_launch_toml(config.run_dir, "sft")
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_toml(config_dir, "sft")
config_path = config_dir / SFT_CONFIG
exclude = (
{"deployment", "slurm", "dry_run", "clean"}
@@ -258,12 +261,12 @@ def sft_slurm(config: SFTConfig):
write_eval_subconfigs(config, config_dir, strip_router=True)
logger.info(f"Wrote eval subconfigs to {config_dir}")
script_path = launcher_dir / SFT_SBATCH
write_slurm_script(config, config_path, script_path, prl_run_id)
write_slurm_script(config, config_path, log_dir, script_path, prl_run_id)
logger.info(f"Wrote SLURM script to {script_path}")
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
log_message = format_log_message(
log_dir=latest_log_dir(config.run_dir),
log_dir=log_dir,
trainer=True,
num_train_nodes=num_nodes,
evals=online_eval,
@@ -294,8 +297,8 @@ def sft_local(config: SFTConfig):
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = get_config_dir(config.run_dir)
write_launch_toml(config.run_dir, "sft")
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_toml(config_dir, "sft")
config_path = config_dir / SFT_CONFIG
write_config(config, config_path)
logger.info(f"Wrote config to {config_path}")
@@ -310,8 +313,6 @@ def sft_local(config: SFTConfig):
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
log_dir = create_attempt_log_dir(config.run_dir)
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
# launcher must partition GPUs between processes; plain SFT leaves them to torchrun.
infer_gpu_ids: list[int] = []
@@ -409,6 +410,8 @@ def sft_local(config: SFTConfig):
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
"PRL_ATTEMPT_CONFIG_DIR": str(config_dir),
"PRL_ATTEMPT_LOG_DIR": str(log_dir),
"PRL_LOG_DIR": str(log_dir),
**wandb_shared_env,
"WANDB_SHARED_LABEL": "evals",
+75 -15
View File
@@ -13,8 +13,9 @@ 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, so an overload cut only blocks admission and
the in-flight pool drains through natural completions.
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
@@ -322,6 +323,20 @@ class Evals:
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),
@@ -356,7 +371,10 @@ class Evals:
# 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
@@ -371,34 +389,66 @@ class Evals:
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
# between the trigger above and the weight reload completing.
self.policy.version = step
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)
await self.consume_epoch(fired, step)
async def consume_epoch(self, fired: list[str]) -> None:
"""Consume dispatcher episodes until every fired env's epoch finalizes,
routing them through the sink and monitors."""
# An env with no examples emits no episodes, so its epoch can never finalize.
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) > 0}
cancellation_task: asyncio.Task[int] | None = None
superseding_step: int | None = None
online = self.config.online
while pending:
item = await self.dispatcher.out_q.get()
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):
raise RuntimeError("Eval dispatcher emitted a group cancellation")
if isinstance(item, DispatchFailure):
eval_batch = self.eval_sink.cancel(item)
elif isinstance(item, DispatchFailure):
eval_batch = self.eval_sink.fail(item)
else:
step = eval_work(item).step
await monitors.log([item], step, "eval", "all")
item_step = eval_work(item).step
await monitors.log([item], item_step, "eval", "all")
eval_batch = self.eval_sink.add(item)
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}; "
f"advancing to checkpoint {superseding_step}"
)
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:
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
@@ -410,12 +460,15 @@ class Evals:
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)
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)
@@ -423,6 +476,13 @@ class Evals:
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"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} | "
+1
View File
@@ -143,6 +143,7 @@ def eval_section(name: str, env_pattern: str) -> ws.Section:
return section(
name,
regexes=[f"eval/{env_pattern}/all/[^/]+/avg@.*", f"eval/{env_pattern}/effective/[^/]+/avg@.*"]
+ [f"eval/{env_pattern}/all/cancelled/mean"]
+ [f"eval/{env_pattern}/{m}" for m in COMMON_METRICS]
+ [f"eval/{env_pattern}/{r}" for r in COMMON_REGEXES],
)
+36 -1
View File
@@ -18,7 +18,7 @@
the weight update) drops train groups already past ``max_off_policy_steps`` — a
compute-saving early cancel; the sink's queue sweep is what guarantees the
bound. Eval episodes are measurements for the policy version they started
with, so they are allowed to finish even if training advances. Train
with. Online evals may explicitly cancel them when a newer checkpoint is ready. Train
episodes sampled from a frozen model never go stale — their generation
source doesn't change with policy updates.
"""
@@ -702,6 +702,7 @@ class Dispatcher:
kind=kind,
env_name=env_name,
group_id=str(group_id),
step=group.step if group is not None else claimed[-1][1].step,
count=cancelled,
reason=reason,
)
@@ -745,6 +746,40 @@ class Dispatcher:
await safe_cancel_all(train_tasks)
return cancelled
async def cancel_eval_step(self, step: int) -> int:
"""Cancel queued and active eval groups for a superseded checkpoint.
Scheduling remains paused until ``on_new_version`` runs after the
replacement weights are live.
"""
if self.eval_source is None or self.eval_envs is None:
return 0
self.policy_update_pending = True
async with self.scheduling_lock:
queued = self.eval_source.cancel_step(step)
group_ids = [gid for gid, group in self.groups.items() if group.kind == "eval" and group.step == step]
cancelled = 0
for group_id in group_ids:
cancelled += await self.drop_group(group_id, reason="superseded")
for request in queued:
count = 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(
GroupCancellation(
kind="eval",
env_name=request.env_name,
group_id=str(uuid.uuid4()),
step=request.step,
count=count,
reason="superseded",
)
)
return cancelled
# ── metrics ────────────────────────────────────────────────────────────
def gauges(self) -> dict[str, float]:
+52 -10
View File
@@ -8,7 +8,7 @@ import verifiers.v1 as vf
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.metrics import EvalEpisodes
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch
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
@@ -20,8 +20,10 @@ class EvalSink:
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)
def add(self, episode: vf.Episode) -> EvalBatch | None:
env_name = episode_env_name(episode)
@@ -50,11 +52,33 @@ class EvalSink:
return self.process_batch(bkey)
return None
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):
return self.process_batch(bkey)
return None
def _group_size(self, group_id: str) -> int:
return len(self.pending_groups[group_id]) + len(self.pending_group_failures[group_id])
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 _batch_size(self, key: tuple[str, int]) -> int:
return len(self.pending_batches[key]) + len(self.pending_batch_failures[key])
return (
len(self.pending_batches[key])
+ len(self.pending_batch_failures[key])
+ self.pending_batch_cancellations[key]
)
def group_size_for(self, env_name: str) -> int:
return self.eval_envs.get(env_name).config.group_size
@@ -64,23 +88,32 @@ class EvalSink:
return len(env.examples) * env.config.group_size
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
keys = set(self.pending_batches) | set(self.pending_batch_failures)
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)
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]
if not group and not failures:
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
else:
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)
buffered[key] = (
buffered.get(key, 0)
+ len(group)
+ len(failures)
+ (cancellation.count if cancellation is not None else 0)
)
return [
(
env_name,
@@ -95,17 +128,23 @@ class EvalSink:
def process_group(self, group_id: str) -> None:
group = self.pending_groups.pop(group_id, [])
failures = self.pending_group_failures.pop(group_id, [])
if not group and not failures:
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
else:
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]
@@ -116,6 +155,7 @@ class EvalSink:
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}"
)
@@ -123,9 +163,11 @@ class EvalSink:
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)
return EvalBatch(
env_name=env_name,
step=step,
episodes=EvalEpisodes(episodes, group_size=self.group_size_for(env_name)),
failures=failures,
cancelled=cancelled,
)
+6
View File
@@ -71,6 +71,12 @@ class EvalSource:
return None
return self.queue.popleft()
def cancel_step(self, step: int) -> list[TaskRequest]:
"""Remove and return queued examples for a superseded eval step."""
cancelled = [request for request in self.queue if request.step == step]
self.queue = deque(request for request in self.queue if request.step != step)
return cancelled
def __bool__(self) -> bool:
return bool(self.queue)
+4 -2
View File
@@ -35,7 +35,7 @@ class Progress:
WorkKind = Literal["train", "eval"]
CancelReason = Literal["stale", "overload"]
CancelReason = Literal["stale", "overload", "superseded"]
@dataclass
@@ -43,11 +43,12 @@ class GroupCancellation:
"""Terminal marker for a dropped group: one message covering every episode
the group still owed the sink (in-flight and never-dispatched), so
count-to-``group_size`` finalization still fires. ``reason`` distinguishes
pipeline decisions (staleness, overload cut) from episode errors."""
pipeline decisions (staleness, overload cut, superseded eval) from episode errors."""
kind: WorkKind
env_name: str
group_id: str
step: int
count: int
reason: CancelReason
@@ -131,6 +132,7 @@ class EvalBatch:
step: int
episodes: EvalEpisodes
failures: list[DispatchFailure]
cancelled: int = 0
class VersionObserver(Protocol):
+4 -5
View File
@@ -52,13 +52,12 @@ export RPC_PORT={{ data_parallel_rpc_port }}
# Paths
export PROJECT_DIR={{ project_dir }}
export CONFIG_PATH={{ config_path }}
export CONFIG_DIR={{ config_dir }}
export OUTPUT_DIR={{ output_dir }}
# Per-attempt log dir: a relaunch never overwrites an earlier attempt's logs.
ATTEMPT=1
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
export LOG_DIR={{ log_dir }}
export PRL_ATTEMPT_CONFIG_DIR=$CONFIG_DIR
export PRL_ATTEMPT_LOG_DIR=$LOG_DIR
mkdir -p $LOG_DIR/inference
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
ln -sfn inference/node_0.log $LOG_DIR/inference.log
# Setup environment
@@ -59,12 +59,10 @@ export PROJECT_DIR={{ project_dir }}
export CONFIG_DIR={{ config_dir }}
export OUTPUT_DIR={{ output_dir }}
export LAUNCHER_DIR={{ launcher_dir }}
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
ATTEMPT=1
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
export LOG_DIR={{ log_dir }}
export PRL_ATTEMPT_CONFIG_DIR=$CONFIG_DIR
export PRL_ATTEMPT_LOG_DIR=$LOG_DIR
mkdir -p $LOG_DIR/trainer $LOG_DIR/inference
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
ln -sfn inference/node_0.log $LOG_DIR/inference.log
@@ -42,13 +42,10 @@ export CONFIG_DIR={{ config_dir }}
export TRAIN_CONFIG_PATH={{ config_path }}
export OUTPUT_DIR={{ output_dir }}
export LAUNCHER_DIR={{ launcher_dir }}
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
ATTEMPT=1
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
export LOG_DIR={{ log_dir }}
export PRL_ATTEMPT_CONFIG_DIR=$CONFIG_DIR
export PRL_ATTEMPT_LOG_DIR=$LOG_DIR
mkdir -p $LOG_DIR/trainer
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
{% if online_eval -%}
mkdir -p $LOG_DIR/inference
@@ -26,6 +26,8 @@
set -e
export PROJECT_DIR={{ project_dir }}
export PRL_ATTEMPT_CONFIG_DIR={{ config_dir }}
export PRL_ATTEMPT_LOG_DIR={{ log_dir }}
# Setup environment
cd $PROJECT_DIR
@@ -26,6 +26,8 @@
set -e
export PROJECT_DIR={{ project_dir }}
export PRL_ATTEMPT_CONFIG_DIR={{ config_dir }}
export PRL_ATTEMPT_LOG_DIR={{ log_dir }}
# Setup environment
cd $PROJECT_DIR
+80 -25
View File
@@ -12,26 +12,67 @@ def get_log_dir(output_dir: Path) -> Path:
return output_dir / "logs"
def create_attempt_log_dir(run_dir: Path) -> Path:
"""Create ``logs/attempt_<n>`` for this launch attempt and repoint ``logs/latest`` to it.
def _attempt_numbers(parent: Path) -> set[int]:
return {
int(path.name.removeprefix("attempt_"))
for path in parent.glob("attempt_*")
if path.name.removeprefix("attempt_").isdigit()
}
Every launch — fresh or resumed — gets its own numbered log directory, so a resume
never overwrites an earlier attempt's logs. Returns the attempt directory."""
logs_dir = get_log_dir(run_dir)
logs_dir.mkdir(parents=True, exist_ok=True)
attempts = (
int(p.name.removeprefix("attempt_"))
for p in logs_dir.glob("attempt_*")
if p.name.removeprefix("attempt_").isdigit()
)
attempt_dir = logs_dir / f"attempt_{1 + max(attempts, default=0)}"
attempt_dir.mkdir()
# Atomically repoint the relative ``latest`` symlink: create a temp link, then rename.
tmp_link = logs_dir / f".{attempt_dir.name}"
def _point_latest(parent: Path, attempt_dir: Path) -> None:
"""Atomically point ``parent/latest`` at a relative attempt directory."""
tmp_link = parent / f".{attempt_dir.name}"
if tmp_link.is_symlink() or tmp_link.exists():
tmp_link.unlink()
os.symlink(attempt_dir.name, tmp_link)
os.replace(tmp_link, logs_dir / "latest")
os.replace(tmp_link, parent / "latest")
def create_attempt_dirs(run_dir: Path) -> tuple[Path, Path]:
"""Create matching config and log directories for one launch attempt.
Returns the concrete resolved-config and log directories. The ``latest``
symlink under each artifact root points to the new attempt.
"""
configs_dir = run_dir / "configs"
logs_dir = get_log_dir(run_dir)
configs_dir.mkdir(parents=True, exist_ok=True)
logs_dir.mkdir(parents=True, exist_ok=True)
attempts = _attempt_numbers(configs_dir) | _attempt_numbers(logs_dir)
attempt_name = f"attempt_{1 + max(attempts, default=0)}"
config_attempt_dir = configs_dir / attempt_name
log_dir = logs_dir / attempt_name
config_dir = config_attempt_dir / "resolved"
config_dir.mkdir(parents=True)
log_dir.mkdir()
_point_latest(configs_dir, config_attempt_dir)
_point_latest(logs_dir, log_dir)
return config_dir, log_dir
def prepare_attempt_dirs(run_dir: Path) -> tuple[Path, Path]:
"""Reuse a launcher-pinned attempt or allocate a new one."""
config_dir = os.environ.get("PRL_ATTEMPT_CONFIG_DIR")
log_dir = os.environ.get("PRL_ATTEMPT_LOG_DIR")
if config_dir is None and log_dir is None:
return create_attempt_dirs(run_dir)
if config_dir is None or log_dir is None:
raise RuntimeError("PRL_ATTEMPT_CONFIG_DIR and PRL_ATTEMPT_LOG_DIR must be set together")
resolved_config_dir = Path(config_dir)
attempt_log_dir = Path(log_dir)
resolved_config_dir.mkdir(parents=True, exist_ok=True)
attempt_log_dir.mkdir(parents=True, exist_ok=True)
return resolved_config_dir, attempt_log_dir
def create_attempt_log_dir(run_dir: Path) -> Path:
"""Create a log-only attempt for standalone processes without config dumps."""
logs_dir = get_log_dir(run_dir)
logs_dir.mkdir(parents=True, exist_ok=True)
attempt_dir = logs_dir / f"attempt_{1 + max(_attempt_numbers(logs_dir), default=0)}"
attempt_dir.mkdir()
_point_latest(logs_dir, attempt_dir)
return attempt_dir
@@ -104,13 +145,21 @@ CACHE_DIR = home_dir() / ".cache" / "prime-rl"
def get_config_dir(output_dir: Path) -> Path:
"""Resolved per-component config dumps (JSON). The launch TOML copy lives one
level up, at `configs/<entrypoint>.toml`."""
return output_dir / "configs" / "resolved"
"""Return the current attempt's resolved config directory.
The environment override pins child processes to their launch attempt. The
legacy path keeps tools compatible with runs created before config attempts.
"""
if config_dir := os.environ.get("PRL_ATTEMPT_CONFIG_DIR"):
return Path(config_dir)
configs_dir = output_dir / "configs"
latest = configs_dir / "latest" / "resolved"
legacy = configs_dir / "resolved"
return legacy if legacy.is_dir() and not latest.exists() else latest
def write_launch_toml(run_dir: Path, name: str) -> None:
"""Copy the launch `@` TOML file(s) verbatim to `configs/<name>.toml`."""
def write_launch_toml(config_dir: Path, name: str) -> None:
"""Copy the launch `@` TOML file(s) to the current config attempt."""
import sys
argv = sys.argv[1:]
@@ -124,9 +173,9 @@ def write_launch_toml(run_dir: Path, name: str) -> None:
if not tomls:
return
texts = [text for _, text in tomls] if len(tomls) == 1 else [f"# @ {p}\n{text}" for p, text in tomls]
config_dir = run_dir / "configs"
config_dir.mkdir(parents=True, exist_ok=True)
(config_dir / f"{name}.toml").write_text("\n".join(texts))
attempt_dir = config_dir.parent
attempt_dir.mkdir(parents=True, exist_ok=True)
(attempt_dir / f"{name}.toml").write_text("\n".join(texts))
def get_launcher_dir(output_dir: Path) -> Path:
@@ -192,7 +241,13 @@ def has_run_artifacts(run_dir: Path) -> bool:
if not run_dir.exists():
return False
launcher_entries = {entry for pattern in LAUNCHER_ARTIFACTS for entry in run_dir.glob(pattern)}
return any(entry not in launcher_entries for entry in run_dir.iterdir())
for entry in run_dir.iterdir():
if entry in launcher_entries:
continue
if entry.name == "logs" and entry.is_dir() and not any(path.is_file() for path in entry.rglob("*")):
continue
return True
return False
def validate_run_dir(
+13
View File
@@ -86,7 +86,18 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
# resolved concatenated document renders as a tree
page.click("#tabs [data-tab=config]")
page.wait_for_timeout(1500)
assert page.locator("#config-attempt-select").input_value() == "latest"
assert page.locator("#config-attempt-select option:checked").inner_text().startswith("latest (attempt ")
assert page.eval_on_selector("#config-view", "e => e.innerText.length") > 100, "config view did not render"
if page.locator("#config-attempt-select option").count() > 2:
latest_config = page.locator("#config-view").inner_text()
first_attempt = page.locator("#config-attempt-select option").nth(1).get_attribute("value")
page.locator("#config-attempt-select").select_option(first_attempt, force=True)
page.wait_for_timeout(1000)
assert page.locator("#config-attempt-select").input_value() == first_attempt
assert page.locator("#config-view").inner_text() != latest_config
page.locator("#config-attempt-select").select_option("latest", force=True)
page.wait_for_timeout(1000)
page.click("#config-format [data-fmt=json]")
page.wait_for_timeout(1500)
assert page.locator("#config-view .j-line").count() > 10, "resolved config tree did not render"
@@ -111,6 +122,8 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
# logs: the merged pane shows lines
page.click("#tabs [data-tab=logs]")
page.wait_for_timeout(PAGE_SETTLE_MS)
assert page.locator("#attempt-select").input_value() == "latest"
assert page.locator("#attempt-select option:checked").inner_text().startswith("latest (attempt ")
log_lines = page.locator(".log-pane .ll").count()
assert log_lines > 10, f"log pane rendered only {log_lines} lines"
+8 -2
View File
@@ -2,6 +2,7 @@ import pytest
from prime_rl.utils.pathing import (
clean_future_steps,
create_attempt_dirs,
get_broadcast_dir,
get_rollout_dir,
get_step_path,
@@ -23,8 +24,13 @@ def test_empty_dir_passes(tmp_path):
def test_dir_with_launcher_artifacts_passes(tmp_path):
run_dir = tmp_path / "submitted"
run_dir.mkdir()
(run_dir / "configs").mkdir()
(run_dir / "configs" / "trainer.toml").touch()
config_dir, log_dir = create_attempt_dirs(run_dir)
(config_dir / "trainer.json").touch()
next_config_dir, next_log_dir = create_attempt_dirs(run_dir)
assert next_config_dir.parent.name == "attempt_2"
assert next_log_dir.name == "attempt_2"
assert (run_dir / "configs" / "latest").resolve() == next_config_dir.parent
assert (run_dir / "logs" / "latest").resolve() == next_log_dir
(run_dir / "launcher").mkdir()
(run_dir / "launcher" / "rl.sbatch").touch()
(run_dir / "launcher" / ".trainer.done").touch()
+1 -1
View File
@@ -6,7 +6,7 @@ the checkpoint's model state, gather rank-parallel, convert to HF format, and
write sharded safetensors plus config/tokenizer assets.
The model and tokenizer configs are read from the run's resolved config
(``<run>/configs/resolved/trainer.json`` or ``sft.json``). LoRA checkpoints are not
(``<run>/configs/latest/resolved/trainer.json`` or ``sft.json``). LoRA checkpoints are not
supported — the script exports full fine-tunes only.
Usage (from the prime-rl repo; more ranks = faster gathers and writes, and