Compare commits

...
Author SHA1 Message Date
samsjaandGitHub b636a8b7ec chore: bump prime-envs to latest main (#3630)
## Summary
- Bump the `deps/prime-envs` submodule from `1f1e050ab` to `1213b7336`
(latest `main`).
  - Pulls in:
-
[prime-envs#791](https://github.com/PrimeIntellect-ai/prime-envs/pull/791):
strip v0 remnants.
-
[prime-envs#795](https://github.com/PrimeIntellect-ai/prime-envs/pull/795):
restore solver network access for training environments.
-
[prime-envs#797](https://github.com/PrimeIntellect-ai/prime-envs/pull/797):
500-trace SWE cheating recall benchmark (new `trace-cheating-recall-500`
judge env).
-
[prime-envs#796](https://github.com/PrimeIntellect-ai/prime-envs/pull/796):
run MCP Atlas and Enterprise Ops Gym services in VMs.
-
[prime-envs#798](https://github.com/PrimeIntellect-ai/prime-envs/pull/798):
fair-use solver prompts for SWE and terminal training tasksets.
-
[prime-envs#805](https://github.com/PrimeIntellect-ai/prime-envs/pull/805):
keep env CI evals off the platform.
-
[prime-envs#770](https://github.com/PrimeIntellect-ai/prime-envs/pull/770):
OfficeQA Pro V2 (new `officeqa-pro-v2` env).
-
[prime-envs#808](https://github.com/PrimeIntellect-ai/prime-envs/pull/808):
complete TMax platform hosting and source references.
-
[prime-envs#814](https://github.com/PrimeIntellect-ai/prime-envs/pull/814):
ask before changing repository skills.
-
[prime-envs#815](https://github.com/PrimeIntellect-ai/prime-envs/pull/815):
support renamed Verifiers eval CLI in CI.
-
[prime-envs#822](https://github.com/PrimeIntellect-ai/prime-envs/pull/822):
remove obsolete Prime VM configuration.
- Relock `uv.lock`: new workspace members `officeqa-pro-v2` and
`trace-cheating-recall-500` (auto-discovered via
`deps/prime-envs/environments/*/*`); env package version bumps.

## Validation

- `uv sync --all-extras --all-packages --locked` passes.
- `uv run pytest tests/unit -m "not gpu"`: 616 passed, 1 skipped.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Training and evaluation behavior can shift (solver prompts, network
access, VM-hosted tool services, new benchmarks) because many SWE,
terminal, and tool-use env packages change together.
> 
> **Overview**
> Updates the **`deps/prime-envs`** submodule to the latest **`main`**
and refreshes **`uv.lock`** so the workspace picks up new and bumped
editable environment packages.
> 
> The lockfile adds two auto-discovered members—**`officeqa-pro-v2`**
(search) and **`trace-cheating-recall-500`** (judge)—and bumps patch
versions across many existing env packages (SWE stacks like
**`openswe`**, **`multiswe`**, **`swesmith-env`**; terminal **`tmax`** /
**`terminal-lego`**; tool-use **`mcp-atlas`** /
**`enterprise-ops-gym`**; plus assorted math, lean, long-context, and
reasoning envs).
> 
> Upstream **`prime-envs`** changes bundled with this bump include
stripping v0 remnants, restoring solver network access for training
envs, fair-use solver prompts for SWE/terminal tasksets, MCP Atlas and
Enterprise Ops Gym running services in VMs, TMax hosting completion,
CI/eval CLI fixes, and related housekeeping—not new logic in this repo
beyond the dependency pin and lock refresh.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
75422004f320992e134a1d188368f15637bf8193. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-22 13:19:08 -07:00
Mika SenghaasandGitHub 9aa8563eae fix(inference): extend startup readiness timeout (#3626)
## Summary
- increase the default inference readiness timeout from 30 minutes to 60
minutes
- keep the direct `check_health` default aligned with `ClientConfig`

Large models can exceed 30 minutes on a cold node while vLLM compiles
architecture-specific kernels and captures CUDA graphs. The previous
default can tear down an otherwise healthy launch just before readiness.

## Test plan
- `PYTHONPATH="$PWD/src:$PWD/packages/prime-rl-configs/src" pytest -q
tests/unit/orchestrator/test_clients.py` (10 passed)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Only increases startup wait defaults; no changes to auth, weight
updates, or runtime inference behavior once ready.
> 
> **Overview**
> Raises the default **inference pool startup wait** from 30 to **60
minutes** so cold starts (e.g. vLLM kernel compile and CUDA graph
capture on large models) are less likely to fail right before `/health`
succeeds.
> 
> The change updates `ClientConfig.wait_for_ready_timeout` in shared
config and the default `timeout` on `check_health`, keeping orchestrator
health polling aligned with the config default used by
`AdminPlane.wait_for_ready`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f9fdfe25be6d643d43e830121bf22b6a9bd036c1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-22 11:58:23 -07:00
Mika SenghaasandGitHub a44dc3572c feat(inference): configurable vLLM router request timeout (#3620)
## Summary

- Add `VllmRouterConfig.request_timeout_secs` (**default 1800 — the
router's own built-in default**, `ge=1`): the maximum lifetime of a
routed request, including streamed completions.
- Wire it through both router launch paths — the Python entrypoint
(`--request-timeout-secs`) and the `_launch_router.sh.j2` template. When
unset, the router behaves exactly as before.
- Long agentic rollouts set it explicitly, e.g. `request_timeout_secs =
3600` for one-hour SWE eval requests.

## Note on "no timeout"

The Rust router applies the value as its HTTP client's **total request
timeout unconditionally** (`server.rs`,
`.timeout(Duration::from_secs(...))`): plain `u64`, no disable sentinel,
and `0` would be an *immediate* timeout. So "no timeout" is not
expressible — a finite configurable value with the upstream default is
the right shape.

## Validation

- `VllmRouterConfig` default (`1800`) / set (`3600`) / `ge=1` rejection
all verified; both launch paths interpolate the same field (the template
already receives the `router` config object).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Operational tuning of router HTTP client timeouts only; no auth or
data-path changes, though misconfigured values could still cut off or
hang long requests.
> 
> **Overview**
> Adds **`request_timeout_secs`** on **`VllmRouterConfig`** (default
**1800s**, minimum 1) so the maximum lifetime of a routed
request—including streamed completions—can be set from inference config
instead of relying on implicit router defaults.
> 
> Both managed router launch paths now pass
**`--request-timeout-secs`**: the local **`start_router`** entrypoint
and the SLURM **`_launch_router.sh.j2`** template read
**`router.request_timeout_secs`**. Long agentic or eval rollouts can
raise the value (e.g. via config override) without patching launch
scripts.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
adf7321a3604f2fc784ab961688a281ab6002165. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 16:22:12 -07:00
Mika SenghaasandGitHub 32f4f40f9e feat(orchestrator): unified taskset shuffle for train and eval sources (#3622)
## Summary

- `EnvConfig.shuffle` (`bool`, default `False`): shuffle the source's
finite taskset **once at startup** with a fixed seed
(`TASKSET_SHUFFLE_SEED = 42`).
- Defined in one place — `EnvConfig`, the shared base — so both
`TrainSourceConfig` and `EvalSourceConfig` inherit it: one knob covers
RL train envs, RL/SFT online evals, and standalone evals. Train
curricula and eval example selection both consume the shuffled order.
- Infinite tasksets reject `shuffle` at startup with a clear error.
- The eval resume allowlist now overrides `source.*.shuffle` (fixed seed
⇒ deterministic across resume).

```toml
[[train.source]]           # or [[eval.source]]
shuffle = true
```

Mirrors the existing SFT-data convention (`shuffle: bool` + fixed seed).

## Validation

- `pytest tests/unit/orchestrator/ tests/unit/eval/
tests/unit/test_configs.py` — 288 passed, 1 skipped.
- Smoke: `TrainSourceConfig(..., shuffle=True)` and
`EvalSourceConfig(..., shuffle=True)` both parse; default is `False`;
resume allowlist updated.
- **Manual eval-selection run (real `Env.start()` path, gsm8k,
`num_examples = 50` of 1319 test tasks; only the env-server network
handshake stubbed — no GPU on the validating node):**
- `shuffle = false`, run 1 → `[0, 1, 2, ..., 49]` (natural source order)
- `shuffle = true`, run 1 → `[588, 1214, 57, 906, 1252, 618, 599, 289,
...]`
- `shuffle = true`, run 2 → identical to run 1 (same 50 tasks, same
order) ✔ reproduces
  - `shuffle = false`, run 2 → identical to run 1 ✔ off is stable
- off vs on selections differ (set overlap 2/50, as expected for a
random 50-of-1319 subset) ✔

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior is opt-in with a fixed seed and only affects task ordering at
startup; infinite tasksets are explicitly rejected.
> 
> **Overview**
> Adds a **`shuffle`** flag on shared **`EnvConfig`** (default
**`false`**) so train and eval sources can reorder a **finite** taskset
once at env startup instead of always taking tasks in source order.
> 
> When **`shuffle=true`**, the orchestrator materializes the taskset and
shuffles it with a fixed seed (**`TASKSET_SHUFFLE_SEED = 42`**), so the
same permutation holds for the whole run and eval example selection
stays reproducible. **Infinite** tasksets fail fast with a clear error.
> 
> Eval **resume** may override **`source.*.shuffle`** alongside other
rollout knobs. New unit tests cover default order, changed selection,
reproducibility, full-taskset selection, and the infinite-taskset
rejection.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8358483c1144ed331f575a5e857fabe390de50c8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 16:20:06 -07:00
Mika SenghaasandGitHub ef07764841 feat(sft): per-row reasoning_effort renderer override (#3621)
## Summary

- A `reasoning_effort` column in the dataset overrides the `[renderer]`
config's `reasoning_effort` field **per row**, so one SFT run can mix
reasoning efforts with the configured renderer serving as the default
for rows that do not set one (or set null).
- Requires a typed renderer config that has the field: `renderer.name =
"auto"` and field-less renderers raise a clear `ValueError`. Renderer
configs are frozen, so resolved configs are cached and rows resolving to
the same config share one renderer instance.
- Doc paragraph in `docs/training.md`; dataloader and sft-dataset tests
updated.

```toml
[renderer]
name = "glm-5.3"          # typed renderer; reasoning_effort = "max" is the row default
# dataset rows may carry reasoning_effort = "low" | "high" | "max" per row
```

## Validation

- `pytest tests/unit/train/sft/` — 47/47 pass.
- E2E with the real GLM-5.3 renderer: rendered prompts carry the per-row
effort preamble (`Reasoning Effort: Low` vs `Max`), invalid efforts
rejected by the config `Literal`, `None` rows fall back to the
configured renderer, and the resolver caches one renderer per distinct
config.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are confined to SFT tokenization/renderer selection with
explicit validation for auto or unsupported renderers; misconfiguration
fails at load time rather than silently wrong training.
> 
> **Overview**
> SFT can now **mix reasoning efforts in one run** via an optional
dataset **`reasoning_effort`** column that overrides the typed
`[renderer]` config per row; null/missing values keep the TOML default.
> 
> **`RendererResolver`** (in `data.py`) builds and **caches** renderers
from `renderer_config` + row overrides instead of a single shared
renderer. **`SFTDataset`** takes a per-example renderer callable;
**`setup_dataset`** / **`train.py`** pass **`renderer_config`** and the
VLM **processor** rather than constructing one renderer up front (train
and validation use the same path).
> 
> Docs in **`training.md`** describe the column, typed-renderer
requirement, and supported model families. Unit tests were updated to
pass `lambda _: renderer` into **`SFTDataset`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3408b9918dccf06d86ab732faa94a18f6233ca31. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 16:20:00 -07:00
7745c669d1 feat(monitors): attach eval runs to a platform-created evaluation (#3619)
## Summary

`PrimeEvalMonitor` attaches to an existing platform evaluation when
`$PRIME_RUNS_EVAL_ID` is set, instead of always registering a new one.
This mirrors how `PrimeTrainMonitor` already attaches to `$RUN_ID`.

Why: A hosted evaluation is created by the platform before its sandbox
starts: the platform owns billing, secrets, timeouts, cancellation and
the final "did every episode reach the platform" check, and it hands the
sandbox the evaluation's id, which the monitor reads from
`$PRIME_RUNS_EVAL_ID`. Today `uv run eval --monitors.prime` inside that
sandbox would call `pr.init(kind="eval", ...)` without an id, register a
second evaluation and leave the platform's one open forever.


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes platform eval registration lifecycle for hosted runs;
misconfiguration (multiple sources or multiple epochs) fails fast with
explicit errors.
> 
> **Overview**
> **Hosted eval sandboxes** can now stream to an evaluation the platform
already created instead of registering a duplicate that leaves the
platform run orphaned.
> 
> When **`PRIME_RUNS_EVAL_ID`** is set, `PrimeEvalMonitor` calls
`pr.init` with that **`id`** (same attach pattern as training’s
**`$RUN_ID`**). Init requires **exactly one** eval source, and
**`open`** rejects a second epoch so one injected id maps to one epoch.
Logs note attachment when **`run.attached`** is true.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b4af11c50eb8201cbaf1b9a903b245a1bb8ed76e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 15:23:56 -07:00
87c5456806 chore(deps): bump vLLM to 0.29.0 (#3617)
Bumps vLLM from 0.28.0 to 0.29.0 and reconciles prime-rl's runtime
monkeypatches with 0.29's reorganized entrypoint layout. Three patches
are now obsolete and removed, each backed by a merged upstream PR.

- Rebound the API server layer onto `vllm.entrypoints.launchers.*`: on
0.29 the old `openai.api_server` path is a deprecation shim, so without
this the custom routes and the `PrimeRlServingTokens` swap would
silently not install.
- Dropped `monkey_patch_fp32_lm_head`: vLLM does the fp32 lm_head
projection natively via `head_dtype`
([#48390](https://github.com/vllm-project/vllm/pull/48390), LoRA path
[#48525](https://github.com/vllm-project/vllm/pull/48525)), so
`enable_fp32_lm_head` now injects `hf_overrides = {"head_dtype":
"float32"}`.
- Dropped the `PrimeRlServingTokens.serve_tokens` `kv_transfer_params`
bridge: upstream threads the params into the engine itself as of
[#42644](https://github.com/vllm-project/vllm/pull/42644), which landed
after the 0.28.0 cut.
- Dropped `monkey_patch_qwen3_coder_param_newline_trim`: upstream
restored the single-newline trim in
[#48846](https://github.com/vllm-project/vllm/pull/48846), making the
patch a byte-for-byte no-op.
- #48390 and #48846 already shipped in 0.28.0, so 0.29's role is to make
`fp32_lm_head` *fatal* via the new positional `skip_gather`; only #42644
is genuinely unlocked by the bump.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 15:36:25 -04:00
12b4d4b050 chore: whitelist the Environments Hub index for uv installs (#3612)
## Summary

- Add an explicit `[[tool.uv.index]]` named `prime-hub` for
`https://hub.primeintellect.ai/primeintellect/simple/` with
`exclude-newer = false`. Hub wheels carry no upload time, so the repo's
7-day `exclude-newer` cooldown filtered all of them out.
- `uv pip install gsm8k --index prime-hub` and `uv add gsm8k --index
prime-hub` now resolve inside prime-rl. The index is `explicit`, so `uv
sync` never consults it and `uv lock --check` passes unchanged.

Only the named index inherits the setting: passing the same URL via
`--extra-index-url` still hits the cooldown (uv matches index config by
name). Other Hub owners need their own entry or `--no-config`.

Verified in a fresh checkout: `uv lock --check`, slim `uv sync`, then
install through `--extra-index-url` (rejected), `--index prime-hub`
(0.1.4 installed), and the per-environment install index (rejected).

Companion: PrimeIntellect-ai/prime#934 (`prime eval run` installs Hub
environments into a prime-rl sandbox; it uses `--no-config` so any owner
works).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dependency-index configuration only; narrows the exclude-newer bypass
to an explicit, opt-in first-party index without changing default sync
behavior.
> 
> **Overview**
> Adds a named **`prime-hub`** uv index pointing at the Environments Hub
with **`exclude-newer = false`**, so Hub wheels (which lack upload
timestamps) are no longer blocked by the repo-wide **7-day**
`exclude-newer` policy.
> 
> The index is **`explicit`**, so default **`uv sync`** / lock checks
stay unchanged; Hub packages resolve only when you opt in (e.g. **`uv
add gsm8k --index prime-hub`**). Passing the same URL via
**`--extra-index-url`** still applies the global cooldown because uv
matches index settings by configured name, not raw URL.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1ac034977bbf2a54ef2977314fc87a9d2f6b1b5f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 10:51:06 -07:00
JannikStandGitHub 64a0decfaa improvement(docker): bake the dashboard extra into the cuda image (#3613)
### What & why

The prime-rl-fft chart runs a standalone read-only dashboard pod per
release (prime-rl-fft #75) that serves prime-rl's run dashboard (`uv run
dashboard`, port 7788) off the run's shared PVC. The chart image does
not include the `dashboard` extra (fastapi/uvicorn), so the pod
previously installed it at start with `uv sync --inexact` — which hangs
on some clusters, leaves the Deployment permanently unready, and times
out the whole release's helm `--wait` readiness gate after 90m, killing
every trainer/inference/orchestrator pod regardless of their own health.
The dashboard was disabled by default as a stopgap (prime-rl-fft #86).

This bakes the `dashboard` extra directly into the cuda image so the
dashboard pod serves straight from the image with no runtime install.

### Changes
- `Dockerfile.cuda`: add `--extra dashboard` to both `uv sync` calls
(third-party deps layer + first-party source layer).

### Notes
- `fastapi` + `uvicorn` are a few MB next to the ~20 GB GPU venv;
negligible size impact.
- Both syncs use `--locked` and `uv.lock` already resolves the
`dashboard` extra — no lockfile changes.
- Follow-ups (fft chart repo, separate PRs): drop the pod-start `uv sync
--inexact` command and re-enable the dashboard by default; expose it to
the platform backend over the tailnet.

### Testing
- No runtime code touched; image CI builds the image from this branch.
- `uv lock --check` equivalent verified: lock already contains the
dashboard extra deps with markers.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Build-only Dockerfile change that adds two small locked deps to the
venv; no application or runtime behavior changes in this repo.
> 
> **Overview**
> **Bakes the `dashboard` optional extra (FastAPI + Uvicorn) into the
CUDA Docker image** so Helm FFT chart dashboard pods can run `uv run
dashboard` from the image without a startup `uv sync`.
> 
> Both dependency install steps in `Dockerfile.cuda` now pass `--extra
dashboard` alongside the existing GPU/flash-attn extras, with a short
comment tying this to the chart dashboard pod. Lockfile is unchanged;
syncs stay `--locked`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
78fecdd68099796469bc2cecce1ad10142d9a76c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 09:27:47 -07:00
samsjaandGitHub a1822f7a0a feat: default enable_ep_weight_filter to true (#3608)
## What

- Adds a typed `inference.vllm.enable_ep_weight_filter` field defaulting
to `true`, so every vLLM server prime-rl launches now passes
`--enable-ep-weight-filter` (previously this flag only appeared as an
explicit pass-through in the GLM-5.3 advanced examples).
- Drops the now-redundant explicit `enable_ep_weight_filter = true` from
the GLM-5.3 examples (`examples/advanced/glm-5.3/swe.toml`,
`examples/advanced/glm-5.3/infer/pd-llmd.toml`).
- Asserts the default lands on the server namespace.

## Why

Under expert parallelism, vLLM's weight filter skips non-local
per-expert tensors **before** reading them from disk: each rank reads
only its own expert shard instead of the full checkpoint (experts are
~85-90% of MoE weight bytes). This cuts load I/O and startup time,
especially on shared storage.

The default is safe elsewhere — vLLM only activates the filter when the
model is MoE, `enable_expert_parallel` is on, and EPLB is off. It is a
silent no-op for dense models, fused-expert checkpoints (GPT-OSS style),
and EPLB runs. The repo pins `vllm>=0.28.0`, which has the flag.

Set `inference.vllm.enable_ep_weight_filter = false` to restore the old
behavior.

Note: #3604 relocates these GLM-5.3 examples to `configs/advanced/` and
its copies still carry the explicit line — drop it when rebasing on this
PR.

## Test plan

- `uv run pytest tests/unit/test_parsers.py tests/unit/test_configs.py`
- Verified `to_namespace()` emits `enable_ep_weight_filter=True` for a
real GLM-5.3 config, and that `--vllm.enable-ep-weight-filter false`
overrides it.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior change is gated in vLLM to MoE + expert parallelism without
EPLB; dense models and other modes are no-ops, with an explicit config
escape hatch.
> 
> **Overview**
> **Expert-parallel MoE loads now opt into vLLM’s EP weight filter by
default**, via a typed `inference.vllm.enable_ep_weight_filter` field
(default `true`) that flows through `to_namespace()` to
`--enable-ep-weight-filter`. That lets each rank read only its local
expert shard at checkpoint load instead of full expert tensors, reducing
I/O and startup time when EP is on and EPLB is off.
> 
> The GLM-5.3 advanced TOML recipes **drop redundant**
`enable_ep_weight_filter = true` lines and rely on the default. A unit
test **asserts** the resolved server namespace includes
`enable_ep_weight_filter=True`. Set
`inference.vllm.enable_ep_weight_filter = false` to disable.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f26215dee423de2a19ec763106fd979183556cef. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 22:57:30 -07:00
samsjaandGitHub 8c2847721a chore(examples): glm-5.3 swe.toml base + swe-llmd.toml append, serve BF16 with vllm-side FP8 (#3607)
## What

Reworks the GLM-5.3 RL examples as a **base + append** pair instead of
two standalone configs, and moves both variants onto the shared
`GLM-5.3-BF16` checkpoint with vLLM-side online FP8 quantization:

- **`swe.toml`** — the base config, carrying all the params that used to
live only in `swe-llmd.toml` (r2e-gym train source under the `rlm`
harness, `deepgemm_fp8` trainer, `cp = 4` / `ep = 8`, 16 train + 16
disaggregated-P/D infer nodes) behind the default **`vllm-router`**.
Inference serves the same **`zai-org/GLM-5.3-BF16`** checkpoint the
trainer broadcasts; vLLM quantizes it to per-block FP8 online
(`quantization = "fp8_per_block"`) — no separate FP8 release checkpoint.
- **`swe-llmd.toml`** — now a small **append overlay**: llm-d router
(EPP scorer tuning), Mooncake KV offload, and run-identity swaps (run
name / W&B project / SLURM job / sandbox runtime label). Launch:

  ```bash
uv run rl @ examples/advanced/glm-5.3/swe.toml # vllm-router
uv run rl @ examples/advanced/glm-5.3/swe.toml @
examples/advanced/glm-5.3/swe-llmd.toml # llm-d + Mooncake
  ```

- **`README.md`** — documents the base/append split, the composed launch
command, and which FILL INs live where.

## Why

- Two nearly-identical 100+ line configs drifted apart; a base + `@`
overlay keeps the llm-d variant a true delta (router + KV offload) and
makes the router the only difference between runs.
- Serving `GLM-5.3-BF16` with online per-block FP8 matches the trainer's
broadcast target and removes the dependency on the official block-FP8
serving release for both variants.

## Validation

Both launch paths resolve and validate end-to-end with `rl --dry-run`
(resolved per-process configs + sbatch generation): the base launches
`vllm-router --policy sticky_least_loaded`; the composed run swaps in
the llm-d router (EPP + Envoy) and enables Mooncake KV offload. Overlay
list-replacement semantics verified — the composed run keeps exactly one
train source, with the runtime label swapped to `glm5-llmd`.

Infer pre-flight configs (`infer/pd.toml`, `infer/pd-llmd.toml`) are
untouched.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are limited to example TOMLs and documentation; no runtime or
library code paths are modified.
> 
> **Overview**
> Reorganizes the GLM-5.3 RL examples so **`swe.toml` is the full base
stack** (r2e-gym / `rlm`, FP8 trainer, P/D inference behind
**`vllm-router`**, serving **`GLM-5.3-BF16`** with online block FP8) and
**`swe-llmd.toml` is a thin overlay** for llm-d router scorer tuning,
Mooncake KV offload, and sandbox runtime labels.
> 
> Most settings that previously lived only in `swe-llmd.toml` move into
`swe.toml`; the llm-d file drops trainer/orchestrator/deployment
duplication. The README is updated to describe **base vs append**
launches (`rl @ swe.toml` vs `rl @ swe.toml @ swe-llmd.toml`), moves
“FILL IN” and Mooncake tuning notes to the right file, and states that
**neither RL file ships `[ckpt]`** by default (overlay to add
checkpoints). The old **`swe.toml` train-source-less / SWE-bench-eval
plane is replaced** by this composable layout—not removed entirely.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c9d87a57a24248945b3035d1cb87dee2f8f66a1a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 19:48:22 -07:00
samsjaandGitHub 9dbe8b5fa0 fix: select GLM-5.3 renderer in examples (#3606)
## Summary
- configure both GLM-5.3 example runs to use the matching `glm-5.3`
renderer

Requires the GLM-5.3 renderer pinned by #3605.
2026-09-18 16:03:56 -07:00
samsjaandGitHub 819993faac chore: bump renderers for GLM-5.3 (#3605)
## Summary
- pin `deps/renderers` to the GLM-5.3 renderer implementation

Depends on PrimeIntellect-ai/renderers#156.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> <sup>[Cursor Bugbot](https://cursor.com/bugbot) is generating a
summary for commit 8c41fdb84cd8bbfa5f2b2fc97887da57fbf3ba40. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 15:40:49 -07:00
Mika SenghaasandGitHub d57c59f16a fix: do not abort on consecutive empty train batches (#3595)
## Summary

- Remove the run-level aborts on consecutive empty train batches:
- The orchestrator raised after 10 consecutive no-sample train batches.
`MAX_CONSECUTIVE_EMPTY_BATCHES` and its counter are gone; an empty batch
now logs a warning and is skipped.
- The train sink raised after 10 batch-equivalents of finalized groups
that shipped no payload. The tally now only throttles the warning
(`_warn_zero_output`); there is no abort.
- Keep both warnings, so a run with no training signal stays visible in
the logs. A dead curriculum, an all-equal reward sweep, or an
infrastructure outage now stalls the run instead of killing it.
- Update the one `docs/algorithms.md` sentence that described the abort.
## Verification

- `uv run pytest tests/unit/orchestrator -q`: 82 passed, 1 skipped. The
8 failures are pre-existing `torch`/`vllm` import errors in a no-extras
env and fail the same way on `main`.
- `ruff check` / `ruff format --check` pass on both changed files.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior change is limited to error handling: runs no longer fail fast
on sustained empty training signal, which may hide config issues but
avoids killing jobs on benign stalls.
> 
> **Overview**
> **Removes run-killing guards** when training produces no shippable
data, so misconfigured curricula or transient all-zero-advantage groups
**stall with warnings** instead of crashing the orchestrator.
> 
> In **`orchestrator.py`**, the **10 consecutive empty-batch abort** is
gone: empty `TrainBatch` samples log *"skipping empty train batch"* and
return without advancing the step. **`train_sink.py`** keeps counting
zero-output finalized units but **`_warn_zero_output`** only emits
throttled warnings—no **`RuntimeError`** after 10 batch-equivalents.
> 
> **`docs/algorithms.md`** now says group-relative `group_size = 1`
empty batches are **skipped at runtime**, not aborted.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3160f47b861a2c9c6cb33fef4961336f9b6560e9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 11:22:15 -07:00
Matej SirovatkaandGitHub c4a78d1134 fix: specialize FP8 indexer quantization constants (#3594)
Compiled GLM-5.3 training fails on its first forward pass because `eps`,
`fp8_min`, and `fp8_max` reach the FP8 indexer quantization kernel as
runtime FP64 scalars. Their arithmetic promotes the quantization result
to FP64, and Triton rejects the resulting conversion with `Unsupported
conversion from f64 to f8E4M3FN with rounding mode rtne`.

Mark these three fixed scalar arguments as `tl.constexpr` so Triton
specializes them at compile time.

Validation: reproduced the failure on an 8-node H200 BF16 trainer with
`torch.compile`, activation checkpointing/offloading, full CPU offload,
and SignSGD. With this patch, the first forward/backward pass and
optimizer update completed, and the trainer began broadcasting policy
v1. The 20-step verification run is still in progress. `git diff
--check` passes.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single-line Triton signature change with no API or logic changes; only
affects compile-time specialization of fixed FP8 bounds.
> 
> **Overview**
> Fixes **compiled training crashes** on the first forward pass when the
FP8 indexer quantizes activations under `torch.compile`.
> 
> The Triton kernel `_per_token_group_quant_fp8` now treats **`eps`,
`fp8_min`, and `fp8_max` as `tl.constexpr`** instead of runtime
arguments. Previously those scalars promoted quant math to FP64, and
Triton failed converting the result to FP8 (`f64` → `f8E4M3FN`).
Specializing them at compile time keeps the quant path in types Triton
can lower correctly; callers still pass the same module-level `FP8_EPS`
/ `FP8_MIN` / `FP8_MAX` constants.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
02f155d8ffb8776346c320be42a6be1f1f5299e9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 13:12:13 +02:00
cacae615e6 chore(examples): rename GLM example folder to glm-5.3 (#3593)
The advanced GLM presets now train GLM-5.3, but the directory was still
named glm-5.2. Rename it and update every inbound link and the
"GLM-5/GLM-5.2" prose in the READMEs and docs.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation and example path updates only; no training, inference,
or runtime code changes.
> 
> **Overview**
> Renames the advanced GLM example from **`glm-5.2`** to **`glm-5.3`**
and updates every inbound link and launch snippet so docs match the
presets that target GLM-5.3.
> 
> **README**, **docs** (`advanced.md`, `configuration.md`,
`scaling.md`), and **examples/README** now point at
`examples/advanced/glm-5.3/` and describe **`GLM-5`/`GLM-5.3`** instead
of 5.2. The **glm-5.3** walkthrough updates `uv run rl` / `uv run
inference` paths; **`infer/pd-llmd.toml`** only fixes its launch comment
to the new path (config content such as `GLM-5.2-FP8` model IDs is
unchanged).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fb2d99039d8719ff2bcdf2ac1e2c7baaa6f49946. 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: Johannes Hagemann <johannes@Johanness-MacBook-Pro.local>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 00:22:35 -07:00
samsjaandGitHub a9005aba8e fix(examples): express GLM-5.2 SWE shared model as a [model] table (#3591)
## Summary
PR #3588 centralized the model id for
`examples/advanced/glm-5.2/swe.toml` as a top-level
string (`model = "zai-org/GLM-5.3-BF16"`), but `RLConfig.model` is a
`SharedModelConfig`
table, so no config class could parse the file and CPU tests on `main`
failed
(`test_load_configs[examples/advanced/glm-5.2/swe.toml]`).

- Express the shared model as a `[model]` table with `name =
"zai-org/GLM-5.3-BF16"`, which
propagates to `trainer.model.name`, `orchestrator.model.name`, and
`inference.vllm.model`
  (same intent as #3588).
- Update the `[inference.vllm]` comment: it now serves the shared BF16
checkpoint with online
  per-block FP8 quantization, not a separate block-FP8 release.

Fixes the CPU Tests failure on `main` introduced by #3588.
2026-09-17 23:55:47 -07:00
samsjaandGitHub 788b9fdd1a Update swe.toml (#3588)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Example config-only change with no application code; verify the stack
resolves the correct vLLM checkpoint now that `[inference.vllm]` no
longer sets a separate `zai-org/GLM-5.3` id.
> 
> **Overview**
> **Centralizes the Hugging Face model id** for the GLM-5.2 SWE advanced
example by adding a top-level `model = "zai-org/GLM-5.3-BF16"` and
dropping duplicate `name` / `model` entries under `[trainer.model]`,
`[inference.vllm]`, and `[orchestrator.model]`.
> 
> Inference still uses the same vLLM settings (BF16 dtype,
`fp8_per_block` quantization, GLM tool parser); only the redundant
per-section model strings are removed so one field drives training and
orchestration.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4520df470f2417d4333f48fb80f40a2ed820574e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
2026-09-17 22:38:22 -07:00
samsjaandGitHub abcf7c0acc docs(examples): update GLM SWE presets to 5.3 (#3587)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Documentation and example TOML checkpoint IDs only; no runtime or auth
logic changes.
> 
> **Overview**
> Updates the **GLM-5.2** advanced SWE example presets and README so
runs target **GLM-5.3**: trainers load **`zai-org/GLM-5.3-BF16`**, while
disaggregated vLLM inference serves the **`zai-org/GLM-5.3`** block-FP8
checkpoint (with short comments explaining the train/serve split).
> 
> **`swe.toml`** and **`swe-llmd.toml`** swap prior **`GLM-5` /
`GLM-5.1`** Hugging Face IDs on **`[inference.vllm]`**,
**`[trainer.model]`**, and **`[orchestrator.model]`**. The base
**`swe.toml`** plane also gains **`[orchestrator.renderer] name =
"glm-5.1"`** so it matches the llm-d stack’s rendering setup. Docs and
launch comments now describe **GLM-5.3** full-stack RL instead of 5.1;
inference-only table rows for **`infer/pd*.toml`** are unchanged in this
diff.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e02482573c596a0c7b575a710e8cf09e38ef4757. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 21:45:53 -07:00
samsjaandGitHub 26c967c6e3 Default IPO to eps 0.3 without KL (#3586)
## Summary

- make IPO use `eps = 0.3` by default
- disable the IPO KL regularizer by default with `kl_tau = 0.0`
- update the algorithm documentation to match

Explicit `[trainer.loss]` values continue to override these defaults.

## Test plan

- instantiated `IPOLossConfig` and the default `TrainerConfig.loss`,
confirming `eps == 0.3` and `kl_tau == 0.0`
- `ruff check packages/prime-rl-configs/src/prime_rl/configs/trainer.py`
2026-09-17 20:59:24 -07:00
Mika SenghaasandGitHub 7760531310 feat: update Prime sandbox SDK (#3585)
## Summary

- Replace the full Prime CLI dependency with `prime-sandboxes` 0.3.0.
- Preserve API key and team discovery from `prime login` through the
sandbox SDK config reader.
- Advance the verifiers submodule to merged
[PrimeIntellect-ai/verifiers#2626](https://github.com/PrimeIntellect-ai/verifiers/pull/2626).
- Document the Prime CLI as a separate tool for login and sandbox
cleanup commands.

## Breaking

- Remove the Prime runtime `vm` and `guaranteed` fields. Delete these
fields from configs. Prime now always creates a VM sandbox.
- Stop publishing ports from Prime service runtimes. Colocate the
service and consumer, or use Docker or Modal for the service runtime.
- Stop installing the `prime` CLI with prime-rl. Run `uv tool install
prime` when the CLI is needed.

## Verification

- `uv lock --check`
- `uv sync --all-packages`
- `uv run ruff check src/prime_rl/orchestrator/clients.py
src/prime_rl/monitors/prime.py`
- `uv run pytest tests/unit/orchestrator/test_clients.py
tests/unit/test_configs.py -q` (199 passed)
- Confirmed `prime_sandboxes.Config` detects the existing CLI login and
team with `PRIME_API_KEY` and `PRIME_TEAM_ID` unset and the `prime`
distribution absent.
- `env -u PRIME_API_KEY -u PRIME_TEAM_ID uv run eval gsm8k -n 1 -r 1 -c
1 --run.name cli-login-smoke --output-dir /tmp/prl-cli-login-smoke`
(reward 1.0, no errors)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how Prime credentials are loaded and sandbox SDK version;
misconfiguration could break Prime Inference headers or sandbox rollouts
until users install the CLI and log in separately.
> 
> **Overview**
> Swaps the **`prime`** PyPI dependency for **`prime-sandboxes>=0.3.0`**
and points API key / team resolution at `prime_sandboxes.Config` instead
of `prime_cli.core.config` in the orchestrator client helpers and Prime
monitors.
> 
> Advanced example READMEs now tell users to install the **`prime`** CLI
separately (`uv tool install prime` + `prime login`) rather than
assuming it ships with prime-rl. The lockfile drops the full **`prime`**
package and its transitive UI stack while bumping **`prime-sandboxes`**
to 0.3.0 (and related Prime packages where resolved).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9c37d34fc380e4c0a8d79159e8323c31fe605ff2. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 20:04:56 -07:00
Matej SirovatkaandGitHub ce65f38fc0 Replace trainer-side FP8 transfer with online inference quantization (#3581)
NCCL weight updates now always send HF checkpoint-format weights and use
vLLM's layerwise reload, letting inference apply its configured
quantization. Remove the trainer-side FP8 transfer switch from config
schemas, propagation, admin requests, and worker RPCs, along with its
unused kernel conversion and loading helpers and tests. No references to
the removed setting remain in tracked project files.

Update both GLM SWE configs to use their BF16 checkpoints, `dtype =
"bfloat16"`, and `quantization = "fp8_per_block"`; align the
orchestrator model names with those checkpoints. EPLB remains rejected
for RL weight updates because the remaining reload path has not been
validated with it.

Validation:
- 131 config and admin/Dynamo RPC unit tests passed, plus both changed
GLM config-loading tests (133 total).
- Full RL config smoke checks cover model-name alignment, NCCL settings
propagation, and EPLB rejection for both examples.
- Ruff lint/format, Python compilation, TOML parsing, and diff
whitespace checks passed.
- The broader config-file sweep was blocked by missing optional taskset
plugins. GPU weight reload was not exercised.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes the critical trainer→inference weight update path and removes
a large alternate loading implementation; misalignment between trainer
weights and vLLM quantization could cause silent drift until GPU reload
is exercised.
> 
> **Overview**
> **Removes trainer-side FP8 kernel-format NCCL weight transfer** in
favor of always broadcasting HuggingFace checkpoint-format tensors and
reloading them in vLLM with layerwise processing, so inference applies
its own quantization settings.
> 
> The `weight_broadcast.quantize_in_weight_transfer` flag is deleted
from shared/trainer/orchestrator schemas, RL propagation,
`/init_broadcaster` RPCs, Dynamo admin, and the NCCL broadcaster/worker
path. Related trainer conversion (`convert_layer_to_vllm_kernel`,
GLM-MoE-DSA kernel export, `quantize_to_vllm_kernel_format`) and
inference helpers (`load_weights_kernel`, EPLB expert remapping) are
removed along with their unit tests.
> 
> **Example GLM SWE configs** switch from `*-FP8` checkpoints to BF16
base weights with `dtype = "bfloat16"` and `quantization =
"fp8_per_block"` on the vLLM side; orchestrator model names match.
> 
> **EPLB** is no longer tied to quantized NCCL transfer—`enable_eplb`
now fails validation for any RL run with weight updates, since the
checkpoint reload path is not validated with EPLB.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
33bf980a95d5ee259f0f8d7b52a7e29b7d8e4a63. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 16:43:34 -07:00
Matej SirovatkaandGitHub 1c45dc4572 Add quantization type for inference configuration (#3580)
Restrict `VllmConfig.quantization` to `fp8_per_block` or `None` using a
consistently named `QuantizationType` alias beside the other vLLM type
alias. `None` continues to let vLLM infer quantization from the
checkpoint.

Update `configs/debug/concurrency.toml` to use `fp8_per_block` so it
validates against the typed field.

Validation: Ruff lint and formatting checks passed. A config smoke check
passed for imports, the default, acceptance of `fp8_per_block`,
rejection of `fp8`, and the updated concurrency config's vLLM section.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Tightening `quantization` to a single literal will reject any existing
TOML/CLI values other than `fp8_per_block`; only the debug config is
updated in this PR.
> 
> **Overview**
> Introduces a **`QuantizationType`** literal on
**`VllmConfig.quantization`**, restricting the inference config field to
**`"fp8_per_block"`** instead of an arbitrary string (still optional;
**`None`** lets vLLM infer from the checkpoint).
> 
> Updates the **debug concurrency** run to set **`quantization =
"fp8_per_block"`**, replacing the previous **`"fp8"`** value so online
quantization matches vLLM’s per-block FP8 mode (consistent with
block-wise FP8 / DeepGEMM expectations elsewhere in inference config).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2a65ad30df0866134dd3454f70033d602c40e2ab. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-09-17 16:17:49 -07:00
Mika SenghaasandGitHub 4a80d747db fix(dashboard): compress large HTTP responses (#3579)
Large run dashboards transfer every metrics chunk without compression,
making full-history loads expensive over remote connections. Enable the
existing GZip middleware for responses of at least 1,000 bytes, using
compression level 1 to limit CPU overhead.

Browsers negotiate gzip automatically. JSON payloads and pagination
offsets are unchanged, and server-sent events remain uncompressed. This
reduces network transfer size while adding compression CPU overhead; it
does not reduce the browser's JSON parsing or chart-rendering work.

Validation: Ruff lint/format and `git diff --check` passed. HTTP checks
verified gzip/identity payload equality, `Vary: Accept-Encoding`,
small-response bypass, and immediate uncompressed SSE delivery. A
headless Chromium smoke check verified that metrics load and charts
render without JavaScript errors after restarting the dashboard.

The initial metrics response reads up to 4 MiB of uncompressed JSONL for
quick initial chart rendering; subsequent responses read up to 16 MiB to
reduce sequential round trips. A short inline comment explains the
smaller initial response. The compressed size varies with the data. All
chart metrics remain available.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dashboard-only transport and read-size tuning; no auth or training
logic, with gzip negotiated via standard headers.
> 
> **Overview**
> Large dashboard API payloads (especially paginated **metrics JSONL**)
no longer go over the wire uncompressed. The FastAPI app now registers
**`GZipMiddleware`** with a **1,000-byte minimum** and **compression
level 1**, so browsers that send `Accept-Encoding: gzip` get smaller
transfers without heavy CPU; tiny responses and streaming endpoints like
SSE are unchanged in behavior.
> 
> **Metrics pagination** is adjusted alongside that: the per-chunk cap
rises from **4 MiB to 16 MiB** for follow-up requests (`offset > 0`),
cutting round trips on huge runs, while the **first** chunk at `offset
== 0` still reads **4 MiB** so initial charts can render quickly. The
API shape (`rows`, `offset`, `size`) is the same—only read sizes and
optional gzip on eligible responses change.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
57809813f385c93c54bf3243f8688060c8e1811a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 16:17:27 -07:00
8df2329a70 chore(trainer): update the reduce_scatter API and fix a ring attention edge case (#3570)
Drops a deprecated collective call in `ring_attn.py`.
`torch.distributed.reduce_scatter_tensor` is
deprecated in the pinned torch and emitted a `FutureWarning` on every
ring step:

```
FutureWarning: `torch.distributed.reduce_scatter_tensor` is deprecated. Please use `torch.distributed.reduce_scatter_single` instead.
```

It is now a thin wrapper delegating to `reduce_scatter_single` with an
identical signature, so the
swap is a pure rename.

While in there, a small edge-case cleanup in `ring_attention_backward`.
The gradient buffers were
allocated with `torch.empty_like`, which inherits the input's strides,
and on the
`heads_k_stride == num_kv_heads` branch they are passed straight to the
reduce-scatter. NCCL ignores
a destination's strides and fills its storage linearly, so a
non-contiguous `dk`/`dv` would silently
come back scrambled. `new_empty` always allocates contiguous.
Unreachable today, since
`heads_k_stride` is hardcoded to `1` with no config surface.

- `_ring_attention_backward_fake` has to move with it, or inductor bakes
the old strides into an
  `assert_size_stride` guard.
- `dq` is unaffected: flash kernels honor output strides, NCCL does not.
- Not every deprecated call site is covered.
`trainer/distributed/collectives.py:159,178` still use
`all_gather_into_tensor` and `reduce_scatter_tensor`, left as a
follow-up. The
`all_gather_into_tensor` warning still emitted on this path comes from
`AllGatherComm` in the
  `ring_flash_attn` package, not from our code.

## Verification

`tests/unit/train/models`: 181 passed, 5 skipped, unchanged. Checked
red-green with a local 2-rank
NCCL script (not committed, needs 2 GPUs), comparing contiguous against
head-major `k`/`v` with
bitwise-identical inputs.

Before, at `heads_k_stride = 4 == num_kv_heads`:

```
dk: bitwise_match=False max_abs_diff=1.27539 max_rel_diff=1.33811
dv: bitwise_match=False max_abs_diff=0.978516 max_rel_diff=0.97093
```

After:

```
dk: bitwise_match=True max_abs_diff=0 max_rel_diff=0
dv: bitwise_match=True max_abs_diff=0 max_rel_diff=0
```

`max_rel_diff` is normalized by the tensor's max magnitude. bf16 noise
on this shape is around
`4e-3`, so the pre-fix difference is structural rather than numerical.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 17:19:03 -04:00
samsjaandGitHub 487d8a76d1 feat(examples): add 4-node and 2-node GLM-4.5-Air scaleswe budget variants (#3548)
## Summary

Follow-up to #3546: the two budget variants and docs updates from that
PR were pushed after it was merged, so they never landed on main. This
PR carries them.

Adds two budget variants of the GLM-4.5-Air `scaleswe` example that keep
the single-node sign-SGD trainer setup (full optimizer offload +
skip-optimizer checkpointing) from before the Muon switch:

- `swe-budget.toml` + `swe-4-node.toml`: 1 train + 3 infer replicas (the
topology `swe.toml` used before #3546), batch size 256
- `swe-budget.toml` + `swe-2-node.toml`: 1 train + 1 infer replica at
batch size 64 (4 groups of 16) — train a 100B+ MoE on only two nodes

The variants are overlays rather than full copies: the shared recipe
(sign-SGD trainer, router replay, GRPO linear length penalty,
deployment/ckpt/broadcast/inference settings) lives in
`swe-budget.toml`, and each variant file only carries the deltas —
topology, batch size, per-variant SLURM job name / sandbox cleanup label
/ W&B run name, and the train/eval sources with their matching runtime
labels. Launch them composed, left-to-right:

```
uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml
```

Router replay, `max_off_policy_steps`, and the length-penalty weights
are the same as `swe.toml`. Each variant keeps its own SLURM job name,
sandbox cleanup label, and W&B run name so they can run side by side.

## Changes

- **`swe-budget.toml`** (new): shared base of the budget variants — the
single-node sign-SGD trainer recipe (cp=4 ulysses, full optimizer
offload, GLM-5.1 memory stack) plus the shared settings.
- **`swe-4-node.toml`** / **`swe-2-node.toml`**: now thin overlays over
`swe-budget.toml` — `num_infer_replicas` 3 / 1, batch size 256 / 64,
per-variant identity, and the sources with their labels.
- **`tests/unit/test_configs.py`**: `test_load_configs` retries files
that no config class parses standalone as overlays over each sibling
TOML — the documented `@ base.toml @ overlay.toml` composition.
- **Example README**: the table lists the budget variants as
`swe-budget.toml + <variant>` compositions; the launch section shows the
composed command.
- **`docs/scaling.md`** / **`docs/configuration.md`**: link the two-node
config ("train a 100B+ MoE on only two nodes"); scaling.md notes it is
an overlay on the shared base.

## Validation

- `uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @
examples/advanced/glm-4.5-air/swe-4-node.toml --dry-run`
- `uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @
examples/advanced/glm-4.5-air/swe-2-node.toml --dry-run`
- Config-level checks against the installed config package: the base
parses standalone; the composed configs resolve to configs identical to
the pre-split standalone files (compared resolved `model_dump()`, only
the auto-generated run name differs); the overlays alone fail validation
as intended (fail fast instead of silently launching a default-config
run).
2026-09-17 13:45:25 -07:00
d05fe6de95 feat: split dashboard overview and metrics tabs (#3578)
## Summary
- The dashboard's `Metrics` tab is now two tabs for every run type.
**Overview** is the curated view: the W&B overview sections for training
runs (train, eval, stability, inference, performance) and the episode
pane for eval runs (progress bar, summary tiles, swarms, usage and
timing). **Metrics** is every key in `metrics.jsonl`, one pane per key,
with a regex filter, smoothing and collapse/expand. The Overview/All
toggle is gone; the tabs replace it.
- Eval runs load `metrics.jsonl` next to their episode series, so the
time-keyed `inference/`, `concurrency/` and `dispatcher/` rows the
runner samples during the epoch chart on the Metrics tab the same way
they do for RL runs. Before, an eval run had no way to reach its raw
metric keys at all.
- The Metrics tab groups keys by path instead of by stat family. `Flat`
makes one section per parent path (`dispatcher/cancelled` holds `eval`,
`gsm8k`, `train`; `dispatcher` holds `mode`), sorted so a parent
precedes its children. `Nested` walks the key segments as a tree of
sections (`dispatcher` holds the `mode` pane and the nested `cancelled`,
`errored`, `inflight`, `off_policy`, `queued` sections).
- A section's pane grid keeps the 12px rhythm before the sections nested
under it; previously the nested section header sat flush against the
panes above.
- The two tabs share one metric store and one chart registry: the open
tab owns the charts and re-renders on switch, each tab keeps its own
search, and the smoothing window is shared. The dashboard skill, README,
`docs/eval.md`, `docs/training.md` and the browser smoke test (which now
also exercises the Metrics tab) are updated to match.

**Eval Overview**

<img width="1608" height="1045" alt="Screenshot 2026-09-17 at 1 00
24 PM"
src="https://github.com/user-attachments/assets/bd54ffa2-d18c-4379-acfb-7e3cb8982dcd"
/>

**Eval Metrics**

<img width="1608" height="1045" alt="Screenshot 2026-09-17 at 1 00
49 PM"
src="https://github.com/user-attachments/assets/53eca142-b7de-47db-baee-cd6561bf2e9f"
/>

**Train Overview**

<img width="1608" height="1045" alt="Screenshot 2026-09-17 at 1 01
04 PM"
src="https://github.com/user-attachments/assets/3860a4e4-ff1a-4502-9df6-88fff2174ce3"
/>

**Train Metrics**

<img width="1608" height="1045" alt="Screenshot 2026-09-17 at 1 01
16 PM"
src="https://github.com/user-attachments/assets/5e0a23b7-91ef-42f4-ab55-85aeadb7ee59"
/>

## Verification
Headless Chromium against the dashboard served from this branch, no
console errors on either tab:

- `uv run rl @ configs/ci/integration/reverse-text/start.toml
--max-steps 5`: Overview renders 23 curated panes including the
inference section; Metrics lists 1135 keys, 209 `inference/` families
and all five `concurrency/` gauges.
- `uv run eval gsm8k -n 16 -r 2` against a local `uv run inference`
server with adaptive concurrency: Overview renders the episode pane (32
episodes, 7 tiles); Metrics lists 870 keys, 213 `inference/` families
and the five `concurrency/` gauges.
- Flat and nested section structure checked for the `dispatcher/` and
`concurrency/` keys of the eval run as listed above.
- `tests/integration/dashboard_smoke.py` passes on both run dirs.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are confined to the local dashboard UI, static assets, docs,
and smoke tests; no server-side training or eval pipeline logic.
> 
> **Overview**
> The run dashboard replaces the single **Metrics** tab and its
Overview/All toggle with two tabs: **Overview** (default) for the
curated W&B-style layout—training sections or the eval episode pane—and
**Metrics** for every key in `metrics.jsonl`, with regex filter,
flat/nested path grouping, and shared smoothing.
> 
> Eval runs now stream **`metrics.jsonl` alongside the episode series**,
so time-keyed `inference/`, `concurrency/`, and similar rows appear on
Metrics instead of being unreachable. Chart rendering is refactored
around `CHART_VIEWS`: one metric store and chart registry, re-mounting
when switching tabs, per-tab search prefs, and eval-specific controls
moved to Overview.
> 
> Docs (`eval.md`, `training.md`, dashboard skill/README) and
**`dashboard_smoke.py`** are updated to expect six views and to exercise
both tabs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ce08f3f18f343a5c0b7b38585bb40a9409798117. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-17 13:09:50 -07:00
Cooper MillerandGitHub a563a03d61 chore: require prime-runs 0.1.3 (#3571)
Require `prime-runs[train]>=0.1.3` and update the lockfile from 0.1.2 to
0.1.3. FFT image builds use `uv sync --locked`, so the PyPI release
alone leaves them on the previous SDK and its dual-upload behavior.

With the new SDK, training episodes upload only to Prime Traces when the
account has access; accounts without access retain legacy samples. Run
lifecycle and metrics continue through Platform. Only the SDK
requirement and its locked artifact change; pinned submodules and other
resolved packages are preserved.

Validation: `uv lock --check` passed; TOML and the resolved 0.1.3
requirement were verified; all 288 published SDK tests passed against
the locked prime-traces 0.0.3 dependency. A GPU training run was not
performed.

Rollout: rebuild and promote the FFT image after merge.
PrimeIntellect-ai/platform#5452 separately handles duplicate list
entries and displaying native traces inside the full run page.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> No in-repo logic changes, but the locked SDK upgrade alters how
training episodes are uploaded once images are rebuilt—worth validating
in staging before wide rollout.
> 
> **Overview**
> Raises the **`prime-runs[train]`** floor from **>=0.1.1** to
**>=0.1.3** in `pyproject.toml` and refreshes **`uv.lock`** so resolved
**`prime-runs`** moves from **0.1.2** to **0.1.3** (PyPI artifact hashes
only; no other dependency churn in this diff).
> 
> This matters because FFT training images install with **`uv sync
--locked`**, so the lockfile must advance for builds to pick up the new
SDK—not just the PyPI release. **`PrimeTrainMonitor`**
(`src/prime_rl/monitors/prime.py`) still calls the same **`prime_runs`**
APIs; behavior shifts come from **0.1.3** (e.g. trace-aware episode
uploads vs legacy samples for accounts without Traces access, while run
lifecycle/metrics stay on Platform).
> 
> After merge, **rebuild and promote the FFT image** so production
training runs the locked **0.1.3** SDK.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
21c2f421dfbf883bb9ca7eda4ed0a8cf10776fd7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 11:09:42 -07:00
Mika SenghaasandGitHub de08c72769 feat(inference): sticky least-loaded routing (#3563)
## Summary

Makes `sticky_least_loaded` the default routing algorithm on
`vllm-router` (ported from upstream into our fork in
https://github.com/PrimeIntellect-ai/router/pull/55). New session are
routed to the engine with _least active sessions_, any requests in an
active sessions are sticky-routed to maximize prefix cache hits. So this
is a mix of least loaded and consistent hashing which should be strictly
better for RL workloads.

- pin vllm-router v0.2.1 release wheels for x86_64 and aarch64
- make sticky_least_loaded the default vllm-router policy while
preserving explicit policy overrides
- release rollout sessions on success, failure, and cancellation for
managed routed inference, retaining discarded retry trace IDs
- call /finish_session without capability probing or 404/405 caching;
log individual failures at debug level and continue future cleanup
- document the new default and lifecycle behavior

## Context

- Router implementation:
https://github.com/PrimeIntellect-ai/router/pull/55
- Router release:
https://github.com/PrimeIntellect-ai/router/releases/tag/v0.2.1
- Side-by-side experiment:
https://github.com/PrimeIntellect-ai/prime-rl/pull/3553

## Verification

We ran matched 100-step GLM-4.5-Air ScaleSWE jobs on six H200 nodes (2
trainer + 4 TP=8 inference replicas), changing only the vllm-router
policy: [sticky
least-loaded](https://wandb.ai/primeintellect/routing/runs/b44ce2f5354a416bb37788a4db9d12c3)
versus [consistent
hashing](https://wandb.ai/primeintellect/routing/runs/de4b5c72f95c4c5ebbc7e9614690af52).
They reached trainer step 100 in 8h46m and 8h44m respectively, with
nearly identical mean step time (309s vs. 308s).

<img width="1239" height="762" alt="Screenshot 2026-09-17 at 10 11
13 AM"
src="https://github.com/user-attachments/assets/a3204c40-49b0-41f0-b1ae-9d85391f893d"
/>

| Metric | Sticky least-loaded | Consistent hashing | Difference |
| --- | ---: | ---: | ---: |
| Decode throughput | 13.85k tokens/s | 13.11k tokens/s | +5.6% |
| Prefill throughput | 702.6k tokens/s | 665.0k tokens/s | +5.7% |
| Decode-token imbalance (CV) | 1.2% | 6.8% | 82% lower |
| Running-request imbalance (CV) | 5.1% | 23.9% | 79% lower |
| KV-usage imbalance (CV) | 8.2% | 25.1% | 67% lower |


Sticky processed about 6% more tokens in essentially the same wall time.
The higher useful throughput and markedly lower engine imbalance,
without an end-to-end regression, make it the better default.

## Validation

- uv sync --all-extras --all-packages
- uv lock --check
- uv run pytest tests/unit/orchestrator tests/unit/test_configs.py -q
(276 passed, 1 skipped)
- uv run ruff check .
- verified the installed vllm-router CLI exposes sticky_least_loaded
- 10 focused local cleanup checks: successful and failed episodes,
cancellation, overload/stale/superseded drops, shutdown, max steps,
cancellation during cleanup, and continued cleanup after a 404

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes default multi-replica routing and adds best-effort session
cleanup on the rollout hot path; failures are logged but could leave
stale router session state on older routers.
> 
> **Overview**
> Switches the default **vllm-router** policy from `consistent_hash` to
**`sticky_least_loaded`**, pins **vllm-router v0.2.1**, and documents
that new `X-Session-ID` sessions land on the least-loaded replica while
later turns stay sticky for KV reuse.
> 
> For managed deployments where `admin_base_url` bypasses the router for
engine admin, the orchestrator now **releases router sessions when
rollouts finish**: after each successful env episode it calls
**`/finish_session`** per trace id via the client-facing router URL,
probes support once, and disables cleanup on 404/405 so external routers
are unaffected. Explicit `[inference.router] policy` overrides still
work.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
571b09581344e4ee420044aa8392ec97f9a4b538. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 10:55:15 -07:00
Mika SenghaasandGitHub 7f811c01a8 chore: bump verifiers to latest main (#3572)
## Summary

- Bump the `deps/verifiers` submodule from `5a69fb4d` (`feat: stream
served episodes turn by turn (#2512)`) to `28f08939` (latest `main`).
- Commits this pulls in:
- [vf#2616](https://github.com/PrimeIntellect-ai/verifiers/pull/2616)
(`ff3b8dc5`): fix(v1): recover the routed-experts row dropped at each
turn boundary — a reused sampled prefix node keeps a placeholder final
routing row until a later turn's prefill forwards it; it is now
repaired.
- [vf#2618](https://github.com/PrimeIntellect-ai/verifiers/pull/2618)
(`28f08939`): fix(serve): stream repaired routing rows — served
multi-turn episodes had the worker's #2616 repair but the delta stream
never delivered it, so the client kept placeholder routing rows; indexed
`routing_repairs` now reach the client assembly.
- Together they keep `routed_experts` training data correct for
multi-turn MoE episodes under env servers (the router-replay /
routed-experts data path).
- `uv.lock` is unchanged: verifiers is an editable path dependency and
the new commits touch no dependency metadata.

## Verification

- `git -C deps/verifiers merge-base --is-ancestor 5a69fb4d 28f08939` —
the new pin descends from the old one.
- `uv lock --check` — passes.
- `uv run pytest deps/verifiers/tests/v1/test_graph.py
deps/verifiers/tests/v1/test_serve_delta.py -q` — 18 passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the routed-experts data path for multi-turn MoE under env
servers; wrong routing rows would corrupt training data, but the change
is an upstream bugfix with targeted tests.
> 
> **Overview**
> Updates the **`deps/verifiers`** submodule from `5a69fb4d` to
**`28f08939`** (latest `main`). No other repo files change—**`uv.lock`**
stays the same because verifiers is an editable path dependency.
> 
> The new pin pulls in two upstream fixes for **multi-turn MoE
`routed_experts` / router-replay** when using env servers: **v1 graph
repair** for a routing row that was dropped at turn boundaries when a
sampled prefix node was reused, and **serve streaming** so those
repaired rows are included in the delta stream instead of leaving
placeholder routing on the client.
> 
> Together this keeps training data aligned with what the worker
actually computed for served multi-turn episodes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0fb3ab40ec5b917c2d0d548ac022fe6b5d08fce8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 10:54:59 -07:00
Mika SenghaasandGitHub 2d6dc64efd fix: log periodic gauges through the monitors (#3565)
## Summary
- The `PeriodicLogger` printed its pipeline view to the console and
called `wandb.log` directly, so the `dispatcher/*`, `concurrency/*`,
`watcher/*`, and `event_loop_lag/*` gauges only ever reached W&B. The
file monitor (and with it the local dashboard's `metrics.jsonl`) and the
Prime monitor never saw them; with W&B disabled the gauges existed only
as console log text.
- The periodic payload now fans out through `monitors.log(payload,
step=None)` like the inference-metrics collector, so every registered
monitor receives it as a time-keyed row and stamps its own time axis.
All W&B-specific logic is gone from the orchestrator and the eval runner
(`eval/runner.py`, which replaced the old evals process in #3471): the
W&B monitor already defines the `_timestamp` axis lazily per key prefix,
so the eager `wandb.define_metric` pre-registration and its
`metric_keys`/`wandb_enabled` plumbing are removed (the now-unused
`DispatcherMetrics.drain_keys` helper goes with it).
- Clean-exit teardown now stops the `PeriodicLogger` before
`monitors.finalize()`, next to the inference collector — both write
through the monitors, and a tick after finalize would land on a finished
W&B / Prime run. The eval runner already drained its loggers first
(`drain()` before `finalize()`); the orchestrator now matches.
- Overview panels, mirrored in the W&B saved view
(`monitors/wandb/overview.py`) and the local dashboard
(`dashboard/static/app.js`), which the overview code keeps in sync: the
inflight panel gains `concurrency/max_inflight` so in-flight episodes
read against the adaptive cap, and the token-rate panels drop their
per-engine tail series (`generation_tokens_total:rate/min`,
`prompt_tokens_total:rate/max`).

## Verification
1-step reverse-text runs (`uv run rl @
configs/ci/integration/reverse-text/start.toml --max-steps 1`, W&B off,
file monitor on), before on `main` vs. after on this branch:

- **before**: `monitors/file/metrics.jsonl` has 13 rows and zero
`concurrency/*` / `dispatcher/*` keys — only
train/eval/inference/loss/perf keys.
- **after**: periodic time-keyed rows (`"step": null`, `"producer":
"orch"`) carrying all `concurrency/*` gauges (`max_inflight`,
`turnover`, `capacity`, `signal`, `growth_multiplier`), 12
`dispatcher/*` keys, 4 `watcher/*` keys, and 7 `event_loop_lag/*` keys.
- **local dashboard overview** (headless browser check against both run
dirs): after, the `dispatcher/inflight/{train,eval}` +
`concurrency/max_inflight` panel renders with data (all charts mounted,
no console errors); before, the panel is absent (no keys, no panel).
- **teardown ordering** (after the finalize-order fix): the last
`metrics.jsonl` write lands strictly before `monitors.finalize()`
(03:54:38.66 vs. the `Finalized metrics` log line at 03:54:39), zero
rows written at or after finalize, clean exit, no `Failed to log`
warnings.
- Re-verified after rebasing onto `main` (picked up the eval-CLI
consolidation and the concurrency-taper commit) and again after the
teardown-order fix — all green.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes observability plumbing and shutdown ordering for background
loggers; behavior is well-scoped but affects all runs’ metrics export
and clean-exit teardown.
> 
> **Overview**
> **Periodic pipeline metrics** (dispatcher, concurrency, watcher, event
loop lag) no longer go only to W&B via direct `wandb.log`.
`PeriodicLogger` now emits each tick through `monitors.log(payload,
step=None)`, so file monitor, dashboard `metrics.jsonl`, Prime, and W&B
all get the same time-keyed rows.
> 
> The orchestrator and eval runner drop `metric_keys`, `wandb_enabled`,
and eager `wandb.define_metric` pre-registration; unused
`DispatcherMetrics.drain_keys` is removed. On clean exit, the
orchestrator **stops `PeriodicLogger` before `monitors.finalize()`**,
matching inference metrics teardown so nothing writes after the run is
closed.
> 
> **Overview charts** (W&B overview + local dashboard) add
`concurrency/max_inflight` to the inflight panel and simplify token-rate
panels to fleet sum only (no per-engine min/max tails).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
be479ea13c728ab82bacdd9f0773fc70dc0a3b41. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 10:02:47 -07:00
07ebe34570 fix(rl): launch env servers in multi-node RL runs (#3568)
Multi-node RL runs currently launch no environment servers. The
orchestrator waits 600 seconds
for an address file that nobody writes, then times out, and the trainer
sits in the weight
broadcast until its own timeout.

The flat-to-nested refactor in #3471 replaced `format_log_message`'s two
flat `train_env_names` /
`eval_env_names` parameters with a single `env_names: dict[str,
list[str]]` and updated all four
call sites in `rl.py`. Two of them really are `format_log_message` calls
and were correct. The
other two are `template.render(...)` calls feeding

[`multi_node_rl.sbatch.j2:542-559`](https://github.com/PrimeIntellect-ai/prime-rl/blob/d5ed9fb7e4233c6f4914af2652c3bda69bddb0c7/src/prime_rl/templates/multi_node_rl.sbatch.j2#L542-L559),
which still reads the flat names:

```diff
# src/prime_rl/entrypoints/rl.py:534,574 in c394c2e1b, write_slurm_script
-            train_env_names=train_env_names,
-            eval_env_names=eval_env_names,
+            env_names={"train": train_env_names, "eval": eval_env_names},
```

```jinja
{# multi_node_rl.sbatch.j2:542,550, unchanged by this PR #}
{%- if train_env_names or eval_env_names %}
{%- for name in train_env_names %}
```

Under Jinja's default `Undefined`, a name that was never passed is
indistinguishable from an
empty list: `{% if train_env_names or eval_env_names %}` is false either
way and nothing raises.
The generated script was therefore identical to one for a run that
legitimately has no env
servers. This reverts the two render calls to flat kwargs and leaves the
three
`format_log_message` calls on the nested dict.

- The failure is silent: the generated sbatch and the per-source env
JSON both look correct, and
the first symptom is `TimeoutError: env server never published its
address ... within 600.0s`.
- Single-node and SFT are unaffected. Single-node goes through
`rl_local`, which spawns env
servers as subprocesses; `sft.py` already spreads its env names as
`**eval_vars`, the flat form
  `multi_node_sft.sbatch.j2` wants.

## Verification

**Render level.** The pre-fix script is 13 lines shorter, and those 13
lines are the entire
env-server block:

```sh
uv run rl @ examples/basic/reverse-text/rl.toml --deployment.type multi_node --deployment.num-train-nodes 1 --deployment.num-infer-nodes 1 --slurm.partition all --max-steps 2 --run.name envserver-check --no-dashboard --dry-run
grep -c "uv run env-server" $PRL_OUTPUT_DIR/envserver-check/launcher/rl.sbatch
```

Before: `0`. After: `2`, one for the train source and one for the eval
source. Diffing the two
generated scripts shows nothing else moved (comment block elided):

```diff
@@ -331,0 +332,13 @@
+    mkdir -p $LOG_DIR/envs/train
+    uv run env-server @ $CONFIG_DIR/envs/train/reverse-text.json \
+        > $LOG_DIR/envs/train/reverse-text.log 2>&1 &
+    mkdir -p $LOG_DIR/envs/eval
+    uv run env-server @ $CONFIG_DIR/envs/eval/reverse-text-eval.json \
+        > $LOG_DIR/envs/eval/reverse-text-eval.log 2>&1 &
```

**Runtime.** Before, from one of the failing multi-node runs, the
orchestrator polls for a file
no process will write and gives up after 600s:

```
TimeoutError: env server never published its address to
<run>/configs/attempt_1/resolved/envs/train/reverse-text.address within 600.0s
```

After, a 2-node reverse-text run on Qwen3-0.6B spawns the server, which
publishes its address
46s later, and training completes:

```
14:48:47  <run>/logs/attempt_1/envs/train/reverse-text.log created
14:49:33  EnvServerPool up: address=tcp://127.0.0.1:42101 workers=1/inf multiplex=128
15:01:56  SUCCESS Step 2 | 1.2s | Loss 0.0038 | Entropy 0.6078 | Grad. Norm 0.7942
```

That log file is the cleanest discriminator: the shell redirect on the
`uv run env-server` line
creates it, so before the fix it never exists at all.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 13:02:37 -04:00
c1ac451e39 fix(trainer): declare contiguous outputs in the fp8 and ring attention fakes (#3567)
Three custom-op fake kernels declared output strides copied from their
inputs, while the real kernels return freshly allocated contiguous
buffers. `torch.compile` trusts the fake, bakes its strides into an
`assert_size_stride` guard, and the guard fires at runtime. This showed
up first in the fp8 MoE backward with activation checkpointing off,
where `ac=full` had been hiding the expert backward inside a recompute
region:

```
assert_size_stride(buf2, (32, 1408, 4096), (5767168, 1, 1408), 'torch.ops.prime_rl.grouped_fp8_gemm_backward.default')
AssertionError: expected size 1408==1408, stride 4096==1 at dim=1; expected size 4096==4096, stride 1==1408 at dim=2
```

All three fakes now declare metadata that is a pure function of their
inputs' shapes and dtypes, independent of the inputs' strides, of the
`needs_grad_*` flags, and of an unstated bf16 contract.

- `grouped_fp8_gemm_backward`, active: MoE passes a transposed weight;
real `(524288, 1024, 1)` vs fake `(524288, 1, 512)`.
- `ring_attn::attention`, active: rope leaves `q` non-contiguous, so
real `(1024, 128, 1)` vs fake `(128, 32768, 1)`, on every CP ring step.
- `fp8_blockwise_mm_backward` and the grouped GEMM's `grad_x`, latent:
masked only because production inputs are contiguous.
- The fp8 kernels' unobservable placeholder allocations are contiguous
too, which is what drops the flag-conditional stride.
- `ring_attn.py` needed no real-kernel change, since `torch.cat` is
already unconditionally contiguous.
- `_compute_grad_weight` downcasts to `weight.dtype`, not a hardcoded
bf16; a no-op today, as call sites pre-cast.
- Verified already correct, left alone: both fp8 forward fakes,
`attention_backward`, and the forward's `softmax_lse`.
- `compile=on, ac=off, fp8 MoE` now completes a full forward and
backward on the GLM-4.5-MoE path.

Noticed while auditing, not addressed: `gpt_oss` has its own ring
implementation that bypasses this op.

## Verification

An `opcheck` test for the four fp8 ops was added in `02f3f684b` and
removed again in `49ce67cff`: it needs an SM90+ GPU and `deep_gemm`, so
it would only ever skip on CI's `vm` runner. To re-run it on a Hopper or
Blackwell node:

```
git show 02f3f684b:tests/unit/train/models/test_fp8_fake_kernels.py > tests/unit/train/models/test_fp8_fake_kernels.py
DG_JIT_CACHE_DIR=<warm deepgemm cache> uv run pytest tests/unit/train/models/test_fp8_fake_kernels.py -v
```

`torch.library.opcheck` with `test_utils=["test_schema",
"test_faketensor"]` compares the real op's output shape, stride, and
dtype against the fake's. On 8x H200 that is 26 passed post-fix; against
the pre-fix sources it fails exactly the 9 cases where a grad is
requested and its corresponding input is non-contiguous and passes the
other 17, so it discriminates rather than failing everywhere. The
ring-attention fake was verified the same way under a two-rank
`torchrun` harness, not committed since a distributed GPU test would
also only skip on CI. `uv run pytest tests/unit/train/models` is green
on the same node: 177 passed, 5 skipped.

Verified end to end with a harness built from production code only
(`Glm4MoeForCausalLM`, `configure_moe_runtime` with
`DeepGemmFP8MoEComputeConfig`, `apply_compile`, `setup_fsdp`):
`compile=on, ac=off` completes forward and backward at `ep` 1, 2, and 4,
up to real GLM-4.5-Air dimensions on 8 H200s. Restoring the pre-fix fake
reproduces the original `assert_size_stride` traceback at the same
shapes, so the check is not inert.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 12:59:53 -04:00
rasdaniandGitHub d5ed9fb7e4 chore: ask before changing repository skills (#3564)
Require agents to suggest specific repository skill changes, explain the
benefit, and wait for user approval before editing. Existing explicit
requests or approvals remain sufficient; ordinary code, workflow,
documentation, and PR requests do not authorize skill changes. Reading
and following skills remains allowed.

Changes only `AGENTS.md`, replacing its automatic skill-maintenance
requirement with the same approval guidance as
https://github.com/PrimeIntellect-ai/prime-envs/pull/814.

Validation: `git diff --check` passed; file-scoped pre-commit hooks
completed (Python-only hooks skipped this Markdown-only change).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Markdown-only policy change in `AGENTS.md` with no runtime or security
impact.
> 
> **Overview**
> Updates **agent policy in `AGENTS.md`** so repository skills under
`skills/` are no longer auto-maintained when code or workflows change.
> 
> The Skills section drops the requirement to check and update skills
after codebase edits, and replaces the “you must update skills when you
fix workflows” rule with **explicit user approval**: propose a concrete
skill change, explain why, and wait before creating, editing, renaming,
deleting skills or their symlinks. Prior explicit approval still counts;
ordinary code, workflow, docs, or PR work does **not** grant permission
to touch skills. Agents may still read and follow skills unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6e13660903da49dda03394923b97dee985fe779b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-16 19:50:35 -07:00
b4a41d3f2c perf(deepseek-v4): fuse the mHC chain and route unweighted RMS norms through quack (#3558)
DeepSeek V4's manifold-constrained hyper-connection (mHC) chain ran
eager and cost far more than
its arithmetic warrants: a python Sinkhorn loop of roughly 119 tiny
launches over stream mixing
matrices, an fp32 copy of the flattened streams materialized purely as
an intermediate, a
multi-kernel write-back over the full (batch, sequence, stream, hidden)
tensor, and a `q_b_norm`
whose input was non-contiguous. This fuses or reroutes all four.

- The unweighted RMS norms (the mHC input norms and attention's
`q_b_norm`) dispatch to quack
through the same gate the shared `RMSNorm` uses, with an optional
`out_dtype`. `q_b_norm` moves
ahead of the head transpose so quack's flatten is a view rather than a
copy; RMS over the channel
  axis commutes with the transpose exactly.
- The input norms take the bf16 streams directly and emit fp32, so the
fp32 copy is never
  materialized. The gate math downstream of the norm stays fp32.
- The Sinkhorn loop and the write-back become two Triton ops vendored
from NVIDIA/Megatron-LM at
`bb5dfd08f` (BSD-3, full license text reproduced in the file header).
They require a power-of-two
`hc_mult` and a CUDA input, both of which Triton itself enforces, and
the eager implementations
move to `eager_reference.py`, where the tests measure the kernels
against them.
- The rank-4 mHC residual is named `mhc_states` throughout, so
`hidden_states` always means the
rank-3 collapsed sequence, and the write-back moves onto
`DeepseekV4HyperConnection` as
  `update_states`.
- Both fused paths are covered on GPU, measured against the eager
references rather than a
  runtime fallback branch.

Forward/backward ms per call on an H200 at batch 1, sequence 16384,
`hc_mult` 4, hidden dimension
4096 (the Sinkhorn row is measured on the stream mixing tensor):

| Op | Before | After |
| --- | --- | --- |
| mHC front half | 2.89 / 8.10 | 1.05 / 2.54 |
| Sinkhorn | 1.05 / 3.14 | 0.10 / 0.81 |
| Stream write-back | 5.96 / 7.89 | 0.40 / 0.94 |
| `q_b_norm` | 0.99 / 2.85 | 0.30 / 0.96 |

A 4-node full-depth A/B goes from 15.97 to 13.11 s/step at 4.2 GiB lower
peak. That was measured on
the SFT-optim stack, not this branch: on `main` step time is
optimizer-offload dominated, so the
same A/B there would hide the change inside the offload's shadow.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-16 20:35:30 -04:00
Mika SenghaasandGitHub d7339fcf25 fix(orchestrator): taper concurrency growth by KV usage (#3556)
## Summary

The adaptive controller currently grows the admission cap by 25% per
pipeline turnover until GPU-KV usage crosses 60%, then stops growing
until the 80% soft-cap. That discontinuity can carry the cap into a
corrective trim too quickly.

This changes growth to taper linearly from 1.20× per turnover at 0%
GPU-KV usage to 1.00× at the 80% soft-cap. Above the soft-cap, the
existing soft-trim behavior remains unchanged. The controller also
exposes the active growth multiplier as a gauge.

## Verification

Validation run from #3542. Qwen3-30B-A3B on Terminal Lego on 2 nodes.
Can observe oscillating heavy growth and hard cut prior to this PR and
sigmoidish growth and no episode preemptions.

<img width="582" height="245" alt="Screenshot 2026-09-15 at 9 26 47 PM"
src="https://github.com/user-attachments/assets/dedf2bbe-0c8e-4434-93fb-de79b829ff44"
/>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes orchestrator admission AIMD tuning, which can affect
throughput and preemption/cut behavior under load, though trims and cuts
above the soft-cap are unchanged.
> 
> **Overview**
> Replaces the **fixed 1.25× cap growth per pipeline turnover** (while
KV stayed below 60%) with a **usage-dependent multiplier** that scales
from **1.20× at 0% GPU-KV** down to **1.0× at the 80% soft-cap**, so
growth eases before trims instead of stopping abruptly at 60%.
> 
> **Signal handling** no longer treats “KV above grow threshold” as
overload for gating; **soft pressure** is tied to crossing
**`KV_USAGE_SOFT_CAP`**, while **persistent queue overload** still
drives **hard** signals. **`record_episode`** applies
**`growth_multiplier**` instead of a constant factor, and
**`concurrency/growth_multiplier`** is exported as a gauge for
observability.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bc42bf362df09c89e5a3c47bbb2f11bf21d5923d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-16 11:58:36 -07:00
c394c2e1bd 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>
2026-09-16 11:04:24 -07:00
xianzheng shanandGitHub 0d372c1fd6 fix(inference):Fix native disk KV cache offload tier type (#3538)
## Summary

Align the disk-backed KV cache secondary tier with vLLM's registered
filesystem tier name: `fs`, not
`fs_python`.[#43600](https://github.com/vllm-project/vllm/pull/43600)

## Problem

The inference configuration emitted a secondary tier of the form

```python
{"type": "fs_python", "root_dir": <configured disk path>}
```

but the tier factory only registers the filesystem secondary tier under
the name `fs`:

```text
example, fs, p2p, obj
```

Because the identifier did not match, vLLM aborted engine initialization
with:

```text
ValueError: Unknown secondary tier type: 'fs_python'
```

## Changes

- Rename the filesystem secondary tier identifier from `fs_python` to
`fs` everywhere it is constructed or referenced — configuration
generation, tier-factory registration, and log messages.
- Keep `root_dir` as the configured disk path; no behavioural change to
the tier itself, only its name.
- Update the affected tests to use `fs`.
- No changes to the TOML configuration format.

## Validation

With CPU offload and disk offload both enabled, on vLLM `vLLM 0.28.0`
and a Qwen3-4B inference configuration:

- the engine initializes without the `Unknown secondary tier type`
error;
- `fs_python` no longer appears in generated configs or logs.
2026-09-16 17:35:16 +02:00
9f4eef81a3 perf(optim): reuse pinned CPU buffers in CPUOffloadOptimizer (#3552)
Allocate `CPUOffloadOptimizer`'s CPU-side buffers once, pinned, and copy
optimizer state into them non-blocking, instead of allocating a fresh
pageable buffer plus a fresh pinned buffer on every step.

- The old path copied each state tensor into fresh pageable memory
blocking, then `.pin_memory()` allocated a second buffer and copied
again host to host. `Tensor.to` cannot allocate pinned memory, and
`non_blocking` was set to `not self.pin_memory`, which disabled the
async path in the one case where a pinned destination would have made it
work.
- Buffers are keyed by `(parameter, state key)` and reallocated if a
state tensor's shape or dtype changes, which covers `load_state_dict`.
- One `torch.cuda.synchronize()` now ends the offload, replacing the
per-tensor stall. The `pin_memory=False` path and the host-to-device
direction are unchanged, the latter deliberately: those tensors must be
freshly allocated for the GPU memory to be released between steps.
- The first commit adds the tests with the buffer-reuse one marked
`xfail`, since the three correctness tests pass on the old code and only
that one exposes the bug. The second commit drops the `xfail`.
- Measured on DS V4-Flash SFT, one node of 8x H200 at 6 layers,
`seq_len` 131072, `cp=8`, `ep=8`, micro-batch 1, 10 steps, steady-state
medians, with the fix as the only change from production defaults:
optimizer 26.9 s to 3.0 s and whole step 30.9 s to 6.5 s, at an
unchanged 103.8 GiB peak. Trace of the old 26.7 s window: 18.2 s
pageable D2H at 2.2 GB/s, 5.4 s `pin_memory` re-copy, 1.5 s pinned H2D,
and 0.15 s of AdamW kernels. Per-rank optimizer state is what sizes this
window, and the 6-layer proxy carries 4.93e9 parameters per rank against
production's 4.44e9, so it is not a scaled-down number.

Verified on an H200: 3 passed / 1 xfailed at the test commit, 4 passed
at the fix commit, with `tests/unit/train/test_cpu_adam.py` and
`tests/unit/test_configs.py -k offload` still green.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 16:02:32 -07:00
1d9ab255eb fix(docker): drop removed gpt-oss extra from uv sync (#3549)
#3424 removed the gpt-oss optional-dependency group from pyproject.toml,
but Dockerfile.cuda still passed --extra gpt-oss to uv sync, which fails
on undefined extras and broke every image build since.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Build-only Dockerfile alignment with pyproject extras; no application
or dependency logic changes beyond fixing the sync command.
> 
> **Overview**
> Repairs **CUDA Docker image builds** that broke after the `gpt-oss`
optional extra was removed from `pyproject.toml` (#3424).
> 
> Both `uv sync` steps in `Dockerfile.cuda` (the cached third-party
layer and the full workspace sync after sources are copied) no longer
pass `--extra gpt-oss`. **`uv` was failing** on an undefined extra; the
remaining extras (`gpu`, flash-attn variants, `disagg`, `quack`,
`kernels`, `mamba-ssm`, etc.) are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b340617baed2ffb69a2a1adc800e9264f4c32ba2. 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: Johannes Hagemann <johannes@Johanness-MacBook-Pro.local>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 22:03:42 -07:00
152 changed files with 6590 additions and 3228 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 -2
View File
@@ -43,9 +43,9 @@ Namespaces are one honking great idea -- let's do more of those!
## Skills
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs). When you make changes to the codebase, check if any skills need to be updated to stay accurate.
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs).
You are responsible for maintaining the skills folder. When a workflow fails and you fix it – whether with help from the user or through trial and error – you must update the skills to make implicit knowledge explicit. You are also responsible for keeping the skills up to date whenever you or anyone else modifies the code.
If a repository skill could benefit from an update, suggest the specific change, explain why it would help, and ask the user for approval before making it. Wait for approval before creating, modifying, renaming, or deleting skills, including their supporting files and symlinks. If the user has already explicitly requested or approved the skill change, proceed without asking again. Requests to change code, fix workflows, update documentation, or open a PR do not implicitly authorize skill changes. You may read and follow skills without changing them.
## Testing
+3 -2
View File
@@ -94,9 +94,10 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# Third-party deps only — source edits don't bust this layer. First-party
# editables install in the source-layer sync below. No build-context bind
# mount here: .git would bust the cache every commit.
# `--extra dashboard` (fastapi/uvicorn) is baked in so the fft chart's dashboard pod needs no runtime uv sync (see PR body).
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
@@ -132,7 +133,7 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
+4 -3
View File
@@ -38,7 +38,7 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
7. Hackable, modular, and extensible by design.
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.2/).
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.3/).
## Models support
@@ -204,7 +204,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
3. [**GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` training with P/D disaggregation, the `llm-d` router, and FP8.
3. [**GLM-5**](examples/advanced/glm-5.3/): Large-scale `GLM-5`/`GLM-5.3` training with P/D disaggregation, the `llm-d` router, and FP8.
## Docs
@@ -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"
+1 -1
View File
@@ -135,5 +135,5 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
quantization = "fp8"
quantization = "fp8_per_block"
enable_return_routed_experts = true
+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
+1 -1
View File
@@ -188,7 +188,7 @@ For large MoE serving, splitting prefill and decode onto separate vLLM groups ca
| Agentic (SWE, Lean) | 3:1 | Long growing contexts → prefill-heavy |
| Non-agentic (math, chat) | 1:2 | Short prompts, long generations → decode-heavy |
Example config: [`examples/advanced/glm-5.2/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.2/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.2/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2/infer).
Example config: [`examples/advanced/glm-5.3/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.3/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.3/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3/infer).
Monitor live queue depths to detect imbalance:
+3 -3
View File
@@ -112,7 +112,7 @@ patterns = ["WARNING"]
def drop_warnings(rollout, *, patterns: list[str]) -> list[list[bool]]: ...
```
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and aborts after repeated zero-trainable batches), not at config time.
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and skips it), not at config time.
### Per-Env Algorithms
@@ -209,9 +209,9 @@ The knobs under `[trainer.loss]` are:
| Knob | Default | What it does |
|---|---|---|
| `eps` | 0.1 | Maximum absolute probability change before a token is masked. |
| `eps` | 0.3 | Maximum absolute probability change before a token is masked. |
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
| `kl_tau` | 0.0 | Temperature on the KL regularizer. Set to 0 to disable. |
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
+3 -3
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>.*`).
@@ -225,11 +225,11 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
**Advanced** (32–2048 GPUs, SLURM):
- [**Qwen3-30B-A3B**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-30b-a3b) — `Qwen3-30B-A3B` on math, SWE, and tool use.
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal.
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal; includes a variant that trains the 100B+ MoE on only two nodes.
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation and FP8.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale `GLM-5`/`GLM-5.3` inference with P/D disaggregation and FP8.
### Worked Example: Compose, Override, Dry-Run
+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 overview 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. The metrics tab charts every key of the run's `metrics.jsonl`: the epoch's `eval/<env>/…` summaries and the time-keyed `inference/` and `concurrency/` rows the runner samples while the epoch is in flight.
### 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.
+5 -3
View File
@@ -190,8 +190,10 @@ Both backends support the 2 most important things:
- P/D disaggregation - handling the prefill and decode stages separately
### Routing policies
The 2 policies you might want to configure are:
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - it hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica.
The policies you might want to configure are:
- `sticky_least_loaded` - the default policy. A new `X-Session-ID` is assigned to the least-loaded replica, then every later turn in that rollout remains on the same replica for KV cache reuse. The orchestrator releases sessions when rollouts complete, fail, or are cancelled, including traces discarded during retries. Failed release requests are logged without disabling future cleanup.
- `consistent_hash` - hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica, preserving KV cache reuse without considering current load.
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
@@ -285,7 +287,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.28 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.29 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
```toml
[trainer]
+1
View File
@@ -7,6 +7,7 @@
"overview",
"configuration",
"training",
"eval",
"inference",
"scaling",
"algorithms",
+2 -1
View File
@@ -233,7 +233,8 @@ gpus_per_node = 8
Full multi-node configs ship under [`examples/advanced/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced):
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/configs/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
- [`glm-5.3/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale and P/D-disaggregated inference across the GLM-5 family.
- [`glm-4.5-air/swe-2-node.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-4.5-air/swe-2-node.toml) — train a 100B+ MoE on only two nodes: a single-node sign-SGD trainer (full optimizer offload) paired with one inference replica at batch size 64. An overlay on the shared `swe-budget.toml` base — launch with `uv run rl @ swe-budget.toml @ swe-2-node.toml`.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
+12 -9
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
@@ -161,6 +162,8 @@ name = "qwen3"
enable_thinking = false
```
A `reasoning_effort` column in the dataset sets the renderer's `reasoning_effort` field per row, on top of the `[renderer]` config. The column requires a typed renderer that has that field (for example `gpt-oss`, `qwen3.8`, `deepseek-v4`); rows with a null value use the configured renderer unchanged. This lets one run mix reasoning efforts, with the `[renderer]` value as the default for rows that do not set one.
If a model needs another template control, add it to that model's renderer config in `renderers` (for example a new field on the relevant `*RendererConfig`) and consume it in the renderer implementation.
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5.
@@ -201,17 +204,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 +223,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 +334,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,14 +350,14 @@ 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
```
### Dashboard
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with six views per run: an overview (the W&B overview sections, read from the file monitor's `metrics.jsonl`), metrics (every key in that file, one pane each, with a regex filter), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
+2 -3
View File
@@ -10,7 +10,7 @@ Larger runs on frontier models, one folder per model, each with a launch README
- [`qwen3-30b-a3b/`](advanced/qwen3-30b-a3b/README.md) — `Qwen3-30B-A3B` RL on math (`i3_math`), SWE (`r2e-gym`), and agentic tool use (general-agent on Modal). 2 train + 2 infer nodes; the SWE config runs at 131k context with `ep = 8` + `cp = 2`.
- [`glm-4.5-air/`](advanced/glm-4.5-air/README.md) — `GLM-4.5-Air` (100B MoE) RL across search, SWE, and terminal domains at 131k context, with agents in sandboxes. 2 train + 4 infer nodes (SWE: 1 + 3).
- [`glm-5.2/`](advanced/glm-5.2/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
- [`glm-5.3/`](advanced/glm-5.3/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
- `intellect-3.1/` — reproduce the `INTELLECT-3.1` run: 4 train + 12 infer nodes on SWE.
All advanced configs submit through SLURM (the `rl` entrypoint writes the sbatch job when the config has a `[slurm]` table) and are monitored with `uv run dashboard`. See the per-model README for the full walkthrough.
@@ -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).
+9 -6
View File
@@ -1,22 +1,25 @@
# GLM-4.5-Air
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0).
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0). The SWE configs also ship budget variants: `swe-4-node.toml` (1 train + 3 infer) and `swe-2-node.toml` — train a 100B+ MoE on only two nodes. Both are thin overlays on a shared `swe-budget.toml` base: the base holds the recipe, the overlay the topology, batch size, and per-run identity.
| Config | Trains on | Evals on | Topology |
|---|---|---|---|
| [`search.toml`](search.toml) | `openseeker` + `redsearcher` (search QA, `rlm` harness + `search` skill) | `browsecomp` (500 examples) | 2 train + 4 infer nodes |
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 2 train + 4 infer nodes |
| [`swe-budget.toml`](swe-budget.toml) + [`swe-4-node.toml`](swe-4-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
| [`swe-budget.toml`](swe-budget.toml) + [`swe-2-node.toml`](swe-2-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 1 infer node |
| [`terminal.toml`](terminal.toml) | `tmax` (per-task Docker image, `rlm` ipython harness) | `swebench-verified` + `terminal-bench-2` (avg@4) | 2 train + 4 infer nodes |
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8`. `search.toml` and `terminal.toml` train with Muon on 2 nodes; `swe.toml` fits the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer. Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8` (plus expert parallelism on `swe.toml`). `search.toml`, `swe.toml`, and `terminal.toml` train with Muon on 2 trainer nodes. The budget variants instead fit the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer; `swe-2-node.toml` cuts the batch size to 64 (4 groups of 16) to match the throughput of its single inference replica. They don't parse standalone: compose them left-to-right over `swe-budget.toml` (`uv run rl @ swe-budget.toml @ swe-2-node.toml`). Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
## Requirements
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — if you use those, log the `prime` CLI in (it ships with prime-rl's dependencies), and each config's `slurm.pre_run_command` will clean up the run's orphaned sandboxes by label before launching:
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. Install the `prime` CLI separately and log in. Each config's `slurm.pre_run_command` then cleans up the run's orphaned sandboxes by label before launch:
```bash
uv run prime login # or: uv run prime config set-api-key <your-key>
uv tool install prime
prime login # or: prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend) and drop the `slurm.pre_run_command` cleanup line.
@@ -54,7 +57,7 @@ uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
--run.name glm45air-swe
```
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. For SWE on a smaller budget, compose a budget variant over its base: `uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml` trains the 100B+ MoE on only two nodes. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
## Monitor with the dashboard
@@ -0,0 +1,41 @@
# Budget variant of swe.toml: train a 100B+ MoE on only two nodes (1 train + 1 infer replica) with
# the single-node sign-SGD trainer. Overlay for swe-budget.toml — this file only carries the
# deltas, so compose the two (left-to-right merge, see docs/configuration.md "TOML Composition"):
#
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml
#
# The batch size is 64 (4 groups of 16), matching the rollout throughput of the single inference
# replica. The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the
# budget variants can run side by side.
[slurm]
job_name = "glm45air-swe-2-node"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe-2-node" -y || true'
[deployment]
num_infer_replicas = 1
[monitors.wandb]
name = "glm45air-scaleswe-2-node"
[orchestrator]
batch_size = 64
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-2-node"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-2-node"]
env.agent.timeout.rollout = 3600
@@ -0,0 +1,42 @@
# Budget variant of swe.toml: the same recipe on four nodes (1 train + 3 infer replicas, the
# topology swe.toml used before the Muon switch) with the single-node sign-SGD trainer. Overlay for
# swe-budget.toml — this file only carries the deltas, so compose the two (left-to-right merge, see
# docs/configuration.md "TOML Composition"):
#
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-4-node.toml
#
# Batch size 256 (16 groups of 16) matches the rollout throughput of the three inference replicas.
# The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the budget
# variants can run side by side.
[slurm]
job_name = "glm45air-swe-4-node"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe-4-node" -y || true'
[deployment]
num_infer_replicas = 3
[monitors.wandb]
name = "glm45air-scaleswe-4-node"
[orchestrator]
batch_size = 256
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-4-node"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-4-node"]
env.agent.timeout.rollout = 3600
@@ -0,0 +1,114 @@
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Shared base of the budget variants of swe.toml
# (`swe-4-node.toml`, `swe-2-node.toml`): the pre-Muon recipe with the single-node sign-SGD
# trainer, composed as `uv run rl @ swe-budget.toml @ <variant>.toml`. Router replay is enabled
# (trainer.enable_router_replay replays the routed-expert decisions returned by inference via
# enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe model, which supports routed_experts.
#
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
#
# Inference serves the bf16 checkpoint as-is (no quantization). The trainer fits on one node via
# cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus the
# memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
# skip-gather / skip-optimizer checkpointing. Concurrency is fully default: the controller derives
# its start from the measured KV budget and adapts from there.
#
# The variant overlays on top of this base set the inference replica count and batch size, the
# per-variant SLURM job name / sandbox cleanup label / W&B run name, and the train/eval sources
# with their matching runtime labels.
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
partition = "all"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[monitors.wandb]
project = "swe-ablations"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
[resume]
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
optim_cpu_offload = false
full_offload = true
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "sign_sgd"
# --- Orchestrator ---
[orchestrator]
group_size = 16
max_off_policy_steps = 32
[orchestrator.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
# --- Inference ---
[inference]
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
enable_return_routed_experts = true
-87
View File
@@ -1,87 +0,0 @@
seq_len = 131072
[log]
level = "debug"
[monitors.wandb]
project = "glm5-pd-disag"
[weight_broadcast]
type = "nccl"
port = 29502
timeout = 12000
quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
num_train_nodes = 16
gpus_per_node = 8
num_infer_replicas = 2
[inference.deployment]
type = "disaggregated"
prefill_nodes_per_replica = 4
decode_nodes_per_replica = 4
[inference.vllm]
model = "zai-org/GLM-5-FP8"
tool_call_parser = "glm47"
gpu_memory_utilization = 0.80
enable_expert_parallel = true
enable_eplb = false
[slurm]
job_name = "glm5-pd-disag"
[ckpt]
interval = 100
[trainer]
dist_timeout_seconds = 7200
[trainer.model]
name = "zai-org/GLM-5"
impl = "custom"
attn = "flash_attention_2" # dsa is skipping flash attn anyway
fused_lm_head_token_chunk_size = 2048
ep = 8
[trainer.model.ac]
freq = 1
[trainer.model.compile]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "adamw"
lr = 1e-6
weight_decay = 0.1
[orchestrator]
batch_size = 4096
group_size = 16
max_off_policy_steps = 16
[orchestrator.concurrency]
initial_inflight = 4096
max_inflight = 8192
[orchestrator.model]
name = "zai-org/GLM-5-FP8"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm5-pd-disag", "swe-bench-verified"]
[inference]
# we need <0.85 bc glm5 layers are too large for 0.85
use_deep_gemm = true
@@ -1,22 +1,23 @@
# GLM-5 family at scale
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5`, `GLM-5.1`, and `GLM-5.2-FP8` — at 131k context: 16 trainer nodes on the custom MoE implementation (expert parallelism; the llm-d variant adds context parallelism) and P/D-disaggregated FP8 inference. The `-llmd` variants front the inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. They also offload KV to a Mooncake distributed CPU pool (1TB per node by default).
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5.3-BF16` for training and serving alike, quantized to per-block FP8 online on the vLLM side — at 131k context: 16 trainer nodes on the custom MoE implementation (expert + context parallelism) and P/D-disaggregated FP8 inference. The [`swe-llmd.toml`](swe-llmd.toml) append fronts the same inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. It also offloads KV to a Mooncake distributed CPU pool (1TB per node by default).
| Config | What it runs | Topology |
|---|---|---|
| [`swe.toml`](swe.toml) | GLM-5 RL plane: 16 train nodes, eval on `swebench-verified` every 20 steps, default vLLM router over 2 P/D replicas (4 prefill + 4 decode nodes each). Declares **no train source** — compose yours on top with an `[[orchestrator.train.source]]` overlay. | 16 train + 16 infer nodes |
| [`swe-llmd.toml`](swe-llmd.toml) | Full-stack GLM-5.1 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), llm-d router + Mooncake KV offload. | 16 train + 16 infer nodes |
| [`swe.toml`](swe.toml) | Base GLM-5.3 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), serves `GLM-5.3-BF16` with online per-block FP8 quantization behind the default `vllm-router`. | 16 train + 16 infer nodes |
| [`swe-llmd.toml`](swe-llmd.toml) | Append for `swe.toml`: swaps in the llm-d router (EPP scorer tuning) + Mooncake KV offload — launch as `rl @ swe.toml @ swe-llmd.toml`. | same |
| [`infer/pd.toml`](infer/pd.toml) | Inference-only pre-flight: P/D-disaggregated `GLM-5-FP8`. | 6 infer nodes |
| [`infer/pd-llmd.toml`](infer/pd-llmd.toml) | Inference-only pre-flight: `GLM-5.2-FP8` with llm-d + Mooncake. | 16 infer nodes |
## Requirements
- A Slurm cluster with 8-GPU nodes, a shared filesystem, and at least **32 nodes** (16 trainer + 16 inference) for the RL configs. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path. If you have fewer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` (llm-d variant) accordingly.
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d variants).
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in — it ships with prime-rl's dependencies:
- A Slurm cluster with 8-GPU nodes, a shared filesystem, and at least **32 nodes** (16 trainer + 16 inference) for the RL configs. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path. If you have fewer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` accordingly.
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d append).
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, install the `prime` CLI separately and log in:
```bash
uv run prime login # or: uv run prime config set-api-key <your-key>
uv tool install prime
prime login # or: prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend).
@@ -24,9 +25,9 @@ uv run prime login # or: uv run prime config set-api-key <your-key>
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
- `HF_TOKEN` — the GLM-5 family checkpoints are gated models.
- `WANDB_API_KEY` — both RL configs log to W&B (`[monitors.wandb]`).
- `WANDB_API_KEY` — both RL variants log to W&B (`[monitors.wandb]`).
### Install llm-d (llmd variants only)
### Install llm-d (llm-d append only)
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
@@ -47,28 +48,27 @@ uv sync --all-extras --all-packages
## Tweak before launching
- `swe-llmd.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`. `swe.toml` needs `--slurm.partition <your-partition>` or `--output-dir` overrides on the command line.
- `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
- `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
- `swe-llmd.toml` ships without `[ckpt]` — add a checkpoint overlay if you want resume support.
- `swe.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`.
- `swe-llmd.toml` `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
- `swe-llmd.toml` `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
## Start the run
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
```bash
# GLM-5.1 RL with llm-d + Mooncake (recommended)
uv run rl @ examples/advanced/glm-5.2/swe-llmd.toml
# GLM-5.3 RL behind the default vllm-router
uv run rl @ examples/advanced/glm-5.3/swe.toml
# GLM-5 base plane — compose your train source onto it
uv run rl @ examples/advanced/glm-5.2/swe.toml @ my-train-source.toml
# with the llm-d router + Mooncake KV offload appended
uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
```
The inference configs are standalone pre-flights: they serve the FP8 checkpoint through the same entrypoint the trainer uses (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster` included — never call `vllm serve` directly), and are a fast way to check that this cluster can serve the model at all before committing it to a run:
```bash
uv run inference @ examples/advanced/glm-5.2/infer/pd.toml
uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
uv run inference @ examples/advanced/glm-5.3/infer/pd.toml
uv run inference @ examples/advanced/glm-5.3/infer/pd-llmd.toml
```
## Monitor with the dashboard
@@ -97,6 +97,6 @@ Pass several output directories to track parallel experiments side by side (`uv
## Checkpoint and resume
`swe.toml` checkpoints every 100 steps (`[ckpt] interval = 100`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
Both RL configs ship without `[ckpt]` — add a `[ckpt]` overlay (e.g. `interval = 100`) for periodic checkpoints. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
See [Scaling](../../../docs/scaling.md) for SLURM details and [Inference](../../../docs/inference.md) for the disaggregated-inference and router reference.
@@ -2,7 +2,7 @@
# Step 3 / goal target. Topology mirrors the proven original glm5.1_llmd_inference
# (job 348 succeeded): 8 prefill nodes (4 replicas x 2) + 8 decode nodes (1 replica).
#
# Launch: uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
# Launch: uv run inference @ examples/advanced/glm-5.3/infer/pd-llmd.toml
output_dir = "/shared/outputs/glm5.2-16node-llmd"
@@ -60,5 +60,4 @@ reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
+47
View File
@@ -0,0 +1,47 @@
# llm-d append for swe.toml: fronts the P/D-disaggregated inference plane with
# the llm-d router (Endpoint Picker + Envoy) and offloads KV to a Mooncake
# distributed CPU pool. Everything else is inherited from the base config:
#
# uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
[run]
name = "glm5-llmd"
[monitors.wandb]
project = "glm5-llmd"
[slurm]
job_name = "glm5-llmd"
# Overlays replace arrays of tables wholesale, so the train source is spelled
# out again just to swap the sandbox runtime label.
[[orchestrator.train.source]]
name = "r2e"
env.taskset.id = "r2e-gym"
env.agent.harness.id = "rlm"
env.agent.runtime.labels = ["glm5-llmd"]
[inference.router]
type = "llm-d"
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
@@ -1,23 +1,29 @@
# Base GLM-5.3 RL config: P/D-disaggregated FP8 inference behind the default
# vllm-router. Serves the same GLM-5.3-BF16 checkpoint the trainer broadcasts,
# quantized to per-block FP8 online on the vLLM side. Append swe-llmd.toml to
# front the same plane with the llm-d router + Mooncake KV offload:
#
# uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
max_steps = 10000000
seq_len = 131072
output_dir = "/shared/outputs" # FILL IN: point at your shared filesystem
clean = true
[run]
name = "glm5-llmd"
name = "glm5"
[log]
level = "debug"
[monitors.wandb]
project = "glm5-llmd"
project = "glm5"
name = "base"
[weight_broadcast]
type = "nccl"
port = 29502
timeout = 12000
quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
@@ -52,41 +58,30 @@ num_decode_replicas = 1
"max_num_seqs" = 96
[inference.router]
type = "llm-d"
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
type = "vllm-router"
[inference.vllm]
model = "zai-org/GLM-5.1-FP8"
# Serve the same GLM-5.3-BF16 checkpoint the trainer broadcasts; vLLM quantizes
# it to per-block FP8 online.
model = "zai-org/GLM-5.3-BF16"
dtype = "bfloat16"
quantization = "fp8_per_block"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[slurm]
job_name = "glm5-llmd"
job_name = "glm5"
partition = "all" # FILL IN: set to your cluster's partition
[trainer]
dist_timeout_seconds = 1800
[trainer.model]
name = "zai-org/GLM-5.1"
name = "zai-org/GLM-5.3-BF16"
impl = "custom"
attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
@@ -122,10 +117,10 @@ initial_inflight = 256
max_inflight = 512
[orchestrator.model]
name = "zai-org/GLM-5.1-FP8"
name = "zai-org/GLM-5.3-BF16"
[orchestrator.renderer]
name = "glm-5.1"
name = "glm-5.3"
clear_thinking = false
[orchestrator.train.sampling]
@@ -138,17 +133,9 @@ clear_thinking = false
name = "r2e"
env.taskset.id = "r2e-gym"
env.agent.harness.id = "rlm"
env.agent.runtime.labels = ["glm5-llmd"]
env.agent.runtime.labels = ["glm5"]
[inference]
# <0.80 because glm5 layers are too large for 0.85
use_deep_gemm = true
enable_fp32_lm_head = true
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
+3 -2
View File
@@ -13,10 +13,11 @@ RL on the 30B-A3B MoE across three domains: math, SWE, and agentic tool use. The
## Requirements
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
- **Sandboxes** (`swe.toml` only) — the SWE agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in (it ships with prime-rl's dependencies):
- **Sandboxes** (`swe.toml` only) — the SWE agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, install the `prime` CLI separately and log in:
```bash
uv run prime login # or: uv run prime config set-api-key <your-key>
uv tool install prime
prime login # or: prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on the source for a runtime your environments support (e.g. a local Docker backend).
+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
@@ -38,6 +38,8 @@ All2AllBackend = Literal[
"flashinfer_nvlink_two_sided",
]
QuantizationType = Literal["fp8_per_block"]
class VllmConfig(BaseConfig):
"""Arguments forwarded to the vLLM server, under vLLM's own argument names
@@ -105,7 +107,7 @@ class VllmConfig(BaseConfig):
enable_prefix_caching: bool | None = None
"""Enable prefix caching."""
quantization: str | None = None
quantization: QuantizationType | None = None
"""Online inference quantization method. If None, vLLM infers it from the checkpoint."""
enable_lora: bool = False
@@ -130,6 +132,12 @@ class VllmConfig(BaseConfig):
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB)."""
enable_ep_weight_filter: bool = True
"""Skip non-local expert weights at load time under expert parallelism, so each
rank reads only its own expert shard from disk. No-op for non-MoE models, when
expert parallelism is disabled, or under EPLB (redundant expert slots need all
logical expert weights)."""
enable_dbo: bool = False
"""Enable dual batch overlap (DBO)."""
@@ -220,7 +228,7 @@ class CPUOffloadTier(BaseConfig):
class DiskOffloadTier(BaseConfig):
path: Path
"""Filesystem root for the disk tier. For ``native`` this is the ``fs_python`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
"""Filesystem root for the disk tier. For ``native`` this is the ``fs`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
class BaseKVCacheOffloadConfig(BaseConfig):
@@ -242,14 +250,14 @@ class BaseKVCacheOffloadConfig(BaseConfig):
class NativeKVCacheOffloadConfig(BaseKVCacheOffloadConfig):
type: Literal["native"] = "native"
"""vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs_python`` disk secondary). Fully self-contained — no external processes."""
"""vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs`` disk secondary). Fully self-contained — no external processes."""
def to_connector_dict(self) -> dict[str, Any]:
assert self.cpu is not None
extra: dict[str, Any] = {"cpu_bytes_to_use": int(self.cpu.num_bytes)}
if self.disk is not None:
extra["spec_name"] = "TieringOffloadingSpec"
extra["secondary_tiers"] = [{"type": "fs_python", "root_dir": str(self.disk.path)}]
extra["secondary_tiers"] = [{"type": "fs", "root_dir": str(self.disk.path)}]
return {
"kv_connector": "OffloadingConnector",
"kv_role": "kv_both",
@@ -303,8 +311,11 @@ class VllmRouterConfig(BaseConfig):
type: Literal["vllm-router"] = "vllm-router"
policy: str = "consistent_hash"
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
request_timeout_secs: int = Field(1800, ge=1)
"""Maximum lifetime of a routed request, including streamed completions."""
policy: str = "sticky_least_loaded"
"""Routing policy. Defaults to session-affine least-loaded routing; alternatives include ``consistent_hash`` and ``round_robin``."""
class LlmdRouterConfig(BaseConfig):
@@ -462,7 +473,7 @@ class InferenceConfig(BaseConfig):
"""Return per-token sampling masks (``sampling_mask``) on ``/inference/v1/generate`` responses via vLLM's native ``--return-sampling-mask`` (>= 0.28). The ``rl`` entrypoint enables this field for truncated policy sampling. Standalone inference must set it explicitly because no orchestrator sampling config is available. The field persists into per-node configs and selects the V2 model runner before vLLM starts. Capture is engine-wide: vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0`` while it is on."""
enable_fp32_lm_head: bool = True
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented natively by vLLM's LogitsProcessor, which reads ``head_dtype`` off the HF config, so this flag injects ``hf_overrides = {"head_dtype": "float32"}``."""
enable_fp32_router_logits: bool = True
"""Emit fp32 MoE router logits: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented natively by vLLM, which reads ``moe_router_dtype`` off the HF config — this flag injects ``hf_overrides = {"moe_router_dtype": "float32"}`` (GLM-5.x gets fp32 routing regardless)."""
@@ -636,6 +647,13 @@ class InferenceConfig(BaseConfig):
hf_overrides.setdefault("moe_router_dtype", "float32")
namespace.hf_overrides = hf_overrides
# vLLM's LogitsProcessor reads `head_dtype` off the HF config to pick the
# lm_head projection dtype (fp32 runs as a native bf16xbf16 -> fp32 GEMM).
if self.enable_fp32_lm_head:
hf_overrides = getattr(namespace, "hf_overrides", None) or {}
hf_overrides.setdefault("head_dtype", "float32")
namespace.hf_overrides = hf_overrides
if self.enable_return_sampling_mask:
namespace.return_sampling_mask = True
@@ -643,12 +661,4 @@ class InferenceConfig(BaseConfig):
if kv_transfer_config is not None:
namespace.kv_transfer_config = kv_transfer_config
# Pass prime-rl-specific flags through vLLM's additional_config dict;
# workers read these via get_current_vllm_config().additional_config.
additional_config = getattr(namespace, "additional_config", None) or {}
if self.enable_fp32_lm_head:
additional_config["fp32_lm_head"] = True
if additional_config:
namespace.additional_config = additional_config
return namespace
@@ -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,13 +161,13 @@ 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."""
shuffle: bool = False
"""Shuffle the source's finite taskset once with a fixed seed. The shuffled order is fixed for the whole run; infinite tasksets cannot be shuffled."""
@model_validator(mode="before")
@classmethod
@@ -269,6 +269,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 +296,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 +335,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 +350,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 +406,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):
@@ -431,9 +462,6 @@ class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
@@ -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."""
@@ -145,9 +145,6 @@ class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
port: int = 29501
"""Port for NCCL weight broadcast."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
@@ -368,22 +365,6 @@ class RLConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_quantize_in_weight_transfer(self):
if not isinstance(self.weight_broadcast, SharedNCCLWeightBroadcastConfig):
return self
if not self.weight_broadcast.quantize_in_weight_transfer:
return self
if self.inference is None:
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires an inference config.")
if self.trainer.model.impl != "custom":
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires trainer.model.impl = 'custom'.")
return self
### Auto-setup shared configs (before sub-config construction)
@model_validator(mode="before")
@@ -487,9 +468,7 @@ class RLConfig(BaseConfig):
inference_world_size=inference_world_size,
)
if self.weight_broadcast.type == "nccl":
transport_config = dict(
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
transport_config = {}
trainer_config_type = TrainerNCCLWeightBroadcastConfig
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
else:
@@ -538,18 +517,9 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_eplb_requires_quantized_weight_transfer(self):
if self.inference is None or not self.inference.vllm.enable_eplb:
return self
# TODO(matej): check if weight reloading works itself before supporting EPLB without quantized transfer.
trainer_weight_broadcast = self.trainer.weight_broadcast
if trainer_weight_broadcast.type != "nccl" or not trainer_weight_broadcast.quantize_in_weight_transfer:
raise ValueError(
"inference.vllm.enable_eplb requires weight_broadcast.type = 'nccl' and "
"weight_broadcast.quantize_in_weight_transfer = true."
)
def validate_eplb(self):
if self.inference is not None and self.inference.vllm.enable_eplb:
raise ValueError("inference.vllm.enable_eplb is not supported with RL weight updates.")
return self
@model_validator(mode="after")
@@ -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,
@@ -171,7 +171,7 @@ class DynamoConfig(BaseConfig):
class ClientConfig(BaseConfig):
wait_for_ready_timeout: int = 1800
wait_for_ready_timeout: int = 3600
"""Seconds to wait at startup for the inference pool to become ready."""
base_url: str = "http://localhost:8000/v1"
@@ -568,13 +568,13 @@ class CheckpointConfig(BaseConfig):
class IPOLossConfig(BaseConfig):
type: Literal["ipo"] = "ipo"
eps: float = Field(0.1, ge=0)
eps: float = Field(0.3, ge=0)
"""Maximum absolute probability change before a token is masked."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
kl_tau: float = Field(1e-3, ge=0)
kl_tau: float = Field(0.0, ge=0)
"""Temperature for the KL term."""
@@ -645,9 +645,6 @@ class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
+18 -11
View File
@@ -16,14 +16,15 @@ dependencies = [
"transformers==5.6.2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
"prime>=0.6.19",
"prime-runs[train]>=0.1.1",
"prime-sandboxes>=0.3.0",
"prime-runs[train]>=0.1.3",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
"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"
@@ -55,7 +56,7 @@ gpu = [
"torchvision ; sys_platform == 'linux'",
"torchaudio ; sys_platform == 'linux'",
"torchdata>=0.11.0 ; sys_platform == 'linux'",
"vllm>=0.28.0 ; sys_platform == 'linux'",
"vllm>=0.29.0 ; sys_platform == 'linux'",
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
"torchtitan ; sys_platform == 'linux'",
@@ -145,7 +146,7 @@ override-dependencies = [
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
"apache-tvm-ffi==0.1.11",
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
# vLLM 0.28.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
# vLLM 0.29.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
"nvidia-cutlass-dsl==4.6.2",
"transformers==5.6.2",
@@ -223,8 +224,6 @@ requires-dist = [
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
harbor = "2026-08-11T00:00:00Z"
# we want latest vllm, remove next patch
vllm = false
tokenspeed-mla = false
fastokens = false
flash_attn_3 = false
@@ -268,12 +267,12 @@ torchao = [
dion = { git = "https://github.com/samsja/dion.git", rev = "99e5f7e" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
@@ -309,6 +308,14 @@ name = "pytorch-cu130-test"
url = "https://download.pytorch.org/whl/test/cu130"
explicit = true
# Environments Hub wheels carry no upload time, so the exclude-newer cooldown
# would reject every one of them. The Hub is first-party: skip the cutoff there.
[[tool.uv.index]]
name = "prime-hub"
url = "https://hub.primeintellect.ai/primeintellect/simple/"
explicit = true
exclude-newer = false
[tool.ruff.lint]
select = ["F", "I"]
+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.
+21 -136
View File
@@ -5,164 +5,49 @@ 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.
- Overview and Metrics read the same `monitors/file/metrics.jsonl`. **Overview** is the curated view (the sections of the W&B overview: train, eval, stability, inference, performance). **Metrics** is every key in the file, one pane per key, sectioned by parent path (`Flat`) or as a tree of sections along the key path (`Nested`), with a regex filter; time-keyed rows (`inference/`, `concurrency/`, `dispatcher/`) chart against wall time.
- 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 overview 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).
+6 -40
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
@@ -74,7 +74,9 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
## `inference` — vLLM server
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly.
Router session cleanup runs on successful, failed, and cancelled episodes, including discarded retry traces. Cleanup failures are logged per session and do not disable subsequent releases.
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly. The default `sticky_least_loaded` policy keeps each rollout on one replica while assigning new sessions to the least-loaded replica; RL and SFT online eval automatically release completed sessions.
```bash
uv run inference --vllm.model Qwen/Qwen3-0.6B
@@ -95,43 +97,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 +108,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
+2 -2
View File
@@ -1,8 +1,8 @@
# Dashboard
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
directories (metrics, resolved configs, rollout traces, cited reports,
component logs) at
directories (a curated overview, every logged metric, resolved configs,
rollout traces, cited reports, component logs) at
http://localhost:7788. The trace viewer includes transcript, synchronized
agent timeline, and terminal replay views; timeline activities open the
corresponding transcript call. Needs the `dashboard` extra. Every instance also serves
+161 -19
View File
@@ -28,24 +28,27 @@ 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:
import uvicorn
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
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()
app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=1)
output_dirs: list[Path] = [default_output_dir()]
# run id -> run dir, rebuilt on every /api/runs poll; ids are the run name,
@@ -75,6 +78,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 +244,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 +263,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 +317,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 +393,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 +440,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 +471,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]:
@@ -489,7 +552,7 @@ def read_report(run: str, file: str) -> dict:
# ------------------------------------------------------------------------- metrics
MAX_METRICS_CHUNK = 4 * 1024 * 1024
MAX_METRICS_CHUNK = 16 * 1024 * 1024
"""Per-response cap on /metrics: huge runs stream in chunks the client loops over,
so the first charts paint long before a 100MB metrics.jsonl finishes loading."""
@@ -505,7 +568,9 @@ def read_metrics(run: str, offset: int = 0) -> dict:
rows = []
with path.open("rb") as f:
f.seek(offset)
data = f.read(MAX_METRICS_CHUNK)
# Keep the first response small for quick initial chart rendering.
chunk_size = 4 * 1024 * 1024 if offset == 0 else MAX_METRICS_CHUNK
data = f.read(chunk_size)
if data and b"\n" not in data: # a single line larger than the chunk
data += f.readline()
consumed = data.rfind(b"\n") + 1 # leave a partially-written last line for the next poll
@@ -529,8 +594,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 +1751,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 +1807,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 +2113,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
+54 -10
View File
@@ -21,29 +21,57 @@
</div>
<nav id="tabs">
<button data-tab="config">Config</button>
<button data-tab="metrics" class="active">Metrics</button>
<button data-tab="overview" class="active">Overview</button>
<button data-tab="metrics">Metrics</button>
<button data-tab="traces">Traces</button>
<button data-tab="report">Report</button>
<button data-tab="logs">Logs</button>
</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>
<main>
<section id="tab-metrics">
<section id="tab-overview">
<div class="controls">
<div class="seg" id="metrics-mode">
<button data-mode="overview" class="active">Overview</button>
<button data-mode="all">All</button>
<div id="overview-filter-wrap" class="dd-wrap" hidden>
<button id="overview-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="overview-filter-menu" hidden>
<div class="dd-sec">filter</div>
<label class="dd-row" id="overview-env-row"><span class="t-label">env</span>
<select id="overview-env"></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="overview-errors"><span class="dot"></span>include errors</label>
</div>
</div>
<input id="overview-search" class="search" type="search" placeholder="regex filter, e.g. reward or ^inference/">
<label class="ctl">smooth <input id="overview-smooth" type="range" min="1" max="50" value="1"><span id="overview-smooth-val">off</span></label>
<span id="overview-status" class="muted"></span>
<div class="spacer"></div>
<button id="overview-collapse" class="btn">collapse</button>
<button id="overview-expand" class="btn">expand</button>
</div>
<div id="overview-body"></div>
<div id="swarm-tip" hidden></div>
</section>
<section id="tab-metrics" hidden>
<div class="controls">
<input id="metrics-search" class="search" type="search" placeholder="regex filter, e.g. ^entropy/ or reward">
<label class="ctl">smooth <input id="smooth-range" type="range" min="1" max="50" value="1"><span id="smooth-val">off</span></label>
<label class="ctl">smooth <input id="metrics-smooth" type="range" min="1" max="50" value="1"><span id="metrics-smooth-val">off</span></label>
<span id="metrics-status" class="muted"></span>
<div class="spacer"></div>
<div class="seg" id="all-layout" hidden>
<div class="seg" id="metrics-layout">
<button data-layout="flat">Flat</button>
<button data-layout="nested">Nested</button>
</div>
@@ -91,6 +119,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 +164,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 +217,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 +228,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>
+121 -8
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;
@@ -297,12 +306,14 @@ main > section { flex: 1; min-height: 0; display: flex; flex-direction: column;
/* --------------------------------------------------------------- metrics */
/* stable gutter: no layout shift when collapsing sections hides the scrollbar */
#metrics-body { flex: 1; overflow-y: auto; scrollbar-gutter: stable; min-height: 0; padding-right: 10px; }
#overview-body, #metrics-body { flex: 1; overflow-y: auto; scrollbar-gutter: stable; min-height: 0; padding-right: 10px; }
.chart-card.dragging { opacity: 0.45; }
/* one 12px rhythm everywhere: section-to-section, header-to-panes, pane-to-pane */
details.section { margin-bottom: 12px; }
/* nested sections (all-mode key tree) indent one step */
details.section details.section { margin-left: 14px; }
/* a section's own panes keep the rhythm before the sections nested under them */
details.section > .chart-grid:not(:last-child) { margin-bottom: 12px; }
details.section:not([open]) > summary { margin-bottom: 0; }
/* section headers are full-width bars so the clickable region is obvious */
details.section > summary {
@@ -336,9 +347,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-overview { 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);
@@ -443,7 +530,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
/* metrics regex filter (overview + all) */
#metrics-search, #config-search, #log-search { flex: 1; max-width: 460px; }
#overview-search, #metrics-search, #config-search, #log-search { flex: 1; max-width: 460px; }
/* wandb-style resize handles on every chart card: right edge = width, bottom
edge = height, corner = both. Resizing one pane resizes all of them. */
@@ -633,7 +720,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 +730,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 +1203,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 +1625,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 +1636,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 +1692,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()
+2
View File
@@ -181,6 +181,8 @@ def start_router(config: InferenceConfig) -> subprocess.Popen:
str(config.vllm.data_parallel_size_local or config.vllm.data_parallel_size),
"--request-id-headers",
"x-session-id",
"--request-timeout-secs",
str(config.router.request_timeout_secs),
"--worker-startup-timeout-secs",
"4200",
"--prometheus-port",
+46 -39
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")
@@ -586,7 +594,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 +604,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 +619,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 +667,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()
+169
View File
@@ -0,0 +1,169 @@
"""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.*.shuffle",
"source.*.group_size",
"source.*.serve",
)
"""Config paths a resumed run may change: how many rollouts to run and how to run them,
never what is measured."""
CONFIG_NAME = "eval.json"
"""The resolved config an attempt stamps into its file monitor directory once it is
running, beside the episodes it produces: a resume validates against the config those
episodes were measured with, never against an attempt that was rejected or dry."""
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)
+333
View File
@@ -0,0 +1,333 @@
"""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, 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")
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,
interval=config.log.interval,
)
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()
-2
View File
@@ -391,7 +391,6 @@ class DynamoAdminPlane(AdminPlane):
port: int,
timeout: int,
inference_world_size: int,
quantize_in_weight_transfer: bool = False,
) -> None:
async with self._mutation_lock:
self._require_uninitialized_nccl()
@@ -411,7 +410,6 @@ class DynamoAdminPlane(AdminPlane):
0,
1,
timeout,
quantize_in_weight_transfer,
"default",
],
)
+2 -114
View File
@@ -15,7 +15,6 @@ def apply_shared_vllm_patches():
_patch_lora_key_prefix()
_patch_qwen35_moe_lora_format()
monkey_patch_nano_v3_reasoning_parser()
monkey_patch_qwen3_coder_param_newline_trim()
monkey_patch_minimax_m2_think_end_passthrough()
monkey_patch_return_routed_experts_with_nixl_connector()
monkey_patch_kv_xfer_finished_tolerate_freed()
@@ -248,57 +247,6 @@ def monkey_patch_nano_v3_reasoning_parser():
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
def monkey_patch_qwen3_coder_param_newline_trim():
"""Restore vLLM 0.23's single-newline trim for qwen3_coder tool parameters.
vLLM 0.24's parser engine applies a full ``.strip()`` to every parameter
value in ``_qwen3_arg_converter``; 0.23's ``Qwen3CoderToolParser`` trimmed
exactly one leading and one trailing newline. A full strip corrupts
whitespace-significant string parameters (str_replace-style
``old_str``/``new_str``, file content with an indented first line, values
with intentional trailing newlines), silently changing tool execution and
rewards for agentic runs. Copy of ``_qwen3_arg_converter`` with only the
trim changed. Also covers ``nemotron_v3``, which reuses ``qwen3_config``.
"""
import json
from vllm.parser import qwen3
def _trim_one_newline(value: str) -> str:
if value.startswith("\n"):
value = value[1:]
if value.endswith("\n"):
value = value[:-1]
return value
def _patched_arg_converter(raw_args: str, partial: bool) -> str:
params: dict[str, object] = {}
for match in qwen3._PARAM_RE.finditer(raw_args):
name = match.group(1)
value = match.group(2)
## START PATCHED CODE (upstream: value.strip())
params[name] = _trim_one_newline(value)
## END PATCHED CODE
if partial:
remaining = qwen3._PARAM_RE.sub("", raw_args)
m = qwen3._PARTIAL_PARAM_RE.search(remaining)
if m:
name = m.group(1)
value = m.group(2)
if name:
## START PATCHED CODE (upstream: value.strip())
params[name] = _trim_one_newline(value)
## END PATCHED CODE
return json.dumps(params, ensure_ascii=False)
qwen3._qwen3_arg_converter = _patched_arg_converter
# qwen3_config captures the converter when first built; drop any cached configs.
qwen3.qwen3_config.cache_clear()
def monkey_patch_minimax_m2_think_end_passthrough():
"""Keep the literal ``</think>`` in MiniMax-M2 content on tool-calling turns.
@@ -757,68 +705,6 @@ def monkey_patch_no_moe_lora():
FusedMoEConfig.__post_init__ = _patched__post_init__
def monkey_patch_fp32_lm_head():
"""Run the lm_head projection in fp32, via a native bf16xbf16 -> fp32 GEMM.
Uses ``torch.mm(..., out_dtype=torch.float32)`` (PyTorch >= 2.10) so the
matmul accumulates and emits fp32 directly without zero-padding the bf16
operands or maintaining a separate fp32 weight copy. This avoids the
epilogue truncation to bf16 that `F.linear(bf16, bf16)` does, which is
where lm_head precision actually leaks before the sampler's softmax.
Activated by setting ``additional_config["fp32_lm_head"] = True`` on the
vLLM namespace; the launcher does this when ``inference.enable_fp32_lm_head``
is set. The flag is captured once on ``LogitsProcessor.__init__`` (where
vLLM guarantees a ``set_current_vllm_config()`` context) and stored on the
instance — reading it from ``_get_logits`` during serving doesn't work
because vLLM doesn't keep the context set during forwards.
Tracks vllm-project/vllm#24567 (which uses the operand-upcast approach).
Per @Jackmin801 on PR #2438, native ``out_dtype=fp32`` mm is more efficient
and just as correct.
"""
import torch
from vllm.config import get_current_vllm_config
from vllm.logger import init_logger
from vllm.model_executor.layers.logits_processor import LogitsProcessor
logger = init_logger(__name__)
_original_init = LogitsProcessor.__init__
_original_get_logits = LogitsProcessor._get_logits
def _patched_init(self, *args, **kwargs):
_original_init(self, *args, **kwargs)
vllm_config = get_current_vllm_config()
additional_config = vllm_config.additional_config or {}
self._fp32_lm_head_enabled = additional_config.get("fp32_lm_head", False)
if self._fp32_lm_head_enabled:
logger.warning("fp32 lm_head ENABLED for this LogitsProcessor instance.")
def _patched_get_logits(self, hidden_states, lm_head, embedding_bias):
if not getattr(self, "_fp32_lm_head_enabled", False):
return _original_get_logits(self, hidden_states, lm_head, embedding_bias)
# Native bf16xbf16 -> fp32 GEMM. torch.mm requires 2D inputs; vLLM v1's
# generative path passes 2D [num_tokens, hidden_size] hidden_states, but
# flatten defensively in case some future caller passes 3D.
flat = hidden_states.reshape(-1, hidden_states.shape[-1])
logits = torch.mm(flat, lm_head.weight.t(), out_dtype=torch.float32)
if embedding_bias is not None:
logits = logits + embedding_bias.to(torch.float32)
if hidden_states.dim() > 2:
logits = logits.reshape(*hidden_states.shape[:-1], -1)
logits = self._gather_logits(logits)
if logits is not None:
logits = logits[..., : self.org_vocab_size]
return logits
LogitsProcessor.__init__ = _patched_init
LogitsProcessor._get_logits = _patched_get_logits
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
def monkey_patch_dp_coordinator_startup_timeout():
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
@@ -935,6 +821,8 @@ def monkey_patch_deepseek_v4_per_layer_rope():
Note that nothing in vLLM's DeepSeek V4 calls the module's `forward`; every consumer reads
`cos_sin_cache` and hands it to a fused kernel. The class choice is therefore about the
cache's dtype and row count, not about which channels the module would rotate.
Remove this patch once the pin includes vllm-project/vllm#54815, which ships in 0.29.1.
"""
from vllm.models.deepseek_v4.common import rope as dsv4_rope
+11 -12
View File
@@ -6,10 +6,10 @@ from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from starlette.datastructures import State
from vllm.engine.protocol import EngineClient
from vllm.entrypoints.openai.api_server import init_app_state
from vllm.entrypoints.openai.cli_args import make_arg_parser, validate_parsed_serve_args
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
from vllm.entrypoints.launchers.api_server.app_state import init_app_state
from vllm.entrypoints.launchers.cli_args import make_arg_parser, validate_parsed_serve_args
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
from vllm.entrypoints.serve.lora.protocol import LoadLoRAAdapterRequest
from vllm.logger import init_logger
from vllm.utils.argparse_utils import FlexibleArgumentParser
@@ -26,7 +26,7 @@ from prime_rl.inference.patches import (
)
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
# Still needed in vLLM 0.28 — upstream rejects prompt_len > max_model_len - max_tokens
# Still needed in vLLM 0.29 — upstream rejects prompt_len > max_model_len - max_tokens
monkey_patch_tokenize_params_validation()
# NOTE: Register Nano V3 reasoning parser so configs can use
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
@@ -42,7 +42,7 @@ monkey_patch_strip_routed_experts_from_chat()
# weights concurrently (multi-node disaggregated deployments).
monkey_patch_dp_coordinator_startup_timeout()
logger = init_logger("vllm.entrypoints.openai.api_server")
logger = init_logger("vllm.entrypoints.launchers.api_server.entry")
# Create our own router for custom endpoints
router = APIRouter()
@@ -138,11 +138,10 @@ async def init_broadcaster(request: Request):
timeout = data.get("timeout")
rank_offset = data.get("rank_offset")
inference_world_size = data.get("inference_world_size")
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
session_id = data.get("session_id", "default")
await engine_client(request).collective_rpc(
"init_broadcaster",
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer, session_id),
args=(host, port, rank_offset, inference_world_size, timeout, session_id),
)
return {"status": "ok"}
@@ -177,9 +176,9 @@ async def custom_init_app_state(
state.serving_tokens = prime_serving
import vllm.entrypoints.openai.api_server
import vllm.entrypoints.launchers.api_server.entry
import vllm.v1.utils
from vllm.entrypoints.openai.api_server import build_app as _original_build_app
from vllm.entrypoints.launchers.app import build_app as _original_build_app
from vllm.v1.utils import run_api_server_worker_proc as _original_run_api_server_worker_proc
@@ -202,8 +201,8 @@ def custom_run_api_server_worker_proc(listen_address, sock, args, client_config=
_original_run_api_server_worker_proc(listen_address, sock, args, client_config, **uvicorn_kwargs)
vllm.entrypoints.openai.api_server.init_app_state = custom_init_app_state
vllm.entrypoints.openai.api_server.build_app = custom_build_app
vllm.entrypoints.launchers.api_server.entry.init_app_state = custom_init_app_state
vllm.entrypoints.launchers.api_server.entry.build_app = custom_build_app
vllm.v1.utils.run_api_server_worker_proc = custom_run_api_server_worker_proc
@@ -214,7 +213,7 @@ def server(config: InferenceConfig):
import os
from vllm.entrypoints.cli.serve import run_headless, run_multi_api_server
from vllm.entrypoints.openai.api_server import run_server
from vllm.entrypoints.launchers.api_server.entry import run_server
# Signal worker processes to disable LoRA on MoE layers when LoRA targets don't include experts
lora_target_modules = config.vllm.lora_target_modules
+8 -37
View File
@@ -4,19 +4,11 @@ vLLM ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
priority, ``data_parallel_rank`` header routing, server-side ``max_tokens``
defaulting and ``usage`` reporting. We subclass it for the bits still missing
from the upstream handler:
1. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as ``{data, shape, start, dtype}`` base64 raw-byte
objects (the form the PD router can merge and the renderers parse) instead
of upstream's single ``.npy`` base64 string.
2. ``kv_transfer_params`` bridging — upstream ``ServingTokens.serve_tokens``
parses ``request.kv_transfer_params`` but never threads it into the engine,
so PD disagg never fires on ``/inference/v1/generate``. Fixed upstream by
https://github.com/vllm-project/vllm/pull/42644, which missed the 0.28.0
cut — drop the bridge once we pin a release that includes it.
defaulting and ``usage`` reporting. We subclass it for the one bit still
missing from the upstream handler: compact ``routed_experts`` export — when the
engine emits routing decisions, surface them as ``{data, shape, start, dtype}``
base64 raw-byte objects (the form the PD router can merge and the renderers
parse) instead of upstream's single ``.npy`` base64 string.
Everything else (request/response schema, sampling params, error handling)
delegates to upstream so we track future vLLM changes for free.
@@ -27,17 +19,14 @@ from __future__ import annotations
from collections.abc import AsyncGenerator
from typing import Any
from fastapi import Request
from vllm.entrypoints.openai.engine.protocol import (
ErrorResponse,
RequestResponseMetadata,
)
from vllm.entrypoints.generate.base.protocol import RequestResponseMetadata
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateRequest,
GenerateResponse,
GenerateResponseChoice,
)
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
from vllm.outputs import RequestOutput
from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
@@ -67,25 +56,7 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
class PrimeRlServingTokens(ServingTokens):
"""ServingTokens + compact routed experts + PD kv_transfer_params bridging."""
async def serve_tokens(
self,
request: GenerateRequest,
raw_request: Request | None = None,
) -> GenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
# Upstream parses ``request.kv_transfer_params`` but never threads it
# into the engine, so decode receives an empty NIXL handshake and
# re-prefills the prompt locally (~100x slower under concurrency).
# Bridge it through ``sampling_params.extra_args`` so the engine's KV
# connector picks the params up. Fixed upstream by vllm#42644 (merged
# after 0.28.0) — drop once we pin a release that includes it.
if request.kv_transfer_params is not None:
extra = request.sampling_params.extra_args or {}
extra["kv_transfer_params"] = request.kv_transfer_params
request.sampling_params.extra_args = extra
return await super().serve_tokens(request, raw_request)
"""ServingTokens + compact routed experts."""
async def serve_tokens_full_generator( # type: ignore[override]
self,
@@ -2,7 +2,6 @@ import logging
import os
from prime_rl.inference.patches import (
monkey_patch_fp32_lm_head,
monkey_patch_minimax_m2_for_lora,
monkey_patch_no_moe_lora,
)
@@ -17,6 +16,3 @@ if os.environ.get("PRIME_NO_MOE_LORA") == "1":
monkey_patch_no_moe_lora()
else:
logger.info("PRIME_NO_MOE_LORA=0: no patch applied")
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
monkey_patch_fp32_lm_head()
+1 -12
View File
@@ -7,11 +7,7 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
from vllm.distributed.utils import StatelessProcessGroup
from vllm.logger import init_logger
from prime_rl.inference.vllm.worker.weight_transfer import (
load_weights_checkpoint_layerwise,
load_weights_kernel,
update_mla_absorbed_weights,
)
from prime_rl.inference.vllm.worker.weight_transfer import load_weights_checkpoint_layerwise
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
# This is to get type hints for the Worker class but not actually extend it at runtime as this is required by vLLM worker extension
@@ -99,7 +95,6 @@ class NCCLWeightUpdateWorker(Worker):
rank_offset: int,
inference_world_size: int,
timeout: int,
quantize_in_weight_transfer: bool = False,
session_id: str = "default",
) -> None:
"""Initialize the NCCL broadcast receiver.
@@ -109,7 +104,6 @@ class NCCLWeightUpdateWorker(Worker):
inference_world_size: Total number of inference GPUs across all servers.
"""
del session_id
self.quantize_in_weight_transfer = quantize_in_weight_transfer
# Use the worker's device index directly as the local rank.
# The previous dp_group-based computation broke in vLLM v1 multiprocess
# DP mode where each worker is a separate process with a singleton
@@ -145,11 +139,6 @@ class NCCLWeightUpdateWorker(Worker):
assert isinstance(model, Module)
state_iter = self.nccl_broadcast_receiver.receive_state_dict()
if self.quantize_in_weight_transfer:
load_weights_kernel(model, state_iter)
update_mla_absorbed_weights(model)
return
load_weights_checkpoint_layerwise(
model,
state_iter,
+1 -2
View File
@@ -98,10 +98,9 @@ class NIXLWeightUpdateWorker(Worker):
rank_offset: int,
inference_world_size: int,
timeout: int,
quantize_in_weight_transfer: bool = False,
session_id: str = "default",
) -> None:
del inference_world_size, quantize_in_weight_transfer
del inference_world_size
global_rank = rank_offset + self.device.index
server_url = f"{host}:{port}"
set_ucx_env_defaults(self.device.index)
@@ -1,11 +1,10 @@
from typing import Generator, Iterable
from typing import Iterable
import torch
from torch.nn import Module
from vllm.config import set_current_vllm_config
from vllm.logger import init_logger
from vllm.model_executor.model_loader.reload import finalize_layerwise_reload, initialize_layerwise_reload
from vllm.model_executor.model_loader.weight_utils import remap_moe_expert_weights
logger = init_logger("vllm.inference.vllm.worker_weight_transfer")
@@ -24,116 +23,6 @@ def load_weights_checkpoint_layerwise(
finalize_layerwise_reload(model, model_config)
def _invert_logical_to_physical_map(logical_to_physical_map: torch.Tensor, num_physical_experts: int) -> torch.Tensor:
"""Build a physical expert -> logical expert map from vLLM EPLB state."""
physical_to_logical = torch.full(
(num_physical_experts,),
-1,
dtype=torch.long,
device=logical_to_physical_map.device,
)
logical_indices = torch.arange(
logical_to_physical_map.shape[0],
dtype=torch.long,
device=logical_to_physical_map.device,
)[:, None].expand_as(logical_to_physical_map)
physical_indices = logical_to_physical_map.to(torch.long)
invalid = (physical_indices < -1) | (physical_indices >= num_physical_experts)
if invalid.any():
invalid_indices = physical_indices[invalid].unique().tolist()
raise ValueError(f"EPLB maps to invalid physical experts: {invalid_indices}")
valid = physical_indices >= 0
physical_to_logical[physical_indices[valid]] = logical_indices[valid]
return physical_to_logical
def _build_expert_source_indices(routed_experts, router) -> torch.Tensor | None:
if routed_experts._expert_map is None:
return None
physical_indices = torch.where(routed_experts._expert_map >= 0)[0]
local_indices = routed_experts._expert_map[physical_indices]
physical_indices = physical_indices[local_indices.argsort()]
eplb_layer_state = getattr(router, "eplb_state", None)
logical_to_physical_map = getattr(eplb_layer_state, "logical_to_physical_map", None)
if logical_to_physical_map is None:
return physical_indices
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, routed_experts.global_num_experts)
logical_indices = physical_to_logical[physical_indices.to(physical_to_logical.device)]
if (logical_indices < 0).any():
missing = physical_indices[(logical_indices < 0).to(physical_indices.device)].tolist()
raise ValueError(f"EPLB has no logical mapping for local physical experts: {missing}")
return logical_indices.to(physical_indices.device)
def build_expert_map(model: Module) -> dict[str, torch.Tensor]:
"""Map MoE module names to source expert indices local to this worker.
vLLM 0.24 turned ``FusedMoE`` into a factory returning a ``MoERunner`` and
split the state that used to live on the ``FusedMoE`` module: the expert map
(``_expert_map`` / ``global_num_experts``) now lives on
``MoERunner.routed_experts`` (a ``RoutedExperts``), and the EPLB state on
``MoERunner.router``. Keying by the ``MoERunner`` name prefix-matches the
nested ``routed_experts.*`` weight params after ``load_weights_kernel``
remaps incoming flat names via ``remap_moe_expert_weights``.
"""
from vllm.model_executor.layers.fused_moe import MoERunner
source_indices_by_module: dict[str, torch.Tensor] = {}
for module_name, module in model.named_modules():
if not isinstance(module, MoERunner):
continue
source_indices = _build_expert_source_indices(module.routed_experts, module.router)
if source_indices is None:
continue
source_indices_by_module[module_name] = source_indices
return source_indices_by_module
@torch.no_grad()
def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Tensor], None, None]) -> None:
"""Load vLLM kernel-format tensors using in-place copy_ updates."""
params = dict(model.named_parameters())
expert_source_indices = build_expert_map(model)
loaded = 0
skipped: list[str] = []
shape_mismatches: list[str] = []
# The trainer emits pre-0.24 flat kernel names (``...experts.w13_weight``); since
# vLLM 0.24 the expert params are nested (``...experts.routed_experts.w13_weight``).
# ``remap_moe_expert_weights`` is upstream's compat shim for exactly this transition.
for name, tensor in remap_moe_expert_weights(state_iter, params):
if name not in params:
skipped.append(name)
continue
param = params[name]
if param.shape != tensor.shape:
for module_name, source_indices in expert_source_indices.items():
if not name.startswith(f"{module_name}."):
continue
tensor = tensor[source_indices.to(tensor.device)]
break
if param.shape != tensor.shape:
shape_mismatches.append(f"{name}: param={list(param.shape)} != received={list(tensor.shape)}")
continue
param.copy_(tensor)
loaded += 1
if shape_mismatches:
raise ValueError(f"Kernel weight transfer had {len(shape_mismatches)} shape mismatches: {shape_mismatches}")
if skipped:
raise ValueError(f"Kernel weight transfer skipped {len(skipped)} weights not found in model: {skipped}")
logger.debug(f"Kernel weight transfer copied {loaded} weights in-place")
@torch.no_grad()
def update_mla_absorbed_weights(model: Module) -> None:
"""Recompute MLA absorbed KV weights after in-place kv_b_proj updates."""
+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()
+164 -4
View File
@@ -2,25 +2,45 @@ 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_sandboxes 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:
import verifiers.v1 as vf
BASE_URL_VAR = "PRIME_API_BASE"
EVAL_ID_VAR = "PRIME_RUNS_EVAL_ID"
# How long finish() and the SDK's atexit crash hook let queued uploads drain. The SDK
# default (300 s) is sized for eval sample batches; a crashed training process should
# not linger that long, and a clean finish rarely has more than the last step queued.
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 +48,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 +62,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 +106,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 +136,141 @@ 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()
self.evaluation_id = os.getenv(EVAL_ID_VAR)
if self.evaluation_id and len(self.sources) != 1:
raise ValueError(
f"${EVAL_ID_VAR} names one platform evaluation, so the run needs "
f"exactly one eval source (got {len(self.sources)})"
)
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."""
if self.evaluation_id:
# A hosted launch pre-created the platform evaluation and injected its id -
# attach instead of registering a duplicate. The backend owns its failure
# marking then; a clean finish still completes it.
if self.runs:
raise RuntimeError(f"${EVAL_ID_VAR} holds one epoch, and it already took one")
return pr.init(
kind="eval",
mode=self.mode,
base_url=_base_url(),
id=self.evaluation_id,
finish_timeout=FINISH_TIMEOUT,
)
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:
attached = f" (attached via ${EVAL_ID_VAR})" if run.attached else ""
self.logger.info(f"Streaming {env_name} (Step {step}) evaluation - {run.url}{attached}")
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.
+10 -5
View File
@@ -73,9 +73,9 @@ INFERENCE_PANELS = [
"inference/agg/num_requests_waiting/max",
],
["inference/agg/prefix_cache_hit_rate/pooled", "inference/agg/prefix_cache_hit_rate/min"],
["inference/agg/generation_tokens_total:rate/sum", "inference/agg/generation_tokens_total:rate/min"],
["inference/agg/prompt_tokens_total:rate/sum", "inference/agg/prompt_tokens_total:rate/max"],
["dispatcher/inflight/train", "dispatcher/inflight/eval"],
["inference/agg/generation_tokens_total:rate/sum"],
["inference/agg/prompt_tokens_total:rate/sum"],
["dispatcher/inflight/train", "dispatcher/inflight/eval", "concurrency/max_inflight"],
]
# SFT flavor: no rollout-based train sections — the training signal is the loss curve.
@@ -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()

Some files were not shown because too many files have changed in this diff Show More