Compare commits

...
Author SHA1 Message Date
Konstantin DunasandGitHub 15f4704092 feat(dashboard): show cancelled and failed subagents in the semantic timeline (#3721) 2026-09-30 19:55:47 +02:00
Konstantin DunasandGitHub 8f4ae42fb8 fix(dashboard): detect index rewrite on resume in index_rows (#3732) 2026-09-30 19:26:30 +02:00
d5f29c072a feat: dashboard global filter and train overview tiles (#3725)
## Summary

- **Overview keeps its scroll position across re-renders.** Every new
eval episode (and every new metric key on a training run) rebuilt
`#overview-body` and snapped it to the top, which made analysing
anything below the fold on a live eval impossible. `renderMetricsBody`
now restores `scrollTop` after the rebuild.
- **One filter shared by the overview, the traces table and the trace
viewer.** The filter menu (status, kind, env, outcome) is a single
`<template>` cloned into the three toolbars over one `state.filter`; a
change in any copy applies in all, and the traces tab reloads when it
opens with a filter set elsewhere. On the overview the env / kind pair
narrows the sections and summary tiles; for an eval run the outcome pair
(`ok` / `error`, replacing the per-pane `include errors` toggle) picks
the episodes the distributions read. The server's `errors_only` episode
filter becomes a three-way `ok` parameter.
- **Live rollouts obey the filter.** Live rows arrive by their own poll
and were spliced into the traces table and the viewer's list whatever
the filter said, so `live + eval` still listed the in-flight train
rollouts. They now pass the same kind / env / outcome check as finished
episodes (an outcome filter hides them, since theirs is still open), and
the "N live" count follows.
- **Eval overview is multi-env.** With no env filter every env renders,
one block after another, each headed by its env name and set off by a
rule; the composition panes hold one model per pane instead of two
globals.
- **Train overview leads with a step bar and summary tiles, like the
eval pane.** One cell per step (click opens that step's batch in the
traces tab) with `done/total (share)` beside the bar; a run without
`max_steps` reads `N/∞` over cells that grow instead of a bar that
always looks full. The tiles keep to results: the reward of each train
env and the avg@k of each eval env, each with its change from the first
logged value beside the number (green when it moved the right way), the
error / truncation / timeout rate of the shown scope, and the step time.
An SFT run shows loss, val loss, eval scores, total samples and tokens,
throughput and MFU. Panes default to 300 × 170px (four per row on a
14-inch laptop), a saved pane size still wins. Tiles are the eval pane's
`tileHtml` / `blockBarHtml`, share its hover cards, and wrap for runs
with many envs.
- **Flat, per-env sections with readable panel names.** The overview
reads top to bottom: no collapsible `details`, no collapse / expand
buttons (the Metrics tab keeps its folding sections), one train section
per env with the cross-env aggregate left to the Metrics tab. Panels are
named in caps for reading (`MEAN REWARD`, `MEAN TURNS`, `ERROR RATE`,
`AVG@4`, `GRAD NORM`, `KV CACHE USAGE`, ...) with an `i` mark beside the
title whose hover card says how the value is computed and shows the raw
key; the latest value reads larger in the corner. Pane order stays keyed
by the raw title, and the Metrics tab keeps every key as logged.
- **Eval sections show `avg@k` alone as the score**: it is the mean
reward over the same traces `reward/mean` averages, so the reward panes
only repeated it.
- **SFT sections**: `val loss` / `val perplexity` appear only once a
validation value is logged (the server's `has_validation` meta field
goes); stability adds `max vio` (expert load imbalance) when an MoE
model logs it; performance drops the step and checkpoint time panes.
- Smoke test asserts the step bar, tiles, info marks and the mounted
filter menus; the dashboard skill documents the new overview and the
shared filter.

## Verification

Ran a multi-env RL run (`configs/debug/multi-env/rl.toml`: two
reverse-text train sources + an online eval with a base eval at step 0,
10 steps), a 20-step SFT run (`examples/basic/reverse-text/sft.toml`
with validation and an online eval) and a two-source gsm8k eval against
Prime Inference, served all three from this branch's dashboard, and
drove it with playwright (no console errors):

- Before: scrolling the eval overview to 600px and re-rendering (what a
landed episode triggers) reset `scrollTop` to 0. After: it stays at 600.
- Setting `env = gsm8k-b` in the overview's filter narrows the overview
to that env, and the traces tab then lists only `gsm8k-b` rows with the
same badge; `error`-only narrows the table through the new `ok` param.
- Live rows: with two synthetic live rows (train + eval) injected, `live
+ eval` lists only the eval one, an env filter keeps only its env's, and
an outcome filter hides both.
- Train overview: `10/10 (100%)` bar; tiles `reverse-text-a reward 0.781
▲ +0.606`, `reverse-text avg@1 0.849 ▲ +0.737` (base eval at step 0),
`truncation rate 2% ▼ -72%`; clicking step cell 2 opens the traces tab
in step mode at step 2; with `env = reverse-text-a` only that env's
train section (plus stability / inference / performance) and tiles
remain. A synthetic 20-env run wraps its 25 tiles over four rows with no
horizontal overflow.
- SFT overview: `loss 3.196 ▼ -1.415` (lower is better reads green),
samples 2.2K and tokens 2.6M match the trainer's counters (32 × 4096 ×
20 steps), throughput 19.6K tok/s, MFU 31%.

### Eval overview, two envs (filter unset)

![eval overview multi
env](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/eval-overview-multi-env.png)

### Eval overview narrowed to one env from the same filter

![eval overview
filtered](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/eval-overview-filtered.png)

### The traces tab picks the filter up (env + badge)

![traces filter
shared](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/traces-filter-shared.png)

### Train overview: step bar, summary tiles with base deltas, flat
per-env sections

![train
overview](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/train-overview.png)

### Info mark on a panel

![train overview
info](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/train-overview-info.png)

### Train overview narrowed to one env

![train overview
filtered](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/train-overview-filtered.png)

### Open-ended run (no `max_steps`) and a synthetic 20-env run

![open
ended](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/train-open-ended.png)

![many
envs](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/train-many-envs.png)

### SFT overview (20-step reverse-text SFT with an online eval)

![sft
overview](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/sft-overview.png)

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches episode listing/filter query params and a large front-end
state refactor; incorrect filter wiring could hide episodes or desync
overview vs traces, but changes are UI/read-path focused with no auth or
training logic changes.
> 
> **Overview**
> Introduces a **single run filter** (status, kind, env, outcome) cloned
from one template into the overview, traces table, and trace
viewer—replacing separate env pickers and an “errors only” checkbox.
Episode APIs now take **`ok`** (`true` / `false` / unset) instead of
**`errors_only`**, and live rollout rows honor the same filter.
> 
> **Eval overview** shows **every filtered env** as stacked blocks (not
one env at a time); distributions respect the **ok/error** outcome
toggles. **Training/SFT overview** adds a **clickable step bar**,
**summary tiles** with delta-from-first-logged-value, **readable panel
titles** with **`i` tooltips** (raw metric keys on hover), flat per-env
sections, and **scroll position preserved** on live re-renders. SFT
panel layout tweaks (val metrics when logged, optional MoE `max_vio`,
trimmed performance panes); run meta drops **`has_validation`**.
> 
> Docs and smoke tests updated for the shared filter and new overview
chrome.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6bb87a7a0fd6e94922154649307167a41645913d. 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-29 18:58:49 -07:00
330f174761 feat: unify how source groups pass defaults (#3714)
## Summary

- Add `SourceGroupConfig`, the one base of every source group:
`[orchestrator.train]` (`TrainConfig`), `[orchestrator.eval]` and the
SFT `[eval]` block (`ScheduledEvalConfig`), and the top level of `uv run
eval` (`EvalConfig`). It has one rule: every field that a group and its
source type both declare is a default. Each source inherits the fields
that the group sets, merged under its own with `vf.merge_defaults`:
nested blocks merge key by key, a source's own values win, and a block
whose `type`/`id` differs is the source's alone.
- Remove the four earlier mechanisms: the group `env` merge, the shallow
group `select` merge, and the after-validators that copied `sampling`,
`group_size` (eval) and `interval` onto sources. Adding a shared field
is now one field on the group.
- Move `group_size` and `algo` from `OrchestratorConfig` into the train
group, so train sources inherit them from their group like eval sources
do. `TrainSourceConfig.algo` defaults to `grpo` instead of `None`, which
removes the `algo is not None` guards.
  ```toml
  [orchestrator.train]
  group_size = 16

  [orchestrator.train.algo]
  type = "echo"
  ```
- Let each train source use its own `group_size` over the group's
(source > group, like every default). The runtime already dispatches and
finalizes each group at its env's size. The config checks now require
`batch_size` to be divisible by every train source's group size, and
`concurrency.max_inflight`/`initial_inflight` to cover the largest one;
before, they checked only the group default. The platform run records
the largest source group size as `rollouts_per_example`.
- Migrate the shipped configs (47 TOMLs plus the k8s orchestrator
example), the docs and the `configs` skill (which now also describes the
group-default rule). Every rewritten TOML parses to exactly the old data
with the two keys moved.
- Pin `deps/verifiers` to its main, which merged
PrimeIntellect-ai/verifiers#2709 (`vf.merge_defaults` replaces
`vf.merge_env_defaults`). Raise the `verifiers` minimum to
`0.3.2.dev158`, its first release, in both `pyproject.toml` files, so
the slim `prime-rl-configs` install gets it.

## Breaking

- `orchestrator.group_size` moves to `orchestrator.train.group_size`
(`--orchestrator.train.group-size`). A standalone orchestrator config
moves `group_size` into `[train]`.
- `[orchestrator.algo]` moves to `[orchestrator.train.algo]`
(`--orchestrator.train.algo.*`).
- A source `algo` that sets params without a `type` now keeps the
group's algorithm with those params changed. Before, it meant `grpo`
with those params. A source that sets a `type` still runs its own
algorithm.
- A source's `select.include`/`exclude` now merges with the group's
block key by key (e.g. a group `include.idx` and a source
`include.names` both apply). Before, the source's block replaced the
group's. Lists still replace.
- Nested dicts in a group `sampling` block (e.g. `extra_body`) now merge
with a source's instead of being replaced.

## Verification

- Resolved every shipped config on `origin/main` and on this branch, and
compared what each source ends up with (`name`, `group_size`, `algo`,
`sampling`, `select`, `interval`, `env`): 77 configs, 95 sources, 0
differences. (9 configs need taskset packages that are not installed in
the test env, on both sides.)
- `uv run rl @ <config> --dry-run` on `configs/debug/algo/echo.toml`,
`configs/debug/algo/mixed_grpo_opd.toml`,
`configs/debug/multi-env/rl.toml` and
`examples/basic/reverse-text/rl.toml`: each source resolves the group's
`group_size` and `algo` (or its own `opd`), and the resolved
orchestrator config has no top-level `algo`/`group_size`.
- The slim-install check, run locally: the `prime-rl-configs` wheel
installed outside the workspace resolves `verifiers 0.3.2.dev158`, the
workflow's import script passes, and a train group's `group_size`,
`sampling` and `env` defaults reach its source through
`vf.merge_defaults`.
- `uv run pytest tests/unit/test_configs.py tests/unit/eval
tests/unit/orchestrator tests/unit/test_dashboard_timeline.py`: 303
passed (2 vLLM-only tests deselected). New tests: sources inherit unset
group fields for each kind of default (blocks, a `-r` alias, `interval`)
and round-trip; train sources with group sizes 16 and 8 resolve, and a
batch size or in-flight cap that does not fit both is rejected; each
group field's default equals its source field's.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking config paths and merge semantics can silently change resolved
training/eval settings; batch and concurrency validation is stricter
when sources use different group sizes.
> 
> **Overview**
> Introduces **`SourceGroupConfig`** so train/eval source groups share
one inheritance rule: any field declared on both the group and its
sources (`env`, `sampling`, `select`, `group_size`, `algo`, `interval`,
…) becomes a default merged into each source via `inherit_defaults` /
`vf.merge_defaults`, replacing the old separate env/select merges and
post-validators that copied fields onto sources.
> 
> **Breaking config moves:** `orchestrator.group_size` and
`[orchestrator.algo]` move under **`[orchestrator.train]`** (same for
standalone orchestrator TOMLs: `[train]`). Shipped configs, docs, and
the configs skill are updated accordingly. Per-env **`group_size`**
overrides are first-class; validation now requires `batch_size`
divisible by **every** train source’s group size and concurrency limits
≥ the **largest** group size. Platform monitoring reports the max source
`group_size` as rollouts per example.
> 
> **Semantics changes:** Source `algo` blocks without a new `type`
inherit the group algorithm with partial overrides (not implicit
`grpo`). Group/source **`select`** and nested **`sampling`** dicts
key-merge instead of wholesale replace where applicable. **`verifiers`**
minimum bumped to `0.3.2.dev158` for `merge_defaults`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
536cc3e1190f8f9fc06419af9dffb1eda331168f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 18:31:38 -07:00
HubertandGitHub 91f58bd9d9 fix: shard single-row gate weights along columns for Muon (#3723)
Qwen shared-expert gates can have weight shape `[1, hidden_size]`.
Default FSDP row sharding gives some ranks empty local tensors, which is
incompatible with the equal-shard layout needed by the distributed Muon
update.

Shard 2D single-row parameters along dimension 1 when their width is
divisible by the parameter-sharding degree, obtained directly from
`parallel_dims.get_mesh("dp_shard_cp").size()`. Other parameters retain
the existing fused-parameter placement callback or default placement.
FSDP still uses the HSDP mesh; the divisibility check excludes
replication ranks. The placement rule applies during model setup
regardless of optimizer selection.

There is no additional optimizer-setup validation. Non-divisible layouts
retain the existing placement and failure behavior in Muon.

Validation performed locally:
- Two-rank CPU/Gloo DTensor reproduction with PyTorch 2.8.0: `[1,128]` /
`[0,128]` under `Shard(0)` versus equal `[1,64]` shards under the
placement callback, with exact reconstruction.
- Isolated placement checks across shard degrees 1/2/4/8/16,
non-divisible widths, 1D/3D parameters and fallback delegation.
- Ruff lint/format and `git diff --check` passed. Local diagnostic
scripts are not added to the repository. These checks do not exercise a
full FSDP + Muon GPU update on current main.

Remaining merge blocker: the NIXL weight sender currently assumes
dimension-0 shard offsets. Its handling of column-sharded gates must be
fixed or the incompatible transport/layout combination rejected before
merge. Checkpoint-layout compatibility also needs review.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Alters FSDP/DTensor layout for a narrow class of MoE gate weights;
downstream weight sync or checkpoint code that assumes row-wise sharding
may need matching updates.
> 
> **Overview**
> **FSDP setup** now uses a custom `shard_placement_fn` instead of
passing the fused-parameter callback directly. For **2D weights with a
single row** (e.g. Qwen shared-expert gates shaped `[1, hidden_size]`),
parameters are sharded along **column dimension 1** when the hidden
width is divisible by the **`dp_shard_cp`** mesh size, so every rank
holds an equal local shard for **Muon’s all-to-all**. All other
parameters still use the existing fused `shard_fused_on_dim1` placement
or PyTorch’s default.
> 
> The change pulls in `Shard` from `torch.distributed.tensor` and reads
shard degree from `parallel_dims.get_mesh("dp_shard_cp").size()`
(parameter sharding only, not HSDP replication).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
159c63d852ad37cdeb9e49ed9439fb2cfba47a2c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-30 01:00:37 +02:00
samsjaandGitHub 7f9de649aa fix(utils): throttle BetterStack heartbeat pings (#3715)
## Problem

Since #3664, eval runs beat the Better Stack heartbeat on every landed
episode. `Heartbeat` only coalesced *concurrent* requests (at most one
in flight), so once a ping returned, the very next landed episode fired
a new one. A busy eval lands many episodes per second and blows past
Better Stack's heartbeat rate limit:

```
WARNING BetterStack heartbeat failed with status code: 429
```

The trainer/sft/orchestrator beat once per batch and stay under the
limit only because of step duration.

## Changes

- `Heartbeat` now rate-limits itself: at most one ping every
`min_interval` seconds (default 30), counted from when a ping *starts*,
so a failed ping (429, network error) throttles retries too instead of
retry-storming on every landed episode.
- New `heartbeat.min_interval` config field (default 30, `> 0`
enforced); `Heartbeat` is constructed from the `HeartbeatConfig` object
directly at all four sites (eval runner, orchestrator, rl/sft trainers).
- Beats that arrive within the interval (or while a ping is in flight)
are dropped without an HTTP request. `beat()` stays non-blocking and
event-driven: no startup ping, and the heartbeat still goes stale when
episodes stop landing.

Better Stack monitors only need pings well within their period + grace,
so pinging at most every 30s loses nothing. Size `min_interval` under
the monitor's period if it is unusually short.

## Verification

- `uv run ruff check` and `uv run ruff format --check` pass on the
touched files.
- Throttle behavior checked with a mocked `requests.get` and fake clock:
first beat pings immediately; in-flight and within-interval beats are
dropped; a beat after the interval pings; a failed 429 ping is not
retried within the interval.
- `uv run pytest tests/unit/test_configs.py tests/unit/eval
tests/unit/utils`: failure set identical before/after the change on this
tree — all 67 pre-existing failures are `ModuleNotFoundError`s for
optional taskset packages in a non-GPU sync.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Observability-only change with a safe default interval; no impact on
training, auth, or data paths beyond fewer external heartbeat HTTP
calls.
> 
> **Overview**
> Fixes Better Stack **HTTP 429** errors when eval runs call `beat()` on
every landed episode while only coalescing concurrent pings.
> 
> **`Heartbeat`** now takes full **`HeartbeatConfig`** (not just the
URL) and enforces **`min_interval`** (default **30s**): surplus `beat()`
calls are dropped with no HTTP request; interval is measured from when a
ping *starts*, so failed pings also throttle retries. In-flight
coalescing is unchanged; `_pending` is cleared in a `finally` block.
> 
> New config field **`heartbeat.min_interval`** (`> 0`, default 30) with
eval config docs updated. Eval runner, orchestrator, and RL/SFT trainers
construct `Heartbeat(config.heartbeat)`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b32a69252b8e393e933952e53e30ea7a9b78d67c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-29 12:38:49 -07:00
88f5e6def1 feat: bump vllm-router to 0.2.2 (#3718)
## Summary

- Bump `vllm-router` from 0.2.1 to
[0.2.2](https://github.com/PrimeIntellect-ai/router/releases/tag/v0.2.2)
(amd64 and arm64 release wheels).
- The new router picks up PrimeIntellect-ai/router#58. The default
health-check interval drops from 60s to 20s, and every health-check
cycle refreshes `/v1/models`. Workers that are still loading at startup
no longer stay under `unknown` and miss model-filtered traffic for
minutes.

## Verification

- `uv lock` resolves with `vllm-router v0.2.1 -> v0.2.2`.
- Installed router reports version `0.2.2` and
`RouterArgs.health_check_interval_secs == 20`.
- Ran 5 steps of `configs/basic/reverse-text/rl.toml` single-node on
SLURM (H200) through the router: 5/5 steps, 0% rollout errors, no
tracebacks.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the disaggregated inference routing dependency only, but the
new router changes health-check timing and worker/model discovery
behavior on the critical vLLM serving path.
> 
> **Overview**
> Upgrades the pinned **`vllm-router`** wheels from **0.2.1** to
**0.2.2** for Linux **x86_64** and **aarch64** in `pyproject.toml`, with
matching **`uv.lock`** updates (version, download URLs, and wheel
hashes).
> 
> Installs that use the **`disagg`** extra (and related GPU/disagg
resolution paths) will pull the new router release instead of 0.2.1. No
in-repo application code changes—only dependency resolution.
> 
> The **0.2.2** router (PrimeIntellect-ai/router#58) shortens the
default health-check interval (**60s → 20s**), refreshes
**`/v1/models`** on each health cycle, and avoids workers staying
**`unknown`** while still loading at startup (so model-filtered traffic
is not skipped for long periods).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f8087add142c2f5a8b27b669902335c60d186cc1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 10:04:06 -07:00
JannikStandGitHub 9eacd477f1 fix(docs): reword bare '<=' in scaling.md to avoid MDX parse error (#3713)
## What
A bare `<= 8` in the Expert Parallelism prose of `docs/scaling.md` (line
97) is parsed by MDX as the start of an HTML tag, failing compilation
with:

> `Unexpected character '=' (U+003D) before name, expected a character
that can start a name, such as a letter, '$', or '_'`

This breaks the Mintlify build of the page imported into **public-docs
PR #219** — the preview deploy 404s `/prime-rl/scaling`, so merging #219
before this fix would publish the broken page.

## Change
Reworded `and is <= 8` → `and is at most 8` (one line). Rewording was
chosen over an inline-expression escape (`{'<='}`) because it is robust
in both MDX pipelines and reads naturally in the sentence. Audited the
rest of the file for bare `<`/`>`/`{`/`}` outside code spans: the only
other occurrences are a `>` blockquote (line 185) and an inline `>`
(line 152), both valid MDX; every remaining `<`/`{`/`}` sits inside
backtick code spans.

## Verification
- Compiled with `@mdx-js/mdx@3` (same compiler family Mintlify pins):
  - pre-fix file: `MDX FAIL: Unexpected character '=' ...`
  - fixed file: `MDX OK`
- Rendered meaning is identical to the original sentence.

Blocks #219 (public-docs) — merge this first, then re-run the #219
preview build.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation-only wording change with no runtime or config behavior
impact.
> 
> **Overview**
> Fixes **Mintlify/MDX compilation** for the Expert Parallelism section
in `docs/scaling.md` by rephrasing the EP auto-resolution rule so prose
no longer contains a bare **`<= 8`**, which MDX treats as the start of
an HTML tag and fails to parse.
> 
> The sentence now says the chosen EP degree **is at most 8** instead of
**`is <= 8`**; meaning is unchanged. This unblocks the public-docs
preview for `/prime-rl/scaling` (merge before dependent doc PRs).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fda404ad8bea01b8afbd24b16f32c38d98846d65. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-29 08:04:05 +02:00
JannikStandGitHub 40d130d8f1 feature: prime monitor for SFT trainer (#3614)
## Motivation

Hosted SFT runs (the dedicated FFT path) currently report nothing to the
platform: `SFTConfig.monitors` was the base `MonitorsConfig` (wandb/file
only), so a hosted SFT trainer has no platform run — no metrics, no
billing surface, no "view on platform" link. RL runs get all of this
through `PrimeTrainMonitor` (wired in the RL orchestrator); this PR
gives the SFT trainer the same platform integration.

## What it adds

- **Config**: `SFTConfig.monitors` is now `TrainMonitorsConfig`, so
`[monitors.prime]` (and `--monitors.prime`) is a valid SFT config block.
`monitors.prime.name` defaults to `run.name`, mirroring the
orchestrator's and eval config's name inheritance.
- **Monitor**: `PrimeTrainMonitor.init` learns the SFT registration
shape — base model, no environments (SFT trains on a dataset),
`TrainingSpec(max_steps, batch_size, seq_len)` from the data block, no
rollouts per example, full resolved config dumped to the platform run
record. The RL registration path is unchanged.
- **Trainer** (`trainer/sft/train.py`): passes `monitors.prime` to
`monitors.setup` and calls `monitors.finalize()` after training,
matching the RL trainer's call sites. The existing per-step metric
logging (train loss/perplexity, `optim/lr`, grad norm, throughput,
progress, time) and `[val]` losses now fan out to the platform unchanged
— the platform's existing internal RFT endpoints work as-is.
- **Launcher** (`entrypoints/sft.py`): `build_online_eval_config`
converts the trainer's `TrainMonitorsConfig` into `EvalMonitorsConfig`
for the online-eval process (the platform monitor switches to the
evaluation flavor under the same name). Without this, an `[eval]` +
`[monitors.prime]` run would fail `SFTOnlineEvalConfig` validation.
- **Docs**: platform-monitoring section covers `sft`; SFT launch section
links to it.

Env surface mirrors RL exactly: the monitor reads `$RUN_ID` (attach to
the launcher-pre-created platform run), `$PRIME_API_BASE` and
`$PRIME_API_KEY` — the values the fft chart injects into trainer pods —
and `PRIME_RUNS_MODE=disabled` stays the opt-out. No trainer-side usage
POST is needed: RL's per-step `PI_USAGE_*` billing posts were removed in
#3275; usage/GPU-hours for hosted runs is derived platform-side from the
run record, which the SFT monitor now registers (config dump includes
the deployment topology).

## Tests

- `uv run pytest tests/unit/train/sft/test_prime_monitor.py` — 6 passed
(mocked `prime_runs.init`: registration kwargs for SFT, name
inheritance, W&B project passthrough, `monitors.setup` fan-out of
metrics + finalize, online-eval monitors conversion). This file is
torch-free and runs on macOS.
- `uv run pytest tests/unit/test_configs.py` — identical result to a
clean `origin/main` baseline (67 pre-existing failures on this macOS env
from missing GPU/harness packages — env-dependent, unrelated to this
change; diff of failing tests verified identical).
- `uv run sft @ <minimal sft.toml> --dry-run --monitors.prime` —
resolves; `monitors.prime.name` inherits `run.name` in the resolved
config dump.
- `uv run ruff check` / `ruff format --check` — clean.

Note: the fft validator service picks this schema change up
automatically once a GHCR image is built from a commit containing this
PR (per-image schema venvs install `prime-rl-configs` from the image's
commit). No validator-side change needed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches platform run lifecycle and cross-process shared state on the
run directory; training continues if dashboard record persistence fails,
but incorrect merging could break platform links for SFT+online-eval
runs.
> 
> **Overview**
> Adds **`--monitors.prime` / `[monitors.prime]`** to SFT so hosted runs
register on Prime Lab, stream trainer metrics (including validation),
and call **`monitors.finalize()`** on exit—same flag shape as RL, with
**no rollout episode uploads**.
> 
> **Config wiring:** `SFTConfig.monitors` is **`TrainMonitorsConfig`**;
online eval uses **`EvalMonitorsConfig`** plus
**`build_online_eval_monitors`** so the launcher maps the trainer’s
platform block to **`PrimeEvalMonitorConfig`** for the eval subprocess.
**`monitors.prime.name`** defaults to **`run.name`**. SFT online eval
shares the trainer’s **`run_dir`**; the dashboard platform JSON is
updated via **locked merge**, not separate dirs.
> 
> **`PrimeTrainMonitor`:** For **`SFTConfig`**, registration sends
dataset **`TrainingSpec`** (`max_steps`, `batch_size`, `seq_len`), empty
environments, and the resolved config dump. Docs clarify **best-effort**
finalize (SIGKILL/OOM may skip crash reporting).
> 
> **Concurrency:** Platform **`run.json`** writes use **PID-suffixed
temp files**, a **persistent flock lock** with bounded timeout,
**`update_platform_record` / `_merge_platform_record`**, and
**`asyncio.to_thread`** so eval + trainer don’t clobber each other’s
dashboard link. Lock/storage failures are **logged and skipped**, not
fatal.
> 
> New unit tests cover SFT registration, monitor fan-out, eval monitor
conversion, record merge/lock behavior.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bc33cb262d141c2d788acc5694aec85aea7b9ad4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-29 07:10:43 +02:00
Scott CabrinhaandGitHub 7027f65e5f fix(docker): pin the NIXL wheel build backend (#3720)
## Problem

Image builds on `main` have failed since #3667 merged. Every
`build_image.yaml` run since 2026-09-28 dies in the
`INCLUDE_NIXL_FROM_SOURCE` step, so no amd64/arm64 image is published.
The failing command is the step's own linkage check — the wheel builds
and installs fine:

```
ldd .../.nixl_cu13.mesonpy.libs/plugins/libplugin_UCX.so | grep -q /opt/ucx/lib/libucp.so
```

## Cause

The NIXL wheel build is not reproducible: NIXL's `[build-system]
requires` is an unpinned list, so pip's build isolation resolves the
newest backends at build time.

`meson-python 0.22.0` (uploaded 2026-09-26 08:33Z — after the
from-source images were built 09-25 01:53Z/02:11Z and validated on FFT,
before the first failing main build 09-28 02:35Z) added "support for
removing build RPATH entries added by Meson" plus RPATH/relocation
fixes. NIXL links UCX with bare `-L/opt/ucx/lib -lucp -lucs -luct` and
sets no `install_rpath`, so Meson's build-tree RPATH (the
`RUNPATH=/opt/ucx/lib` the step's comment and the FFT pods' runtime
check rely on) was the only thing making the installed libraries resolve
the image's UCX. 0.22.0 drops it, the check fails, and the registry
image would not resolve `/opt/ucx` at runtime either.

Evidence: identical step text passes on the 09-25 branch builds and
fails on every build from 09-28; the wheels differ by ~3 KB
(rpath/metadata, not content); `origin/main`'s step is unchanged, so the
failure persists.

## Fix

Constrain `meson-python==0.21.1` for the NIXL wheel via `pip wheel
--build-constraint` — the backend the from-source images were validated
with. Same pin in `scripts/install_nixl_from_source.sh`, whose SLURM
path builds the same wheel and drifts the same way.

Also make the linkage check diagnostic: it now prints `readelf -d`
RUNPATH and the `ldd` output before exiting, instead of `grep -q`
failing with no output (the failure above was silent).

## Notes

- Verified without a full image build: the step's shell, joined the way
Docker joins continuations, passes `sh -n` and `bash -n`; the check's
failure path prints diagnostics and exits 1; the skip path
(`INCLUDE_NIXL_FROM_SOURCE=0`) is unchanged.
- Verified with a real build: [run
36518545933](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/36518545933)
(amd64, `fix/nixl-build-constraints` @ 5e3cc4982) passed, image
`commit-5e3cc4982-amd64` pushed. The NIXL step ran
(`INCLUDE_NIXL_FROM_SOURCE=1`) and the linkage check passed; the wheel
is exactly the size of the wheels from the 2026-09-25 builds (3 467 198
bytes, vs 3 470 315 for the failing 0.22.0 build).
- The rest of NIXL's build-system set (`pybind11`, `patchelf`, `pyyaml`,
`build`, `setuptools`) stays unpinned; only the backend whose behaviour
broke is pinned. The constraint file is the lever if we want these
wheels fully reproducible.
- Durable alternative to the pin: set the RPATH explicitly at link time
(`-Wl,-rpath=/opt/ucx/lib` via Meson link args, or `patchelf
--add-rpath` on the installed libraries) so the artifact does not depend
on backend RPATH policy. Not included: it cannot be validated without a
full image build.
2026-09-28 22:47:13 -06:00
eligottsandGitHub d51d0bb84c Delegate prompt metadata to vLLM 0.30 (#3710) 2026-09-28 21:29:41 -07:00
1b929ec184 feat: depend on the prime CLI instead of prime-sandboxes (#3717)
## Summary

- Replace `prime-sandboxes>=0.3.2` with `prime>=0.8.0` in the core
dependencies. `prime` 0.8.0 drops its `verifiers==0.2.0` pin
([prime#940](https://github.com/PrimeIntellect-ai/prime/pull/940)).
`prime-sandboxes` now comes in transitively and stays locked at 0.3.2.
- Remove the separate `uv pip install 'prime>=0.7'` step and its
`verifiers` override from `Dockerfile.cuda`. `uv sync` now installs the
CLI into `/app/.venv` at the locked version.
- Remove the same replay step from the `PRIME_RL_REF` source overlay in
`scripts/docker-entrypoint.sh`.
- Remove `uv tool install prime` from `scripts/install.sh`. `uv sync`
installs the CLI into the project venv.
- Lock changes: add `prime` 0.8.0, `prime-evals` 0.2.4 and
`gitignore-parser` 0.1.13. Bump `prime-traces` 0.0.4 → 0.0.7.

## Verification

- `uv lock` resolves. `uv sync --all-packages --locked` succeeds.
- `uv run --no-sync prime --version` prints `Prime CLI version: 0.8.0`.
- `verifiers` still imports from the editable `deps/verifiers`.
`prime_rl.configs.orchestrator` imports.

I did not build the image.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how the Prime CLI and sandbox stack are installed in Docker
and dev venvs; wrong resolution could still break editable `verifiers`
imports, though the explicit override path is gone.
> 
> **Overview**
> **Switches the project’s direct dependency from `prime-sandboxes` to
the `prime` CLI (`>=0.8.0`)**, so the CLI is installed via `uv sync` at
the locked version instead of a separate install path. `prime-sandboxes`
remains available transitively through `prime`.
> 
> **Removes the Docker/runtime workaround** that ran `uv pip install
'prime>=0.7'` with a `verifiers` overrides file after sync (in
`Dockerfile.cuda` and `scripts/docker-entrypoint.sh`). That existed
because older CLI versions pinned `verifiers==0.2.0` and could replace
the editable `deps/verifiers` wheel; `prime` 0.8.0 drops that pin.
> 
> **Simplifies local setup** by dropping `uv tool install prime` from
`scripts/install.sh`—developers use `uv run prime` from the project
venv.
> 
> Lockfile updates add `prime` 0.8.0 and its new deps (`prime-evals`,
`gitignore-parser`) and bump `prime-traces` to 0.0.7.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
696ae027e29ff470d9f7d40a0d82e3797704f2a1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 19:39:40 -07:00
d72e7e8b1e feat: bump vllm to 0.30.0 (#3716)
## Summary

- Bump vLLM to
[v0.30.0](https://github.com/vllm-project/vllm/releases/tag/v0.30.0).
- Bump the `nvidia-cutlass-dsl` override to 4.7.1. vLLM 0.30.0 and its
quack-kernels 0.6.5 require it.
- Set `--enable-scale-out` on the inference server. vLLM 0.30.0 no
longer registers `/inference/v1/generate` on `vllm serve` without it,
and the orchestrator generates through that endpoint. Set
`inference.vllm.enable_scale_out = false` to opt out.
- Remove two DeepSeek V4 patches that upstream now covers:
- `monkey_patch_deepseek_v4_per_layer_rope`: fixed by
vllm-project/vllm#54815. The reference RoPE test now checks upstream
directly.
- `monkey_patch_deepseek_v4_bf16_o_proj`: upstream
`deep_gemm_fp8_o_proj` has a bf16 path since vllm-project/vllm#56228.

The other patches in `prime_rl/inference/patches.py` stay: their
upstream code is unchanged, or the upstream fix is not released yet.

## Relevant upstream changes

- vllm-project/vllm#54901: MRV2 compacts sampling masks on the GPU. This
fixes an about 2x RL step-time regression with `--return-sampling-mask`.
- vllm-project/vllm#53187: `/inference/v1/generate` returns prompt
metadata. This unblocks #3710.
- vllm-project/vllm#52957: pause and sleep no longer run 32 dummy
forwards per DP rank.
- vllm-project/vllm#56706: fixes stale QK-norm weights after a weight
refit.
- vllm-project/vllm#51485: sleep mode releases NCCL communicator memory.
- vllm-project/vllm#54646: MRV2 CUDA graph capture freezes gc (engine
init 28.9s → 8.2s on H200).
- vllm-project/vllm#54518: NIXL no longer asserts when it cleans up a
failed transfer twice.
- vllm-project/vllm#55548: rsLoRA scaling in MoE expert packing.

## Verification

Ran 5-step RL smoke runs on SLURM (H200) against this branch:

- `configs/basic/reverse-text/rl.toml`, single-node (1 trainer GPU + 1
inference GPU): 5/5 steps, no errors.
- `configs/basic/reverse-text/rl.toml`, multi-node (1 trainer node + 1
inference node): 5/5 steps, no errors.
- `examples/advanced/glm-4.5-air/swe.toml` (2 trainer nodes, 4 × TP8/EP
inference replicas, router replay), with `batch_size = 32`, `group_size
= 8`, and no eval, checkpoint, or wandb. Ran the same config on `main`
(vLLM 0.29.0) for comparison:

| | main (vLLM 0.29.0) | this branch (vLLM 0.30.0) |
|---|---|---|
| Steps completed | 5/5 | 5/5 |
| Tracebacks | 0 | 0 |
| Mismatch KL | 1e-4 – 2e-4 | 1e-4 – 2e-4 |
| Grad norm | 0.33 – 0.87 | 0.26 – 0.44 |
| Reward (steps 1–5) | 0.28, 0.31, 0.13, 0.34, 0.34 | 0.34, 0.34, 0.38,
0.25, 0.41 |
| Trainer peak memory | 110 – 112 GiB | 110 – 113 GiB |

Both runs have a few `scaleswe` harness-setup failures (`uv python find
--script` is unsupported by the sandbox image's uv). This is a verifiers
runtime issue and is independent of the vLLM version.

Unit tests: `tests/unit/inference` and `tests/unit/test_configs.py` pass
(212 tests).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Major inference-engine upgrade touches RL generation, router replay,
and DeepSeek V4 serving; remaining monkey patches and new scale-out
default can change runtime behavior across deployments.
> 
> **Overview**
> **Bumps the GPU inference stack from vLLM 0.29.0 to 0.30.0**,
including lockfile updates for CUTLASS DSL 4.7.1, quack-kernels 0.6.5,
FlashInfer 0.6.18.post1, and huggingface-hub 1.32.0 on Linux.
> 
> **Inference defaults:** vLLM args now turn on **`enable_scale_out`**
when not overridden, so `/inference/v1/generate` stays available for the
orchestrator under 0.30 (opt out with `inference.vllm.enable_scale_out =
false`).
> 
> **Patch cleanup:** Removes
**`monkey_patch_deepseek_v4_per_layer_rope`** and
**`monkey_patch_deepseek_v4_bf16_o_proj`** because upstream 0.30 covers
those paths; DeepSeek V4 RoPE unit tests assert against stock
`build_deepseek_v4_rope` instead of the old monkey patches.
> 
> **Docs:** Router-replay text no longer pins “vLLM 0.29”; it states
standard deployments use the V2 runner.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3c6229d9b08a7f32f74d5cab1dfd1fbb83c43482. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 18:45:39 -07:00
2662c9ace1 feat: select taskset tasks per train and eval source (#3703)
## Summary

- Give every train and eval source a `select` block (`EnvConfig.select`,
a `vf.SelectConfig`): `include`/`exclude` by task `idx`, `ids`, `keys`
or `names`, then `shuffle`, `skip` and `limit`. The orchestrator loads
each source's tasks with `vf.load_taskset(...).select(source.select)`.
prime-rl no longer shuffles or slices tasksets itself, so it picks the
same tasks as `vf-eval` for the same selection.
  ```toml
  [[orchestrator.train.source]]
  env.taskset.id = "gsm8k"
  select.exclude.idx = [":100"]   # hold out the first 100 tasks

  [[orchestrator.eval.source]]
  env.taskset.id = "gsm8k"
  select.include.idx = [":100"]
  ```
- Every source group (`[orchestrator.train]`, `[orchestrator.eval]`, SFT
`[eval]`, the top level of `uv run eval`) takes a shared `select` block.
The same before-validator that layers the group `env` block layers it
under each source, field by field, and a field that the source sets
wins. A source's `include` or `exclude` replaces the group's whole
block. A source `select` that does not validate keeps its own block, so
its error surfaces. For example, this evaluates 128 tasks of each
taskset:
  ```toml
  [orchestrator.eval.select]
  limit = 128
  ```
- Only `uv run eval` has the `-n`/`-s` short flags
(`select.limit`/`select.shuffle`), through `vf.SelectCLIConfig`. The
`rl`, `orchestrator` and `sft` CLIs have several `select` blocks, so
they get no short flags.
- The dashboard derives the expected episode count from `select.limit`,
per source and for vf-shaped configs.
- Migrate the configs, examples and docs from `num_examples` to
`select.limit`. Group-level blocks use `[... .select]` tables.
- Update the eval docs and skill: resume no longer checks the config
(#3690), and a resume matches landed episodes to the new `select` by
`task.key`.
- Update the `configs` skill (`[select]`, `-s`). Update the eval skill:
the `select` shorthands, and common patterns (a random subset, tasks by
position or name, dropping broken tasks, contiguous and random
train/test splits via `include`/`exclude` and `skip`).
- Pin `deps/verifiers` to its main, which merged
PrimeIntellect-ai/verifiers#2695 (`Taskset.select`, `vf.SelectConfig`).
Raise the `verifiers` minimum to `0.3.2.dev152`, its first release, in
both `pyproject.toml` files, so the slim `prime-rl-configs` install gets
it.

Companion PRs: PrimeIntellect-ai/verifiers#2695 (merged),
PrimeIntellect-ai/prime-envs#852 (independent; `compile_statements`
stops calling `head()`).

## Breaking

- `EnvConfig.shuffle` is removed. Use `select.shuffle`.
- `EvalSourceConfig.num_examples` and the group-level `num_examples` are
removed. Use `select.limit` on the source or on the eval block.
- The shuffle seed changes from 42 to verifiers' default 0
(`select.seed`). Existing `shuffle = true` configs pick other tasks, so
eval numbers before and after this change are not comparable.
- Default task keys change for tasksets that never set `idx` (see
verifiers#2695). An interrupted eval of such a taskset cannot resume
across this change.

## Verification

- The slim-install CI check, run locally: the `prime-rl-configs` wheel
installed outside the workspace resolves `verifiers 0.3.2.dev152`, and
the workflow's import script passes.
- `uv run pytest tests/unit/test_configs.py tests/unit/eval
tests/unit/orchestrator tests/unit/test_dashboard_timeline.py`: 296
passed (2 vLLM-only tests deselected; `vllm` is not installed on the
test box). `test_load_configs` loads every migrated TOML.
- Real configs and CLI calls against a local mock OpenAI server (no
inference spend). The mock counted the model calls, and the selected
task `idx` matched an independent oracle:
- `uv run eval @ configs/debug/eval/single-turn.toml`: tasks 0–7 × 2, 16
calls.
- `uv run eval @ configs/debug/eval/resume.toml`: first run 16 calls.
`--resume --select.limit 10` restored 16 episodes and ran only tasks 8–9
(4 calls). `--resume --select.include.idx 0:5` kept the landed episodes
of tasks 0–4 and made no model calls.
- `uv run eval gsm8k -n 4 -s --select.exclude.idx '[0]'`: the oracle's 4
tasks, 4 calls.
- A two-source TOML that splits gsm8k into `[:50]` and the rest under a
group `select` default: both sources match the oracle, 5 calls.
- Config checks: train and eval group `select` defaults reach every
source, a source's own fields win, and the resolved `OrchestratorConfig`
re-validates to the same values. `uv run rl -h`, `orchestrator -h` and
`sft -h` list no `-n`/`-s`; `uv run eval -h` does.
- `uv run rl --dry-run` on `configs/debug/algo/grpo.toml`,
`examples/basic/reverse-text/rl.toml` and
`configs/debug/multi-env/rl.toml`, and `uv run sft --dry-run` on
`examples/basic/reverse-text/sft.toml`: group eval limits (128, 64, 32)
resolve onto each source, a per-source `select.limit = 256` is kept, and
train sources default to all tasks.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking config renames and verifiers-driven
selection/shuffle/task-key semantics affect every train/eval run and
eval resume comparability across the upgrade, though runtime logic is
largely delegated to verifiers.
> 
> **Overview**
> Replaces **`num_examples`** and per-source **`shuffle`** with
verifiers' **`select`** block on every train/eval source (and
group-level `[select]` / `[orchestrator.eval.select]` /
`[eval.select]`). **`select.limit`** caps how many tasks run;
**`include`/`exclude`**, **`shuffle`**, **`skip`**, and **`seed`**
follow verifiers' ordering so prime-rl matches **`vf-eval`** for the
same selection.
> 
> The orchestrator now loads tasks with
**`vf.load_taskset(...).select(source.select)`** instead of client-side
shuffle (seed 42) and **`islice`**. Group config merging layers shared
**`select`** onto each source like **`env`**. **`uv run eval`** maps
**`-n`/`-s`** to **`select.limit`/`select.shuffle`**; eval resume no
longer validates config against the interrupted run—landed episodes are
matched by **`task.key`** to the new **`select`**.
> 
> All example/debug/CI TOMLs, docs, and skills are migrated.
**`verifiers`** minimum is raised to **`0.3.2.dev152`**. The dashboard
expects **`select.limit`** when estimating episode counts.
> 
> **Breaking:** rename configs from **`num_examples`** →
**`select.limit`**, **`shuffle`** → **`select.shuffle`**; default
shuffle seed and task keys may differ from pre-change runs
(resume/comparability implications).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f30798a0a6d20e3a474cb58a6dd48a8a85eb6ace. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 15:39:41 -07:00
NeoandGitHub cde3bcd546 Add new chunked loss impl based on torchtitan (#3673)
Port of torchtitan based chunked loss, which greatly imporves perf on
hopper for smaller models:

<html>
<head>

</head>
<body>
<html>
<head>

</head>
<body>

Model | Old chunked head | New chunked head | Gain
-- | -- | -- | --
Qwen3-30B-A3B, 8×H200, no AC, chunk 1024 | 6.71s | 6.20s | −7.6% step
time (+8.2% throughput)
Qwen3-235B-A22B, 4×8 H200, full AC, chunk 2048 | 14.09s | 14.00s | −0.6%
step time


</body>
</html>


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core LM-head autograd and SFT loss computation; RL/temperature
paths are mostly untouched but shared head code affects all training
modes using injected heads.
> 
> **Overview**
> Adds a **torchtitan-style chunked summed cross-entropy** path on the
fused LM head when `labels` are passed **without** `temperature`, so SFT
no longer fakes unit temperature and negates logprobs (or materializes
full logits on the vanilla path).
> 
> **`FusedOutputLinear`** now branches: no temperature →
`_ChunkedCrossEntropySumFn` returns scalar `loss` and folds
softmax-minus-one-hot grads into hidden/weight during forward (one token
chunk’s full-vocab logits at a time; backward only scales by the
upstream scalar). With temperature, behavior stays on the existing
logprob/entropy path.
> 
> **Vanilla and Gemma** heads mirror the same contract
(`cross_entropy_sum` or Gemma’s chunked logprob sum). SFT **`train.py`**
is unified to masked `IGNORE_INDEX` labels and `out["loss"]`. Config
docs now describe SFT fused-head behavior instead of claiming it is
disabled.
> 
> New unit tests check loss and gradients across fused/vanilla/Gemma
heads and chunk sizes, plus that temperature still uses logprobs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c4d2601e4cc55d6a921d80a33d19eb2e1407a230. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-29 00:33:18 +02:00
Xuan-Phi NguyenandGitHub f962e9c104 feat(rl): add PPO and CISPO loss options (#3697)
## Motivation

The trainer exposes IPO and IcePop but has no built-in PPO or CISPO loss
for controlled math-RL comparisons. PPO clips the token importance-ratio
surrogate; CISPO clips a **detached** importance weight multiplying the
current log probability, so an out-of-band ratio still has a policy
gradient. Both need to operate on the trainer's existing eligible-token
masks and optional per-token weights.

## Design

- Add `PPOLossConfig` / `PPOLoss` with a sign-aware clipped surrogate
(`ratio_low=.8`, `ratio_high=1.2` by default). A separate
`max_importance_ratio=1e4` bounds the otherwise unbounded side while
preserving its capped gradient; metrics report clipped and capped
fractions.
- Add `CISPOLossConfig` / `CISPOLoss`:
`-stop_gradient(clip(p_trainer/p_inference, low, high)) * advantage *
log p_trainer` on eligible tokens. The default lower bound `0` disables
lower clipping; the default upper bound is `5`. Metrics report the
clipped fraction.
- Register both as explicit `trainer.loss.type` choices. Existing loss
defaults and model precision fields are unchanged. #3696 is merged into
main and supplies the stable ratio arithmetic used by the new losses.

## Validation completed

- On the pre-restack head, the GPU loss and config suite had **213
passed**, covering PPO/CISPO values, advantage signs, clipping
gradients, masks, and config validation. Focused rerun after metric
cleanup: **4 passed**. Ruff check/format and SLURM dry run passed.
- At the current #3697 head, 192 config tests, a CPU PPO/CISPO
forward/backward smoke check, and Ruff check/format passed. Four focused
PPO/CISPO GPU tensor tests passed on GPU 7 of
`prime-nebius-puku-h200-gpu-059`, covering clipping, gradients, extreme
ratios, and masks. No full model test was run.
- One-node CISPO smoke job `1575` completed two optimizer updates with
finite loss, entropy, and mismatch KL; orchestrator reward was `0.3125`
then `0.4062` on 32 trainable traces per step, with no episode errors.
It was intentionally stopped after that validation: [W&B
run](https://wandb.ai/primeintellect/qwen30b-math/runs/0c0bb28ed7734551b600cbe52253d7f5).

## Ongoing experiment and private TOML provenance

CISPO job on math qwen3-30b-3a is pending validation. The long-run
reward and stability outcome remains pending.
2026-09-28 13:34:56 -07:00
eligottsandGitHub 771953ee01 Train from inline multimodal rollouts (#3320) 2026-09-28 12:59:05 -07:00
Xuan-Phi NguyenandGitHub e3dd67633d fix(rl): stabilize IPO, IcePop, and ref-KL loss masking (#3696)
## Motivation

Packed RL batches can contain masked tokens with invalid or extreme log
probabilities. IPO, IcePop, and ref-KL previously formed importance
ratios before removing those tokens, so a nominally excluded token could
still produce `0 * inf` or `0 * NaN`. Accepted rare actions could also
overflow `exp(log p_trainer - log p_inference)`, including in
mismatch-KL diagnostics.

## Design

- Select eligible tokens before ratio and KL arithmetic; IcePop and
ref-KL also select accepted tokens before exponentiating their policy
terms.
- Compute IPO's absolute probability-difference gate using `exp(max(log
p, log q)) * -expm1(min(log p, log q) - max(log p, log q))`, retaining
the same `eps` decision with better behavior for nearby small
probabilities.
- Add `IPOLossConfig.max_importance_ratio` (default `1e4`) and cap
accepted IPO/ref-KL forward weights while retaining the capped
policy-gradient coefficient. Bound squared-log-ratio terms and mismatch
diagnostics so they remain finite for extreme finite log ratios.
- Keep masked/unmasked diagnostics, namespace ref-KL metrics, and treat
the shared mismatch-KL helper as internal; leave model precision
settings unchanged.

## Validation completed

- GPU loss tests: **17 passed**, including extreme-ratio forward and
gradient cases. Expanded config suite: **205 passed**. Ruff check and
format passed.
- The stacked CISPO and IPOv2 two-update smoke runs both completed with
finite trainer metrics and no episode errors:
[CISPO](https://wandb.ai/primeintellect/qwen30b-math/runs/0c0bb28ed7734551b600cbe52253d7f5),
[IPOv2](https://wandb.ai/primeintellect/qwen30b-math/runs/3ab7fbd7805d4ebca1d7ff2d1dc0cc84).
These validate this fix in downstream training paths; there was no
standalone PR1 training run.

## Ongoing experiments and config provenance

The 300-step CISPO and IPOv2 runs use this fix through stacked commits.
[IPOv2](https://wandb.ai/primeintellect/qwen30b-math/runs/9045de5680a44a1d9a9f6bd84e9c30f2)
is running; the CISPO job is queued for an 8-GPU node. Long-run outcomes
are pending.

The actual run TOMLs at
`docs/study/examples/qwen3-30b-a3b/math16k_slurm.toml`,
`math_cispo.toml`, and `math_ipov2.toml` are **local and uncommitted**.
Relative to the checked-in [advanced math
example](https://github.com/PrimeIntellect-ai/prime-rl/blob/f87fd0eb3372cded4cf6cfb20e41189796354eae/examples/advanced/qwen3-30b-a3b/math.toml),
the shared local base uses one 8-H200 node (2 trainer, 6 inference GPUs)
instead of two trainer plus two inference nodes; 16,384 sequence tokens
and 15,000 completion tokens instead of 32,768 each; EP 2 + Ulysses CP 2
instead of EP 8; batch size 32, zero allowed off-policy steps, and 64
inflight episodes instead of batch size 512, eight off-policy steps, and
1,024 initial inflight episodes (group size 8 is shared); and vLLM TP 2
/ DP 3 instead of TP 8. It runs 300 steps without the example's AIME
eval source. The model, math taskset, AdamW learning rate (`1e-6`), and
W&B project are shared. The private overlays select CISPO
(`ratio_high=5`) or IPOv2 (`eps=.3`, `ratio_cap=5`, entropy floor `.15`)
and point SLURM at this worktree.
2026-09-28 12:24:58 -07:00
Mika SenghaasandGitHub 0a437ae340 fix: bump verifiers and prime-envs for timeouts (#3709)
## Summary

- Bump Verifiers to
[`c35ebd32`](https://github.com/PrimeIntellect-ai/verifiers/commit/c35ebd320126ee17f6a570a4f3fb8ef0fe0b0ae1).
This includes [the merged timeout
fix](https://github.com/PrimeIntellect-ai/verifiers/pull/2697): an unset
agent rollout timeout no longer falls back to four hours.
- Bump prime-envs to
[`565e8a74`](https://github.com/PrimeIntellect-ai/prime-envs/commit/565e8a74c001b25706d7c958f36d7bb0cd504ddc).
Its Lean helper now works with Verifiers' taskset API.

## Breaking

- An unset agent rollout timeout now inherits the task timeout, or has
no separate limit. Set a positive `env.<agent>.timeout.rollout` to
retain a stage limit.
- `env.<agent>.timeout.rollout = 0` is rejected. Remove the field to
request no separate stage limit.

## Verification

- `uv lock --check --offline` passed with the updated submodules.
- A focused UV smoke test confirmed that an unset agent timeout resolves
to no limit, a positive override resolves as given, and zero fails
validation.
- `git diff --check` passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Behavior change to rollout timeout defaults affects how long agent
stages can run; misconfigured envs may run longer or fail validation
until configs are updated.
> 
> **Overview**
> Updates **Verifiers** and **prime-envs** dependency pins to pick up
upstream fixes and API alignment.
> 
> The Verifiers bump fixes agent rollout timeout resolution: an
**unset** `env.<agent>.timeout.rollout` no longer silently defaults to
four hours—it now follows the task timeout or has no separate stage cap.
**`env.<agent>.timeout.rollout = 0` is now invalid**; omit the field
instead of using zero to mean “no separate limit.” Configs that relied
on the old default or zero need an explicit positive rollout timeout if
they still want a stage limit.
> 
> The **prime-envs** bump updates its Lean helper for Verifiers’ taskset
API.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
dead789c54f98ce0e57ab3fe47f9e819a9b802eb. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-28 12:02:31 -07:00
9a55a0899c [ENG-6355] feat(docker): in-place PRIME_RL_REF source overlay for chart pods (#3686)
## Summary

Reworks the entrypoint's `PRIME_RL_REF` runtime source override so the
prime-rl-fft chart can run a branch on hosted FFT without building an
image for it. Inert unless `PRIME_RL_REF` is set; the default `docker
run` / chart path is unchanged.

The hook already existed (#2850) but was tuned for long-lived
containers: it cloned the full repo (~700 MB of `.git`) and `cp -a`'d
the 20 GB baked venv into a per-ref dir before syncing. As a per-pod
startup step that is unusable. Kubernetes `command:` also replaces the
image ENTRYPOINT, so the fft chart never ran this script at all; the
companion chart PR (PrimeIntellect-ai/fft#101) routes every prime-rl
container through it with a dispatcher-pinned sha.

## Changes

- **Shallow fetch by ref.** Fresh `git init` + `fetch --depth 1 origin
<ref>` + `checkout FETCH_HEAD`, then `submodule update --init
--recursive --depth 1` for the same four public submodules
`build_image.yaml` inits. GitHub serves branches, tags and full shas
alike; abbreviated shas are not fetchable and the comment says so. The
checkout is always fresh: a container is, and the fetch is seconds.
- **Sync into the baked venv instead of copying it.**
`UV_PROJECT_ENVIRONMENT=/app/.venv uv sync --inexact --locked ...` from
the checkout, with the same extras list as `Dockerfile.cuda`. uv
re-points the first-party editables at the checkout and reinstalls only
third-party pins that differ; flash-attn, deep-ep, mamba-ssm and friends
stay as baked. The chart's `uv run --no-sync <entrypoint>` commands
resolve the project from the new cwd.
- **Heavy-pin preflight.** Before syncing, compare the checkout's
`uv.lock` against `/app/uv.lock` for torch, torchvision, torchaudio,
triton, vllm, vllm-router, flash-attn, flash-attn-3, flashinfer-python,
tilelang, deep-ep, deep-gemm, mamba-ssm, nixl, prime-kernels and
quack-kernels. Any difference exits with a message to build an image
instead. The validator in fft runs the same check at dispatch
(PrimeIntellect-ai/fft#102); this is the backstop.
- **Pretend versions like the image build.** The shallow submodule
clones carry no tags, so hatch-vcs stamped verifiers/renderers
`0.0.1.dev1` and every `verifiers>=…` floor in the tree was unmet.
Resolve the same versions the Dockerfile does
(`docker-editable-pretend-versions.sh`), bake them into
`fallback-version` and drop the submodules' git metadata so the fallback
applies. (setuptools-scm's per-dist env vars turned out not to be
honored by hatch-vcs.)
- **Replay the image's prime CLI install, with its verifiers pin
overridden.** `Dockerfile.cuda` installs `prime>=0.7` after its lockfile
sync, which pulls prime-traces / prime-sandboxes / openai past the
lock's pins; the `--locked` sync here rolled them back and `prime env
install` could no longer import. The CLI also pins `verifiers==0.2.0`,
which replaces the editable with the PyPI wheel and breaks prime-rl's
own imports (see below). The replayed install passes `--overrides` with
a one-line file containing `verifiers`. **Workaround, marked
`FIXME(prime#940)` in the script:** remove the override once the prime
CLI drops verifiers as a dependency (PrimeIntellect-ai/prime#940),
together with the matching override in `Dockerfile.cuda` (#3705).
- **Git URL rewrite via `GIT_CONFIG_*` env** instead of `git config
--global`, so pods whose `HOME` is not writable by their uid still clone
the ssh-listed submodules.
- **`PRIME_RL_SOURCE_COMMIT`** is exported and logged so runs record
what actually ran.

## Found along the way: published images ship a broken verifiers

Since #3635 (2026-09-22) the Dockerfile's `uv pip install 'prime>=0.7'`
step replaces the submodule verifiers (0.3.x) with the PyPI
`verifiers==0.2.0` wheel that every prime release since 0.6.30 pins. On
the pristine image and on main-built `v0.9.1.dev128`, `uv run --no-sync
orchestrator --help` and `env-server --help` fail at import
(`verifiers.v1` has no `SingleAgentEnvConfig`; no
`set_base_sandbox_labels`). Runs that install a Hub env at pod start
survive by accident, because that install pulls verifiers 0.3.x back in;
baked-env runs like the nightly FFT configs do not, and nightly FFT has
failed daily since 9/24. The same override fixes the Dockerfile in
#3705.

## Verified on telus (namespace `minh-dev`, image built from this branch
at 478481593, later revisions of the script fetched into the same image)

Overlaying main tip `b94487324`, which adds `get_global_moe_stats` to
the trainer model module, a marker the baked source lacks:

| Check | Result |
|---|---|
| depth-1 fetch + four submodules | 9 s |
| container start → pod command, including the CLI install | ~35 s; ~60
s with a Hub env install |
| `prime_rl`, `verifiers`, `renderers` import from the checkout; marker
present in the overlay, absent in `/app/src` | pass, as root and as uid
1000 (`HOME` on an emptyDir, like the chart's env-servers) |
| vllm / torch / flash-attn versions and site-packages mtimes untouched
| pass |
| editables report `verifiers 0.3.2.dev137`, `renderers 0.1.12.dev2` |
pass |
| `prime --version`, `prime env install --help`, `uv run --no-sync prime
env install primeintellect/wordle` | pass; the install swaps the baked
`wordle` for the Hub's and leaves verifiers alone |
| `uv run --no-sync orchestrator --help`, `env-server --help` | pass
(they fail on the pristine image, see above) |
| `uv pip check` | 7 incompatibilities, down from the image's 107: six
are the image's own lockfile inconsistencies (mamba-ssm/tilelang,
torch/cudnn, vllm/transformers, openai-agents/openai and
python-multipart, flash-attn-4/tvm), the seventh is the intentional
`prime requires verifiers==0.2.0` |
| ref whose lock pins vllm 0.28.0 vs the image's 0.29.0 | refused in 9
s, before any sync, naming `flashinfer-python, vllm` |
| a `PRIME_CLI_SPEC` knob tried in one revision | removed: a
caller-supplied env var must not choose what gets installed into a
hosted pod |

Not exercised: a GPU workload through the overlay (the pods were
CPU-only), and the chart path end to end (needs fft#101 deployed).

## Related

- fft: chart `source` values (PrimeIntellect-ai/fft#101) and validator
`source.ref` resolution with the same lockfile preflight
(PrimeIntellect-ai/fft#102).
- platform `sourceRef` on the dedicated run dispatch and `prime train
--ref` / `--pr` follow.
- Dockerfile fix for the verifiers clobbering: #3705.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how chart/FFT pods bootstrap Python when `PRIME_RL_REF` is set
by mutating `/app/.venv` at startup; mis-synced lockfiles or override
logic could break training entrypoints, though heavy-pin preflight and
the default no-ref path limit blast radius.
> 
> **Overview**
> When **`PRIME_RL_REF`** is set, the Docker entrypoint no longer does a
full repo clone and a 20 GB venv copy into `/tmp`. It
**shallow-fetches** the ref (depth‑1 + four submodules), exports
**`PRIME_RL_SOURCE_COMMIT`**, and **`uv sync`s the checkout into the
baked `/app/.venv`** so editables point at the overlay while heavy GPU
wheels stay untouched.
> 
> Startup adds **guardrails and parity with the image build**: compare
checkout vs image **`uv.lock`** for torch/vllm/flash-attn-style packages
and **exit early** if they drift; apply
**`docker-editable-pretend-versions.sh`** so shallow submodules satisfy
`verifiers`/`renderers` floors; **reinstall `prime>=0.7`** with a
**`verifiers` pip override** so the CLI does not clobber editables.
GitHub SSH URLs are rewritten via **`GIT_CONFIG_*`** (writable without a
global git config), and the process **`cd`s into the checkout** instead
of swapping **`VIRTUAL_ENV`** to a per-ref venv.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b2fddf150dcaadfbe66cc7945ac34dac649d2fc6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 10:29:40 -07:00
Andrew KirillovandGitHub 666297d09c Require prime-sandboxes>=0.3.2 (#3682)
Raises the pyproject floor to `prime-sandboxes>=0.3.2` and refreshes the
lock accordingly (resolves 0.3.2, wheel/sdist hashes cross-checked
against PyPI).

## Why

The hosted-eval stress runner bootstraps this repo with `uv sync
--no-dev --frozen`, so the 429-retry fixes in prime-sandboxes 0.3.2
(status-aware backoff on platform API and gateway retries) only reach
eval rollouts through this lock. 0.3.0 satisfied the old `>=0.3.0` floor
indefinitely - `lock-check` enforces consistency, not freshness - so the
behavioral fix could not arrive without either this bump or a new
automation mechanism.

The floor raise (rather than a lock-only refresh) encodes the actual
requirement: the runtime depends on the 429-retry semantics, and any
future lock regeneration can no longer backslide below 0.3.2. Precedent
for this shape: #3571 (`chore: require prime-runs 0.1.3`).

## What changed

- `pyproject.toml`: `prime-sandboxes>=0.3.0` -> `>=0.3.2`
- `uv.lock`: the matching specifier line; the prime-sandboxes resolution
entries already point at 0.3.2

## Validation

- `uv lock --check` passes (581 packages)
- `uv sync --no-dev --frozen` resolves prime-sandboxes 0.3.2
- `uv run pytest tests/unit/eval -v`: 9 passed
- Regenerated with uv 0.12.19 (older uv reorders unrelated lock tables)

Linear: ENG-5966 (eval-based stress testing).
2026-09-28 09:08:05 -07:00
Scott CabrinhaandGitHub 202f108f33 fix(docker): build NIXL from source by default; isolate the prime CLI install (#3667)
## What

- **NIXL from source (default on).** `Dockerfile.cuda` builds NIXL
0.10.1 against the baked `/opt/ucx` (UCX 1.19.1) by default. The wheel
is renamed to `nixl-cu13` before building, and the build asserts the UCX
plugin links `/opt/ucx/lib/libucp.so`.
`scripts/install_nixl_from_source.sh` gets the same rename for the SLURM
path.
- **prime CLI as an isolated uv tool.** It's installed into
`/app/.tools` instead of `uv pip install`-ing it into `/app/.venv`, with
the executable linked into `/app/.venv/bin`. The build asserts the
workspace `verifiers` is still the one installed.

## Why

**NIXL.** The PyPI `nixl-cu13` wheel bundles its own UCX, which
segfaults on the prefill→decode KV transfer (#2883). The existing
`INCLUDE_NIXL_FROM_SOURCE` option was:
1. **Off by default, never enabled in CI.** Every published image ships
the PyPI wheel. On SLURM, research works around this with a
`pre_run_command` reinstall after each `uv sync`.
2. **Broken when enabled.** NIXL 0.10.1's pyproject names the package
`nixl-cu12`, so the `nixl_cu13-*.whl` glob matched nothing.
3. **A no-op even when installed.** The `nixl` shim imports `nixl_cu13`
before `nixl_cu12`, so the source build sat unused. Upstream's
`contrib/build-wheel.sh` renames via `contrib/tomlutil.py --wheel-name
nixl-cu<major>`, and this PR does the same.

The plugin has `RUNPATH=/opt/ucx/lib`, so it doesn't depend on
`LD_LIBRARY_PATH`.

**prime CLI (regression from #3635).** Every `prime` 0.7.x on PyPI pins
`verifiers==0.2.0`. Running `uv pip install 'prime>=0.7'` into the app
venv resolves against it and replaces:
- workspace `verifiers` (0.3.2.dev) → 0.2.0
- `openai` 2.54 → 3.15
- workspace `prime-pydantic-config` → the PyPI one
- `prime-sandboxes` / `prime-traces` → newer versions

As a result, `prime_rl.configs.orchestrator` fails to import (`module
'verifiers.v1' has no attribute 'SingleAgentEnvConfig'`), and every
component crashes at startup. This affects every image built since
#3635.

## Test plan

- [x] Image `commit-0039ddc20-amd64` (NIXL fix only): the build passed,
and inference pods on telus confirmed the UCX plugin links `/opt/ucx`
1.19.1. The run then crashed on the `verifiers` downgrade above.
- [x] On `commit-a1822f7a0-amd64` (pre-#3635): `uv tool install
'prime>=0.7'` gives a working CLI 0.7.5, and `uv run --no-sync prime env
install primeintellect/reverse-text` installs into `/app/.venv`.
`verifiers` still has `SingleAgentEnvConfig`, and `openai` stays at
2.54.0.
- [x] Earlier, a GLM-5.3 10-node P/D run on FFT/telus with the same NIXL
build (installed in-pod): a chat request through the PD router
succeeded, with 1 NIXL KV transfer of 5.65 MB / 18.8 ms and no segfault
(ENG-6348).
- [x] Image `commit-cef7100c7-amd64` (both fixes, newest main): build
passed, including the new workspace-verifiers assertion. The GLM-5.3
10-node P/D run on telus used it with no in-pod bootstrap: the NIXL UCX
plugin links `/opt/ucx` 1.19.1, all components import cleanly, the
PD-router chat request returned correctly, and NIXL KV transfers
succeeded. Prefill also needed `VLLM_USE_BREAKABLE_CUDAGRAPH=0` on vLLM
0.29; that is separate, in #3669.

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

---------

Signed-off-by: Scott Cabrinha <scott.cabrinha@primeintellect.ai>
2026-09-27 19:35:41 -07:00
133 changed files with 3134 additions and 1594 deletions
+25 -25
View File
@@ -137,38 +137,38 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
# Needed for private environments hub auth.
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
# ships its own UCX which segfaults on prefill→decode KV transfer (#2883);
# rebuilding against our UCX is the documented fix. The rename is required: an
# unrenamed source build is `nixl_cu12`, and the `nixl` shim imports nixl_cu13
# (the PyPI wheel) first, so the fix would silently not apply. Libraries carry
# RUNPATH=/opt/ucx/lib, so no LD_LIBRARY_PATH is needed at runtime.
# Opt out via `--build-arg INCLUDE_NIXL_FROM_SOURCE=0`.
#
# FIXME(prime#940): workaround, remove once the prime CLI drops verifiers as
# a dependency (https://github.com/PrimeIntellect-ai/prime/pull/940). The CLI
# pins verifiers==0.2.0, which replaced the editable verifiers synced above
# with the PyPI wheel and left prime-rl's own entrypoints unable to import;
# the --overrides file ignores that one requirement. When removing it, drop
# the overrides file and the --overrides flag, keep the import assertion, and
# make the same change in scripts/docker-entrypoint.sh, which replays this
# step for the runtime source overlay.
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
printf 'verifiers\n' > /tmp/prime-cli-overrides.txt \
&& VIRTUAL_ENV=/app/.venv uv pip install --overrides /tmp/prime-cli-overrides.txt 'prime>=0.7' \
&& rm /tmp/prime-cli-overrides.txt \
&& /app/.venv/bin/python -c 'import pathlib, verifiers; assert pathlib.Path(verifiers.__file__).is_relative_to("/app/deps/verifiers"), verifiers.__file__'
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
# (#2883); rebuilding against our UCX is the documented fix. Only needed for
# the disaggregated P/D path — default off so training-only / single-node
# inference builds are unaffected. Enable via `--build-arg INCLUDE_NIXL_FROM_SOURCE=1`.
ARG INCLUDE_NIXL_FROM_SOURCE=0
# NIXL's [build-system] requires are unpinned, so pip's build isolation picks up
# new backends as they are released. meson-python 0.22.0 stopped keeping Meson's
# build RPATH in wheel libraries, which dropped RUNPATH=/opt/ucx/lib and failed
# the linkage check below on every build. Pin the validated backend.
ARG INCLUDE_NIXL_FROM_SOURCE=1
ARG NIXL_VERSION=0.10.1
RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
VIRTUAL_ENV=/app/.venv uv pip install pip \
&& git clone --depth 1 --branch ${NIXL_VERSION} https://github.com/ai-dynamo/nixl.git /tmp/nixl \
&& cd /tmp/nixl \
&& uv run --no-project --with tomlkit python contrib/tomlutil.py --wheel-name nixl-cu13 pyproject.toml \
&& printf 'meson-python==0.21.1\n' > /tmp/nixl-build-constraints.txt \
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
LD_LIBRARY_PATH=/opt/ucx/lib:/opt/ucx/lib/ucx \
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/app/deps \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu13-*.whl \
&& rm -rf /tmp/nixl /app/deps/nixl_cu13-*.whl; \
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/tmp/nixl-whl \
--build-constraint /tmp/nixl-build-constraints.txt \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /tmp/nixl-whl/nixl_cu13-*.whl \
&& PLUGIN=/app/.venv/lib/python3.12/site-packages/.nixl_cu13.mesonpy.libs/plugins/libplugin_UCX.so \
&& if ! ldd "$PLUGIN" | grep -q /opt/ucx/lib/libucp.so; then \
echo "ERROR: $PLUGIN does not link /opt/ucx/lib. RUNPATH and ldd output:" >&2; \
readelf -d "$PLUGIN" | grep -E 'RUNPATH|RPATH' >&2 || true; \
ldd "$PLUGIN" >&2; \
exit 1; \
fi \
&& rm -rf /tmp/nixl /tmp/nixl-whl /tmp/nixl-build-constraints.txt; \
fi
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
+5 -3
View File
@@ -63,17 +63,19 @@ type = "adamw"
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 32
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
initial_inflight = 1536
max_inflight = 1536
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
+2
View File
@@ -27,6 +27,8 @@ lr = 1e-5
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 8
[orchestrator.train.sampling]
+3 -1
View File
@@ -16,9 +16,11 @@ name = "hendrycks-sanity"
[orchestrator]
batch_size = 128
group_size = 8
seq_len = 8192
[orchestrator.train]
group_size = 8
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset.id = "math-env"
+2
View File
@@ -17,6 +17,8 @@ name = "reverse-text"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.train.sampling]
+3 -1
View File
@@ -22,7 +22,9 @@ lr = 2e-5
[eval]
interval = 25
num_examples = 32
[eval.select]
limit = 32
[eval.sampling]
max_completion_tokens = 1024
+2
View File
@@ -35,6 +35,8 @@ target_modules = [
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.train.sampling]
+2
View File
@@ -19,6 +19,8 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 8
[[orchestrator.train.source]]
@@ -17,6 +17,8 @@ lr = 1e-5
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
+3 -1
View File
@@ -1,8 +1,10 @@
# 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
[select]
limit = 4
[sampling]
max_completion_tokens = 8192
@@ -17,6 +17,8 @@ rank = 8
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
@@ -14,6 +14,8 @@ rank = 8
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
@@ -20,6 +20,8 @@ impl = "custom"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
@@ -22,15 +22,17 @@ name = "ci-rl-opd"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.algo]
[orchestrator.train.algo]
type = "opd"
[orchestrator.algo.teacher]
[orchestrator.train.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
@@ -48,7 +50,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.select]
limit = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
@@ -22,16 +22,18 @@ name = "ci-rl-sft"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.algo]
[orchestrator.train.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
[orchestrator.train.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
@@ -54,7 +56,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.select]
limit = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
@@ -20,6 +20,8 @@ lr = 3e-6
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
@@ -17,6 +17,8 @@ lr = 3e-6
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
@@ -16,6 +16,8 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
+3 -1
View File
@@ -15,9 +15,11 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
group_size = 8
seq_len = 8192
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
max_inflight = 128
+2
View File
@@ -16,6 +16,8 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
+2
View File
@@ -16,6 +16,8 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
+2
View File
@@ -16,6 +16,8 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 512
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
@@ -15,6 +15,8 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
+1 -1
View File
@@ -16,7 +16,7 @@ Minimal end-to-end configs for the algorithms against bundled verifiers envs, us
The policy inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local frozen model (used by `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed_grpo_opd.toml`) is **not** auto-launched — start it manually on GPU 1.
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for `opd`, `[orchestrator.algo.sampling.source]` for `sft` — with `name` + `base_url`. `opsd` declares none (it self-distills against the live policy). prime-rl never hosts them; only the trainable policy's server is managed by the `rl` entrypoint.
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.train.algo.teacher]` for `opd`, `[orchestrator.train.algo.sampling.source]` for `sft` — with `name` + `base_url`. `opsd` declares none (it self-distills against the live policy). prime-rl never hosts them; only the trainable policy's server is managed by the `rl` entrypoint.
## Start the local frozen model
+4 -2
View File
@@ -14,14 +14,16 @@ name = "debug-echo"
[orchestrator]
batch_size = 32
[orchestrator.train]
group_size = 4
# alphabet-sort's feedback arrives as user messages, so train the user role
# instead of echo's tool default.
[orchestrator.algo]
[orchestrator.train.algo]
type = "echo"
[orchestrator.algo.roles.user]
[orchestrator.train.algo.roles.user]
alpha = 0.1
[[orchestrator.train.source]]
+6 -2
View File
@@ -10,9 +10,11 @@ name = "debug-rl"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[orchestrator.renderer]
@@ -29,7 +31,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+6 -2
View File
@@ -10,9 +10,11 @@ name = "debug-max-rl"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.algo]
[orchestrator.train.algo]
type = "max_rl"
[orchestrator.renderer]
@@ -29,7 +31,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+6 -2
View File
@@ -20,9 +20,11 @@ name = "debug-mixed-grpo-opd"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[orchestrator.renderer]
@@ -48,7 +50,9 @@ algo.teacher.base_url = "http://localhost:8001/v1"
[orchestrator.eval]
interval = 5
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+7 -3
View File
@@ -17,12 +17,14 @@ name = "debug-opd"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.algo]
[orchestrator.train.algo]
type = "opd"
[orchestrator.algo.teacher]
[orchestrator.train.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
@@ -41,7 +43,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+7 -3
View File
@@ -17,12 +17,14 @@ name = "debug-opd-lora"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.algo]
[orchestrator.train.algo]
type = "opd"
[orchestrator.algo.teacher]
[orchestrator.train.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
@@ -41,7 +43,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+6 -2
View File
@@ -10,9 +10,11 @@ name = "debug-rae"
[orchestrator]
batch_size = 32
[orchestrator.train]
group_size = 1
[orchestrator.algo]
[orchestrator.train.algo]
type = "rae"
[orchestrator.renderer]
@@ -31,7 +33,9 @@ env.player1.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.select]
limit = 16
[orchestrator.eval.sampling]
max_completion_tokens = 512
+6 -2
View File
@@ -16,10 +16,12 @@ name = "debug-self-distill"
[orchestrator]
batch_size = 32
[orchestrator.train]
group_size = 1
# reverse-text's demo lives in the "answer" column.
[orchestrator.algo]
[orchestrator.train.algo]
type = "opsd"
demo_key = "answer"
@@ -37,7 +39,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+7 -3
View File
@@ -17,13 +17,15 @@ name = "debug-sft"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 4
[orchestrator.algo]
[orchestrator.train.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
[orchestrator.train.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
@@ -46,7 +48,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+7 -3
View File
@@ -17,13 +17,15 @@ name = "debug-sft-lora"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 4
[orchestrator.algo]
[orchestrator.train.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
[orchestrator.train.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
@@ -46,7 +48,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+6 -4
View File
@@ -88,13 +88,15 @@ type = "sign_sgd"
[orchestrator]
batch_size = 128
group_size = 8
max_off_policy_steps = 32
[orchestrator.algo]
[orchestrator.train]
group_size = 8
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
@@ -117,7 +119,7 @@ interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
num_examples = 100
select.limit = 100
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["debug-concurrency"]
+2 -1
View File
@@ -5,7 +5,8 @@
#
# uv run eval @ configs/debug/eval/multi-env.toml
num_examples = 16
[select]
limit = 16
[[source]]
name = "tb2-bash"
+2 -1
View File
@@ -4,7 +4,8 @@
#
# uv run eval @ configs/debug/eval/multi-turn.toml
num_examples = 16
[select]
limit = 16
[[source]]
env.taskset.id = "terminal-bench-2"
+3 -1
View File
@@ -7,9 +7,11 @@
# <Ctrl-C partway>
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug --resume
num_examples = 8
group_size = 2
[select]
limit = 8
[concurrency]
min_inflight = 2
max_inflight = 2
+3 -1
View File
@@ -3,9 +3,11 @@
#
# uv run eval @ configs/debug/eval/single-turn.toml
num_examples = 8
group_size = 2
[select]
limit = 8
[sampling]
max_completion_tokens = 8192
+5 -1
View File
@@ -9,6 +9,8 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.renderer]
@@ -31,7 +33,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 5
num_examples = 64
[orchestrator.eval.select]
limit = 64
[orchestrator.eval.sampling]
max_completion_tokens = 128
+1 -1
+1 -1
+22 -22
View File
@@ -30,7 +30,7 @@ This page covers the math and the configurable algorithmic components: the algor
## The Algorithm Abstraction
A training algorithm in `prime-rl` is configured under `[orchestrator.algo]`, where **`type` names the algorithm** (`grpo`, `opd`, `sft`, …) and the class defaults are its vetted setting. It has two parts:
A training algorithm in `prime-rl` is configured under `[orchestrator.train.algo]`, where **`type` names the algorithm** (`grpo`, `opd`, `sft`, …) and the class defaults are its vetted setting. It has two parts:
1. **Sampling** (`algo.sampling`) — how train rollouts are produced: which model generates them. `source` is a [model reference](#model-references): `"policy"` (the live policy, the default) or an inline frozen hosted model. Group sizing stays on the env config (`group_size`).
2. **The per-token training signal** — credit assignment and loss routing, fused; the algorithm's own parameters sit directly on `algo`. One mapping from a finalized rollout to per-token *(loss component, weight)* pairs — the credit a token gets and the loss that consumes it are two coordinates of the same output. Group-relative algorithms compute credit on the orchestrator and ship per-token advantage streams; reference-KL algorithms query a reference model at batch-ship time (bounded concurrency) and ship its prefill logprobs for the trainer to evaluate against the live policy. The `type` determines which loss component consumes the action tokens (`rl` / `ce` / `ref_kl`) and what happens to env-provided observation tokens in multi-turn rollouts (masked out by default; `echo` trains on them with weighted CE).
@@ -42,17 +42,17 @@ The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, r
`prime-rl` hosts exactly one model: the trainable policy (`[orchestrator.model]`). Every other model an algorithm uses is an external OpenAI-compatible endpoint, declared *inline on the component that uses it*. A model reference is either the string `"policy"` (the live policy) or a frozen hosted model (`name` + `base_url`):
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "opd"
[orchestrator.algo.teacher] # opd's teacher: the frozen model it scores against
[orchestrator.train.algo.teacher] # opd's teacher: the frozen model it scores against
name = "Qwen/Qwen3-32B"
base_url = "http://localhost:8001/v1"
```
Model *roles* are algorithm-local vocabulary — each algorithm names its reference on the field where the model is actually used, and there is no shared `teacher` slot. `opd` declares a `teacher` field (the frozen model whose reverse KL the policy distills toward); `sft`'s teacher *is* its `sampling.source` (the frozen model it imitates); `opsd` self-distills against the live policy and names no model at all. No role exists outside the algorithm that declares it: the dispatcher, sink, and trainer branch on liveness alone, never on what an algorithm calls a model.
So for `opd` set `[orchestrator.algo.teacher]`; for `sft` set `[orchestrator.algo.sampling.source]`; `opsd` needs neither. `opd`'s teacher must be a frozen endpoint — it is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero); `opsd`'s teacher *is* the live policy by definition (self-distillation conditioned on a demonstration), so it exposes no reference to configure.
So for `opd` set `[orchestrator.train.algo.teacher]`; for `sft` set `[orchestrator.train.algo.sampling.source]`; `opsd` needs neither. `opd`'s teacher must be a frozen endpoint — it is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero); `opsd`'s teacher *is* the live policy by definition (self-distillation conditioned on a demonstration), so it exposes no reference to configure.
Liveness is a property of the reference, not of any role: rollouts sampled from `"policy"` get version-salted prefix caches, carry sampling logprobs for importance ratios, and age off-policy as weights update; rollouts and scores from frozen models get a stable prefix cache and never go stale. Frozen models are externally hosted (`base_url` is required) — `prime-rl` never launches or updates them, and each env's algorithm builds its own client pool to the endpoints it declares.
@@ -61,7 +61,7 @@ Liveness is a property of the reference, not of any role: rollouts sampled from
The `algo.type` names the algorithm, and each type's class defaults are its vetted setting — picking a type with no other keys IS the algorithm:
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo" # the default
```
@@ -83,13 +83,13 @@ Every key beyond `type` is visibly your own assembly — there is no preset laye
```toml
# echo on tool AND user feedback tokens, each at its own weight.
# Setting any role replaces the whole table.
[orchestrator.algo]
[orchestrator.train.algo]
type = "echo"
[orchestrator.algo.roles.tool]
[orchestrator.train.algo.roles.tool]
alpha = 0.25
[orchestrator.algo.roles.user]
[orchestrator.train.algo.roles.user]
alpha = 0.05
```
@@ -98,10 +98,10 @@ A new algorithm is a named class in code, not a config that points at an import
Echo also takes an optional user-supplied token filter that narrows the role selection per rollout — e.g. dropping warning lines from tool output, or tokens the sampler found unlikely:
```toml
[orchestrator.algo.filter]
[orchestrator.train.algo.filter]
import_path = "my_module.drop_warnings"
[orchestrator.algo.filter.kwargs]
[orchestrator.train.algo.filter.kwargs]
patterns = ["WARNING"]
```
@@ -116,14 +116,14 @@ Component compatibility is validated at config time: frozen-model sampling can o
### Per-Env Algorithms
Both components resolve per environment. Each env inherits `[orchestrator.algo]` unless it sets its own, so a single run can mix algorithms across envs — e.g. GRPO on math, ECHO on a terminal env:
Both components resolve per environment. Each env inherits `[orchestrator.train.algo]` like any other group default: an env that sets only some params keeps the group's algorithm with those params changed, and an env that sets a different `type` runs its own algorithm. So a single run can mix algorithms across envs — e.g. GRPO on math, ECHO on a terminal env:
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[[orchestrator.train.source]]
name = "math" # inherits the top-level grpo
name = "math" # inherits the group's grpo
env.taskset.id = "math"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
@@ -139,7 +139,7 @@ algo.type = "echo"
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
@@ -159,7 +159,7 @@ Algorithms operate on native verifier artifacts and annotate their message graph
The pipeline drives these through `finalize_episode` and `finalize_group`. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.train.algo.advantage`.
## Async / Off-Policy Training
@@ -323,10 +323,10 @@ This is intentionally simple — it does the right thing for most envs. Write a
A **length penalty** (`length_penalty` on the `grpo`-family algorithms) can be layered on top to discourage rambling. The `linear` penalty subtracts a single `pass_rate`-scaled penalty from each reward before the GRPO baseline, combining output tokens (`num_output_tokens_weight`), input / context tokens (`num_input_tokens_weight`), and turns (`num_turns_weight`) — each normalized by the group's own max for that quantity, with `num_input_tokens_weight` and `num_turns_weight` defaulting to `0.1`.
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
```
@@ -362,7 +362,7 @@ For example, if three solvers receive rewards `[1, 1, 0]` on one proposed proble
Configure which roles are compared within a single proposed problem with `episode_agents`. For `proposer-solver`, that role is `solver`:
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "hierarchical_grpo"
episode_agents = ["solver"]
@@ -388,7 +388,7 @@ Group-relative baselines assume the group is exchangeable attempts by one agent.
`rae` implements SPIRAL's role-conditioned advantage estimation ([arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): each agent keeps an exponential-moving-average baseline of its own rewards, and every trace's advantage is its reward minus its agent's baseline — measured against the *pre-update* baseline (the unbiased order), then folded in at `decay` (SPIRAL's α, default 0.95). The algorithm instance is per-env, so baselines are keyed per (env, agent) — the paper's per (game, role). Advantages are not normalized, and `group_size` is free (RAE needs no sibling rollouts; `group_size = 1` is fine). Baselines live in orchestrator memory and re-warm from 0 over ~`1/(1 − decay)` traces per agent after a restart.
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "rae"
decay = 0.95
@@ -411,8 +411,8 @@ There is no config hook that points at user code — a new credit-assignment sch
# src/prime_rl/orchestrator/algo/my_algo.py
import torch
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.orchestrator.algo.routing import assign_advantages
from prime_rl.orchestrator.train.algo.base import Algorithm
from prime_rl.orchestrator.train.algo.routing import assign_advantages
class MyAlgorithm(Algorithm):
@@ -436,7 +436,7 @@ Curriculum admission and metrics can inspect the resulting graph-native streams
- `opsd` — SDFT: prepend an expert demonstration as a leading system message (`template`, with a `{demonstration}` placeholder) and score the sample under that demo-conditioned context. The sample is scored verbatim (`hint_block + token_ids`, slicing the hint's logprobs back off), so the join is BPE-clean and it's robust to tool/multimodal prompts and any number of turns. The scoring reference *is* the live policy — self-distillation names no teacher. opsd builds its own renderer to tokenize the hint block: the tokenizer is always the live policy's (not configurable — there is no separate model), and only the `renderer` family is settable (defaults to `"auto"`, resolved from the policy tokenizer; set it to match a non-auto policy renderer). The demonstration is read from the example's `info[demo_key]`, falling back to a top-level rollout field of the same name (e.g. `answer`).
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "opsd"
demo_key = "demonstration"
```
+17 -2
View File
@@ -171,16 +171,31 @@ env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — takes an `env` block that each of its sources inherits. A source's own `env` values win. The block holds only the knobs that every env and taskset has: `retries`, `timeout`, `max_concurrent_agents`, `interception`, and `taskset.task` and `taskset.system_prompt`. Ids and agents stay on each source:
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — holds defaults for its sources. Every field that a group and its sources both have is a default: `env`, `sampling`, `select` and `group_size`, plus `algo` on the train group and `interval` on the eval groups of a training run. Each source inherits the fields that its group sets. One rule applies to all of them: nested blocks merge key by key, a source's own values win, and a block whose `type` (e.g. of `algo`) differs from the group's is the source's alone.
```toml
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
type = "grpo"
[[orchestrator.train.source]]
env.taskset.id = "math"
group_size = 32 # this source's own value wins over the group's 16
[orchestrator.eval.env]
retries.max_retries = 3
retries.include = ["ProviderError", "SandboxError"]
timeout.episode = 7200
[orchestrator.eval.select] # evaluate 128 tasks of each taskset
limit = 128
```
`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.
The group `env` block holds only the knobs that every env and taskset has: `retries`, `timeout`, `max_concurrent_agents`, `interception`, and `taskset.task` and `taskset.system_prompt`. Ids and agents stay on each source. `select` picks which tasks of a source's taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit`, in that order.
`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; 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>.*`).
+10 -5
View File
@@ -32,19 +32,21 @@ 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`). `<taskset-id>` cannot be combined with a TOML that defines `[[source]]` blocks; next to one, `--env.<field>` sets the shared [env block](#configuration) instead. `uv run eval -h` lists them.
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`/`-s`/`-r` set `select.limit`/`select.shuffle`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). `<taskset-id>` cannot be combined with a TOML that defines `[[source]]` blocks; next to one, `--env.<field>` sets the shared [env block](#configuration) instead. `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]]`:
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]`, `[select]`, `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
[select] # every source inherits these
limit = 32
[client]
base_url = "http://localhost:8000/v1"
@@ -67,9 +69,12 @@ env.agent.harness.id = "bash"
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
select.include.idx = ["0:30"]
```
Per-source `num_examples`, `group_size` and `sampling` override the top-level defaults. The top-level `[env]` block holds the env knobs that every source inherits (see [Environments](configuration.md#environments)); a source's own `env` values win.
Per-source `group_size` and `sampling` override the top-level defaults. The top-level `[env]` block holds the env knobs that every source inherits (see [Environments](configuration.md#environments)); a source's own `env` values win.
Each field a source sets in its `select` overrides the same field of the top-level `[select]`. `select` picks which tasks of the taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit` (see verifiers' [Selecting tasks](../deps/verifiers/docs/v1/tasksets.md#selecting-tasks)). Train sources take the same `select`.
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.
@@ -85,7 +90,7 @@ 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.
A landed episode counts toward the task with its `task.key`, so `select` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. 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
+1 -1
View File
@@ -287,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.29 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`. Standard deployments use the V2 model runner. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
```toml
[trainer]
+1 -1
View File
@@ -94,7 +94,7 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is <= 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is at most 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
```toml
[trainer.model]
+15 -8
View File
@@ -59,9 +59,9 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|---|---|
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.constant_trainer_batch_size` | Keep trainer batches constant when samples have no training signal, such as zero advantage on all tokens. Enabled by default. Disable it for faster collection with variable trainer batch sizes. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `orchestrator.train.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[orchestrator.train.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
@@ -86,7 +86,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
### Algorithms
The RL entrypoint supports several training algorithms, switched via `[orchestrator.algo]`'s `type` (see [Algorithms](algorithms.md#the-algorithm-abstraction) for the full reference, model references, and per-algorithm customization):
The RL entrypoint supports several training algorithms, switched via `[orchestrator.train.algo]`'s `type` (see [Algorithms](algorithms.md#the-algorithm-abstraction) for the full reference, model references, and per-algorithm customization):
| `algo.type` | Frozen model | Use case |
|---|---|---|
@@ -101,7 +101,7 @@ The RL entrypoint supports several training algorithms, switched via `[orchestra
A new algorithm is a named class in code, not a config — see [Algorithms § Authoring an Algorithm](algorithms.md#authoring-an-algorithm).
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for `opd` (the frozen model scored against), `[orchestrator.algo.sampling.source]` for `sft` (the model it samples from) — each with `name` + `base_url`. `opsd` declares no frozen model: it self-distills against the live policy. The `rl` entrypoint only manages policy inference — start frozen-model servers yourself and point `base_url` at them:
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.train.algo.teacher]` for `opd` (the frozen model scored against), `[orchestrator.train.algo.sampling.source]` for `sft` (the model it samples from) — each with `name` + `base_url`. `opsd` declares no frozen model: it self-distills against the live policy. The `rl` entrypoint only manages policy inference — start frozen-model servers yourself and point `base_url` at them:
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
@@ -182,14 +182,18 @@ uv run sft @ examples/basic/reverse-text/sft.toml --monitors.wandb
Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manages this for you — see [Scaling § SFT and Torchrun](scaling.md#sft-and-torchrun) for non-default layouts; multi-node SFT goes through [SLURM](scaling.md#slurm)).
`--monitors.prime` streams the run to the Prime Intellect platform — see [Platform Monitoring](#platform-monitoring).
### Online Evals
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `num_examples` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `select` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
```toml
[eval]
interval = 25
num_examples = 32
[eval.select]
limit = 32
[[eval.source]]
name = "reverse-text"
@@ -381,6 +385,7 @@ Register a run on the Prime Intellect platform (Prime Lab) and stream training m
```bash
uv run rl @ rl.toml --monitors.prime
uv run sft @ sft.toml --monitors.prime # same flag on the SFT trainer
```
Or set it in TOML:
@@ -390,7 +395,9 @@ Or set it in TOML:
name = "my-experiment"
```
The monitor is a thin layer over the [`prime-runs`](https://github.com/PrimeIntellect-ai/prime/tree/main/packages/prime-runs) SDK (installed as `prime-runs[train]`): it registers the run, streams per-step metrics, uploads every 10th step's episodes (full conversations with rewards and advantages) to the run's sample viewer, and closes the run out. A process that exits without finishing is reported as crashed. Uploaded episodes are keyed to the platform run by the SDK; the orchestrator's own run id (the launcher's `PRL_RUN_ID`) stays on W&B and in the local records.
The monitor is a thin layer over the [`prime-runs`](https://github.com/PrimeIntellect-ai/prime/tree/main/packages/prime-runs) SDK (installed as `prime-runs[train]`): it registers the run, streams per-step metrics, uploads every 10th step's episodes (full conversations with rewards and advantages) to the run's sample viewer, and closes the run out. Finalization is best-effort SDK delivery: a process that exits without finishing is reported crashed when the SDK's atexit hook runs, but an abrupt kill (SIGKILL, OOM, node loss) skips the report and a lost finalize is not retried — the platform owns the terminal state of attached (`RUN_ID`) and managed runs. Uploaded episodes are keyed to the platform run by the SDK; the orchestrator's own run id (the launcher's `PRL_RUN_ID`) stays on W&B and in the local records.
On `sft` the monitor registers the run with the dataset-batched training fields (`max_steps`, `batch_size`, `seq_len`) and streams the trainer's per-step metrics and validation losses; SFT has no rollouts, so no episodes are uploaded.
Requires `PRIME_API_KEY` (`prime login` or the env var) and a team (`PRIME_TEAM_ID`, or the team selected with `prime login`) enabled for external runs. A configured monitor must work: a missing key or a team outside the allowlist fails the launch. `PRIME_RUNS_MODE=disabled` keeps the monitor configured but opens no platform run; `RUN_ID=<id>` attaches to an external run a launcher already created instead of registering a new one. Currently internal-only.
@@ -398,6 +405,6 @@ Requires `PRIME_API_KEY` (`prime login` or the env var) and a team (`PRIME_TEAM_
- **Start small.** Run `examples/basic/reverse-text/rl.toml` end-to-end on 2 GPUs before scaling. If the smoke run finishes cleanly, your install is good.
- **Batch size ≥ 64.** Smaller batches give noisy gradient estimates and the trainer's overhead-per-step dominates throughput. 64 is the practical floor; 128–512 is the range for quick ablations; production RL often runs at 1024+.
- **Group size ≥ 8.** Bigger groups (`orchestrator.group_size`) make it more likely that a task produces a mix of high- and low-reward rollouts, which is what gives the trainer a usable signal — if all rollouts in a group succeed or all fail, the within-group advantage collapses to zero and the trainer learns nothing from that task. Bigger groups also tighten advantage normalization. 8 is the floor; 16–32 is common.
- **Group size ≥ 8.** Bigger groups (`orchestrator.train.group_size`) make it more likely that a task produces a mix of high- and low-reward rollouts, which is what gives the trainer a usable signal — if all rollouts in a group succeed or all fail, the within-group advantage collapses to zero and the trainer learns nothing from that task. Bigger groups also tighten advantage normalization. 8 is the floor; 16–32 is common.
- **Runs never share a directory.** Every launch writes to its own run directory `<output_dir>/<run_name>`, auto-named `<envs>--<model>--<short-id>` by default. Name runs you want to find again or resume with `--run.name <name>`; re-using a name blocks unless you resume or pass `--clean`.
- **Use `--dry-run` before SLURM.** Validators (e.g. CP needs flash-attention) fail fast in dry-run and slow in queue.
+6 -4
View File
@@ -68,9 +68,11 @@ type = "muon"
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 32
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
initial_inflight = 256
max_inflight = 512
@@ -79,10 +81,10 @@ max_inflight = 512
name = "glm-4.5"
thinking_retention = "all"
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
@@ -148,7 +150,7 @@ interval = 20
[[orchestrator.eval.source]]
name = "browsecomp"
num_examples = 500 # full set is 1266; cap eval at 500
select.limit = 500 # full set is 1266; cap eval at 500
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
@@ -83,13 +83,15 @@ type = "sign_sgd"
# --- Orchestrator ---
[orchestrator]
group_size = 16
max_off_policy_steps = 32
[orchestrator.algo]
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
+5 -3
View File
@@ -79,13 +79,15 @@ type = "muon"
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 32
[orchestrator.algo]
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
+5 -3
View File
@@ -69,9 +69,11 @@ type = "muon"
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 32
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
initial_inflight = 256
max_inflight = 512
@@ -80,10 +82,10 @@ max_inflight = 512
name = "glm-4.5"
thinking_retention = "all"
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
+3 -1
View File
@@ -109,9 +109,11 @@ weight_decay = 0.0
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
initial_inflight = 256
max_inflight = 512
+2
View File
@@ -45,6 +45,8 @@ weight_decay = 0.01
[orchestrator]
batch_size = 2048
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
+3 -1
View File
@@ -42,9 +42,11 @@ lr = 1e-6
[orchestrator]
batch_size = 512
group_size = 8
max_off_policy_steps = 8
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
initial_inflight = 1024
+3 -1
View File
@@ -43,9 +43,11 @@ lr = 1e-6
[orchestrator]
batch_size = 512
group_size = 8
max_off_policy_steps = 16
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
initial_inflight = 1024
+3 -1
View File
@@ -32,9 +32,11 @@ freq = 1
[orchestrator]
batch_size = 512
group_size = 16
max_off_policy_steps = 32
[orchestrator.train]
group_size = 16
[[orchestrator.train.source]]
env.taskset.id = "general-agent"
env.taskset.min_tier = 1
+3 -1
View File
@@ -5,9 +5,11 @@
# uv run eval @ examples/basic/alphabet-sort/eval.toml
model = "Qwen/Qwen3-4B-Instruct-2507"
num_examples = 20
group_size = 3
[select]
limit = 20
[client]
base_url = "http://localhost:8000/v1"
+2
View File
@@ -26,6 +26,8 @@ lr = 1e-5
[orchestrator]
batch_size = 256
[orchestrator.train]
group_size = 16
[orchestrator.train.sampling]
+3 -1
View File
@@ -13,9 +13,11 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
group_size = 8
seq_len = 8192
[orchestrator.train]
group_size = 8
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset.id = "math-env"
+3 -1
View File
@@ -5,9 +5,11 @@
# uv run eval @ examples/basic/reverse-text/eval.toml
model = "Qwen/Qwen3-0.6B"
num_examples = 20
group_size = 3
[select]
limit = 20
[client]
base_url = "http://localhost:8000/v1"
+3 -1
View File
@@ -10,6 +10,8 @@ name = "reverse-text"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.train.sampling]
@@ -29,7 +31,7 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text-eval"
num_examples = 256
select.limit = 256
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+3 -1
View File
@@ -15,7 +15,9 @@ lr = 2e-5
[eval]
interval = 25
num_examples = 32
[eval.select]
limit = 32
[eval.sampling]
max_completion_tokens = 1024
+3 -1
View File
@@ -5,9 +5,11 @@
# uv run eval @ examples/basic/wiki-search/eval.toml
model = "Qwen/Qwen3-4B-Instruct-2507"
num_examples = 20
group_size = 3
[select]
limit = 20
[client]
base_url = "http://localhost:8000/v1"
+2
View File
@@ -31,6 +31,8 @@ target_modules = [
[orchestrator]
batch_size = 512
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
+3 -1
View File
@@ -5,9 +5,11 @@
# uv run eval @ examples/basic/wordle/eval.toml
model = "Qwen/Qwen3-1.7B"
num_examples = 20
group_size = 3
[select]
limit = 20
[client]
base_url = "http://localhost:8000/v1"
+2
View File
@@ -16,6 +16,8 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 512
[orchestrator.train]
group_size = 16
[[orchestrator.train.source]]
+2
View File
@@ -13,6 +13,8 @@ num_infer_gpus = 1
[orchestrator]
batch_size = 32
[orchestrator.train]
group_size = 8
[orchestrator.train.sampling]
+3 -1
View File
@@ -1,7 +1,6 @@
max_steps = 20
seq_len = 2048
batch_size = 128
group_size = 16
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -10,6 +9,9 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
project = "reverse-text"
name = "reverse-text"
[train]
group_size = 16
[train.sampling]
max_completion_tokens = 128
+1 -1
View File
@@ -10,7 +10,7 @@ dependencies = [
"renderers>=0.1.11",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.3.2.dev143",
"verifiers>=0.3.2.dev158",
]
[build-system]
@@ -1,9 +1,10 @@
import uuid
from pathlib import Path
import verifiers.v1 as vf
from pydantic import AliasChoices, Field, model_validator
from prime_rl.configs.monitors import EvalMonitorsConfig, MonitorsConfig
from prime_rl.configs.monitors import EvalMonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
@@ -27,11 +28,12 @@ class ServedEvalConfig(EvalSourcesConfig):
rate limiting."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat for the run: one ping per landed episode — the first
"""BetterStack heartbeat for the run: pinged by landed episodes — the first
landed episode is the first beat, so the run's boot never shows up as a
stale-prone silence. When episodes stop landing, the pings stop and the heartbeat
goes stale on Better Stack after its grace period. Size that period + grace above
the longest legitimate gap between episodes."""
stale-prone silence. Pings are throttled to at most one every
``heartbeat.min_interval`` seconds. When episodes stop landing, the pings stop
and the heartbeat goes stale on Better Stack after its grace period. Size that
period + grace above the longest legitimate gap between episodes."""
@property
def env_addresses(self) -> dict[tuple[str, str], str | None]:
@@ -57,14 +59,15 @@ class EvalConfig(ServedEvalConfig):
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
"""Client of the inference server. Defaults to Prime Inference."""
select: vf.SelectCLIConfig = vf.SelectCLIConfig()
"""Task selection that every source inherits (``-n`` sets ``limit``, ``-s`` sets
``shuffle``). Each field a source sets on its own ``select`` wins over this one."""
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."""
@@ -87,9 +90,7 @@ class EvalConfig(ServedEvalConfig):
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."""
landed episodes rejoin the epoch and only the rollouts still owed run."""
log: LogConfig = LogConfig()
@@ -157,8 +158,14 @@ class SFTOnlineEvalConfig(ScheduledEvalConfig, ServedEvalConfig):
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
monitors: EvalMonitorsConfig = EvalMonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``).
``EvalMonitorsConfig``, not the base ``MonitorsConfig``: the launcher
converts the trainer's ``[monitors.prime]`` into a
``PrimeEvalMonitorConfig`` for the online-eval process, and the base
type would drop (or forbid) the prime block at the eval.json
dump/re-parse boundary."""
@model_validator(mode="after")
def auto_setup_broadcasts_dir(self):
@@ -640,6 +640,11 @@ class InferenceConfig(BaseConfig):
if "enable_prompt_tokens_details" not in extra_fields:
namespace.enable_prompt_tokens_details = True
# The orchestrator generates through /inference/v1/generate, a scale-out
# endpoint that vLLM registers only with `--enable-scale-out`.
if "enable_scale_out" not in extra_fields:
namespace.enable_scale_out = True
# vLLM's DeepseekV2-family (and transformers-backend MoE) gates read
# `moe_router_dtype` off the HF config to pick the router logits dtype.
if self.enable_fp32_router_logits:
@@ -1,9 +1,10 @@
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from typing import Annotated, Any, Literal, TypeAlias, get_args
import verifiers.v1 as vf
from pydantic import Field, SerializeAsAny, ValidationError, model_validator
from pydantic import AliasChoices, BaseModel, Field, SerializeAsAny, TypeAdapter, ValidationError, model_validator
from pydantic.fields import FieldInfo
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.algorithm import (
@@ -166,8 +167,8 @@ class EnvConfig(BaseConfig):
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."""
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."""
select: vf.SelectConfig = vf.SelectConfig()
"""Which of the taskset's tasks this source uses: ``include``/``exclude`` by ``idx``, ``ids``, ``keys`` or ``names``, then ``shuffle``, ``skip`` and ``limit``, applied in that order."""
@model_validator(mode="before")
@classmethod
@@ -194,20 +195,32 @@ class EnvConfig(BaseConfig):
return self
def merge_group_env(data: Any) -> Any:
"""Shared ``mode="before"`` body for source groups: layer the group's ``env`` block
under the ``env`` block of each raw source."""
if not isinstance(data, dict) or data.get("env") is None:
return data
try:
shared = vf.SharedEnvConfig.model_validate(data["env"])
except ValidationError:
return data # the ``env`` field reports the errors once, not once per source
data["source"] = [
{**source, "env": vf.merge_env_defaults(shared, source.get("env"))} if isinstance(source, dict) else source
for source in data.get("source") or []
]
return data
def inherit_defaults(defaults: dict[str, Any], source: dict) -> dict:
"""Fill in one raw source with its group's ``defaults`` (field name to validated
group value). A config block such as ``sampling`` is filled in key by key with
``vf.merge_defaults``; a plain value such as ``group_size`` is used only when the
source leaves it unset. The source's own values always win, and a block that the
source passes as an already-built config is kept as is."""
merged = dict(source)
for name, value in defaults.items():
own = source.get(name)
if isinstance(value, BaseModel):
if own is None or isinstance(own, dict):
merged[name] = vf.merge_defaults(value, own)
elif name not in source:
merged[name] = value
return merged
def raw_field(data: dict, name: str, field: FieldInfo) -> tuple[bool, Any]:
"""Whether raw ``data`` sets field ``name``, under its name or an alias (``-r``
arrives as ``r``), and the value it sets."""
alias = field.validation_alias
keys = [name, *(alias.choices if isinstance(alias, AliasChoices) else [alias] if alias else [])]
for key in keys:
if isinstance(key, str) and key in data:
return True, data[key]
return False, None
class StandardSamplerConfig(BaseConfig):
@@ -289,13 +302,14 @@ class TrainSourceConfig(EnvConfig):
"""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."""
"""Rollouts generated per example for GRPO group-relative advantages. Overrides the
train group's ``group_size`` for this env, so envs can use different sizes."""
algo: AlgoConfig | None = None
"""Training algorithm for this env. Inherits from the top-level
``orchestrator.algo`` when unset; set ``type`` (and its params) to give
this env its own algorithm."""
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm for this env: sampling plus the per-token training signal
(credit assignment and loss routing, fused — its ``type`` names the algorithm).
Setting only some params keeps the group's algorithm; a different ``type`` is
this env's own algorithm."""
curriculum: CurriculumConfig | None = None
"""User-authored task sampler and admission gates. The default cycles
@@ -306,9 +320,6 @@ class EvalSourceConfig(EnvConfig):
sampling: EvalSamplingConfig = EvalSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
num_examples: int = -1
"""Eval examples to sample from the dataset. ``-1`` uses all available examples."""
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)."""
@@ -317,37 +328,68 @@ 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."""
"""Step interval at which to evaluate this env."""
class TrainConfig(BaseConfig):
source: list[TrainSourceConfig] = Field(default_factory=list)
"""Training sources."""
class SourceGroupConfig(BaseConfig):
"""A list of sources plus defaults for them.
Any field that both the group and its source type declare (``env``, ``sampling``,
``select``, ``group_size``, ...) is a default. Before validation, each source gets
the group's value for every such field that the group sets:
- a field the source sets itself keeps the source's value;
- a nested block is filled in key by key (``vf.merge_defaults``);
- a block with a different ``type``/``id`` (e.g. another ``algo``) is the source's
alone.
A field the group leaves unset is not passed on, so each group field must default
to the same value as the source field it feeds."""
env: vf.SharedEnvConfig = vf.SharedEnvConfig()
"""Env knobs that every training source inherits: the fields every env and taskset
has, such as ``retries`` and ``timeout``. A source's own ``env`` values win."""
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
"""Env knobs that every source inherits: the fields every env and taskset has, such
as ``retries`` and ``timeout``."""
@model_validator(mode="before")
@classmethod
def resolve_group_env(cls, data):
return merge_group_env(data)
def inherit_group_defaults(cls, data: Any) -> Any:
"""Pass the group's set defaults down into each raw source."""
if not isinstance(data, dict) or not isinstance(data.get("source"), list):
return data
(source_type,) = get_args(cls.model_fields["source"].annotation)
defaults: dict[str, Any] = {}
for name, field in cls.model_fields.items():
if name == "source" or name not in source_type.model_fields:
continue
is_set, raw = raw_field(data, name, field)
if not is_set:
continue
try:
defaults[name] = TypeAdapter(field.rebuild_annotation()).validate_python(raw)
except ValidationError:
continue # the group field reports its own errors once, not once per source
data["source"] = [
inherit_defaults(defaults, source) if isinstance(source, dict) else source for source in data["source"]
]
return data
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
is configured per env, defaulting to elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.source:
if "sampling" not in env.model_fields_set:
env.sampling = TrainSamplingConfig(**group_sampling)
else:
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
env.sampling = TrainSamplingConfig(**merged)
return self
class TrainConfig(SourceGroupConfig):
source: list[TrainSourceConfig] = Field(default_factory=list)
"""Training sources."""
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Sampling that every training source inherits."""
select: vf.SelectConfig = vf.SelectConfig()
"""Task selection that every training source inherits."""
group_size: int = Field(1, ge=1)
"""Rollouts generated per example that every training source inherits unless it
sets its own. ``batch_size`` must be divisible by every source's group size."""
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm that every training source inherits. Defaults to ``grpo``."""
@model_validator(mode="after")
def validate_unique_env_names(self):
@@ -360,46 +402,21 @@ class TrainConfig(BaseConfig):
return self
class EvalSourcesConfig(BaseConfig):
"""Eval sources and the group-level defaults they inherit."""
class EvalSourcesConfig(SourceGroupConfig):
"""Eval sources and the defaults they inherit."""
source: list[EvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources."""
env: vf.SharedEnvConfig = vf.SharedEnvConfig()
"""Env knobs that every eval source inherits: the fields every env and taskset
has, such as ``retries`` and ``timeout``. A source's own ``env`` values win."""
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
"""Shared eval sampling configuration; can differ from training sampling."""
"""Sampling that every eval source inherits; can differ from training sampling."""
num_examples: int = -1
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
select: vf.SelectConfig = vf.SelectConfig()
"""Task selection that every eval source inherits, e.g. ``limit = 128`` to evaluate
128 tasks of each taskset."""
group_size: int = Field(1, ge=1)
"""Default rollouts per example. Can be overridden per env."""
@model_validator(mode="before")
@classmethod
def resolve_group_env(cls, data):
return merge_group_env(data)
@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
"""Rollouts per example that every eval source inherits."""
@model_validator(mode="after")
def validate_non_empty_sources(self):
@@ -428,7 +445,7 @@ class ScheduledEvalConfig(EvalSourcesConfig):
"""Evaluation sources, each with its own step interval."""
interval: int = Field(100, ge=1)
"""Step interval at which to evaluate the model."""
"""Step interval that every eval source inherits."""
skip_first_step: bool = False
"""If True, skip the startup eval that otherwise runs before any
@@ -439,14 +456,6 @@ class ScheduledEvalConfig(EvalSourcesConfig):
crash that left in-flight evals unfinished). By default, assumes a clean
exit where all evals already completed."""
@model_validator(mode="after")
def resolve_env_intervals(self):
"""Per-env intervals inherit the group-level interval."""
for source in self.source:
if "interval" not in source.model_fields_set:
source.interval = self.interval
return self
@property
def intervals(self) -> dict[str, int]:
"""Step interval per eval env, by resolved name."""
@@ -550,12 +559,6 @@ TRAIN_TOP_K_BOUND = 512
class OrchestratorConfig(BaseConfig):
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
assignment and loss routing, fused — its ``type`` names the algorithm).
Defaults to ``grpo``. Override per source via ``[[orchestrator.train.source]]``'s
``algo``."""
model: ModelConfig = ModelConfig()
"""The model being trained: its model fields plus the client of the live
vLLM deployment (``[orchestrator.model] name = ...`` with
@@ -619,9 +622,6 @@ class OrchestratorConfig(BaseConfig):
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight concurrency control (``[orchestrator.concurrency]``)."""
group_size: int = Field(1, ge=1)
"""Output sequences returned per example during training."""
seq_len: int = 2048
"""Training sequence length. Shorter samples are padded; longer samples are truncated."""
@@ -658,20 +658,10 @@ class OrchestratorConfig(BaseConfig):
self.monitors.prime.name = self.monitors.wandb.name
return self
@model_validator(mode="after")
def inherit_env_algorithms(self):
"""Envs without their own algorithm inherit the top-level one.
Declared before any validator that reads ``algo``."""
for env_cfg in self.train.source:
if env_cfg.algo is None:
env_cfg.algo = self.algo.model_copy(deep=True)
return self
@model_validator(mode="after")
def validate_env_algorithms(self):
"""Let each algorithm reject environments it cannot score correctly."""
for env_cfg in self.train.source:
assert env_cfg.algo is not None # resolved by inherit_env_algorithms
env_cfg.algo.validate_env(env_cfg.env)
return self
@@ -682,9 +672,9 @@ class OrchestratorConfig(BaseConfig):
Owned here: every truncating config gets a top-k bound (bounds the sampling
masks); opd/opsd is rejected (full-vocab prefill refs would mix
normalizations). Frozen-source envs sample externally and are exempt."""
policy_samplings = [
env.sampling for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy"
] or ([self.train.sampling] if not self.train.source else [])
policy_samplings = [env.sampling for env in self.train.source if env.algo.sampling.source == "policy"] or (
[self.train.sampling] if not self.train.source else []
)
truncating = [sampling for sampling in policy_samplings if sampling.truncates_distribution()]
if not truncating:
return self
@@ -714,7 +704,7 @@ class OrchestratorConfig(BaseConfig):
for sampling in unbounded:
sampling.top_k = TRAIN_TOP_K_BOUND
algos = [env.algo for env in self.train.source if env.algo is not None] or [self.algo]
algos = [env.algo for env in self.train.source] or [self.train.algo]
if any(algo.type in ("opd", "opsd") for algo in algos):
raise ValueError(
"opd/opsd is not supported with truncated train sampling: reference logprobs are full-vocab "
@@ -727,7 +717,7 @@ class OrchestratorConfig(BaseConfig):
@property
def any_policy_sourced(self) -> bool:
"""True when at least one train env samples rollouts from the live policy."""
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.source)
return any(env.algo.sampling.source == "policy" for env in self.train.source)
@model_validator(mode="after")
def validate_renderer_auto_resolves(self):
@@ -774,18 +764,18 @@ class OrchestratorConfig(BaseConfig):
if not has_rollout_batch and not has_token_batch:
self.batch_size = 128
if self.batch_size is not None and self.batch_size % self.group_size != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
group_sizes = [source.group_size for source in self.train.source] or [self.train.group_size]
if self.batch_size is not None and any(self.batch_size % size for size in group_sizes):
raise ValueError(
f"Batch size {self.batch_size} must be divisible by every train source's group_size {sorted(set(group_sizes))}"
)
for field in ("max_inflight", "initial_inflight"):
value = getattr(self.concurrency, field)
if value is not None and value < self.group_size:
raise ValueError(f"concurrency.{field} must be at least the number of rollouts per example")
# Propagate the top-level ``group_size`` into each train env that didn't set its own.
for env_cfg in self.train.source:
if "group_size" not in env_cfg.model_fields_set:
env_cfg.group_size = self.group_size
if value is not None and value < max(group_sizes):
raise ValueError(
f"concurrency.{field} must be at least the largest train group_size ({max(group_sizes)})"
)
return self
@@ -795,7 +785,6 @@ class OrchestratorConfig(BaseConfig):
for env in self.train.source:
# Policy-sourced rollouts hit our vLLM server; frozen-sourced
# rollouts may hit external OAI endpoints that reject these knobs.
assert env.algo is not None
if env.algo.sampling.source == "policy":
env.sampling.extra_body.setdefault("top_k", -1)
env.sampling.extra_body.setdefault("min_p", 0.0)
@@ -805,9 +794,7 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def validate_policy_top_k_consistency(self):
"""Require one top-k capture mode across the live policy server."""
policy_sources = [
env for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy"
]
policy_sources = [env for env in self.train.source if env.algo.sampling.source == "policy"]
enabled = [env for env in policy_sources if env.sampling.top_k is not None]
disabled = [env for env in policy_sources if env.sampling.top_k is None]
if enabled and disabled:
@@ -618,9 +618,7 @@ class RLConfig(BaseConfig):
on, vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0``,
so eval sampling against the same server must set both."""
policy_samplings = [
env.sampling
for env in self.orchestrator.train.source
if env.algo is not None and env.algo.sampling.source == "policy"
env.sampling for env in self.orchestrator.train.source if env.algo.sampling.source == "policy"
] or ([self.orchestrator.train.sampling] if not self.orchestrator.train.source else [])
if not any(sampling.truncates_distribution() for sampling in policy_samplings):
return self
@@ -10,7 +10,7 @@ from renderers.base import MODEL_RENDERER_MAP
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.monitors import TrainMonitorsConfig
from prime_rl.configs.shared import (
EnvVars,
HeartbeatConfig,
@@ -229,8 +229,8 @@ class SFTConfig(BaseConfig):
log: TrainerLogConfig = TrainerLogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
monitors: TrainMonitorsConfig = TrainMonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
run: RunConfig = Field(default_factory=RunConfig)
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
@@ -249,7 +249,8 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_run_identity(self):
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
default the run directory and W&B run name to it when not set explicitly."""
default the run directory, W&B run name and platform run name to it when not
set explicitly."""
if self.run.name is None:
dataset = str(getattr(self.data, "name", "")).split("/")[-1]
model = self.model.name.split("/")[-1]
@@ -259,6 +260,8 @@ class SFTConfig(BaseConfig):
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
matmul_precision: Literal["highest", "high", "medium"] = "high"
@@ -222,6 +222,11 @@ class HeartbeatConfig(BaseConfig):
url: str
"""URL to send the heartbeat to."""
min_interval: float = Field(30.0, gt=0)
"""Minimum seconds between pings. Beats can arrive far more often (evals beat once
per landed episode); surplus beats are dropped to stay under Better Stack's heartbeat
rate limit. Size it well under the monitor's period."""
class MetricsServerConfig(BaseConfig):
port: int = Field(8000, ge=1, le=65535)
@@ -345,7 +345,7 @@ class ModelConfig(BaseModelConfig):
"""Debugging knobs for the model and distributed training."""
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 8192
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. In SFT the fused head computes the summed cross-entropy and its gradients chunk by chunk, holding one chunk's full-vocab logits at a time."""
@model_validator(mode="after")
def trust_remote_code_only_with_hf(self):
@@ -574,6 +574,9 @@ class IPOLossConfig(BaseConfig):
eps: float = Field(0.3, ge=0)
"""Maximum absolute probability change before a token is masked."""
max_importance_ratio: float = Field(1e4, ge=1, allow_inf_nan=False)
"""Cap the importance weight of accepted tokens while preserving its policy gradient."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
@@ -600,6 +603,41 @@ class IcePopLossConfig(BaseConfig):
return self
class PPOLossConfig(BaseConfig):
type: Literal["ppo"] = "ppo"
ratio_low: float = Field(0.8, gt=0, le=1, allow_inf_nan=False)
"""Lower ratio bound for the clipped surrogate."""
ratio_high: float = Field(1.2, ge=1, allow_inf_nan=False)
"""Upper ratio bound for the clipped surrogate."""
max_importance_ratio: float = Field(1e4, ge=1, allow_inf_nan=False)
"""Cap the unbounded side of the surrogate while preserving its gradient."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
@model_validator(mode="after")
def validate_max_importance_ratio(self):
if self.max_importance_ratio < self.ratio_high:
raise ValueError("max_importance_ratio must be at least ratio_high")
return self
class CISPOLossConfig(BaseConfig):
type: Literal["cispo"] = "cispo"
ratio_low: float = Field(0.0, ge=0, le=1, allow_inf_nan=False)
"""Lower bound for the detached importance weight; zero disables lower clipping."""
ratio_high: float = Field(5.0, ge=1, allow_inf_nan=False)
"""Upper bound for the detached importance weight."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
class CustomLossConfig(BaseConfig):
type: Literal["custom"] = "custom"
@@ -610,7 +648,9 @@ class CustomLossConfig(BaseConfig):
"""Kwargs forwarded to the loss function."""
LossConfig: TypeAlias = Annotated[IPOLossConfig | IcePopLossConfig | CustomLossConfig, Field(discriminator="type")]
LossConfig: TypeAlias = Annotated[
IPOLossConfig | IcePopLossConfig | PPOLossConfig | CISPOLossConfig | CustomLossConfig, Field(discriminator="type")
]
class FakeDataLoaderConfig(BaseConfig):
@@ -107,7 +107,8 @@ def propagate_shared_fields(data: Any) -> Any:
# [monitors.file] leaf. (Bare empty ``[monitors.file]`` block enablement is at the end.)
propagate("monitors.file.path", "trainer.monitors.file.path", "orchestrator.monitors.file.path")
# [monitors.prime] leaf → orchestrator only (the trainer has no platform integration).
# [monitors.prime] leaf → orchestrator only (the RL trainer has no platform
# integration; the SFT trainer does, but it parses SFTConfig directly).
propagate("monitors.prime.name", "orchestrator.monitors.prime.name")
# [tokenizer]. ``chat_template`` also flows to ``inference.vllm`` (vLLM's
+12 -12
View File
@@ -16,7 +16,7 @@ dependencies = [
"transformers==5.6.2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
"prime-sandboxes>=0.3.0",
"prime>=0.8.0",
"prime-runs[train]>=0.1.3",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
@@ -29,7 +29,7 @@ dependencies = [
"rich>=14.0.0",
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"verifiers[harbor]>=0.3.2.dev143",
"verifiers[harbor]>=0.3.2.dev158",
"renderers[multimodal]>=0.1.12.dev2",
"pybase64>=1.4.2",
"orjson>=3.10",
@@ -56,7 +56,7 @@ gpu = [
"torchvision ; sys_platform == 'linux'",
"torchaudio ; sys_platform == 'linux'",
"torchdata>=0.11.0 ; sys_platform == 'linux'",
"vllm>=0.29.0 ; sys_platform == 'linux'",
"vllm>=0.30.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'",
@@ -146,9 +146,9 @@ 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.29.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
# vLLM 0.30.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
"nvidia-cutlass-dsl==4.6.2",
"nvidia-cutlass-dsl==4.7.1",
"transformers==5.6.2",
"torch>=2.13.0",
"openenv-core",
@@ -217,10 +217,10 @@ requires-dist = ["nixl-cu13==0.10.1"]
# so resolve that variant without installing both runtime packages.
[[tool.uv.dependency-metadata]]
name = "nvidia-cutlass-dsl"
version = "4.6.2"
version = "4.7.1"
requires-dist = [
"nvidia-cutlass-dsl-libs-base==4.6.2",
"nvidia-cutlass-dsl-libs-cu13==4.6.2",
"nvidia-cutlass-dsl-libs-base==4.7.1",
"nvidia-cutlass-dsl-libs-cu13==4.7.1",
]
[tool.uv.exclude-newer-package]
@@ -270,12 +270,12 @@ torchao = [
dion = { git = "https://github.com/samsja/dion.git", rev = "6f9242d" }
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.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'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ 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'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.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'" },
+104 -45
View File
@@ -5,67 +5,126 @@ set -e
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
# Allow runtime override of the prime-rl source itself.
# PRIME_RL_REF can be a git tag, branch, or commit hash. PRIME_RL_REPO
# PRIME_RL_REF can be a git tag, branch, or full commit hash. PRIME_RL_REPO
# optionally points at a fork; defaults to the upstream repo.
#
# We clone into a per-ref dir under /tmp, seed the venv from the baked
# /app/.venv so heavy wheels (flash-attn, mamba-ssm, …) survive, then
# `uv sync --inexact` re-installs prime_rl from the override source.
# Workdir + PATH swap so the chart's `uv run trainer/inference/orchestrator`
# resolves the entrypoints from the override venv.
# The ref is fetched shallowly under /tmp and synced INTO the baked
# /app/.venv: uv re-points the first-party editables (prime_rl, verifiers,
# renderers, ...) at the checkout and reinstalls only third-party pins
# that differ from the image's lockfile, so the heavy prebuilt wheels
# (flash-attn, deep-ep, mamba-ssm, ...) are never rebuilt. A container
# starts from a fresh filesystem, so mutating /app/.venv in place is safe.
# The pods of the prime-rl-fft chart run this with a sha pinned by the
# dispatcher; the exported PRIME_RL_SOURCE_COMMIT records what ran.
if [ -n "$PRIME_RL_REF" ]; then
PRIME_RL_REPO="${PRIME_RL_REPO:-https://github.com/PrimeIntellect-ai/prime-rl.git}"
# Slug + content hash for the cache dir name. Slug keeps the path
# Slug + content hash for the checkout dir name. Slug keeps the path
# human-readable; the hash (over repo + ref) prevents collisions
# between distinct refs that slugify the same way (e.g. `feat/foo`
# vs `feat-foo`) and between the same ref on different forks.
REF_SLUG="${PRIME_RL_REF//\//-}"
REF_HASH=$(echo -n "${PRIME_RL_REPO}|${PRIME_RL_REF}" | md5sum | cut -c1-12)
DEST="/tmp/prime-rl-${REF_SLUG}-${REF_HASH}"
# Rewrite ssh://git@github.com URLs to https so submodules listed
# with SSH URLs (deps/verifiers, deps/renderers, deps/research-envs)
# can be cloned from the pod without ssh keys.
git config --global url."https://github.com/".insteadOf "git@github.com:"
if [ ! -d "$DEST/.git" ]; then
echo "[prime-rl] cloning ${PRIME_RL_REPO} for ${PRIME_RL_REF}"
rm -rf "$DEST"
git clone --recurse-submodules "$PRIME_RL_REPO" "$DEST"
# Rewrite git@github.com URLs to https so submodules listed with SSH
# URLs (deps/verifiers, deps/renderers, deps/prime-envs) clone from the
# pod without ssh keys. Via GIT_CONFIG_* rather than `git config
# --global`: the pod's HOME may not be writable by its uid.
export GIT_CONFIG_COUNT=1
export GIT_CONFIG_KEY_0="url.https://github.com/.insteadOf"
export GIT_CONFIG_VALUE_0="git@github.com:"
rm -rf "$DEST"
git init --quiet "$DEST"
git -C "$DEST" remote add origin "$PRIME_RL_REPO"
# Depth-1 fetch of the ref itself: GitHub serves branches, tags and
# full commit shas alike (abbreviated shas are not fetchable), and
# prime-rl's history (~700 MB of .git) is not needed to run it.
echo "[prime-rl] fetching ${PRIME_RL_REF} from ${PRIME_RL_REPO}"
git -C "$DEST" fetch --quiet --depth 1 origin "$PRIME_RL_REF"
git -C "$DEST" checkout --quiet --force --detach FETCH_HEAD
# Same public submodules the image build inits (build_image.yaml);
# a pinned commit that isn't the submodule's branch tip is fetched by
# sha, which GitHub allows.
git -C "$DEST" submodule sync --quiet --recursive
git -C "$DEST" submodule update --quiet --init --recursive --depth 1 -- \
deps/pydantic-config deps/verifiers deps/renderers deps/prime-envs
PRIME_RL_SOURCE_COMMIT=$(git -C "$DEST" rev-parse HEAD)
export PRIME_RL_SOURCE_COMMIT
echo "[prime-rl] source overlay at ${PRIME_RL_SOURCE_COMMIT}"
# Give the verifiers/renderers editables the same versions the image
# build does (Dockerfile.cuda): resolve them with the repo's script
# (git describe, else the highest `>=` floor any pyproject declares),
# then bake them into hatch-vcs's fallback-version and drop the
# submodules' git metadata so the fallback is what gets used. The
# shallow clones carry no tags, so hatch-vcs would otherwise stamp
# them 0.0.1.dev1 and every `verifiers>=…` floor in the tree would be
# unmet.
if [ -f "$DEST/scripts/docker-editable-pretend-versions.sh" ]; then
eval "$(bash "$DEST/scripts/docker-editable-pretend-versions.sh" --shell "$DEST")"
rm -f "$DEST/deps/verifiers/.git" "$DEST/deps/renderers/.git"
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" "$DEST/deps/verifiers/pyproject.toml"
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" "$DEST/deps/renderers/pyproject.toml"
fi
# Always fetch + checkout so mutable refs (branches/tags) pick up new
# commits between pod restarts. No-op for immutable SHAs.
echo "[prime-rl] refreshing ${PRIME_RL_REF}"
git -C "$DEST" fetch --quiet --tags --force origin
git -C "$DEST" checkout --quiet --force "$PRIME_RL_REF"
# Fast-forward to upstream tip when PRIME_RL_REF is a branch name.
# Silently no-ops for SHAs/tags (no `origin/<sha>` exists).
git -C "$DEST" reset --hard --quiet "origin/${PRIME_RL_REF}" 2>/dev/null || true
# Refresh submodules to whatever the parent commit pins. `sync`
# picks up URL changes in .gitmodules between checkouts on cache
# hit; `update --init --recursive` applies the pinned SHAs.
git -C "$DEST" submodule sync --recursive
git -C "$DEST" submodule update --init --recursive
if [ ! -d "$DEST/.venv" ]; then
# Seed from the baked venv so the heavy wheels (flash-attn,
# mamba-ssm, …) don't have to be rebuilt. Plain `cp -a` (no
# hardlinks): a subsequent `uv sync` writes into this tree, and
# hardlinks would leak those writes back into /app/.venv when
# /tmp and /app share a filesystem.
cp -a /app/.venv "$DEST/.venv"
fi
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
# --inexact keeps the seeded venv's pre-built wheels (flash-attn-3,
# deep-ep, mamba-ssm) in place; uv only rebuilds them if the override's
# lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev --all-packages --all-extras --group mamba-ssm )
export VIRTUAL_ENV="$DEST/.venv"
export PATH="$DEST/.venv/bin:$PATH"
# Wheels the in-place sync cannot rebuild: a lockfile that pins any of
# these differently from the image needs a real image build. Fail here
# rather than minutes later inside a half-installed torch. Stdlib only;
# --project /app pins the interpreter to the baked venv whatever the cwd.
uv run --no-sync --project /app python - "$DEST/uv.lock" /app/uv.lock <<'HEAVY_PINS_PY'
import sys
import tomllib
HEAVY = {
"torch", "torchvision", "torchaudio", "triton", "vllm", "vllm-router",
"flash-attn", "flash-attn-3", "flashinfer-python", "tilelang",
"deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels",
}
def pins(path):
with open(path, "rb") as f:
lock = tomllib.load(f)
out = {}
for pkg in lock.get("package", []):
if pkg.get("name") in HEAVY:
source = repr(sorted((pkg.get("source") or {}).items()))
out.setdefault(pkg["name"], set()).add((pkg.get("version"), source))
return out
ref_pins, image_pins = pins(sys.argv[1]), pins(sys.argv[2])
drift = sorted(name for name in HEAVY if ref_pins.get(name) != image_pins.get(name))
if drift:
print(
f"[prime-rl] {sys.argv[1]} pins {', '.join(drift)} differently from the image; "
"the runtime source overlay cannot rebuild these. Build an image for this ref "
"(build_image.yaml) or run it on an image whose lockfile matches.",
file=sys.stderr,
)
sys.exit(1)
HEAVY_PINS_PY
# Sync the checkout into the baked venv. Same extras as Dockerfile.cuda
# so an unchanged lockfile is a no-op for third-party packages (keep
# the two lists in sync). --inexact leaves packages the checkout
# doesn't declare in place instead of uninstalling them.
export UV_PROJECT_ENVIRONMENT=/app/.venv
export VIRTUAL_ENV=/app/.venv
echo "[prime-rl] syncing ${DEST} into /app/.venv"
( cd "$DEST" && uv sync --inexact --locked --no-dev --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 )
# The chart's `uv run --no-sync <entrypoint>` commands resolve the
# project from the cwd; the venv itself stays /app/.venv via
# UV_PROJECT_ENVIRONMENT above.
cd "$DEST"
fi
# Allow runtime override of the verifiers package version.
# VERIFIERS_VERSION can be a git tag, branch, or commit hash. Runs after the
# PRIME_RL_REF swap so when both are set the install lands in the override
# venv (uv pip install targets $VIRTUAL_ENV when exported).
# PRIME_RL_REF overlay so when both are set verifiers is installed last
# (uv pip install targets $VIRTUAL_ENV, which is /app/.venv either way).
if [ -n "$VERIFIERS_VERSION" ]; then
echo "Installing verifiers version: $VERIFIERS_VERSION"
uv pip install --reinstall-package verifiers \
-3
View File
@@ -134,9 +134,6 @@ main() {
source $HOME/.local/bin/env
fi
log_info "Installing prime..."
uv tool install prime
log_info "Syncing virtual environment..."
uv sync --all-extras
+12 -2
View File
@@ -82,6 +82,10 @@ else
fi
cd "$NIXL_SRC"
git checkout "$NIXL_VERSION"
# Name the wheel nixl-cu13 (pyproject says nixl-cu12): the `nixl` shim imports
# nixl_cu13 first, so a nixl_cu12 build would sit unused next to the PyPI wheel.
git checkout -- pyproject.toml
uv run --no-project --with tomlkit python contrib/tomlutil.py --wheel-name nixl-cu13 pyproject.toml
export PKG_CONFIG_PATH="$UCX_INSTALL/lib/pkgconfig"
export LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}"
@@ -90,7 +94,13 @@ export LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:
WHEEL_DIR="$PROJECT_DIR/deps"
mkdir -p "$WHEEL_DIR"
uv pip install pip 2>/dev/null
"$PYTHON" -m pip wheel . --no-deps --wheel-dir="$WHEEL_DIR"
# NIXL's [build-system] requires are unpinned; meson-python 0.22.0 stopped
# keeping Meson's build RPATH in wheel libraries, which drops the link to the
# UCX built above. Constrain the backend to the version these wheels were
# validated with (same pin as Dockerfile.cuda).
printf 'meson-python==0.21.1\n' > "$WORKSPACE/nixl-build-constraints.txt"
"$PYTHON" -m pip wheel . --no-deps --wheel-dir="$WHEEL_DIR" \
--build-constraint "$WORKSPACE/nixl-build-constraints.txt"
WHEEL=$(ls "$WHEEL_DIR"/nixl*.whl | head -1)
WHEEL=$(ls "$WHEEL_DIR"/nixl_cu13-"$NIXL_VERSION"-*.whl | head -1)
echo "=== NIXL wheel built at: $WHEEL ==="
+6 -4
View File
@@ -63,19 +63,21 @@ env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
Each source group (`[orchestrator.train]`, `[orchestrator.eval]`, the `sft` `[eval]` block, the top level of `eval`) holds defaults that its sources inherit: every field that the group and its sources both have (`env`, `sampling`, `select`, `group_size`, plus `algo` on train and `interval` on online eval). Blocks merge key by key, a source's own values win, and a block whose `type` differs is the source's alone.
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). 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).
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]`, `[select]`, `group_size` at the top level, plus the single-source shorthands `uv run eval <taskset-id> --env.<field> <value> -n N -s -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.
**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.train.algo.type max_rl`) or a TOML overlay file.
**vLLM pass-through** — `[inference.vllm]` uses vLLM's own argument names (`model`, `tensor_parallel_size`, `data_parallel_size`, `max_model_len`, ...) and forwards *any* key to the vLLM server, typed by prime-rl or not: `[inference.vllm] max_num_seqs = 256`, or `--inference.vllm.max-num-seqs 256` on the CLI. CLI values are JSON-coerced, so dict-valued vLLM args work as `--inference.vllm.compilation-config '{"cudagraph_mode": "NONE"}'`. Non-vLLM knobs (router, deployment, weight broadcast, kv-cache offload, env vars) stay on `[inference]` itself.
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.train.algo] type = "max_rl"`). Omit `type` to keep the default variant.
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1`, `adv_tau = 1.0`, and `kl_tau = 1e-3`. Omit the section to use these defaults. Set `type = "icepop"` for ratio masking with `ratio_low = 0.2`, `ratio_high = 5.0`, and `adv_tau = 1.0`; IcePop has no separate KL term. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**Algorithms** — `[orchestrator.train.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.train.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Each train source inherits the group algorithm: a source `algo` with a different `type` is its own algorithm (`[orchestrator.train.source.algo] type = "opd"`), and params without a `type` keep the group's algorithm with those params changed. prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.train.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.train.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
+3 -2
View File
@@ -9,11 +9,12 @@ description: Find, start, use, and stop the local run dashboard for metrics, con
What is not obvious from the UI:
- 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.
- Overview and Metrics read the same `monitors/file/metrics.jsonl`. **Overview** is the curated view: a step bar (click a cell for that step's batch), summary tiles (reward per train env and avg@k per eval env, each with the change from its first logged value in the corner; error / truncation / timeout rate; step time), then the sections of the W&B overview (train, eval, stability, inference, performance) with readable panel names (hover a panel's `i` for how it is computed and its raw key). **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.
- The `filter` menu (status, kind, env, outcome) is one state shared by the overview, the traces tab and the trace viewer: an env or outcome set in one applies in all. On the overview it narrows the sections and tiles to that env / kind and, for an eval run, the distributions to that outcome (`ok` / `error`; errored episodes read red).
- 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).
- For an eval run the overview tab shows every env the filter keeps, one block after another when there are several (the progress head names each): 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.
+38 -4
View File
@@ -23,18 +23,20 @@ uv run eval @ eval.toml --monitors.prime # stream eac
- 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.
- Shorthands (single-source runs): `<taskset-id>`, `--env.<field> <value>`, `-n` `select.limit`, `-s` `select.shuffle`, `-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):
Minimal multi-source TOML (the eval block is flattened to the top level; per-source `select`, `group_size`, `sampling` override the top level):
```toml
model = "Qwen/Qwen3-4B"
num_examples = 32
group_size = 4
[select]
limit = 32
[client]
base_url = "http://localhost:8000/v1"
@@ -48,6 +50,38 @@ env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
## Select tasks
`select` picks which tasks of a source's taskset run. The steps apply in a fixed order: `include` and `exclude` (by `idx` position, `ids`, `keys` or `names`), then `shuffle` (under `seed`, default 0), `skip`, `limit`. Set it once for every source of a group (`[select]` in an eval TOML, `[orchestrator.eval.select]`, `[orchestrator.train.select]`), or per source (`select.limit = 50` in a `[[source]]`); a source's own fields win.
```bash
uv run eval gsm8k -n 50 # the first 50 tasks
uv run eval gsm8k -n 50 -s # a random subset of 50 (same tasks every run)
uv run eval gsm8k -n 50 -s --select.seed 1 # another random subset
uv run eval gsm8k --select.include.idx 0:10,42 # tasks by position (ints and Python slices)
uv run eval terminal-bench-2 --select.include.names '["fix-git"]' # tasks by name; `ids` and `keys` work the same
uv run eval terminal-bench-2 --select.exclude.keys '["<task.key>"]' # drop known-broken tasks (keys are on every trace)
```
Disjoint train/test splits from one taskset:
```toml
# contiguous: eval on the first 100 tasks, train on the rest
[[orchestrator.eval.source]]
env.taskset.id = "gsm8k"
select.include.idx = [":100"]
[[orchestrator.train.source]]
env.taskset.id = "gsm8k"
select.exclude.idx = [":100"]
# random: the same shuffle on both sides; eval takes 100, train skips them
# eval: select.shuffle = true, select.limit = 100
# train: select.shuffle = true, select.skip = 100
```
The shuffle comes before `skip` and `limit`, so a larger `limit` extends the same selection: resuming a `-n 50 -s` run with `-n 100` keeps the 50 landed tasks and adds 50 more.
## 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).
@@ -72,4 +106,4 @@ The progress line in `eval.log` counts live rollouts by phase (`- boot 1 · runn
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.
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. Any config may be overridden on resume (`select`/`group_size` change what is owed); keep the model, sampling and env config the same to keep the landed episodes comparable. Env servers are children of the eval process and exit with it.
+46 -21
View File
@@ -81,7 +81,7 @@ _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()
_index_cache: OrderedDict[Path, tuple[int, bytes, list[dict]]] = OrderedDict()
_rows_cache: OrderedDict[Path, tuple] = OrderedDict() # key, rows, entered, by_trace, consumed, last row
_tokenizer_cache: dict[str, object] = {}
_piece_cache: dict[tuple[str, int], str] = {}
@@ -272,13 +272,14 @@ def eval_env(config: dict) -> str | None:
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:
"""What one ``[[source]]`` will produce, from its config alone: without a
``select.limit`` the count is unknown up front unless the source names its tasks."""
taskset = (source.get("env") or {}).get("taskset") or {}
limit = (source.get("select") or {}).get("limit")
tasks = taskset.get("tasks")
if limit is None and not tasks:
return None
return (count if count >= 0 else len(tasks)) * (source.get("group_size") or 1)
return (limit if limit is not None else len(tasks)) * (source.get("group_size") or 1)
def eval_totals(config: dict) -> dict[str, int | None]:
@@ -294,7 +295,7 @@ def eval_total_episodes(config: dict) -> int | None:
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
return ((config.get("select") or {}).get("limit") or 0) * (config.get("num_rollouts") or 0) or None
def run_meta(run_dir: Path) -> dict:
@@ -350,7 +351,6 @@ def run_meta(run_dir: Path) -> dict:
"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": eval_env(config),
"total_episodes": eval_total_episodes(config),
"eval_totals": eval_totals(config),
@@ -1015,8 +1015,15 @@ def timeline_lane(
starts = [span["started_at"] for span in spans if span.get("started_at") is not None]
ends = [span["ended_at"] for span in spans if span.get("ended_at") is not None]
started = started_at if started_at is not None else min(starts or ends, default=None)
terminal = next(
(span["status"] for span in lifecycle if span["status"] in {"cancelled", "failed", "timeout"}),
None,
)
status = (
("completed" if all(span["status"] == "completed" for span in lifecycle + activities) else "running")
(
terminal
or ("completed" if all(span["status"] == "completed" for span in lifecycle + activities) else "running")
)
if branch
else timeline_status(trace)
)
@@ -1207,6 +1214,13 @@ def semantic_context_lanes(
ordered_components = sorted(components, key=lambda component: (component_start(component), component))
cross_edges = [edge for edge in edges if component_for[edge["source_node"]] != component_for[edge["target_node"]]]
# subagent_failed (child -> parent) marks its source; subagent_cancel (parent -> child) its target.
context_outcome = {}
for edge in cross_edges:
if edge["type"] == "subagent_failed":
context_outcome[component_for[edge["source_node"]]] = "failed"
elif edge["type"] == "subagent_cancel":
context_outcome[component_for[edge["target_node"]]] = "cancelled"
created_components = {
component_for[edge["target_node"]]
for edge in cross_edges
@@ -1276,6 +1290,10 @@ def semantic_context_lanes(
default=None,
)
completed = bool(trace.get("is_completed"))
# A cancelled/failed context is done even if the trace as a whole is not.
outcome = context_outcome.get(component)
status = outcome or ("completed" if completed else "running")
ended_at = end if (outcome is not None or completed) else None
label = f"{agent_label} · context {context_index}"
lifecycle = (
[
@@ -1284,8 +1302,8 @@ def semantic_context_lanes(
"label": label,
"track": "lifecycle",
"started_at": start,
"ended_at": end if completed else None,
"status": "completed" if completed else "running",
"ended_at": ended_at,
"status": status,
}
]
if start != float("inf")
@@ -1304,6 +1322,8 @@ def semantic_context_lanes(
"agent": agent_label,
"index": context_index,
}
if outcome is not None:
lane["context"]["outcome"] = outcome
if component in unlinked_components:
lane["context"]["unlinked"] = True
if component in attempt_by_component:
@@ -1446,9 +1466,14 @@ def index_rows(path: Path) -> list[dict] | None:
size = path.stat().st_size
with _lock:
cached = _lru_get(_index_cache, path)
# A resume rewrites/truncates the index (dropped errored rows, then re-grows it),
# so the bytes before the old EOF change: reusing the cache append-only would splice
# stale rows in. Detect it via file_checkpoint, exactly like line_offsets().
if cached and (cached[0] > size or (cached[0] and file_checkpoint(path, cached[0]) != cached[1])):
cached = None
if cached and cached[0] == size:
return cached[1]
rows, read_from = (list(cached[1]), cached[0]) if cached and cached[0] < size else ([], 0)
return cached[2]
rows, read_from = (list(cached[2]), cached[0]) if cached else ([], 0)
with path.open("rb") as f:
f.seek(read_from)
for raw in f:
@@ -1460,7 +1485,7 @@ def index_rows(path: Path) -> list[dict] | None:
break
read_from += len(raw)
with _lock:
_lru_put(_index_cache, path, (read_from, rows))
_lru_put(_index_cache, path, (read_from, file_checkpoint(path, read_from), rows))
return rows
@@ -1521,7 +1546,7 @@ def row_filter(
kind: str | None = None,
env: str | None = None,
episode: str | None = None,
errors_only: bool = False,
ok: bool | None = None,
start: float | None = None,
end: float | None = None,
):
@@ -1538,7 +1563,7 @@ def row_filter(
return False
if episode is not None and row.get("id") != episode:
return False
if errors_only and row.get("ok"):
if ok is not None and bool(row.get("ok")) != ok:
return False
arrival = row.get("arrival") or 0
return not ((start is not None and arrival < start) or (end is not None and arrival >= end))
@@ -1566,7 +1591,7 @@ def list_stream_episodes(
kind: str | None = None,
env: str | None = None,
episode: str | None = None,
errors_only: bool = False,
ok: bool | None = None,
sort: str = "arrival",
order: str = "desc",
offset: int = Query(default=0, ge=0),
@@ -1593,7 +1618,7 @@ def list_stream_episodes(
if upto is not None:
rows = rows[:upto]
envs, kinds = index_facets(run_dir)
keep = row_filter(step=step, kind=kind, env=env, episode=episode, errors_only=errors_only, start=start, end=end)
keep = row_filter(step=step, kind=kind, env=env, episode=episode, ok=ok, start=start, end=end)
if sort == "arrival":
# the index is already in arrival order: walk it from the right end and stop
# once the page is full, so the common view costs a page rather than a run
@@ -1628,7 +1653,7 @@ def episode_histogram(
step: int | None = None,
kind: str | None = None,
env: str | None = None,
errors_only: bool = False,
ok: bool | None = None,
bars: int = Query(default=80, ge=8, le=500),
) -> dict:
"""Episodes finishing per time bin, over the same filters as the table — the
@@ -1636,7 +1661,7 @@ def episode_histogram(
the episodes and the bin is the roundest interval that keeps the bar count sane,
so a run of any length reads the same."""
run_dir = get_run_dir(run)
rows = filter_rows(episode_rows(run_dir), step=step, kind=kind, env=env, errors_only=errors_only)
rows = filter_rows(episode_rows(run_dir), step=step, kind=kind, env=env, ok=ok)
arrivals = sorted(row["arrival"] for row in rows if isinstance(row.get("arrival"), (int, float)))
if not arrivals:
return {"bins": [], "bin": 60, "start": None, "end": None, "total": 0}
File diff suppressed because it is too large Load Diff
+37 -67
View File
@@ -41,25 +41,10 @@
<main>
<section id="tab-overview">
<div class="controls">
<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>
<div id="overview-filter-wrap" class="dd-wrap flt-wrap"></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>
@@ -111,32 +96,7 @@
<button data-mode="stream" class="active" title="every episode, newest first">Stream</button>
<button data-mode="step" title="the cohort shipped at one step">Step</button>
</div>
<div id="trace-filter-wrap" class="dd-wrap">
<button id="trace-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
<span id="trace-filter-count" class="badge" hidden></span>
</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>
<button data-kind="eval" class="on">eval</button>
</div>
</div>
<label class="dd-row"><span class="t-label">env</span>
<select id="trace-env"><option value="">all envs</option></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<div id="trace-filter-wrap" class="dd-wrap flt-wrap"></div>
<select id="trace-sort" title="sort" data-label="sort">
<option value="arrival:desc">arrival ↓</option>
<option value="arrival:asc">arrival ↑</option>
@@ -221,31 +181,7 @@
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
</div>
<div class="tm-head tm-ctlrow">
<div id="tm-filter-wrap" class="dd-wrap">
<button id="tm-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="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>
<button data-kind="eval" class="on">eval</button>
</div>
</div>
<label class="dd-row"><span class="t-label">env</span>
<select id="tm-env"><option value="">all envs</option></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<div id="tm-filter-wrap" class="dd-wrap flt-wrap"></div>
<select id="tm-sort" title="sort" data-label="sort">
<option value="arrival:desc">arrival ↓</option>
<option value="arrival:asc">arrival ↑</option>
@@ -325,6 +261,40 @@
</aside>
</div>
<!-- one filter over every view: the overview, the traces table and the trace viewer
each host a copy, and a change in any of them shows up in all -->
<template id="filter-tpl">
<button class="btn dd-btn flt-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
<span class="badge flt-count" hidden></span>
</button>
<div class="dd-menu dd-filters" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row flt-status-row"><span class="t-label">status</span>
<div class="seg toggle-seg flt-status">
<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 flt-kinds">
<button data-kind="train" class="on">train</button>
<button data-kind="eval" class="on">eval</button>
</div>
</div>
<label class="dd-row"><span class="t-label">env</span>
<select class="flt-env"><option value="">all envs</option></select>
</label>
<div class="dd-row"><span class="t-label">outcome</span>
<div class="seg toggle-seg flt-outcome">
<button data-outcome="ok" class="on" title="episodes that finished without an error">ok</button>
<button data-outcome="error" class="on" title="episodes that errored">error</button>
</div>
</div>
</div>
</template>
<script src="/static/vendor/uPlot.iife.min.js"></script>
<script src="/static/app.js"></script>
</body>
+44 -9
View File
@@ -333,7 +333,7 @@ details.section > summary {
details.section > summary:hover { color: var(--grey-6); border-color: var(--grey-3); }
details.section .sec-chev { margin-left: auto; transition: transform 0.12s; font-size: 10px; color: var(--grey-4); }
details.section[open] .sec-chev { transform: rotate(90deg); }
.chart-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(var(--pane-min, 260px), 1fr)); gap: 12px; }
.chart-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(var(--pane-min, 300px), 1fr)); gap: 12px; }
/* eval runs: running-average stat cards instead of x/y chart panes */
.stat-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; }
.stat-card { background: var(--grey-2); border: 1px solid var(--hairline); padding: 12px 14px; min-width: 0; }
@@ -349,13 +349,17 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
}
.stat-value { font-size: 20px; color: var(--grey-6); margin: 6px 0 0; }
/* eval progress: one cell per expected episode */
.eval-progress { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; }
/* the tab already leaves 12px under its toolbar: 4px more reads as 16px, matching the gap below */
.eval-progress { display: flex; flex-direction: column; gap: 8px; margin: 4px 0 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-pct { font-size: 16px; font-weight: 500; color: var(--grey-6); white-space: nowrap; }
.ep-head .name { font-size: 16px; font-weight: 600; color: var(--grey-6); }
.ep-blocks { display: flex; gap: 2px; height: 28px; }
/* no horizon: fixed cells that wrap, so the bar grows rather than fills */
.ep-row .ep-blocks.open { flex: 0 1 auto; flex-wrap: wrap; height: auto; }
.ep-blocks.open .ep-cell { flex: 0 0 14px; height: 14px; }
.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); }
@@ -366,7 +370,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
/* 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-host { height: var(--pane-h, 170px); margin-top: 6px; }
.swarm { display: block; }
.swarm .sw-bg { fill: transparent; }
.swarm circle { fill: var(--accent); fill-opacity: 0.7; cursor: pointer; }
@@ -398,14 +402,40 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
.tm-line.timeout { fill: var(--timeout); }
.comp-pane [data-part].dim { opacity: 0.2; }
.comp-pane .tm-node.dim { opacity: 0.35; }
/* the summary is one row whatever the count: the tiles share the width equally */
.sum-grid { margin-bottom: 4px; display: grid; grid-template-columns: none; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); gap: 12px; }
/* the summary tiles share the width equally and wrap only once they would squeeze */
.sum-grid { margin-bottom: 4px; display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 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-label { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
/* the headline may break before its change mark when the tile is narrow */
.sum-tile .stat-value { overflow-wrap: anywhere; }
.sum-tile .stat-value { font-size: clamp(16px, 1.7vw, 24px); margin-top: 8px; }
.sum-tile.rate-warn .stat-value { color: #ffd166; }
.sum-tile.rate-bad .stat-value { color: var(--negative); }
.sum-tile.rate-timeout .stat-value { color: var(--timeout); }
/* the change from the base value sits beside the headline */
.tile-delta { display: inline-block; margin-left: 8px; font-size: 11px; color: var(--grey-4); white-space: nowrap; }
.tile-delta.good { color: var(--positive); }
.tile-delta.bad { color: var(--negative); }
/* the overview's panels wear readable names, set like the tile labels; the mark opens how each is computed */
#overview-body .chart-card .chart-title { flex: 0 1 auto; text-transform: uppercase; letter-spacing: var(--track-caps); }
.chart-info {
flex-shrink: 0;
width: 13px;
height: 13px;
border: 1px solid var(--grey-3);
border-radius: 50%;
font: 500 9px var(--font-mono);
line-height: 12px;
text-align: center;
color: var(--grey-4);
cursor: help;
align-self: center;
}
.chart-info:hover { color: var(--grey-6); border-color: var(--grey-5); }
#swarm-tip .tip-note { max-width: 320px; white-space: normal; color: var(--grey-5); margin-bottom: 4px; }
#swarm-tip .tip-key { color: var(--grey-4); font-size: 10px; margin-top: 4px; }
/* several eval envs follow one another, a rule between them */
.eval-env + .eval-env { border-top: 2px solid var(--grey-3); padding-top: 22px; margin-top: 10px; }
.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); }
@@ -456,7 +486,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
text-overflow: ellipsis;
flex: 1;
}
.chart-last { font-size: 12px; font-weight: 500; color: var(--grey-6); }
.chart-last { margin-left: auto; font-size: 15px; font-weight: 600; color: var(--grey-6); }
.chart-empty {
height: 120px;
display: flex;
@@ -893,6 +923,8 @@ mark.hit {
}
.tl-edge-key i.subagent-call { border-color: var(--infra); }
.tl-edge-key i.subagent-return { border-color: var(--risk); }
.tl-edge-key i.subagent-cancel { border-color: var(--negative); border-top-style: dashed; }
.tl-edge-key i.subagent-failed { border-color: var(--negative); }
.tl-edge-key i.compaction-attempt { border-color: var(--chart-2); border-top-style: dotted; }
.tl-edge-key i.compaction { border-color: var(--chart-2); border-top-style: dashed; }
.tl-edge-key i.custom { border-color: var(--accent); border-top-style: dotted; }
@@ -943,6 +975,7 @@ mark.hit {
.tl-state { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
.tl-state.completed { color: var(--positive); }
.tl-state.failed { color: var(--negative); }
.tl-state.cancelled { color: var(--negative); }
.tl-state.timeout { color: var(--timeout); }
.tl-state.running { color: var(--infra); }
.tl-tooltip {
@@ -1014,6 +1047,8 @@ mark.hit {
.sg-edge.continuation { opacity: 0.34; }
.sg-edge.subagent-call { stroke: var(--infra); stroke-width: 2.2; opacity: 0.9; }
.sg-edge.subagent-return { stroke: var(--risk); stroke-width: 2.2; opacity: 0.9; }
.sg-edge.subagent-cancel { stroke: var(--negative); stroke-width: 2.2; opacity: 0.9; stroke-dasharray: 5 3; }
.sg-edge.subagent-failed { stroke: var(--negative); stroke-width: 2.2; opacity: 0.9; }
.sg-edge.compaction-attempt { stroke: var(--chart-2); stroke-dasharray: 2 4; opacity: 0.66; }
.sg-edge.compaction { stroke: var(--chart-2); stroke-dasharray: 5 4; opacity: 0.9; }
.sg-edge.custom { stroke: var(--accent); stroke-dasharray: 2 4; opacity: 0.9; }
+1 -1
View File
@@ -21,7 +21,7 @@ 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]
usage: uv run eval [<taskset-id>] [--env.<field> <value> ...] [-n N] [-s] [-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
+1 -3
View File
@@ -243,9 +243,7 @@ def rl_local(config: RLConfig):
frozen_endpoints: list[str] = []
for env in config.orchestrator.train.source:
algo = env.algo
assert algo is not None, "TrainSourceConfig.algo must be resolved before launch (inherit_env_algorithms)"
for ref in (algo.sampling.source, getattr(algo, "teacher", None)):
for ref in (env.algo.sampling.source, getattr(env.algo, "teacher", None)):
if isinstance(ref, FrozenModelConfig):
frozen_endpoints.append(f"{ref.name} ({ref.base_url})")
if frozen_endpoints:
+17 -1
View File
@@ -9,6 +9,7 @@ from subprocess import Popen
from threading import Event, Thread
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.monitors import EvalMonitorsConfig, PrimeEvalMonitorConfig, TrainMonitorsConfig
from prime_rl.configs.orchestrator import OnlineEvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.shared import LogConfig
@@ -72,6 +73,16 @@ def resolve_resume_step(config: SFTConfig) -> int | None:
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
def build_online_eval_monitors(monitors: TrainMonitorsConfig) -> EvalMonitorsConfig:
"""The online-eval process's monitors: same W&B and file config as the trainer's,
with the platform monitor switched to the evaluation flavor under the same name."""
return EvalMonitorsConfig(
wandb=monitors.wandb,
file=monitors.file,
prime=PrimeEvalMonitorConfig(name=monitors.prime.name) if monitors.prime is not None else None,
)
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
@@ -85,9 +96,14 @@ def build_online_eval_config(config: SFTConfig) -> SFTOnlineEvalConfig:
broadcasts_dir=get_broadcast_dir(config.run_dir),
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
# Same run dir as the trainer: the dashboard reads the eval's
# file-monitor artifacts from the run directory, so a separate
# output dir would hide them. The train-vs-eval record collision
# is resolved by record merging in prime_rl.monitors.prime, not
# by directory separation.
output_dir=config.run_dir,
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
monitors=config.monitors,
monitors=build_online_eval_monitors(config.monitors),
)
return SFTOnlineEvalConfig(**{**eval_config.model_dump(exclude=set(run_fields)), **run_fields})
+1
View File
@@ -47,6 +47,7 @@ class OnlineEval:
await monitors.setup(
producer="online-eval",
wandb=config.monitors.wandb,
prime=config.monitors.prime,
file=config.monitors.file,
output_dir=config.output_dir,
run_config=config,
+1 -1
View File
@@ -84,7 +84,7 @@ class EvalRunner:
# sit inside the ping stream as an abnormally long silence and flip a healthy
# run stale. Until then the heartbeat has simply never been pinged.
if config.heartbeat is not None:
self.heart = Heartbeat(config.heartbeat.url)
self.heart = Heartbeat(config.heartbeat)
# 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
-229
View File
@@ -21,8 +21,6 @@ def apply_shared_vllm_patches():
monkey_patch_online_fp8_parameter_cast()
monkey_patch_deepseek_v4_allowed_layer_types()
monkey_patch_deepseek_v4_request_tools_placement()
monkey_patch_deepseek_v4_per_layer_rope()
monkey_patch_deepseek_v4_bf16_o_proj()
def monkey_patch_deepseek_v4_allowed_layer_types():
@@ -185,110 +183,6 @@ def monkey_patch_kv_xfer_finished_tolerate_freed():
logger.warning("Patched Scheduler._update_from_kv_xfer_finished to tolerate freed (aborted) KV-transfer reqs.")
def monkey_patch_deepseek_v4_bf16_o_proj():
"""Run DeepSeek V4's output projection in bf16 when the weights are not FP8.
vLLM's DeepSeek V4 output projection is FP8-only. All three CUDA attention
classes (``DeepseekV4FlashMLAAttention``,
``DeepseekV4FlashInferMLAAttention``, ``DeepseekV4FlashInferSM120Attention``)
implement ``_o_proj`` by calling ``deep_gemm_fp8_o_proj``
(``vllm/models/deepseek_v4/nvidia/ops/o_proj.py``), which dereferences
``wo_a.weight_scale``, falling back to ``wo_a.weight_scale_inv``, and hands
the result to DeepGEMM's ``fp8_einsum``. There is no branch on quant config
or weight dtype, and ``_o_proj`` is an ``@abstractmethod`` dispatched purely
by platform subclass, so no attention backend routes around it. A bf16
checkpoint has neither attribute and therefore fails with
``AttributeError: 'ColumnParallelLinear' object has no attribute
'weight_scale_inv'``.
Quantizing is not an answer, because nothing quantizes by default:
``[inference.vllm] quantization`` is unset, which leaves vLLM to infer the
scheme from the checkpoint. bf16 DeepSeek V4 checkpoints are a first-class
artifact here, written by ``tools/convert_fp8_to_bf16.py``,
``tools/convert_dcp_to_bf16.py``, and trainer exports, and they carry no
scales for the op to find. Passing ``--quantization fp8_per_block`` does
produce a correct ``weight_scale_inv`` and is a genuine alternative on
hardware whose DeepGEMM build has block-scaled FP8 kernels, but it changes
the served numerics, so it is a deployment decision rather than a fix for
serving the bf16 weights as given.
Only the unquantized case is redirected: an FP8 weight keeps using vLLM's own
kernel, so a real FP8-serialized checkpoint behaves exactly as before. The
condition is the weight dtype rather than the presence of
``weight_scale_inv``, so a checkpoint that *is* quantized but whose scales
ended up in the wrong layout still fails loudly instead of being silently
rerouted.
The replacement mirrors the Triton kernel's arithmetic
(``vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py:95-105``)
without the quantization step. The trailing ``rope_dim`` channels of each head
carry an inverse RoPE over interleaved pairs, with ``cos_sin_cache`` holding
``rope_dim // 2`` cosines followed by the matching sines:
y[even] = x[even] * cos + x[odd] * sin
y[odd] = x[odd] * cos - x[even] * sin
The remaining ``nope_dim`` channels pass through. The projection is the same
grouped contraction ``fp8_einsum`` performs, with the group axis recovered by
reshaping: head ``g * heads_per_group + i`` belongs to group ``g`` at offset
``i * head_dim``, matching the kernel's own
``g = pid_gh // heads_per_group`` indexing.
Rotation is computed in fp32 and the contraction runs in bf16, whose CUDA
matmuls accumulate in fp32. That is strictly more accurate than the FP8 path
it replaces, and it avoids materializing an fp32 copy of the attention output.
"""
from vllm.models.deepseek_v4.nvidia import flashinfer_sparse, flashmla
from vllm.models.deepseek_v4.nvidia.ops import o_proj as o_proj_module
original_o_proj = o_proj_module.deep_gemm_fp8_o_proj
if getattr(original_o_proj, "_prime_rl_has_bf16_fallback", False):
return
def _inverse_rope(o, positions, cos_sin_cache, rope_dim):
num_tokens, num_heads, head_dim = o.shape
half_rope = rope_dim // 2
cos_sin = cos_sin_cache[positions].float()
cos = cos_sin[:, :half_rope].view(num_tokens, 1, half_rope)
sin = cos_sin[:, half_rope:].view(num_tokens, 1, half_rope)
rotated = o[:, :, head_dim - rope_dim :].float().reshape(num_tokens, num_heads, half_rope, 2)
even, odd = rotated[..., 0], rotated[..., 1]
pairs = torch.stack((even * cos + odd * sin, odd * cos - even * sin), dim=-1)
out = o.clone()
out[:, :, head_dim - rope_dim :] = pairs.reshape(num_tokens, num_heads, rope_dim).to(o.dtype)
return out
def _patched_o_proj(o, positions, cos_sin_cache, wo_a, wo_b, *, n_groups, heads_per_group, **kwargs):
if wo_a.weight.dtype == torch.float8_e4m3fn:
return original_o_proj(
o,
positions,
cos_sin_cache,
wo_a,
wo_b,
n_groups=n_groups,
heads_per_group=heads_per_group,
**kwargs,
)
x = _inverse_rope(o, positions, cos_sin_cache, kwargs["rope_dim"])
x = x.reshape(o.shape[0], n_groups, heads_per_group * o.shape[-1])
weight = wo_a.weight.view(n_groups, kwargs["o_lora_rank"], -1)
z = torch.einsum("tgr,gdr->tgd", x, weight)
return wo_b(z.flatten(1))
_patched_o_proj._prime_rl_has_bf16_fallback = True
o_proj_module.deep_gemm_fp8_o_proj = _patched_o_proj
# Both attention modules did `from ...ops.o_proj import deep_gemm_fp8_o_proj` at
# import time, so patching the defining module alone would not reach the names
# their `_o_proj` methods actually call.
flashmla.deep_gemm_fp8_o_proj = _patched_o_proj
flashinfer_sparse.deep_gemm_fp8_o_proj = _patched_o_proj
def monkey_patch_nano_v3_reasoning_parser():
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
@@ -795,126 +689,3 @@ def monkey_patch_dp_coordinator_startup_timeout():
zmq_addr_pipe.close()
DPCoordinator._wait_for_zmq_addrs = _patched_wait_for_zmq_addrs
_DEEPSEEK_V4_YARN_ROPE_TYPES = frozenset({"yarn", "deepseek_yarn", "deepseek_llama_scaling"})
def _deepseek_v4_rope_parameters(rope_parameters, *, compress_ratio, max_position_embeddings):
"""Flat, single-layer rope parameters for `build_deepseek_v4_rope`.
Handles both on-disk schemas. The real checkpoint ships a flat legacy `rope_scaling`, which
vLLM's config shim normalizes in place. HF's own `DeepseekV4Config` nests the parameters
under `main`/`compress` rope-type labels instead, and so does this repo's port. vLLM's shim
cannot read that: `is_rope_parameters_nested` only recognizes nesting by *attention* layer
type, so transformers leaves the sub-dicts alone and injects a top-level
`rope_type="default"` beside them. Upstream then builds unscaled RoPE for every layer and
hands `get_rope` a cache key containing a dict, which is unhashable. Selecting the branch
this layer wants resolves both. Upstream picks the base from `config.rope_theta` /
`config.compress_rope_theta` on its own either way.
"""
rope_parameters = rope_parameters if isinstance(rope_parameters, dict) else {}
# `compress_ratio` is already clamped to >= 1 by the caller, so <= 1 is "no compressor",
# i.e. the reference's `else` branch. vLLM lumps the MTP layers in here too.
is_sliding = compress_ratio <= 1
if any(isinstance(value, dict) for value in rope_parameters.values()):
label = "main" if is_sliding else "compress"
branch = rope_parameters.get(label)
if not isinstance(branch, dict):
raise ValueError(
f"DeepSeek V4 rope_parameters is nested by rope type but has no {label!r} "
f"sub-dict; found {sorted(rope_parameters)}."
)
parameters = dict(branch)
else:
parameters = dict(rope_parameters)
rope_type = parameters.get("rope_type", parameters.get("type", "default"))
if is_sliding or rope_type not in _DEEPSEEK_V4_YARN_ROPE_TYPES:
# Plain RoPE, written as YaRN with `factor=1` rather than as `rope_type="default"`.
# The table is the same either way, since `_compute_inv_freq`'s interpolated and
# extrapolated frequencies coincide at `factor=1` and `yarn_get_mscale` returns 1.0,
# but `"default"` would route `get_rope` to a plain `RotaryEmbedding`, whose cache
# follows the ambient dtype and so fails the fp32 assertion in
# `vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py`.
# `original_max_position_embeddings` is widened because the cache is
# `original_max * factor` rows and must still span the context.
rope_type = "yarn"
parameters["factor"] = 1
parameters["original_max_position_embeddings"] = max_position_embeddings
parameters["rope_type"] = rope_type
return parameters
def monkey_patch_deepseek_v4_per_layer_rope():
"""Give each DeepSeek V4 layer the RoPE its reference implementation uses.
DeepSeek ships the reference inside the checkpoint we serve, at
https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731/tree/main/inference. Its
`model.py:481-485` picks the frequencies per layer:
if self.compress_ratio:
original_seq_len, rope_theta = args.original_seq_len, args.compress_rope_theta
else:
# disable YaRN and use base rope_theta in pure sliding-window attention
original_seq_len, rope_theta = 0, args.rope_theta
and `precompute_freqs_cis` (`model.py:206-235`) applies the NTK-by-parts ramp only when
`original_seq_len > 0`. So a pure sliding-window layer gets plain RoPE at `rope_theta` and
every compressed layer gets YaRN at `compress_rope_theta`. HF's `DeepseekV4Config` splits its
`rope_parameters` into `main`/`compress` for the same reason, and so does this repo's trainer.
`vllm/models/deepseek_v4/common/rope.py`'s `build_deepseek_v4_rope` branches the base on
`compress_ratio` but never the scaling, so on the real checkpoint it hands YaRN to layers 0
and 1 as well. No config value can correct that: `rope_type` is one global field there.
So this patch resolves `rope_parameters` per layer instead, which also gives upstream a
schema and a dtype it can handle; see `_deepseek_v4_rope_parameters` above.
Measured against the reference's own frequencies, at the test's `factor=16`,
`original_max_position_embeddings=4096` geometry, this takes the sliding layers from 5.1e-03
max absolute error to 6e-08, the float32 residual the compressed layers already have. The
rope tests in `tests/unit/train/models/test_deepseek_v4.py` are that comparison, over both
on-disk schemas and both scaled and unscaled configs.
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
original_build = dsv4_rope.build_deepseek_v4_rope
if getattr(original_build, "_prime_rl_matches_deepseek_reference", False):
return
def _patched_build(config, *, head_dim, rope_head_dim, max_position_embeddings, compress_ratio):
# Swapping a copy in also spares `config.rope_parameters` upstream's in-place mutation,
# which otherwise leaves the last-built layer's `rope_theta` on the shared config.
original_parameters = config.rope_parameters
config.rope_parameters = _deepseek_v4_rope_parameters(
original_parameters,
compress_ratio=compress_ratio,
max_position_embeddings=max_position_embeddings,
)
try:
return original_build(
config,
head_dim=head_dim,
rope_head_dim=rope_head_dim,
max_position_embeddings=max_position_embeddings,
compress_ratio=compress_ratio,
)
finally:
config.rope_parameters = original_parameters
_patched_build._prime_rl_matches_deepseek_reference = True
dsv4_rope.build_deepseek_v4_rope = _patched_build
# `attention.py` imports the builder into its own namespace, so the defining module alone
# would not reach the already-bound reference.
from vllm.models.deepseek_v4 import attention as dsv4_attention
dsv4_attention.build_deepseek_v4_rope = _patched_build
+1 -1
View File
@@ -26,7 +26,7 @@ from prime_rl.inference.patches import (
)
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
# Still needed in vLLM 0.29 — upstream rejects prompt_len > max_model_len - max_tokens
# Still needed in vLLM 0.30 — 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.
+23 -23
View File
@@ -2,16 +2,16 @@
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 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.
prefix-cache salting, lora dispatch, multimodal content parts and features,
prompt logprobs, priority, ``data_parallel_rank`` header routing, server-side
``max_tokens`` defaulting, ``usage`` reporting, and expanded prompt metadata.
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.
Everything else delegates to upstream so we track future vLLM changes for free.
"""
from __future__ import annotations
@@ -33,9 +33,8 @@ from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
# Overrides upstream's base64 ``.npy`` string form with the compact
# ``{data, shape, start, dtype}`` object the PD router merges and the
# renderers parse.
# Overrides upstream's base64 ``.npy`` string form with the compact object
# the PD router merges and the renderers parse.
routed_experts: dict[str, Any] | None = None # type: ignore[assignment]
@@ -52,11 +51,11 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
)
for choice in response.choices
]
return PrimeRlGenerateResponse(**{**dict(response), "choices": choices})
return PrimeRlGenerateResponse(**{**response.model_dump(exclude={"choices"}), "choices": choices})
class PrimeRlServingTokens(ServingTokens):
"""ServingTokens + compact routed experts."""
"""ServingTokens with compact routed experts."""
async def serve_tokens_full_generator( # type: ignore[override]
self,
@@ -66,22 +65,23 @@ class PrimeRlServingTokens(ServingTokens):
model_name: str,
request_metadata: RequestResponseMetadata,
) -> ErrorResponse | GenerateResponse:
# Capture routed_experts as vLLM streams request outputs, then post-process
# the final response into our GenerateResponse subclass so the encoded
# experts surface in the JSON.
capture: _GenerateRoutedExpertsCapture | None = None
routed_experts: _GenerateRoutedExpertsCapture | None = None
if self.model_config.enable_return_routed_experts:
capture = _GenerateRoutedExpertsCapture(
routed_experts = _GenerateRoutedExpertsCapture(
result_generator,
start=request.sampling_params.routed_experts_prompt_start,
)
result_generator = capture
result_generator = routed_experts
response = await super().serve_tokens_full_generator(
request, result_generator, request_id, model_name, request_metadata
request,
result_generator,
request_id,
model_name,
request_metadata,
)
if capture is not None and isinstance(response, GenerateResponse):
response = capture.post_process(response)
if routed_experts is not None and isinstance(response, GenerateResponse):
response = routed_experts.post_process(response)
return response
+145 -19
View File
@@ -1,17 +1,22 @@
from __future__ import annotations
import asyncio
import fcntl
import os
import time
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Callable, Iterator
import orjson
import prime_runs as pr
from prime_sandboxes import Config as PrimeConfig
from prime_rl.configs.monitors import PrimeEvalMonitorConfig, PrimeTrainMonitorConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_platform_run_path
from prime_rl.utils.utils import sanitize
@@ -28,12 +33,18 @@ 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)."""
"view on platform" link (atomic replace: a reader never sees a torn file).
The tmp file is pid-suffixed: the trainer and the online-eval process
share the run directory, and two writers sharing one tmp path can tear
each other's staged file mid-write."""
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)
tmp = path.with_suffix(f".json.tmp.{os.getpid()}")
try:
tmp.write_bytes(orjson.dumps(record, option=orjson.OPT_INDENT_2))
tmp.replace(path)
finally:
tmp.unlink(missing_ok=True)
def read_platform_record(output_dir: Path) -> dict[str, Any] | None:
@@ -41,6 +52,73 @@ def read_platform_record(output_dir: Path) -> dict[str, Any] | None:
return orjson.loads(path.read_bytes()) if path.is_file() else None
# Bounded wait for the record lock: a blocking flock(LOCK_EX) would stall the
# async event-loop thread for as long as the other writer holds the lock.
RECORD_LOCK_TIMEOUT = 10.0
RECORD_LOCK_POLL = 0.05
@contextmanager
def _platform_record_lock(output_dir: Path) -> Iterator[None]:
"""Cross-process read-modify-write lock for the platform record: the
trainer and the online-eval process merge into the SAME run.json, and an
unlocked read-modify-write lets one clobber the other's snapshot. POSIX
flock on a sibling .lock file. The lock file is NEVER unlinked: a waiting
writer can still hold the unlinked inode's lock while a new writer
creates and locks a fresh file — two simultaneous "exclusive" locks and
a lost merge; a stable lock inode is the whole guarantee. Acquisition is
BOUNDED (`RECORD_LOCK_TIMEOUT`), retried with non-blocking flock so the
async event-loop thread never blocks; `TimeoutError` past the bound.
Storage errors that make locking impossible (e.g. ENOLCK) raise
immediately instead of retrying."""
path = get_platform_run_path(output_dir)
path.parent.mkdir(parents=True, exist_ok=True)
lock_path = path.with_suffix(path.suffix + ".lock")
with open(lock_path, "a+b") as lock_file:
deadline = time.monotonic() + RECORD_LOCK_TIMEOUT
while True:
try:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except BlockingIOError:
if time.monotonic() >= deadline:
raise TimeoutError(f"platform record lock at {lock_path} still held after {RECORD_LOCK_TIMEOUT}s")
time.sleep(RECORD_LOCK_POLL)
try:
yield
finally:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
def _merge_platform_record(
output_dir: Path,
merge: Callable[[dict[str, Any]], dict[str, Any]],
) -> None:
"""Best-effort locked read-modify-write of the platform record: run
`merge` on the current record under the record lock and atomically
replace the file. The record only backs the dashboard's "view on
platform" link, so a lock or storage failure (TimeoutError, ENOLCK, ...)
is logged and SKIPPED, never fatal to training; the dashboard just misses
the link for that run."""
try:
with _platform_record_lock(output_dir):
write_platform_record(output_dir, merge(read_platform_record(output_dir) or {}))
except OSError:
get_logger().warning(
f"Failed to persist the platform record at {get_platform_run_path(output_dir)} "
f"(lock or storage error); the dashboard's platform link may be missing. "
f"Training continues."
)
def update_platform_record(output_dir: Path, update: dict[str, Any]) -> None:
"""Best-effort locked read-modify-write of the platform record: `update`
overlays the current record (preserving keys it doesn't set). Use for
every writer that shares the file — a naive overwrite drops concurrent
writers' keys."""
_merge_platform_record(output_dir, lambda record: {**record, **update})
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."""
@@ -54,8 +132,12 @@ class PrimeTrainMonitor(Monitor):
The run handle owns what ``TrainRun`` used to do by hand: the RFT
lifecycle (register or attach, finalize), the per-step metrics POSTs, the
every-10th-step Parquet sample uploads (presign -> PUT -> confirm), and
the terminal status — a process that exits without finalizing is reported
crashed by the SDK's atexit hook, replacing the old ``_mark_failed`` one.
the terminal status. Delivery is BEST-EFFORT: the SDK's atexit hook
reports a process that exits without finalizing, but an abrupt kill
(SIGKILL, OOM, node loss) skips the hook and a lost finalize is not
retried here — the platform owns the terminal state of attached
($RUN_ID) and managed runs. `FINISH_TIMEOUT` bounds the queued-upload
drain, not the SDK's finalize HTTP retries.
``init``/``finish`` do network I/O and run in worker threads; the log
calls are queue puts onto the SDK's uploader thread, which owns retries
@@ -69,9 +151,25 @@ class PrimeTrainMonitor(Monitor):
init_kwargs: dict[str, Any]
if run_id := os.getenv("RUN_ID"):
# A managed launch pre-created the platform run and injected its id -
# attach instead of registering a duplicate. The backend owns the run's
# failure marking then; a clean finish() still marks it completed.
# attach instead of registering a duplicate. The platform owns the
# attached run's failure/completion marking; a clean finish() is
# delivered best-effort and does not by itself mark it completed.
init_kwargs = {"id": run_id}
elif isinstance(config, SFTConfig):
# SFT trains on a dataset, not on environments, and has no rollouts - the
# platform run is registered without both.
init_kwargs = dict(
name=self.config.name,
model=config.model.name,
environments=[],
training=pr.TrainingSpec(
max_steps=config.max_steps or 0,
batch_size=config.data.batch_size,
seq_len=config.data.seq_len,
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
),
config=config.model_dump(exclude_none=True, mode="json"),
)
elif config is not None:
init_kwargs = dict(
name=self.config.name,
@@ -80,7 +178,9 @@ class PrimeTrainMonitor(Monitor):
training=pr.TrainingSpec(
max_steps=config.max_steps or 0,
batch_size=config.batch_size,
rollouts_per_example=config.group_size,
rollouts_per_example=max(
(source.group_size for source in config.train.source), default=config.train.group_size
),
seq_len=config.seq_len,
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
),
@@ -107,7 +207,15 @@ class PrimeTrainMonitor(Monitor):
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})
# Merge, not overwrite: a concurrent eval process (SFT
# online evals share the trainer's run dir) may already
# have written its evaluations record. Off the event
# loop: the flock retry must not stall it.
await asyncio.to_thread(
update_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)")
@@ -170,7 +278,19 @@ class PrimeEvalMonitor(Monitor):
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": {}})
# Merge, not overwrite: when the eval process shares the
# trainer's run dir (SFT online evals), the train record's
# platform link (kind/id/url) must survive; a standalone
# eval keeps the plain eval-shaped record. Locked RMW.
def _eval_init_update(record: dict[str, Any]) -> dict[str, Any]:
if record.get("kind") == "train":
record.setdefault("evaluations", {})
record["run_id"] = self.run_id
return record
return {"kind": "eval", "run_id": self.run_id, "evaluations": {}}
# Off the event loop: the flock retry must not stall it.
await asyncio.to_thread(_merge_platform_record, output_dir, _eval_init_update)
else:
self.logger.info(f"Platform evaluations disabled ({pr.MODE_ENV}=disabled)")
@@ -229,13 +349,19 @@ class PrimeEvalMonitor(Monitor):
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)
def _eval_epoch_update(record: dict[str, Any]) -> dict[str, Any]:
record.setdefault("kind", "eval")
record.setdefault("run_id", self.run_id)
record.setdefault("evaluations", {})[env_name] = {
"step": step,
"id": run.id,
"url": run.url,
}
return record
# Off the event loop: the flock retry must not stall it.
await asyncio.to_thread(_merge_platform_record, self.output_dir, _eval_epoch_update)
return run
async def log_eval_plan(self, env_name: str, step: int, expected: int) -> None:
+9
View File
@@ -0,0 +1,9 @@
from prime_rl.multimodal.base import ForwardPolicy, MaterializedMM, MultimodalAdapter
from prime_rl.multimodal.registry import get_multimodal_adapter
__all__ = [
"ForwardPolicy",
"MaterializedMM",
"MultimodalAdapter",
"get_multimodal_adapter",
]

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