Compare commits

...
140 Commits
Author SHA1 Message Date
Mika SenghaasandGitHub 6b3364d1a8 fix: align evals with applied policies (#3385)
## Summary

- Route startup and later policy loads through one `WeightWatcher`
update path. Advance `policy.version` and trigger evals only after
inference applies the weights.
- Key fresh startup evals to policy v0. On resume, evaluate the loaded
checkpoint only when `retrigger_on_resume=true`.
- Pause rollout scheduling across each weight apply so rollout
provenance matches the policy served at dispatch.
- Remove the resume-step broadcast directory before the trainer rebuilds
its startup handshake.
- Always broadcast and consume the final RL policy. Remove the
conditional final-broadcast config and helper path.
- Remove the mixed-policy eval warning. Keep the minimum policy version
in metrics and success logs.
- Remove the parenthesized step from eval success logs.

## Verification

Before the fix, a 20-step reverse-text run with eval interval 1
reproduced the bug:

- Eval step 20 used policy v18.
- The final policy broadcast triggered eval step 21 with policy v20.
- The run wrote step-21 eval artifacts.

After the fix, this requested interval-10 run completed all 20 steps:

```bash
uv run rl @ examples/basic/reverse-text/rl.toml \
  --orchestrator.eval.interval 10 \
  --orchestrator.eval.num-examples 1 \
  --orchestrator.eval.group-size 1 \
  --orchestrator.eval.source '[{"name":"reverse-text-eval","env":{"taskset":{"id":"reverse-text"},"agent":{"harness":{"id":"null"},"runtime":{"type":"subprocess"}}}}]' \
  --no-monitors.wandb --no-dashboard
```

- Eval step 10 used policy v10.
- Final eval step 20 used policy v20.
- No step-21 eval artifacts were written.

A two-step run without evals applied final policy v2 and exited cleanly.
This verifies unconditional final broadcast and consumption.

Fresh and resumed two-step smokes verified the startup matrix:

- A fresh interval-1 run evaluated policies v0, v1, and v2.
- Resume from v2 with `retrigger_on_resume=false` skipped v2, then
evaluated v3 and v4.
- Resume from v2 with `retrigger_on_resume=true` evaluated v2, v3, and
v4.
- Resume from v2 with interval 3 skipped v2 and evaluated v3 only.
- Every resumed startup rebuilt its v2 broadcast handshake and exited
cleanly.

After the final review fixes, a fresh interval-1 run evaluated v0, v1,
and v2. A resume from v2 with `retrigger_on_resume=false` skipped only
v2, then evaluated v3 and v4.

```bash
uv run pytest \
  tests/unit/test_configs.py \
  tests/unit/orchestrator/test_batch.py \
  tests/unit/utils/test_pathing.py -q
# 156 passed

uv run ruff check \
  src/prime_rl/orchestrator/orchestrator.py \
  src/prime_rl/orchestrator/watcher.py \
  src/prime_rl/orchestrator/dispatcher.py \
  src/prime_rl/orchestrator/eval_source.py \
  src/prime_rl/utils/pathing.py \
  src/prime_rl/trainer/rl/train.py \
  src/prime_rl/utils/utils.py \
  packages/prime-rl-configs/src/prime_rl/configs/rl.py \
  packages/prime-rl-configs/src/prime_rl/configs/shared.py \
  tests/unit/utils/test_pathing.py \
  tests/utils.py
# All checks passed!
```

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes core RL orchestration around weight updates, rollout
scheduling barriers, and eval timing—incorrect ordering could cause
wrong-policy evals or inference crashes during weight swaps.
> 
> **Overview**
> Fixes evals running against stale or wrong policy versions by tying
**eval triggers and `policy.version` to inference actually applying
weights**, not merely publishing them.
> 
> **Policy lifecycle:** `WeightWatcher` now advances `policy.version`
only after `receive()` completes, routes startup sync through
`sync_startup` + shared `on_update` hooks, and registers orchestrator
hooks for eval and dispatch-gate refresh. Batch shipping and shutdown
waits refer to **inference-applied** versions.
> 
> **Eval scheduling:** Eval fires from `trigger_eval` after each applied
policy (including startup v0 on fresh runs). Resume skips re-eval at the
checkpoint step unless `retrigger_on_resume=true`; final eval uses
`force` at `max_steps` without a spurious step-21 epoch. The dispatcher
blocks new scheduling across weight swaps via `policy_update_pending`
and a scheduling lock.
> 
> **Broadcast config:** Removes `broadcast_final` and
`final_broadcast_version`; the trainer **always** broadcasts every step
including the final policy, and resume cleanup deletes broadcast dirs
from the resume step onward so the startup handshake is rebuilt.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5fa6b01df79f028ad974509ff78e9e51188cf1f0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-25 12:32:45 -07:00
eligottsandGitHub 544bd6205a feat(dashboard): agent view commands + report tab with verified citations (#3387) 2026-08-25 12:24:51 -07:00
rasdaniandGitHub 3460245d63 feat(dashboard): expose tool context and rendered tokens (#3377)
## Summary

- show `trace.tools` as a distinct, collapsible model-context block in
the Messages view, with tool counts/names, full descriptions, formatted
parameter schemas, and per-item/schema/all copy actions
- add a separate `Rendered` view that decodes recorded post-renderer
`token_ids` for the selected trace and branch as a full sequence,
retaining special tokens and offering decoded-text and authoritative-ID
copy actions
- compose both `Messages` and `Rendered` with the `Text`, `Advantage`,
`Logprob`, `Mask`, and `Content` signal dropdown, with explicit
unavailable states for missing IDs, missing model metadata, tokenizer
load failures, and decode failures

## Details

The Messages view continues to render literal `message.content`. Tool
definitions are shown immediately after the first system message in a
purple-accented context card, so they are not presented as
system-message text; traces without a system message keep the card at
the top. The collapsed row shows the count and normalized names;
expanding it exposes each full description and scrollable JSON schema.
Direct tool objects, OpenAI-style `function` wrappers, multiple
definitions, missing fields, and malformed values degrade to readable
fallback labels.

Rendered does not rerun or infer a chat template. The server uses
`client.renderer_model_name` with the existing run-model fallback,
concatenates the recorded node spans in the selected root-to-leaf order,
and calls the tokenizer once for the full sequence with special-token
skipping disabled. The selected branch controls which decoded sequence
is shown; the all-branches option uses recorded node write order. With
`Text` selected, Rendered shows that exact full-sequence decode. With
another signal selected, it shows the same recorded sequence as token
spans with the existing color scale and token hover metadata.

Compatibility is intentionally additive: the default endpoint response
and default Messages/Text display stay unchanged, token strings are
still fetched lazily for overlays, and full rendered text is only added
when `rendered=true` is requested. The mode buttons and signal dropdown
are independent, and a one-time preference migration recovers sessions
that briefly saved `Rendered` in the signal field.

Episode navigation and token/render enrichment use separate request
lifecycles. Opening or closing an episode invalidates prior enrichment,
while changing controls during an in-flight open no longer discards the
episode response; the newly opened episode then picks up any enrichment
required by the latest controls. Decode failures remain branch-local in
the viewer: valid text for the selected branch is shown even if another
branch fails to decode.

## Verification

- `uv run --no-sync ruff format --check
src/prime_rl/dashboard/server.py`
- `uv run --no-sync ruff check src/prime_rl/dashboard/server.py`
- `uv run ruff check src/prime_rl/dashboard`
- `node --check src/prime_rl/dashboard/static/app.js`
- `git diff origin/main...HEAD --check`
- exercised a generic synthetic two-branch trace through the live
dashboard API with three tool-definition shapes; verified renderer-model
selection, retained `<|im_start|>` / `<|im_end|>` markers, separate
branch text, all-node ordering, and existing per-token pieces

## Visual description

A compact `Tool definitions · 3 tools · lookup, calculate, tool 3` row
appears directly after the system message. It expands into nested tool
cards with full prose and scrollable monospace schemas. `Messages` /
`Rendered` buttons sit beside a signal dropdown containing `Text`,
`Advantage`, `Logprob`, `Mask`, and `Content`. Either mode can use any
signal; Rendered/Text shows the exact decoded transcript, while Rendered
with an overlay shows colored token spans. A hover tooltip describes the
signal choices. A screenshot is not included because a browser runtime
was unavailable in the checkout used for verification.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Additive dashboard and optional episode API fields; no changes to
training, auth, or data persistence beyond larger lazy-loaded episode
payloads.
> 
> **Overview**
> The trace viewer adds **Messages** vs **Rendered** modes and surfaces
**`trace.tools`** as model context separate from message text.
> 
> In **Messages**, tool definitions appear in a collapsible context
block (after the first system message when present), with descriptions,
parameter schemas, and copy actions; message bodies still show literal
**`message.content`**. **Rendered** decodes recorded post-renderer
**`token_ids`** per branch (or all nodes) via **`renderer_model_name`**
with run-model fallback—no chat-template reconstruction—and reports
missing IDs, model, tokenizer, or decode failures.
> 
> The episode API accepts optional **`tokens`** and **`rendered`** query
params; **`rendered_token_text`** on the server concatenates branch
paths and decodes full sequences with special tokens retained. The UI
lazily fetches enrichment, versions open/enrichment requests to avoid
stale responses, and shares the Text / Advantage / Logprob / Mask /
Content signal dropdown across both modes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
596f7d3fe9746c9283d8a872b1d506c26a525e1a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-25 11:40:30 -07:00
3758321f08 fix: preserve final eval during teardown (#3324)
## Summary

- Use successful trainer and orchestrator exits as the shared completion
condition in local and multi-node SLURM launchers.
- Let each SLURM component publish `.trainer.done` or
`.orchestrator.done`, then stop inference after both markers exist.
- Make trainer-only fake-data SLURM runs stop after `.trainer.done`; no
orchestrator exists in that mode.
- Store all generated SLURM scripts and coordination files under
`<run_dir>/launcher/`.
- Store SLURM stdout and stderr under `<run_dir>/launcher/logs/`.
- Apply the launcher layout to RL, SFT, decoupled SFT eval, and
standalone inference entrypoints.
- Keep local launchers unchanged on disk. They do not create `launcher/`
because they persist no launcher files.
- Preserve failure propagation through `srun --kill-on-bad-exit=1`.

At `max_steps`, the trainer can exit while the orchestrator still drains
the final eval. The template previously tore down the node after the
first background process exited. This killed the final eval. A clean
exit also did not trigger `--kill-on-bad-exit`, so inference nodes could
hold the allocation until wall time.

## Breaking

- Generated SLURM scripts move from `<run_dir>/*.sbatch` to
`<run_dir>/launcher/*.sbatch`. Update manual submission commands and
tooling to use the new paths.
- SLURM job logs move from `<run_dir>/*job_*.log` to
`<run_dir>/launcher/logs/*job_*.log`. Update log collection and
monitoring paths.

## Verification

Before this change, a 1000-step GLM-4.5-Air run lost its final eval at
450 of 500 tasks. The six-node allocation then remained active for
another 23 hours.

After this change, a 10-step reverse-text run evaluated at its final
step and exited successfully:

- The final eval completed all 64 rollouts with no rollout errors.
- The trainer finished at 01:39:08 UTC.
- The orchestrator drained its pipeline and finished at 01:39:14 UTC.
- Inference stopped after both terminal components finished.
- The launcher exited with code 0 and released both GPUs.

A two-node trainer-only fake-data dry run rendered a one-marker watcher
with no `ORCHESTRATOR_DONE` reference. The normal inference path still
rendered the two-marker watcher. Both scripts passed `bash -n`.

All RL, SFT, decoupled SFT eval, and inference SLURM variants rendered
successfully. Every rendered script passed `bash -n`. Local RL, SFT, and
inference dry runs did not create `launcher/`.

An additional two-node SLURM run used the regular reverse-text
configuration with 100 eval rollouts per evaluation:

- The trainer completed all 20 steps and wrote `launcher/.trainer.done`.
- The orchestrator continued to drain queued evaluations after trainer
completion.
- The orchestrator then wrote `launcher/.orchestrator.done`.
- Both nodes logged teardown with exit code 0, and the job released its
allocation.

Ruff passed. The pathing unit tests passed with 10 tests.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes multi-node SLURM lifecycle and coordination (eval completion
vs allocation hold time) and breaks paths for manual `sbatch` and log
monitoring; incorrect completion logic could still strand nodes or kill
in-flight evals.
> 
> **Overview**
> Fixes premature SLURM teardown at `max_steps` when the trainer exits
while the orchestrator is still draining the **final eval**. Multi-node
RL jobs no longer stop on the first background process exit; trainer
rank 0 and the orchestrator publish **`launcher/.trainer.done`** and
**`launcher/.orchestrator.done`** on success, and every node waits for
the appropriate pair (trainer-only vs trainer+orchestrator) before
killing inference and releasing the allocation. Failures still propagate
via **`srun --kill-on-bad-exit=1`**.
> 
> **Breaking layout change:** generated `*.sbatch` scripts, coordination
sentinels, and SLURM `job_*.log` output move from the run directory root
to **`&lt;run_dir&gt;/launcher/`** and **`launcher/logs/`** for RL, SFT,
decoupled SFT eval, and standalone inference. Entrypoints and Jinja
templates pass `launcher_dir` / `launcher_log_dir`; local launches stay
unchanged on disk (no `launcher/`). Docs and training skills note the
new paths; `format_log_message` and `LAUNCHER_ARTIFACTS` validation
follow the same layout.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
02f3807d4a4f9cd53830b9b90e4035c386d01bdc. 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 <noreply@anthropic.com>
2026-08-24 21:58:23 -07:00
Mika SenghaasandGitHub 01dc127b1a fix: synchronize before the pre-broadcast empty_cache (#3383)
## Summary
- One-line fix for the deterministic `CUDA error: an illegal memory
access` that killed every SignSGD run without full optimizer offload
since #3234.
- `torch.cuda.empty_cache()` returns cached blocks to the driver; a
kernel still in flight that references a cached block faults once its
block is freed under it. The pre-broadcast `empty_cache` (added in #3234
for FP8 gather headroom) runs immediately after `optimizer.step()` —
SignSGD's per-param loop leaves thousands of tiny kernels still running
at that point, while AdamW's compact foreach step happens to finish in
time, which is why only SignSGD crashed. Draining pending work with
`torch.cuda.synchronize()` before releasing blocks closes the race for
every optimizer, at ~ms cost once per step.

## Verification

All on the same GLM-4.5-Air scaleswe config (2 trainer + 2 inference
nodes, `sign_sgd` + `optim_cpu_offload`, no full offload):

| state | outcome |
|---|---|
| main | illegal memory access right after step 1, 2/2 slurm attempts |
| main + `CUDA_LAUNCH_BLOCKING=1` | no crash — ordering, not indexing |
| **main + this one line** | [runs
clean](https://wandb.ai/primeintellect/swe-ablations?nw=nwuser&search=sgd-nooffload):
11+ steps and counting, healthy grad norms, no restarts |

Supersedes #3373 — its foreach SignSGD rewrite turned out to be
unnecessary for correctness (verified by running the untouched optimizer
with only this line).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the per-step RL training hot path and GPU memory lifecycle
before weight broadcast; the change is narrow and matches existing
synchronize-before-empty_cache patterns elsewhere, but any extra sync
can affect step timing.
> 
> **Overview**
> Fixes a **CUDA illegal memory access** that could occur right after
`optimizer.step()` when the trainer frees GPU cache before broadcasting
weights.
> 
> The pre-broadcast `torch.cuda.empty_cache()` (for FP8 gather headroom)
can return cached blocks to the driver while **optimizer kernels are
still in flight**—especially with SignSGD’s many small per-parameter
updates. The change **drains pending GPU work** via
`torch.cuda.synchronize()` immediately before `empty_cache()`, with
expanded comments explaining the race.
> 
> This is a one-line behavioral fix in the RL training loop’s
weight-broadcast path; it does not change broadcast semantics, only
ordering so memory is not reclaimed under active kernels.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8947aa400631ca5a2dab829642f7755fab7dafd0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 18:33:04 -07:00
Konstantin DunasandGitHub 663b53bbc2 fix: silence W&B Weave advertisement on wandb.init (#3380) 2026-08-25 01:51:29 +02:00
f96a46f090 feat(configs): add PRL_OUTPUT_DIR env var for default output_dir (#3375)
Lets a user set a persistent default output location for all runs
without repeating --output-dir on every launch. Precedence stays class
default ("outputs") < PRL_OUTPUT_DIR < TOML < CLI, since the new
default_factory only fires when output_dir is untouched by TOML/CLI
merge.

Also respected by the dashboard UI.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 19:15:19 -04:00
01994b8168 fix: misc dashboard improvs (#3374)
## Summary

- refresh live metrics and trace rows on the same five-second cadence
- better `no data yet` for unavailable overview data
- show episode and trace errors at the bottom of the trace viewer
- add the task key as `task ID` to the identity section of the trace
overview pane
- use `n/a` for missing value uniformly; some spots showed an en dash.
- allow filter from trace viewer

## Verification

### Overview empty state

<img width="1608" height="1045" alt="Screenshot 2026-08-24 at 3 54 20
PM"
src="https://github.com/user-attachments/assets/02e06087-5286-435e-9776-52ec9502f7f5"
/>

### Errors

<img width="1608" height="1045" alt="Screenshot 2026-08-24 at 3 52 29
PM"
src="https://github.com/user-attachments/assets/b39a28cc-c50d-467c-b7f7-39c354a5e008"
/>

### Task ID

<img width="318" height="151" alt="Screenshot 2026-08-24 at 3 52 42 PM"
src="https://github.com/user-attachments/assets/f12f50b5-685d-4ca5-8b80-5c89877cab43"
/>

### Checks

- `node --check src/prime_rl/dashboard/static/app.js`
- `git diff --check`
- dashboard browser smoke against `outputs/reverse-text-rl`
- live append browser repro for metrics, trace rows, and new trace steps
- fake inference URL eval and browser layout check with a full traceback
- headless browser render of a synthetic `ProviderError` episode:
collapsed and expanded traceback, `task ID` row, consistent `n/a`
placeholders, red-marked error rows in the sidebar

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Frontend-only dashboard static assets; no API or training-path
changes. Risk is limited to UI regressions in metrics/traces polling and
the trace modal.
> 
> **Overview**
> This PR tightens **live updates** and **trace UX** in the static
dashboard (`app.js`, `index.html`, `style.css`).
> 
> **Polling & loading:** Poll interval moves to **5s**; metrics and
traces refresh when switching tabs with live on, on tab visibility, and
when re-enabling live. Metrics streaming stops retrying the same offset
when a partial JSONL line sits at EOF; `fetching` guards avoid
overlapping metrics/trace loads.
> 
> **Traces:** Step selection **follows the latest preferred step** while
you’re on the tail (historical picks and an open modal stay put). Empty
trace/metrics states use shorter labels and the episode table keeps its
chrome with an in-table empty row to avoid layout shift. Overview panels
show **“no data yet”** for configured eval sections before data lands.
> 
> **Trace viewer:** Episode/trace **errors render as banners** at the
bottom of the message column (with expandable tracebacks); **task ID**
appears in the identity pane. The modal gets the same
**filter/sort/env/errors** controls as the traces tab, synced through
shared state. Error episodes are highlighted in the sidebar list.
> 
> **Polish:** Missing numeric/overview fields use **`n/a`** instead of
en dashes (empty eval env list still shows **–**). Run overview merges
the full run record from the runs list on refresh.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
239dc7797d996fb0b17badb9dd60b640474b431d. 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 <noreply@anthropic.com>
2026-08-24 16:11:11 -07:00
e6b5e4de5d feat: auto-started dashboard daemon (#3371)
## Summary

- Launchers (`rl`, `sft`) register their output dir in
`~/.cache/prime-rl/dashboard/dirs.json` and make sure one dashboard
serves it (`ensure_dashboard` in the new `entrypoints/dashboard.py`,
kept free of `dashboard`-extra imports). Every dashboard instance serves
its CLI dirs **plus** the registry, re-read live — a run in a new output
dir appears on the one live URL without a restart: one dashboard per
host per user.
- Discovery goes through `daemon.json` (pid + **actual** url), so it
survives port spillover — nothing ever probes port 7788. A live daemon's
URL is logged (`Dashboard running at <url>`); interactive sessions spawn
a detached daemon (own session — killing a run never takes it down) when
none is live (`Dashboard started at <url>`); non-tty launches (CI,
nohup) only register. A stale claim from a dead process is taken over on
the next start.
- `--isolated` is the escape hatch: serve only the given dirs, no
registry read/write, no discovery claim (launchers ignore the instance).
`dashboard: bool = True` on RL/SFT opts a run out via `--no-dashboard`.
- The daemon carries the process title `PRL::Dashboard` via the shared
`set_proc_title`. `psutil` is promoted from transitive to a core
dependency so `prime_rl.utils.process` imports in the slim GPU-free env.
- Launcher startup now ends with a `Dashboard · <url>` banner (blank
lines around, green url) as the last log, after `Launcher complete` (was
`Startup complete. Showing ... logs`). The launcher no longer tails
orchestrator/trainer logs into its terminal - the dashboard is the
monitoring surface.
- New `skills/dashboard/SKILL.md` teaches agents discovery, liveness
checks, and kill/restart commands; `monitor-run` and `start-run` skills
point at it.

Supersedes #3368, rebuilt on the (now merged) stack #3369 (PRL prefix) →
#3370 (GPU extra; the server is a normal package member, so no
setproctitle fallback and no duplicated cache-dir logic); targets
`main`.

## Verification

E2E on this box: daemon claims `daemon.json` with pid + url and shows
`PRL::Dashboard` in `ps`; `ensure_dashboard` from a second process
registers a fresh output dir and the live dashboard absorbs it (run
count grows without restart); a second instance spills to port 7789 and
does **not** steal the claim; `--isolated` serves only its dirs and
leaves the registry untouched; a pty-spawned launcher starts a detached
daemon that survives the launcher's exit; slim `uv sync --extra
dashboard` env (no torch/vllm) imports `entrypoints.dashboard`,
`dashboard.server`, and `set_proc_title`, and `dashboard --help` works;
`tests/unit/test_configs.py` passes (122).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are local dev/monitoring UX and read-only dashboard serving;
training paths are unchanged aside from optional subprocess spawn and
registry file writes.
> 
> **Overview**
> **RL and SFT launchers** now register each run’s `output_dir` in a
per-user registry and ensure a single local dashboard serves it. New
`dashboard: bool = True` (disable with `--no-dashboard`) drives
`ensure_dashboard` in `entrypoints/dashboard.py`, which reuses a live
daemon via `~/.cache/prime-rl/dashboard/daemon.json` or spawns a
detached process in interactive TTY sessions only.
> 
> The **dashboard server** merges CLI dirs with `dirs.json` (live
re-read), claims/releases daemon discovery, adds **`--isolated`** to opt
out of the registry, and moves sidecar cache under the shared dashboard
state dir. The **`dashboard` console script** now enters through
`entrypoints.dashboard.main`.
> 
> **Launcher UX** drops `tail -F` on orchestrator/trainer logs; startup
ends with **Launcher complete** and a **Dashboard · url** banner.
**`psutil`** is a direct dependency so process titles work without the
GPU stack. Agent skills/docs describe discovery, liveness, and
kill/restart.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
035e7ec4c1a2671db778a85a42147d332a8a73ed. 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 <noreply@anthropic.com>
2026-08-24 15:12:09 -07:00
a5853ce9ab feat: slim uv sync (#3370)
## Summary

- The CUDA/linux-only stack (torch+cu128 index, vllm, torchtitan,
mooncake-transfer-engine, ring-flash-attn, dion, tilelang,
flash-linear-attention, torchao, nvidia-ml-py, modelexpress) moves from
core dependencies into a **`gpu` extra** (linux-marked), and
`darwin/arm64` joins `tool.uv.environments` — a bare `uv sync` now
resolves and installs on a MacBook (slim: configs, monitors, dashboard,
CLI tooling). `uv sync --all-extras` — already the recommended install
on GPU machines — pulls everything exactly as before (`all` aggregates
`gpu` too).
- Every other GPU extra (`flash-attn-3`, `flash-attn-cute`, `disagg`,
`gpt-oss`, `quack`, `kernels`, the `mamba-ssm` group) gets linux markers
so the darwin lock split resolves; the torch cu128 index sources are
linux-scoped.
- CI (`cpu_tests`, benchmarks) and the docker entrypoint's
`PRIME_RL_REF` override sync move to `--all-extras`; `Dockerfile.cuda`
adds `--extra gpu`; the install skill documents the split.
- The dashboard's standalone PEP 723 `--script` form is removed: `uv
sync --extra dashboard && uv run dashboard` is now the dependency-free
path everywhere, and `server.py` becomes a normal package member — it
imports the new `CACHE_DIR` from `utils/pathing` instead of duplicating
the cache-dir logic.

## Breaking

- `uv sync` without extras no longer installs the training/inference
stack; use `uv sync --all-extras` (recommended) or `--extra gpu`.
Anything invoking `uv sync --extra flash-attn` alone must add `--extra
gpu`.
- `uv run --script src/prime_rl/dashboard/server.py` no longer works
(header removed); use `uv sync --extra dashboard && uv run dashboard`.

## Verification

On linux: bare `uv sync --extra dashboard` produces an env with no
torch/vllm from which `uv run dashboard` serves real runs end to end;
`uv sync --all-extras --all-packages` restores the full env (torch
2.11+cu128, vllm import, `entrypoints.rl` import OK);
`tests/unit/test_configs.py` (122 passed) and the dashboard browser
smoke pass. `uv lock` resolves all three environments including the new
darwin split.

#3369 (PRL prefix) is merged and this now targets `main`; the
dashboard-daemon PR (#3371) lands on top.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes the default dependency contract and Docker runtime `uv sync`
behavior; anyone on bare `uv sync` or old dashboard script paths will
miss GPU deps, and PRIME_RL_REF overrides now pull all extras (including
heavy disagg/quack) at pod startup.
> 
> **Overview**
> **Slim default install:** Core dependencies no longer pull the Linux
CUDA training stack (torch/cu128, vllm, torchtitan, mooncake,
ring-flash-attn, dion, tilelang, flash-linear-attention, torchao,
modelexpress, nvidia-ml-py). Those move behind a new **`gpu` optional
extra** (linux-marked). Other GPU extras (`flash-attn-3`, `disagg`,
`quack`, `kernels`, `mamba-ssm`, etc.) get linux markers;
**`darwin/arm64`** is added to `tool.uv.environments` so a bare `uv
sync` resolves on macOS. The **`all`** extra now includes
`prime-rl[gpu]`.
> 
> **Install paths updated:** CI (`cpu_tests`, benchmarks) and
**`Dockerfile.cuda`** sync with **`--all-extras`** / explicit **`--extra
gpu`** so Linux GPU images still get the full stack.
**`scripts/docker-entrypoint.sh`** on `PRIME_RL_REF` overrides switches
from a hand-picked extra list to **`uv sync --inexact --all-extras`**
(plus `mamba-ssm` group)—so override checkouts may install disagg/quack
at startup, not only flash-attn/gpt-oss.
> 
> **Dashboard:** The PEP 723 **`uv run --script`** standalone form is
removed from `server.py`; docs/skills point to **`uv sync --extra
dashboard && uv run dashboard`**. Dashboard sidecar cache uses shared
**`CACHE_DIR`** from `utils/pathing` (`home_dir()` fallback to temp).
> 
> **Breaking:** `uv sync` alone no longer installs training/inference
deps—use **`uv sync --all-extras`** (recommended on GPU Linux) or
**`--extra gpu`** (and add flash-attn etc. as before). **`uv run
--script src/prime_rl/dashboard/server.py`** no longer works.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
64562e87834dc6ef1eba7ab372b50f102088cb5f. 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 <noreply@anthropic.com>
2026-08-24 14:43:45 -07:00
Mika SenghaasandGitHub 38582b2bf1 chore: bump verifiers to 0.3.1 (#3372)
## Summary

- require the stable `verifiers[harbor]>=0.3.1` release instead of a
development build
- point the Verifiers submodule at the published `v0.3.1` tag

## Verification

- `uv lock --check`
- built `verifiers-0.3.1-py3-none-any.whl` and `verifiers-0.3.1.tar.gz`
from `deps/verifiers`
- verified the submodule commit has the exact `v0.3.1` tag

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dependency constraint only—switches from a dev pre-release to the
stable 0.3.1 minimum with no application code changes in this diff.
> 
> **Overview**
> Pins **`verifiers[harbor]`** to the stable **`>=0.3.1`** release
instead of the prior **`>=0.3.1.dev59`** development build in
`pyproject.toml`.
> 
> This moves dependency resolution off a pre-release dev tag onto the
published 0.3.1 line while keeping the same optional **`harbor`** extra
and existing editable **`deps/verifiers`** source configuration.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f399e80c03ad6e26533aa770df28e90c69517891. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 14:24:46 -07:00
a266325605 feat: rename proc-title prefix to PRL (#3369)
## Summary

- `PRIME_RL_PROC_PREFIX` becomes `PRL`, so every component's process
title reads `PRL::Trainer`, `PRL::Orchestrator`, `PRL::Inference`,
`PRL::EnvServer`, `PRL::Launcher`, ... — shorter to type and grep. The
`monitor-run` skill's process tree is updated.

## Breaking

- Process titles change from `PRIME-RL::<Name>` to `PRL::<Name>`;
anything matching the old prefix (`pgrep -f PRIME-RL`, dashboards, ops
scripts) must switch.

First PR of a 3-stack: PRL prefix → CPU-only `uv sync` (GPU deps behind
an extra) → dashboard daemon.

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 14:17:03 -07:00
Konstantin DunasandGitHub b9de4a0f7a fix(orchestrator): make dispatch failures explicit (#3364) 2026-08-24 22:23:30 +02:00
75663f0d4c feat: add local run dashboard (#3351)
## Summary

Adds a local run dashboard for SFT / RL / Eval runs. Start with

```bash
# default (all runs in outputs/, port 7788)
uv run dashboard 
```

For example, populate with

```
# rl run
uv run rl @ examples/basic/reverse-text/rl.toml --run.name reverse-text-rl

# sft run
uv run sft @ examples/basic/reverse-text/sft.toml --max-steps 10 --run.name reverse-text-sft

# eval run (multi-agent, multi-branch)
uv run eval \
  --env.id agentic-judge \
  --env.taskset.id terminal-bench-2 \
  --env.taskset.tasks '["fix-git"]' \
  --env.solver.harness.id rlm \
  --env.solver.harness.summarize-at-tokens 4000 \
  --env.judge.harness.id bash \
  --run.name tb2-agentic-judge
```

Combines the best things from W&B + PI platform. Fully isolated
agent-maintained logic in `prime_rl.dashboard`. Fully supersedes the
previously advertised tmux viewer. Should basically be always on when
working with prl locally.

## Gallery

**Configs**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 01 35
PM"
src="https://github.com/user-attachments/assets/a6dec2e2-26d0-49a9-a220-f1baa8c7b1ea"
/>

**Metrics**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 01 55
PM"
src="https://github.com/user-attachments/assets/c38cbac5-177e-4850-a3fc-d09e10da6185"
/>

**Trace Overview**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 02 08
PM"
src="https://github.com/user-attachments/assets/27f4d197-3969-4334-a629-161ac5df434d"
/>

**Trace Viewer**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 02 47
PM"
src="https://github.com/user-attachments/assets/2b9c4aed-20bb-4623-a272-93b5603a79d3"
/>

**Logs**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 03 08
PM"
src="https://github.com/user-attachments/assets/91aa3334-8f97-409a-9f8a-d9e19bff1892"
/>

## Breaking

- `scripts/tmux.sh` is removed — the dashboard replaces the tmux
log-pane workflow (docs, example walkthroughs, and the monitor-run skill
updated).

- Resolved per-component configs move from `{run_dir}/configs/*.json` to
`{run_dir}/configs/resolved/*.json`; `configs/` now holds the launch
TOML (`rl.toml`/`sft.toml`). Anything reading the old paths must switch
(the dashboard reads both layouts).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are additive for training (new CLI and docs) plus removal of
the tmux helper; the config path split may break external tooling that
still reads `{run_dir}/configs/*.json` directly.
> 
> **Overview**
> This PR adds **`uv run dashboard`** — a local web UI (default
**http://localhost:7788**) for watching SFT/RL/eval runs from output
directories only: **metrics** (W&B-style overview from `metrics.jsonl`),
**configs** (launch TOML vs merged resolved JSON), **rollout traces**
with per-token advantage/logprob views, and **merged component logs**.
It ships as a **`dashboard` optional extra** (FastAPI/uvicorn) or as
**`uv run --script src/prime_rl/dashboard/server.py`** on machines
without full GPU deps.
> 
> **`scripts/tmux.sh` is removed**; docs, basic examples, and the
**monitor-run** skill now recommend two terminals plus the dashboard
instead of tmux panes. Side-by-side ablations on one node can use **`uv
run dashboard outputs`** to track multiple experiments.
> 
> **Resolved configs** from dry-run and launches are documented at
**`{run_dir}/configs/resolved/*.json`**, with the launch TOML at
**`configs/*.toml`**; the dashboard server still reads the old flat
`configs/*.json` layout for older runs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
99d9a8f34e9c53b7de1f6a74f82c4053285ba506. 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 <noreply@anthropic.com>
2026-08-24 12:59:39 -07:00
Mika SenghaasandGitHub a975cab86d chore: bump renderers to 0.1.10 (#3367)
## Summary

- Require renderers 0.1.10 in Prime RL and prime-rl-configs.
- Update the renderers submodule to the 0.1.10 release.
- Update the verifiers submodule to the latest main commit.
- Refresh lock metadata for both dependency constraints.

## Verification

- uv lock --check
- uv run --no-project --with pre-commit pre-commit run --files
pyproject.toml packages/prime-rl-configs/pyproject.toml uv.lock

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> <sup>[Cursor Bugbot](https://cursor.com/bugbot) is generating a
summary for commit 95ca34dcca9b2737cf2ebb431a47391ed874052a. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 11:33:20 -07:00
Garrett GoonandGitHub 9aa5f1f2c8 docs(install): document pre-commit hook install step (#3366)
`uv sync --group dev` only installs the pre-commit package; the git hook
stays inert until `uv run pre-commit install` runs, which the install
skill omitted (README's Development section already covers it).
2026-08-24 14:25:05 -04:00
Matej SirovatkaandGitHub c09bb0b30c fix(nccl): avoid cloning received weight tensors (#3365)
## Summary

- yield tensor views into the contiguous NCCL receive buffer instead of
cloning every reconstructed tensor
- avoid duplicating checkpoint payloads while vLLM performs layerwise
weight loading

The change intentionally keeps the existing flat receive stream and vLLM
reload lifecycle. Trainer state-dict boundaries are transport framing,
not loader semantics: vLLM tracks layer completion from the weights
loaded for each module.

## Safety

Each yielded tensor is a disjoint view of the receive buffer. A view
retains its underlying storage, so the buffer cannot be released while
the loader still references one of its tensors. The existing consumers
either copy tensors directly into model parameters or synchronously
process the ordered checkpoint stream.

## H200 reproduction

The reported Laguna-S-2.1 failure was reproduced with one EP8 trainer
node, one TP8 inference node, BF16 checkpoint transfer, and
`gpu_memory_utilization = 0.94`. The receiver code at the tested
baseline (`f53e4d9c`) is unchanged on current `main`.

| Receiver | Startup v0 | Post-training v1 |
|---|---:|---:|
| `main` | OOM on a 20 MiB clone in state dict 3/49; HTTP 500; retry
decoded `54639` state dicts | — |
| this change | 49/49 on all 8 ranks; HTTP 200 | 49/49 on all 8 ranks;
HTTP 200 |

Both successful transfers took approximately 12 seconds by broadcast
markers; the trainer reported `time/broadcast_weights = 13.2418s` for
v1. The inference server subsequently completed two rollout batches, and
the trainer completed its first optimization step.

At `gpu_memory_utilization = 0.97`, the baseline failed earlier while
allocating the 4.64 GiB receive buffer itself, so `0.94` was used to
isolate the additional clone allocation.

## Validation

- `uv run --no-sync pytest -q tests/unit/inference
tests/unit/transports/test_nccl_broadcast.py` — 14 passed, 1 existing
skip
- `uv run --no-sync ruff check
src/prime_rl/inference/vllm/worker/nccl.py`
- `uv run --no-sync python -m py_compile
src/prime_rl/inference/vllm/worker/nccl.py`
- `git diff --check`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches distributed weight-transfer memory semantics on the inference
path; incorrect view lifetime could corrupt loads, but consumers copy
into model parameters synchronously.
> 
> **Overview**
> Fixes GPU OOM during NCCL weight broadcast by **not cloning** each
tensor when splitting the per-dtype receive buffer in
`receive_state_dict`.
> 
> Reconstructed weights are now **views** into the contiguous
`concatenated` buffer (`view(shape)` only), so checkpoint payloads are
not duplicated while vLLM runs layerwise loading via
`load_weights_checkpoint_layerwise` / `load_weights_kernel`. The flat
NCCL stream and per-state-dict receive lifecycle stay the same; disjoint
views keep the buffer alive until consumers finish using yielded
tensors.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d7bd908099d5cffb6792b9b40bdbd322851bc19a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 11:12:34 -07:00
3e93371dad chore: bump verifiers and prime-envs to latest main (#3363)
## Summary
- Bump the `deps/verifiers` submodule from `d4f3d5a8c` to `807aaf389`
(latest `main`).
  - Pulls in:
- [vf#2425](https://github.com/PrimeIntellect-ai/verifiers/pull/2425):
forward sampling parameters across dialects.
- [vf#2428](https://github.com/PrimeIntellect-ai/verifiers/pull/2428):
centralize v1 egress policy decisions.
- [vf#2427](https://github.com/PrimeIntellect-ai/verifiers/pull/2427):
simplify v1 CLI plumbing.
- Bump the `deps/prime-envs` submodule from `b30aad36` to `26dafdc9`
(latest `main`).
  - Pulls in:
-
[prime-envs#761](https://github.com/PrimeIntellect-ai/prime-envs/pull/761):
environment-design rules in AGENTS.md.
-
[prime-envs#762](https://github.com/PrimeIntellect-ai/prime-envs/pull/762):
CI fix for swebench 5 + prime-sandboxes 0.2.37.
-
[prime-envs#684](https://github.com/PrimeIntellect-ai/prime-envs/pull/684):
deshuffle-papers environment.
-
[prime-envs#675](https://github.com/PrimeIntellect-ai/prime-envs/pull/675):
DeepSWE environment.
- Relock `uv.lock`: new workspace members `deep-swe` and
`deshuffle-papers`; `mcp-atlas` 0.3.0 → 0.3.1, `swesmith-env` 0.1.2 →
0.1.3.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Dependency/submodule bump that pulls new training environments and
tighter swebench/prime-sandboxes pins; not auth-critical, but can change
eval/training behavior.
> 
> **Overview**
> Bumps `deps/verifiers` and `deps/prime-envs` to latest `main` and
relocks `uv.lock`.
> 
> **verifiers** picks up sampling-parameter forwarding across dialects,
centralized v1 egress policy, and simpler v1 CLI plumbing.
> 
> **prime-envs** adds the `deep-swe` and `deshuffle-papers` workspace
environments, plus env-design AGENTS.md rules. `mcp-atlas` goes 0.3.0 →
0.3.1 (`prime-sandboxes>=0.2.37`); `swesmith-env` goes 0.1.2 → 0.1.3
(`swebench>=4.1.0,<5`).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b5b07f4795eb911daf72d30203dbd617dec63b37. 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 <noreply@anthropic.com>
2026-08-23 18:11:10 -07:00
f53e4d9c63 fix: health-check only the router when admin clients bypass it (#3359)
## Summary

- `AdminClients.wait_for_ready` still health-checks every engine and the
router, but when admin URLs bypass a router, the per-engine waiting
lines log at debug. Startup then logs one info waiting line instead of
one per engine plus the router:

```
03:18:09    INFO Waiting for inference server at http://localhost:8000 to start up (30s elapsed)
03:18:09    INFO Waiting for inference server at http://localhost:8100 to start up (30s elapsed)
```

- `check_health` grows a `quiet` flag that demotes its periodic waiting
lines to debug.
- Deployments without a router (no `client.admin_base_url`) keep logging
at info, as before.

Waiting only on the router is not enough: the llm-d router (Envoy) only
routes `/v1/` and `/inference/v1/`, so `/health` 404s and `check_health`
treats that as "no health route" and skips. The engines therefore stay
part of the readiness wait for correctness; the router just owns the
info-level log. Caveat: on llm-d deployments the info-level waiting line
disappears once Envoy binds its port (the engine waits continue at
debug).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Readiness polling and log-level only; no change to auth, weights, or
request serving. Timeout behavior is the same, just split across two
concurrent health waits.
> 
> **Overview**
> Fixes readiness for llm-d/Envoy routers: `/health` on the router 404s
and was treated as “no health route,” so waiting on the router alone was
not a real ready signal.
> 
> `AdminClients.wait_for_ready` now health-checks engines and router in
parallel. Engine waits use a new `quiet` flag so periodic “waiting”
lines log at debug when a router is present; the router still logs at
info. Deployments without `admin_base_url` are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5167b63bac1ed60edf3f79a99ed470d25a6a026e. 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 <noreply@anthropic.com>
2026-08-22 22:03:11 -07:00
Mika SenghaasandGitHub cabbd132eb feat: unified weight transport protocol (#3357)
## Summary

The weight-broadcast core: one protocol for every transport instead of
three private ones.

- **One handshake per version, on every transport**:
`WeightSender.broadcast` is a template method - the trainer resets the
step dir and offers (`.sender_ready`), blocks until the consumer
acknowledges (`.receiver_ready`), transfers (`.started`), commits
(`.finished`), and cleans old dirs. Filesystem does the full handshake:
no consumer run-ahead while the trainer writes, no version skipping ("fs
== nccl behavior").
- **`WeightReceiver`**: consumer-side counterpart, colocated with its
sender per transport file
(`transports/weights/{base,filesystem,nccl,nixl}`). The weight watcher,
the orchestrator startup rendezvous, and the evals process drive the
same object; discovery is uniform on `.sender_ready`. Every offered
version must be received - a failed receive fails the run. This deletes
the NIXL version-cap/cycle-counting hack (markers are versioned on every
transport). The engine-side byte receiver stays in
`inference/vllm/worker`.
- **Consumption-driven sequencing**: broadcast `v{N}` iff something
consumes it. `broadcast_final` lives once on the shared
`BaseWeightBroadcastConfig`, launcher-stamped, never user-set (RL:
`orchestrator.eval is not None`; SFT: `True`). With evals, the final
eval measures `v{max_steps}` on every transport.
- **Bounded handshake**: the trainer's wait for the receiver raises
`TimeoutError` after `weight_broadcast.timeout` (now on the shared
config base, so filesystem has it too), with progress warnings every
60s.
- **Unified cleaning**: keep exactly `{step, step-1}` - broadcasts are
purely transitive, `checkpoints/` owns persistence. Fixes NCCL/NIXL dirs
leaking forever.
- **Fail-fast startup**: RL and SFT both broadcast the incoming policy
before the first step; resume hygiene (`prune_broadcasts_beyond`) lives
at the trainer call sites and prunes stale future dirs.

## Breaking

- On-disk sentinels replaced: `STARTED`/`STABLE`/`NCCL_READY` →
`.sender_ready`/`.receiver_ready`/`.started`/`.finished`, one uniform
handshake per version. Trainer and orchestrator must ship together. A
resume over old broadcast dirs re-broadcasts the startup version.
- Filesystem runs in lockstep with its consumer: the trainer blocks
until each version is acknowledged (bounded by
`weight_broadcast.timeout`), no longer writes versions nobody consumes,
and the consumer no longer skips to the newest version.
- RL with evals broadcasts `v{max_steps}` and the final eval measures it
(metric shift). Without evals, `v{max_steps}` is skipped on every
transport.
- Broadcast-dir retention: exactly the last 2 dirs on every transport
(NCCL/NIXL dirs were previously leaked; SFT kept newest-only).

## Verification

Stack 6/6 of the #3335 breakup; the composed stack is tree-identical to
the e2e-verified #3335 branch (FFT NCCL 10→20 with resume, FFT
filesystem 10→20 with resume, LoRA filesystem 15→20 with resume,
LoRA+NCCL config rejection - all green; per-leg details in #3335).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Rewrites the trainer–inference weight-sync protocol (handshake,
version sequencing, eval/startup rendezvous) across all transports. A
mismatch or timeout now blocks or fails the run rather than skipping a
version.
> 
> **Overview**
> Unifies filesystem, NCCL, and NIXL weight updates onto one lockstep
handshake so every offered policy version is acknowledged before
transfer.
> 
> Trainer `WeightSender.broadcast` now always offers `.sender_ready`,
waits for `.receiver_ready` (bounded by `weight_broadcast.timeout`),
then marks `.started` / `.finished`. Orchestrator, evals, and the weight
watcher all drive a shared `WeightReceiver` instead of per-transport
polling (`STABLE` / `NCCL_READY` / ModelExpress cycle counting). Failed
receives fail the run; filesystem no longer lets the consumer skip ahead
while the trainer writes.
> 
> Broadcasts are consumption-driven: `v{max_steps}` is sent only when a
final eval will measure it (`broadcast_final`, launcher-stamped). Both
RL and SFT fail-fast with a startup broadcast, prune stale future dirs
on resume, and keep only `{step, step-1}` on disk. Trainer and consumer
must ship together — on-disk sentinels are a breaking change.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
53da37d3028a5755afc3615581c9664bfc47bf85. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-22 20:04:36 -07:00
Mika SenghaasandGitHub 947a02aafc feat: serve the LoRA adapter under the base model name (#3358)
## Summary

- Register the single training adapter under `config.model.name`: the
adapter shadows the base model (vLLM resolves `lora_requests` before the
base-model match; verified on the pinned vLLM 0.26), so requests keep
addressing one stable name and nothing switches model names mid-run.
- `update_weights` becomes artifact-driven: a weight dir holding
`adapter_config.json` is hot-swapped as an adapter (a vLLM-native
in-place reload, no engine pause); anything else is a full checkpoint
load.
- Deletes the adapter-naming machinery: the per-version model-name
rewrite in watcher/orchestrator/evals, evals' fixed `eval-adapter` name
and disk-sniff dance, `update_model_name`, and the dead
`unload_lora_adapter`.
- Guardrails: `modules_to_save` is rejected when the weight broadcast is
live (only adapter tensors ship - fully-trained modules would silently
diverge from inference); the LoRA/in-memory rejection states the real
reason (vLLM loads adapters only from a PEFT-shaped directory on disk).
The fallback, if a future vLLM rejects registering an adapter under a
served model name, is documented in the `/load_lora_adapter` wrapper: a
distinct constant name set once at startup.

## Breaking

- `orchestrator.model.lora.name` config field removed (with its
`r{rank}-a{alpha}` auto-derivation). External clients that addressed the
adapter name must use the base model name.
- Inference `max_loras` default 8 → 1 (in-place reload reuses one slot);
the `max_cpu_loras = 100` unload-era override is removed.

Part of the #3335 breakup (stack 5/6); re-lands #3356, whose
squash-merge landed on the stacked base branch instead of main. Verified
e2e as part of #3335 (LoRA reverse-text 15→20 with resume, reward
climbing under the base name).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the LoRA inference serving path and is a breaking config
change (`orchestrator.model.lora.name` removed, `max_loras` default
8→1). Wrong adapter naming or slot count would mis-serve or fail weight
updates.
> 
> **Overview**
> Registers the single training LoRA under `config.model.name` so the
adapter shadows the base model in vLLM. Requests keep using one stable
name; each policy version is an in-place reload (no engine pause, no
mid-run `model_name` rewrite).
> 
> `update_weights` is now artifact-driven: a dir with
`adapter_config.json` loads as LoRA; anything else is a full checkpoint.
Adapter-naming machinery is gone (`orchestrator.model.lora.name`, evals'
`eval-adapter`, `update_model_name`, `unload_lora_adapter`). `max_loras`
defaults to 1 and `max_cpu_loras` is dropped.
> 
> Rejects `modules_to_save` on live broadcasts (only adapter tensors
ship) and documents why LoRA needs filesystem broadcast. Clients that
used a custom adapter name must now hit the base model name.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7e4ba4ce153ee54b87816b573701cf9f95bda928. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-22 19:58:13 -07:00
Mika SenghaasandGitHub f615de9383 refactor: split InferencePool into InferenceClient and AdminClients (#3355)
## Summary

- Split `InferencePool` into two explicit classes under
`prime_rl.orchestrator.clients` (moved out of `utils.client`):
`InferenceClient` (data plane: train/eval client configs, model name,
prefill scoring - single-valued, one router endpoint) and `AdminClients`
(admin plane: one httpx client per engine process, in GPU-rank order -
the `rank_offset` math in the broadcast init depends on it; readiness
checks).
- Data-plane variables are named `clients` across the codebase
(`policy_pool`/`pool`/`policy_inference` renamed; the dispatcher uses
`policy_clients` to distinguish from frozen-source clients).
- Fixes the httpx-client leak: `InferencePool.stop()` closed only the
prefill scorer, leaking N+1 admin/router clients per pool; `aclose()`
now closes all of them.
- Deletes the dispatcher's `pinned_client` - a no-op since the
single-URL router (the client for a group never changes).

Behavior-preserving otherwise: the LoRA-name plumbing and the NCCL_READY
marker semantics are untouched (they change in the stacked follow-ups).

Part of the #3335 breakup (stack 4/6).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches orchestrator inference wiring, weight updates, and shutdown,
but is a behavior-preserving split plus a resource-leak fix. NCCL
world-size is now required rather than defaulted.
> 
> **Overview**
> Splits the combined `InferencePool` into a **data plane**
(`InferenceClient`: train/eval clients, model name, prefill scoring) and
an **admin plane** (`AdminClients`: per-engine httpx clients in GPU-rank
order, readiness). Client helpers now live under
`prime_rl.orchestrator.clients`.
> 
> Call sites (orchestrator, evals, dispatcher, algorithms, generation
sources, watcher) take `clients` / `admin_clients` instead of a pool.
Frozen endpoints use a one-shot `check_inference_ready` instead of a
persistent admin plane.
> 
> Also **closes the httpx leak** (`aclose()` now shuts down admin/router
clients, not just the scorer), drops the unused dispatcher
`pinned_client`, and requires `inference_world_size` for NCCL init.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
19092eeb66bd30ff0fe34e5e64eb9a3276fa9c0f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-22 19:54:55 -07:00
Mika SenghaasandGitHub 1093f9b914 refactor: rename transports.rollouts to transports.batch (#3354)
## Summary

- Rename `transports.rollouts` → `transports.batch`: the module ships
packed training batches, not rollouts.
`MicroBatchSender`/`MicroBatchReceiver` (and the ZMQ/FileSystem
variants) become `BatchSender`/`BatchReceiver`;
`setup_micro_batch_{sender,receiver}` become
`setup_batch_{sender,receiver}`.
- The `MicroBatch` payload type, every `list[MicroBatch]` signature, and
the `rollout_transport` config field are unchanged.

Part of the #3335 breakup (stack 3/6).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-08-22 19:34:34 -07:00
Mika SenghaasandGitHub 67ab1d6667 chore: remove dead extra_headers_from_state config (#3353)
## Summary

- Remove the `client.extra_headers_from_state` config field and the
`auto_setup_session_headers` validator that populated it. The field has
no readers: v1 clients send the `X-Session-ID` sticky-routing header
themselves, from the rollout's trace id (`SESSION_ID_HEADER` in
`verifiers/v1/clients`, attached per request in `train.py` and
`eval.py`). Verified at the wire: requests through the real vf client
arrive at the router with the header and route sticky per session.

## Breaking

- `client.extra_headers_from_state` config field removed (dead - nothing
read it).

Part of the #3335 breakup (stack 2/6, on #3352).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-08-22 19:33:01 -07:00
Mika SenghaasandGitHub 04e796d21b fix: treat a resume past max_steps as the last step (#3352)
## Summary

- A run resumed from a checkpoint at or beyond `max_steps` never matched
the `is_last_step ==` check, so the trainer idled forever waiting for a
batch that would not come. `>=` makes it exit as the last step.

Part of the #3335 breakup (stack 1/6).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-08-22 19:32:45 -07:00
9f29e5388e chore: clean up trainer and orchestrator logging (#3345)
## Summary

Log audit of the trainer and orchestrator, from a side-by-side read of a
full run's logs and the code that emitted them.

**Conventions** (applied everywhere):
- Every potentially slow action logs an active-tense info line first
(`Initializing X`, `Waiting for X`) — the last info line always names
the action that crashed or hung.
- Each one is paired with a debug completion carrying `format_time`
timing (`Initialized X in 1.2s`). All debug timings now use
`format_time`.
- Component inits log exactly `Initializing X ({config})`. Monitors log
a names-only summary plus one full-config line per monitor, from
`monitors.setup`.

**Gaps filled** (previously silent hang points): startup weight sync
(can block minutes), orchestrator teardown (info + one debug line per
stage, so a wedged component is identifiable),
`setup_torch_distributed`, device mesh init, trainer startup broadcast,
W&B finalize.

**Setup reorder** (orchestrator): local init first — sender, filesystem
weight broadcast — then the waits last before the main loop (env servers
→ inference pool → NCCL/NIXL handshake → startup sync). The NCCL/NIXL
handshake stays post-readiness (it POSTs to live engines); the
checkpoint's curricula restore follows `envs.start()` (`TrainSource`
needs loaded tasksets). One awaited metrics scrape primes the
concurrency controller so `Derived initial max inflight` logs before
`Starting orchestrator loop`.

**Renames and demotions** (highlights):
- `waiting for trainer to broadcast checkpoint N` → `Waiting for the
trainer to broadcast policy v{N}`; steps vs 0-indexed policy versions
untangled throughout.
- The inference wait is info every 30 s (`Waiting for inference server
at {url} to start up (30s elapsed)`), error at debug — was a warning
every 10 s.
- One identity line on all three processes: `Starting from scratch` /
`Resuming from step {N}`; `Broadcasting base policy weights (v{N})`.
- Launcher: `Starting {name} server`, `Starting orchestrator` (no
"process").
- Removed the per-group success debug in the train sink (flooded one
line per group); drop-path logs stay, renamed `Dropped group | ... |
reason=...`.
- Demoted to debug: ZMQ sender/receiver init/close, `Using shared W&B
mode`, `Loading model config`, executor setup, GC line. LoRA debug no
longer dumps the full model repr.
- Punctuation/tense/indexing: `Saving final checkpoint at step N`, no
trailing `.`/`!` on finish lines, 1-indexed micro steps.

## Verification

Ran alphabet-sort debug-level runs on this branch (from scratch,
`--resume.step 2`, and post-merge): clean startup → steps → drain →
teardown on both processes, all lines rendering as intended, e.g.

```
INFO  Syncing inference to the trainer's startup broadcast (v0)
DEBUG Synced inference to policy v0 in 115ms
INFO  Stopping orchestrator components
DEBUG Stopping dispatcher
SUCCESS Orchestrator finished
```

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Mostly logging, but orchestrator setup order, resume-step timing,
NCCL/NIXL after pool ready, and an extra metrics probe change real
startup/teardown sequencing. A hang or resume mismatch would show up at
run start.
> 
> **Overview**
> Makes trainer/orchestrator/launcher logs follow a consistent pattern:
an **info** line for each potentially slow action (`Initializing` /
`Waiting`), then a **debug** completion with `format_time`. Identity
lines are aligned (`Starting from scratch` / `Resuming from step N`),
policy versions are labeled `v{N}`, and noisy lines (ZMQ init, GC,
per-group success, full model repr) are demoted or removed.
> 
> **Orchestrator `setup` is reordered**, not just reworded: local work
(packer, micro-batch sender, filesystem broadcast) runs first; env
servers, inference readiness, NCCL/NIXL handshake, and startup weight
sync wait last. Resume step is applied before those waits. Teardown now
logs each stage. An awaited `inference_metrics.probe()` primes the
concurrency controller before the loop starts.
> 
> Inference health wait is info every 30s (errors at debug). Drop-path
logs stay as `Dropped group | … | reason=…`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f1f33c0fc2fa3a2193118991c256cee0aae232ff. 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 <noreply@anthropic.com>
2026-08-22 16:59:26 -07:00
822db2902c feat: drop orchestrator-side renderer for trace-stamped mm token map (#3349)
## Summary

- Drop the orchestrator-side renderer: the orchestrator built a full
`Renderer` only to read `mm_token_type_id_map` off it and stamp
per-token modality markers in `trace_to_samples`. verifiers now stamps
the map onto the trace at turn commit and exposes the training-ready
stream as `Branch.mm_token_type_ids` (PrimeIntellect-ai/verifiers#2424)
— the orchestrator consumes that and builds no renderer at all.
- `trace_to_samples` reads `branch.mm_token_type_ids` directly; the
`mm_token_type_ids_mapping` parameter and its `TrainSink`/`Orchestrator`
plumbing are gone.
- `setup_policy_inference_pool` (now just an `InferencePool`
construction) is inlined into `Orchestrator.setup()`; its mock-based
unit test file is removed.
- Bumps `deps/verifiers` to verifiers main, which includes the merged
PrimeIntellect-ai/verifiers#2424. Rollout rendering is unchanged — it
already happens inside verifiers' renderer train client.

## Verification

Before/after 6-step multimodal RL runs (color-codeword,
`Qwen/Qwen3.5-4B`, 1 train + 1 infer GPU, batch 64, group 8):

- **Before** (main): rewards 0.17 → 0.36 across 6 steps, 0% errors, all
samples trainable, losses finite.
- **After** (this PR + vf#2424): rewards 0.13 → 0.42 across 6 steps, 0%
errors, all samples trainable, losses finite. The trainer hard-fails on
image samples missing `mm_token_type_ids` (`prepare_sample` raises), so
completing all steps proves the new path delivers them. The after-run's
orchestrator log contains no renderer initialization.
- Offline equivalence on the after-run's 833 dumped traces (2499
branches): every trace's stamped `mm_token_type_id_map` equals the
renderer map the orchestrator used to build (`{<|image_pad|>: 1,
<|video_pad|>: 2}`), and per-token ids computed the old way match
`Branch.mm_token_type_ids`' computation exactly.
- `tests/unit/orchestrator` green (the pre-existing `test_qwen3_vl_e2e`
failure needs a live vLLM and fails identically on main).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the multimodal training-sample path: missing or mismatched
`mm_token_type_ids` would fail trainer `prepare_sample`. Behavior now
depends on verifiers stamping the map correctly rather than a local
renderer.
> 
> **Overview**
> Stops building an orchestrator-side `Renderer` just to stamp
multimodal token types. Training samples now take `mm_token_type_ids`
from `branch.mm_token_type_ids` (stamped by verifiers at turn commit).
> 
> `setup_policy_inference_pool` is inlined as a direct `InferencePool`
construction. `TrainSink` / `Orchestrator` no longer plumb
`mm_token_type_ids_mapping`, and the helper’s unit tests are removed.
Rollout rendering is unchanged (still inside the renderer train client).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4e6fde2b910f91e80fd460704077f87c98329032. 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 <noreply@anthropic.com>
2026-08-22 16:36:48 -07:00
Mika SenghaasandGitHub adfbc6003d feat: expose repository skills to codex (#3347)
## Summary

- Add `.agents/skills` as a symlink to the shared `skills/` directory.
- Make repository skills available through Codex default discovery.

## Verification

- Confirmed `.agents/skills` resolves to `../skills`.
- Commit hooks passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Config-only symlink for agent skill discovery; no runtime, auth, or
data-handling changes.
> 
> **Overview**
> Adds a `.agents/skills` symlink to `../skills` so Codex can discover
the repo’s shared skills via its default lookup path.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
625149a26b20bafa2d3901222d4c1b7f4bdef35b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-22 15:44:18 -07:00
94a93203cf fix: only pkill zombie torchrun/vLLM processes in CI (#3346)
## Summary
- Gate the autouse `cleanup_zombies` fixture in `tests/conftest.py` on
`USERNAME_CI`.
- The fixture pkills `-f torchrun` / `-f VLLM` host-wide at every test
module start. In CI this cleans up zombies from previous tests, but
locally it kills any concurrent training run on the box.
- `USERNAME_CI` is already set to `CI_RUNNER` by all CI pytest jobs
(`cpu_tests`, `gpu_tests`, `nightly_tests`) and already keys the `user`
fixture, so CI behavior is unchanged and no workflow changes are needed.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Test-only fixture change; CI behavior is preserved. Residual risk is
local leftover processes if tests leak zombies without USERNAME_CI.
> 
> **Overview**
> Stops the autouse `cleanup_zombies` fixture from host-wide `pkill` of
`torchrun`/`VLLM` on local pytest runs, so concurrent training jobs are
no longer killed.
> 
> The kill still runs when `USERNAME_CI` is set (already used by CI
pytest jobs), so CI zombie cleanup is unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
454f89e5c269d62410f2ea007b884537dd964045. 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 <noreply@anthropic.com>
2026-08-22 15:44:00 -07:00
f0d27513a4 chore: glm-4.5-air swe example to bf16 + bash harness (#3343)
## Summary

- `examples/advanced/glm-4.5-air/swe.toml`: serve inference from the
bf16 checkpoint directly — drop `quantization = "fp8"` from
`[inference.vllm]`.
- Switch the train and eval harnesses from `rlm` to `bash`. Drop the
rlm-only `summarize_at_tokens` knobs.
- Update the header comments to match.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Example-only TOML config; no training, inference, or harness code
changes.
> 
> **Overview**
> Updates the GLM-4.5-Air SWE example so inference serves the **bf16**
checkpoint directly (drops vLLM `fp8` quantization) and train/eval use
the **bash** harness instead of **rlm**, including removing
`summarize_at_tokens`. Header comments are aligned with that.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
72032855baa5712daab635147683cf9c09541bf0. 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 <noreply@anthropic.com>
2026-08-22 13:45:23 -07:00
684f0d0afe chore: fold source sub-configs into dotted keys (#3344)
## Summary

- Fold every `[[...source]]` entry's nested sub-configs into dotted keys
in one block (`env.taskset.id = "..."`, `env.agent.harness.id = "..."`)
instead of one full-path subsection header per nested config. Applies to
all train/eval source blocks in `configs/`, `examples/`, and `k8s/` (51
TOML files, −868/+322 lines).
- Move the top-level `[monitors.prime]` block up next to
`[monitors.wandb]` in the 4 files where it sat inside the orchestrator
section.
- Apply the same style to the TOML snippets in `docs/` and the `configs`
/ `training/start-run` skills, and document the convention in the
configs skill. Nested arrays of tables (e.g.
`[[...source.env.taskset.task.judges]]`) keep their full-path headers.

Purely cosmetic — no config semantics change. Verified by asserting
`tomllib` parses every file to an identical dict before and after, and
by diffing the resolved-config JSON from `rl --dry-run` (identical up to
the CLI-passed `output_dir`).

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 13:39:56 -07:00
559b44772e chore: bump verifiers to latest main (#3337)
## Summary
- Bump the `deps/verifiers` submodule from `4bcb48e` to `a60a606`
(latest `main`).
- Pulls in:
- [vf#2410](https://github.com/PrimeIntellect-ai/verifiers/pull/2410):
prime-sandboxes 0.2.39 + pooled per-loop sandbox client.
- [vf#2422](https://github.com/PrimeIntellect-ai/verifiers/pull/2422):
evals run through the env server by default.
- [vf#2423](https://github.com/PrimeIntellect-ai/verifiers/pull/2423):
strip the hub org prefix before importing a plugin module.
- Relock `uv.lock`: prime-sandboxes 0.2.37 → 0.2.39, connect-python →
connectrpc 0.11.1, new protobuf-py transitive deps.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Dependency bump of the verifiers/sandbox stack can change eval routing
and RPC client behavior; lockfile-only surface but runtime impact is
non-trivial.
> 
> **Overview**
> Advances the `verifiers` pin and relocks `uv.lock` so
`prime-sandboxes` moves **0.2.37 → 0.2.39**.
> 
> That pull also replaces `connect-python` with `connectrpc` 0.11.1 and
adds transitive `protobuf-py` / `protobuf-py-ext`. Upstream verifiers
changes include a pooled per-loop sandbox client, evals defaulting
through the env server, and stripping the hub org prefix on plugin
import.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
13b8ad796e06175e26b6196815631c2bbf40e36a. 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 <noreply@anthropic.com>
2026-08-21 22:39:59 -07:00
Konstantin DunasandGitHub 1e756307ae refactor(orchestrator): make dispatch contracts explicit (#3334) 2026-08-22 00:58:37 +02:00
2441fd5142 feat: drop on in-queue staleness + first-class cancellation type (#3313)
## Summary

Refactors staleness handling around the exact consumption-lag definition
(#3050's framing), toward #3310.

- **Exact measurement**: `episode_staleness()` decomposes each trained
episode's staleness from its `PolicySpan` into the in-flight share (`end
- start`, weight updates during generation) and the in-queue remainder
(buffered between completion and ship). New per-step metrics:
`off_policy/{mean,max}`, `off_policy/{in_flight,in_queue}/{mean,max}`,
`off_policy/dropped`; the step log line's `Max Off-Policy` uses the
exact definition. Every quality metric in the step log and the wandb
`effective` subset is computed over exactly the traces shipped to the
trainer this step (`batch.cohort`); only `Error`/`Cancelled`/`Ratio` are
arrival-window rates, since over the shipped set they are
0/0/share-of-shipped by construction.
- **In-queue enforcement**: previously only in-flight episodes were aged
and dropped — an episode that finished quickly and sat in the sink
accumulated staleness that was measured at ship but never enforced. Now
the sink sweeps `pending_batch` before every readiness check and voids
anything past `max_off_policy_steps`, so the bound is a hard guarantee
on trained data. The dispatcher's version-boundary sweep remains as a
compute saver (it must run before the engine pause for KV-abort safety)
and uses the same exact step-based formula.
- **Tail semantics**: the trainer now broadcasts every version except
`v{max_steps}` (the only one nothing can sample from), instead of
skipping the final `TARGET_LAG+1`. The orchestrator stays alive for the
last rendezvous (`wait_for_final_broadcast`), so `max_off_policy_steps`
holds exactly on every step including the final batch, and the tail
special-casing this used to need is gone (the dispatch gate's
final-batch exception and the watcher's shortened ModelExpress window).
Draining now starts right after shipping the final batch — the old
trigger needed a further batch to *fill*, which burned a batch of
inference and, under a tight `max_off_policy_steps`, never filled at all
(end-of-run livelock).
- **First-class cancellation**: dropped groups emit one typed
`Cancellation(group_id, count, reason)` on `out_q` instead of
per-episode synthetic `Cancelled`-error episodes; queue-voided episodes
are tracked in a `cancelled` id-set on the episode collections,
alongside `sampled`/`admitted`. Cancellations no longer confound error
metrics: `has_error` stays pure (overload cuts and staleness drops are
no longer counted as errors), the effective subset excludes cancelled
episodes explicitly, and the step log / wandb gain separate `Cancelled`
rates. A stale-voided group also bypasses curriculum admission — a
pipeline decision is not a task result.

## Breaking

- **wandb**: new `train/*/all/**/cancelled/mean` and per-step
`off_policy/*` keys; cancellations no longer appear under
`*/error/Cancelled` or inflate `has_error/mean`.
`dispatcher/off_policy_level/{mean,max}` →
`dispatcher/off_policy/{mean,max}`, now reporting the exact step-based
staleness of in-flight work instead of the aged in-flight counter.
- **Zero-output abort accounting**: cancelled groups still advance the
zero-output budget (by their full owed episode count), but stale-voided
groups no longer feed the curriculum via `on_result`.
- **Trainer broadcast schedule**: in-memory transports now broadcast
`v{max_steps-1}` (previously skipped); the orchestrator waits for it
before tearing down. The final drain no longer requires (or generates) a
throwaway post-final batch.
- **The bound's meaning tightened**: staleness now counts queue time,
not just weight updates during generation. A config tuned under the old
in-flight-only definition drops more aggressively at the same numeric
value; `max_off_policy_steps = 0` now means strictly synchronous (heavy
oversampling drops), where the old `0` only meant "no update
mid-generation".

## Verification

- Behavioral smoke (stubbed envs, no GPU): stale `Cancellation` voids
arrived episodes without reading as error; a fully-cancelled group still
advances the zero-output budget by its owed count; overload cancellation
finalizes the partial group and its survivors still train; the queue
sweep un-fills a batch, marks the episode cancelled, and counts drops;
the dispatcher drops exactly the groups past the bound and emits one
typed `Cancellation`; `effective` excludes cancelled while
`has_error`/`cancelled` stay disjoint.
- `tests/unit/orchestrator`, `tests/unit/test_configs.py`,
`tests/unit/transports`: 201 passed (the `test_qwen3_vl_e2e` failure is
pre-existing on `main`).
- `ruff check` and `ruff format --check` clean.
- E2E: 15-step reverse-text run with
`--orchestrator.max-off-policy-steps 0` (true on-policy), clean exit in
3m 21s. **All 15 step lines report `Max Off-Policy 0` and `Error 0.0%`**
— including the final batch, which now trains on the freshly-broadcast
`v{max_steps-1}`. Both enforcement layers fired throughout (45
queue-sweep drops, 14 in-flight cancel sweeps) with per-step `Cancelled`
up to 70% and zero genuine rollout failures — e.g. `Step 2 | … | Max
Off-Policy 0 | Error 0.0% | Cancelled 70.3% | …`; under the old
error-marker representation those cancellations would have read as
`Error ~70%`. Draining started immediately at the final ship (`Shipped
the final batch — draining pipeline`). Reward climbed 0.14 → ~0.77.
- E2E (filesystem broadcast): 8-step reverse-text run with
`--weight-broadcast.type filesystem --orchestrator.max-off-policy-steps
0`, clean exit for both processes. All 8 steps report `Max Off-Policy 0`
and `Error 0.0%` — including the final batch, since filesystem writes
every version (no skip path) and the final-broadcast wait is correctly
inert (0 occurrences). Drain fired at the final ship; the trainer wrote
all broadcast dirs and finished cleanly. NIXL is safe by construction
(trainer skip window and the watcher's ModelExpress guard both derive
from `max_steps` and moved in lockstep) but has not been exercised
end-to-end.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 14:55:24 -07:00
967fbf25ef fix(sft): resumed runs restart the data stream with num_workers > 0 (#3332)
## Summary

Since #3299 made `data.num_workers` default to 1, **every resumed SFT
run silently restarts the training data from the beginning** and freezes
the data position it writes into subsequent checkpoints.

Root cause: `train()` called `iter(dataloader)` before the resume path's
`ckpt_manager.load(..., dataloader=dataloader)`. With worker processes,
`iter()` forks the worker with a copy of the dataset in its *initial*
state; the later `load_state_dict` only stashes state for a future
iterator that is never created. Two symptoms:

- the resumed run consumes the dataset from row 0 again (visible as a
loss-slope kink at every resume — repeated data);
- `state_dict()` keeps returning the stashed loaded state, so every
post-resume checkpoint stores the resume-point position instead of the
live one, compounding across restarts.

Fix: create the iterator only after the potential resume load, with a
comment stating the constraint.

Also: `get_dataset_state` unpacked exactly one worker snapshot, crashing
**any** run with `num_workers > 1` at the startup log line (start or
resume) — it now returns positions keyed per worker, and stops dumping
`pending_sample` token buffers into the log. It keeps parsing the
loader's stashed state rather than the dataset object: after a resume
the restored position exists only there (the main-process dataset object
stays at position 0; workers receive the state on fork). This is now the
single code path: `num_workers = 0` (the only case with a different,
inline state layout) is no longer supported.

## Breaking

- `data.num_workers = 0` is rejected at config time (`ge=1`). Inline
main-process data loading is gone; use `num_workers = 1` (the default).

## Verification

A/B on `configs/ci/integration/reverse-text-sft/{start,resume}.toml`
(Qwen3-0.6B, 1 node, 2 GPUs, 5 steps + resume to 10), comparing
`checkpoints/step_N/trainer/dataloader/rank_0.pt` worker-snapshot
dataset state:

| variant | ckpt step_5 | ckpt step_10 (post-resume) |
|---|---|---|
| main, `num_workers=1` | `{'step': 213}` | `{'step': 213}` — frozen,
data restarted from row 0 |
| main, `num_workers=2` | — | crashes at startup (`ValueError: too many
values to unpack` in `get_dataset_state`) |
| this PR, `num_workers=1` | `{'step': 213}` | `{'step': 407}` —
advanced correctly |
| this PR, `num_workers=2` | `{'worker_0': 111, 'worker_1': 111}` |
`{'worker_0': 213, 'worker_1': 213}` — per-worker state restored and
advanced; workers consume disjoint shards |

Discovered on a production 500-step GLM-4.5-Air SFT run (india): after
two crash-resumes, both post-resume checkpoints carried the identical
dataset position (`{'step': 6657}` at step 150 *and* step 300) and the
loss slope steepened at each resume boundary from re-trained data.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 14:04:58 -07:00
e6d2b3f252 fix: meta load order (#3333)
* test(trainer): add xfail demonstrating buffer-reinit-after-load bug

load_dcp_from_hf runs init_buffers_post_meta() after dcp_load() writes
checkpoint values into persistent buffers, so any model whose reinit
touches a persistent buffer (e.g. Laguna's MoE expert_bias) has the
loaded value silently clobbered back to its reinit default.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(trainer): reinit buffers before loading checkpoint, not after

load_dcp_from_hf ran init_buffers_post_meta()/fix_model_post_empty()
after dcp_load() had already copied checkpoint values into persistent
buffers, silently clobbering any buffer both a reinit hook touches and
a checkpoint legitimately ships (e.g. Laguna's MoE expert_bias). Move
the call to run once, immediately after to_empty(), matching the
existing correct ordering in setup_model's checkpoint-deferred branch.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(trainer): rename test_model_load_order.py to models/test_state_loading.py

Group it with the other cross-cutting model-mechanism tests
(test_checkpointing.py, test_fused_moe.py) rather than the top-level
train/ dir, and name it for what it covers (weight-checkpoint state
loading) since models/test_checkpointing.py already covers activation
checkpointing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 16:41:15 -04:00
Konstantin DunasandGitHub 13553dd88a refactor(orchestrator): rename sampler to generation source (#3330) 2026-08-21 20:36:15 +02:00
Konstantin DunasandGitHub d37b57ba6e docs(training): correct saved episode references (#3329) 2026-08-21 20:36:08 +02:00
Konstantin DunasandGitHub 802a364e6a fix(orchestrator): label eval avg@k by episode group size (#3328) 2026-08-21 20:36:03 +02:00
Konstantin DunasandGitHub 9b9de2f1bc fix(orchestrator): apply taskset system_prompt override on the RL path (#3327) 2026-08-21 19:42:57 +02:00
fe38722e8b feat: enable nccl for sft online evals (#3323)
* enable nccl for sft online evals

* support multi-node sft nccl evals

* fix: enforce NCCL-requires-inference at the launcher, not the model validator

The launcher strips [inference] and [deployment] from the trainer sub-config
of a decoupled multi-node deployment, so the re-parsed sub-config tripped the
validator's guard and crashed every trainer rank at startup.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: remove accidentally committed gitlink

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: broken line continuation in NCCL sbatch template blocks

The {% if %} blocks left a whitespace-only line after the backslash
continuation, terminating the launch command early: the trainer/evals
processes ran without their tee pipelines (empty node_*.log/evals.log)
and the stray '2>&1 | tee ... &' ran as a separate command, mis-assigning
EVALS_PID.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* share weight broadcast config policy

* revert shared weight broadcast policy

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 22:34:32 -07:00
minh hoangandGitHub c69f5b0389 feat: support Qwen3.8 (#3314)
Qwen3.8 reuses the Qwen3.5 architecture verbatim — the dense 27B reports
`model_type: qwen3_5` / `Qwen3_5ForConditionalGeneration`, the 2.4T-A95B
reports `qwen3_5_moe_text` — but both places that enable Qwen3.5 keyed off
the repo name, so neither picked it up.

Trainer: gate the three Qwen3.5 patches on the loaded config's `model_type`
instead of a substring of `model.name`. The name check missed
`Qwen/Qwen3.8-27B` and the `qwen3_5_moe` fallback only caught the MoE
sibling, so the dense 27B trained without `_patch_qwen3_5_linear_attn_varlen`
— GatedDeltaNet gets no cu_seqlens, conv/SSM state leaks across packed
sequences, and 48 of its 64 layers are linear attention. model_type also
covers Qwen3.6 and renamed fine-tunes, which the name check missed too.

Parsers: `^Qwen/Qwen3\.5-` doesn't match the dotted 3.6/3.8 names and the
`^Qwen/Qwen3-` catch-all only matches hyphenated ones, so both parsers
auto-resolved to None and vLLM launched without either flag. Qwen3.8's chat
template opens `<think>` at the generation prompt, so reasoning would land
in `content` and tool calls would go unparsed.
2026-08-20 21:59:40 -07:00
29e4222767 feat: remove weight checkpointing (#3316)
* feat!: remove weight checkpointing

The trainer saves only DCP checkpoints. HF weights on disk exist in two
forms: weight broadcasts — the transient trainer-to-inference transport,
which SFT now ships for online evals (same filesystem component RL
uses, broadcast at eval steps, newest kept only) — and offline
conversion of DCP checkpoints via scripts/dcp_to_hf.py (full models and
LoRA adapters).

WeightCheckpointManager, the weights/step_N dirs, and the ckpt.weights
config surface (weights, weights_only, skip_gather_master_weights,
save_adapter_separately) are removed. The evals process watches
broadcasts/step_N (OnlineConfig.weights_dir renamed to broadcasts_dir)
and loads adapter broadcasts of LoRA runs via /load_lora_adapter. The
weight save/gather helpers move to prime_rl.utils.weights.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: wait for the resume-step broadcast before retriggering

The trainer rebroadcasts the resumed policy only after loading the
model, so a one-shot STABLE check usually lost the race and the watch
loop never retried (last_step is pre-seeded to the resume step). Wait
for the broadcast; give up only when a newer stable broadcast proves it
was already cleaned away.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: enable LoRA on the eval inference server

SFT LoRA online evals reload raw adapter broadcasts via
/load_lora_adapter, which requires enable_lora on the server. Mirror
the RL validator: set enable_lora and max_lora_rank when LoRA is on,
warn when inference is externally managed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: defer offline DCP->HF converter to a follow-up

The converter needs more standalone testing (incl. GPU-free use) and will
land in its own PR. The resume-preserves-weights test now compares the DCP
checkpoints directly via dcp_to_torch_save; the PEFT adapter-export tests
move to the follow-up with the script.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: DCP comparison keys and dtypes in resume test; idempotent rebroadcast

The trainer wraps DCP state as {app: {model: ...}}, so the converted
torch save must be indexed through 'app' — the bare 'model' lookup
raised KeyError. The two compared runs also train in different compute
dtypes (fp32 vs bf16 under full offload), so compare in bf16, which is
what the resumed model actually loaded.

The SFT startup rebroadcast now skips when the resume step's broadcast
already exists with STABLE: rewriting the same dir in place would race
an evals process already reloading it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 20:29:42 -07:00
e3e3a87dea feat: rank-parallel sharded save for filesystem broadcast (#3315)
* feat: rank-parallel sharded save for filesystem broadcast

Gather full weights cooperatively and let every rank convert and write
its own layer-aligned slice as safetensors shards, instead of funneling
everything through the master rank. D2H copies go through persistent
pinned buffers and overlap the per-tensor all-gathers. The broadcast is
always sharded safetensors now; the save_sharded and save_format knobs
are gone.

Laguna-XS.2 (68GB bf16) on 2 GPUs: gather 25.1s -> 2.7s, total save
83.1s -> 51.9s (the write phase is disk-bound on a single NVMe;
rank-parallel writes scale with per-node writers on shared
filesystems).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: create save dir in save_state_dict_parallel

Callers no longer need to pre-create the directory; a fresh save dir
made every rank's shard write fail with a safetensors I/O error.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: note the same-stream invariant on the staging copy

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: clarify HF conversion branches and resolve_fqn

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: blocking D2H copies in the parallel gather

Drop the pinned staging buffers and non-blocking copies: their safety
rested on same-stream allocator-reuse ordering, which is subtle to
maintain. Each rank still copies only its slice, and the parallel shard
writes — the dominant cost at scale — are unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: derive layer ownership from the module tree

Replace the FQN regex with prefixes taken from the children of every
'layers' ModuleList. State-dict keys and module names come from the
same tree traversal, so the prefixes match keys verbatim, wrapper
components and all.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Revert "refactor: derive layer ownership from the module tree"

This reverts commit 740059c835ac8025af00ab58cdbe1aef941168ee.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 20:29:14 -07:00
NeoandGitHub 65e4b915ba Relock prime-kernels after refreshing the v0.8.0 wheels (#3321) 2026-08-21 01:44:20 +02:00
a686a90405 Add custom vendored kernels (#3154)
* Add custom vendored kernels

* Add fused MoE kernel

* Fix comments, simplify kernel toml metadata, make sure deps for prime-kernels match prime-rl directly

* Update to latest fused moe kernel

* Add prime-flash-moe integration in addition to locally compiled kernels

* Add mxfp8 routing support for prime-flash-moe

* Fix MXFP8 backward for fused MoE for correctly group aligned experts

* Torch fused grouped_mm backward for fused MoE forward

* Fix release upload in kernel build: install gh in container, grant contents write

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Set GH_REPO for release upload: container checkout trips git dubious-ownership

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Pin prime-kernels at the v0.8.0 prebuilt wheels behind a kernels extra

The wheels were backfilled onto v0.8.0 from this branch
(build_kernels.yaml run 31429866271); uv sync --extra kernels now
installs them instead of requiring a local nvcc build.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Format kernel MoE files with ruff 0.13

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Fix memory corruption of triton kernel for large numel quants, where N >= 2^31=INT_MAX

* Make the kernel a git-submodule

* Move the kernels into the prime-kernels submodule

The `prime-kernels` wheel — build system, registry and every kernel's Python
surface — now lives in its own monorepo, PrimeIntellect-ai/prime-kernels,
checked out here as the `kernels/` submodule. flash_moe's C++/CUDA sources,
previously a nested prime-flash-moe submodule, are committed there too, so one
non-recursive init brings in everything a source build needs.

Integration is unchanged: `uv sync --extra kernels` still resolves the prebuilt
wheels from a prime-rl release, `uv pip install --no-build-isolation -e kernels`
still builds from source, and build_kernels.yaml still attaches the wheels to
every release. Its `paths` trigger moves from `kernels/**` to the `kernels`
gitlink, which is the only path prime-rl tracks now, and ruff excludes the whole
submodule rather than just the vendored sources.

* Update kernels

* Fix comments

* Add tests for the fused MoE

* Bump prime-kernels to 2ceaf9e

* Remove stray uv.lock for prime-rl-configs

* Verify mxfp8 grad values and needs_input_grad handling

* Print epsilons in tests

* Print epsilons in tests

* Print epsilons in tests

* Print epsilons in tests

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 01:28:32 +02:00
991b925e6e validate scheduler steps at config time (#3318)
A linear scheduler with warmup_steps + decay_steps > max_steps only
failed deep into trainer setup, via a bare assert in
setup_linear_scheduler. Add validate_scheduler to the configs package
and call it from TrainerConfig and SFTConfig so the run fails at
config validation instead. Also covers cosine schedulers, which need
max_steps and warmup_steps < max_steps.

The runtime assert stays as a backstop (SFT resume with skip_scheduler
shrinks the step budget at runtime) but now carries a message.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 15:06:34 -07:00
Konstantin DunasandGitHub 03cdc51575 refactor(orchestrator): score native episodes (#3297) 2026-08-21 00:06:29 +02:00
NeoandGitHub cb5f1e72bb Turn fused adamw on by default except when we do cpu offloading (#3305) 2026-08-20 09:01:59 -07:00
samsjaandGitHub 52eebada92 fix(tests): seed qwen3_moe parity test RNG and widen grad tolerance (#3290)
test_qwen3_moe compares HF and prime-rl gradients in bf16 with an
unseeded random draw; FA2 backward is not bit-deterministic, so the
embedding grad diff (observed 512-1344) occasionally crosses the
atol=1000 threshold, failing CI with 'Max grad diff: 1024.0' on main
and unrelated PRs.

- autouse fixture pins torch.manual_seed(0) so the input/init draw is
  deterministic (verified grad diff stays in 512-768 on this seed)
- bump grad atol 1000 -> 2048 to absorb FA2 backward reduction-order
  noise that seeding cannot remove (60/60 random seeds pass at 2048,
  worst observed 1344)
2026-08-19 20:30:47 -07:00
NeoandGitHub 5d0fc8ba2e Mario/cpu optimization dataloader (#3299)
* USe dataloder threads and pinnd memory tranfers async

* Fix PRNG

* Reset fused lm head token chunk size to 4k

* Revert lm head chunk size to default, another PR does this

* Remove unused prefetch factor

* Fix PRNG bug
2026-08-19 20:26:12 -07:00
Mika SenghaasandGitHub c2a25f0622 feat: soft and hard kv cap (#3307)
* Split kv trims into soft and hard tiers

A trim at the 0.8 trigger now only lowers the cap and lets completions
drain the pool — at that level there is still headroom, and at steady
state completions usually outrun in-place context growth, so
cancelling immediately pays a certain cost to avoid a merely possible
one. Only if usage climbs past 0.9 despite the closed gate does the
trim also cancel the excess (the prior behavior), preserving the
thrash-cliff guarantee: worst case, a soft trim escalates to a hard
one a cooldown later, still well before the cliff. Emergency cuts are
unchanged.

* Add 2-node concurrency debug config

GLM-4.5-Air scaleswe on the bash harness, 1 train + 1 infer node,
default concurrency, 100-instance SWE-Bench eval.

* Rename trim thresholds to KV_USAGE_SOFT_CAP / KV_USAGE_HARD_CAP

* Fix stale header in the concurrency debug config
2026-08-19 16:00:14 -07:00
bc9e186963 feat: adaptive concurrency for online evals (#3309)
* feat: first-class evaluator with adaptive concurrency

Promote the evaluator out of the orchestrator package into
prime_rl.evaluator and let it run standalone multi-env evals (no
[online] block: one epoch against the served weights, then exit) as
well as SFT online evals ([online]: watch the weights dir per
checkpoint; the sft launcher writes this config).

Scheduling reuses the orchestrator pipeline 1:1: an eval-only
Dispatcher sized by the adaptive ConcurrencyController
([eval.concurrency], replaces eval.max_inflight_episodes), fed by the
InferenceMetricsCollector's /metrics polls. Overload cuts only block
admission - eval episodes are measurements and always run to
completion.

The evaluator spawns an env server per source without an explicit
serve.address; the sft launcher keeps spawning its own and stamps the
derived addresses into the evaluator config.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: stop evaluator collectors before monitor finalize

The periodic logger and the inference-metrics collector log to the W&B
run, so a poll landing after monitors.finalize() warns about a finished
run - mirror the orchestrator and stop them on the clean path first.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: fail fast when adaptive concurrency has no metrics

External inference APIs (e.g. Prime Inference) expose no vLLM /metrics,
so the concurrency controller never bootstraps and the cap would
silently sit at min_inflight forever. The evaluator now probes /metrics
once at startup: no engine metrics + an adaptive band raises with the
fix (pin min_inflight = max_inflight); a pinned band runs fixed with a
warning. A successful probe also bootstraps the controller before the
first dispatch.

Add examples/evals/swe.toml: SWE-bench Verified + Terminal-Bench 2
against deepseek/deepseek-v4-flash on Prime Inference, 1h agent cap,
pinned band.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: rename evaluator command and configs to evals

Per review: the command is uv run evals, the config classes are
EvalsConfig / EvalsEvalConfig in prime_rl.configs.evals, the package is
prime_rl.evals, and the launcher artifacts follow (evals.json,
evals.log, shared-W&B labels). Docs section is Evals. Add EvalsConfig
to the config-load CI check so examples/evals/*.toml are validated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: drop the Evaluator name entirely

Class Evals in prime_rl.evals.evals, run_evals wrapper, Evals proc
title and log lines; prose refers to the evals process. No identifier
or doc references evaluator anymore.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: drop the standalone evals section for now

Keep the online-evals doc updates (command rename, [eval.concurrency])
and the start-run skill runbook.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: reject skip_first_step on standalone evals

The first trigger honors skip_first_step, and standalone mode has only
that trigger - the run would exit successfully without evaluating
anything. Reject the combination at config time.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: cap CI concurrency at 128 in-flight episodes

The adaptive ramp on CI's small engine floods the router until its
circuit breakers open (ProviderError: No available workers) - 512 is
still past what the deployment sustains.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: lower wiki-search initial_inflight to the CI cap

initial_inflight must not exceed max_inflight.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 15:05:19 -07:00
NeoandGitHub bfb0fe346e Remove pipeline sync in inner loss function loop by replacing the bra… (#3294)
* Remove pipeline sync in inner loss function loop by replacing the branch with branchless code

* Ruff format
2026-08-19 12:56:19 -07:00
NeoandGitHub 2acb19eccd Increase chunk size to 8k (#3302) 2026-08-19 12:53:00 -07:00
69308b88cb chore: move transport code to prime_rl.transports (#3308)
Consolidate the two send/recv stacks under one package:

- prime_rl.transport (rollouts, orch -> trainer) is now
  prime_rl.transports.rollouts
- prime_rl.trainer.rl.broadcast (weights, trainer -> orch -> infer)
  is now prime_rl.transports.weights

Both keep the base.py + concrete implementations structure. The vLLM
worker extensions and the orchestrator weight watcher stay in place
and import the shared primitives from the new location.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 12:14:21 -07:00
0630b7bff7 feat: adaptive concurrency (#3285)
* docs: add adaptive concurrency design

Feedforward token budget (n_max = kappa * C / G) from learned per-env
episode costs, trimmed by a binary engine-overload signal (AIMD on
kappa). Covers eval/train cost weighting, the step-1 freeze, and KV
offloading. Supersedes the reactive KV-target controller from #2908.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: clock adaptive-concurrency updates to steps

Re-evaluate n_max once per training step (G reweigh + at most one
kappa growth) - aligned with the per-step eval gate and naturally
plant-clocked, since step time tracks mean episode time. HARD cuts
stay on the 5s poll: waiting for a step boundary would sustain thrash.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: spec ConcurrencyController abstraction + config

Self-contained controller with [orchestrator.concurrency] config:
max_inflight ceiling (replaces orchestrator.max_inflight_episodes),
optional initial_inflight to skip the ramp, adaptive kill switch.
Kappa initialized by continuity at freeze exit. Pure state machine
driven by collector pushes, dispatcher completions, and the step loop.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: adaptive concurrency always on

Drop the adaptive flag from the design - the controller is not
optional. max_inflight is the only escape hatch (hard ceiling).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: adaptive rollout concurrency controller

ConcurrencyController sizes the dispatcher's in-flight cap as
n_max = clamp(kappa * C / G, group_size, max_inflight): a feedforward
token budget from engine KV capacity and learned per-env episode
costs, trimmed by a binary per-engine overload signal (HARD
preemption cut on the 5s poll, per-step growth otherwise). Always on.

- [orchestrator.concurrency]: max_inflight ceiling + initial_inflight;
  replaces max_inflight_episodes and oversampling_factor
- InferenceMetricsCollector always polls (wandb mirroring stays
  gated), parses cache_config_info labels for KV capacity, and pushes
  EngineLoadSample facts to the controller; the old waiting-queue
  overload warning is subsumed by the SOFT signal
- Dispatcher: dynamic set_limit, burst-capped refill, episode
  completion hook (env, kind, tokens, duration)
- configs/concurrency/: three e2e configs (low start, overload start,
  GLM-Air SWE with 10-turn eval)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: backoff naming + config comment fixes

Rename cut factors to BACKOFF_FACTOR / ESCALATED_BACKOFF_FACTOR,
describe kappa as the over-commit factor, add wandb project +
max_num_seqs to the hendrycks e2e configs (the vLLM default of 128
would queue instead of building KV pressure), and point verification
at the W&B gauges (the periodic logger does not feed metrics.jsonl).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: add no-eval concurrency e2e config

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: frozen_steps knob + 50-step e2e configs

concurrency.frozen_steps (default 0) pins the cap for the first k
steps; the first re-evaluation lands at the k -> k+1 boundary. HARD
cuts stay live inside the freeze. The e2e configs run 50 steps at
default gpu_memory_utilization with AIME avg@4 evals every 10 steps,
8k max_model_len, and run names matching the config file names.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: motivate higher frozen_steps values

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: rename concurrency e2e configs

hendrycks-low-no-eval -> hendrycks-initial-low,
hendrycks-low -> hendrycks-initial-low-eval,
hendrycks-high -> hendrycks-initial-high-eval.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: migrate example configs to initial_inflight

The old max_inflight_episodes values become concurrency.initial_inflight
starting caps - a hard ceiling is usually not wanted with the adaptive
controller.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: use config blocks for concurrency in examples

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: raise max_off_policy_steps in hendrycks configs

The adaptive cap runs hundreds of episodes in flight against a
64-sample batch, so episodes span more steps than the default
off-policy budget of 8.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: slash-namespace dispatcher gauge keys

dispatcher/inflight/{train,eval,groups} and
dispatcher/off_policy_level/{max,mean}, mirroring the
cancelled/errored/queued key scheme.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: drop groups-in-flight gauge

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: derive initial cap from engine max context

With initial_inflight unset, the starting cap is the pessimistic
bound C / max_model_len: an episode cannot exceed the engine context,
so that many episodes always fit. max_model_len comes from /v1/models
(set explicitly or taken from the model config) and also replaces
seq_len as the cost-estimate bootstrap once known.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: richer concurrency logging + wandb inflight mirror

- Active-voice change lines with state snapshots:
  '{Increased,Decreased} concurrency {x} -> {y} at step {n} ({reason})
  - kappa=.. cost=.. capacity=.. signal=..' plus per-env EWMA
  snapshots at debug
- One-time capacity report after the first poll ('Inference reports
  3.0M tokens of KV cache capacity - max model len 8.2K') and a
  derivation line when the initial cap is runtime-derived
- Collector accepts extra_metrics and mirrors
  inference/dispatcher/inflight/{train,eval} into the per-poll W&B
  payload so inflight reads on the engine time axis

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: show inflight vs cap in the wandb overview

Drop the inference/-prefixed mirror; the dispatcher gauges keep their
own keys and join the overview's inference section as one panel
(dispatcher/inflight/{train,eval} + concurrency/max_inflight), on the
same wall-time axis as the engine metrics.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: survive out-of-vocab ids in logprobs detokenization

Padded-vocab models (Qwen: logits dim > tokenizer vocab) can sample
out-of-vocab ids once RL updates shift the untrained tail logits.
vLLM's _restore_leading_spaces then iterates a None raw piece and the
TypeError kills the async output processor and the engine (hit twice
in the 50-step concurrency verification runs, at steps 37 and 12).
Guard the raw piece; the id still detokenizes via decode.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: apply concurrency bootstrap only once

The bootstrap guard in observe() held true on every metrics poll
until the first train step set kappa. The cap was recomputed from
the moving cost EWMA every ~5s, so it flapped by hundreds of
episodes before step 1. Latch it: one feedforward raise on the
first capacity observation, then updates only at step boundaries
(HARD cuts stay live).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: say episodes for in-flight units

The dispatcher's permit unit is one episode (one env.run, possibly
several traces), so in-flight logs and identifiers now say episodes:
InflightEpisode, cancel_inflight_{train_,}episodes, and the console
lines (pipeline view, off-policy cancel warning, drain notice, mode
switch).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: drop cap series from overview inflight panel

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: fix stale overview comment

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: step-clock the cost EWMA folding

The estimates updated per completed episode with alpha 0.1 - a
~10-episode memory over a heavy-tailed length distribution, which
swung G (and the cap) by 20-30% between steps. Completions now
accumulate between step boundaries and fold in as one interval mean
(alpha 0.3 per step), so a step's worth of episodes averages out
before the estimate moves. Simulated max step-to-step cap swing drops
to ~5% under a Pareto length mix at 150 completions/step.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: interpolate eval and train cost mixes

The eval census was a hard 0 -> 1 -> 0 gate: while any eval work was
in flight, G priced the whole pool from the eval mix, then snapped
back to the train mix at the drain boundary. Now the census decrements
per completed eval episode and G blends the two mixes on the eval
share of the cap, min(1, remaining / n_max): a full jump only when the
epoch actually fills the pool, and a continuous glide back to the
train price as it drains.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: 512-episode bias-corrected cost EWMA

Replace the step-folded estimator with a per-episode EWMA at
alpha = 1/512: the smoothing horizon is fixed in episodes, so it no
longer scales with batch size or step cadence. Bias-corrected
(decayed sum over decayed weight) so early estimates equal the plain
mean instead of anchoring on the first episode - an eval env at 120
episodes per epoch prices correctly from its first epoch. Simulated
step-to-step cap swing stays ~5% under a Pareto length mix.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: default frozen_steps to 1

At the step-1 boundary the cost EWMA has only seen the episodes that
completed fastest — the short ones — so the first re-evaluation
overshoots the cap (observed 256 -> 2139 with a 2K estimate on SWE
episodes that average far longer). Holding the cap for one step lets
the first full batch complete before the estimate is trusted.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: make frozen_steps=1 actually freeze the first boundary

on_step incremented completed_steps before checking frozen, so the
step-1 boundary compared 1 < frozen_steps and values 0 and 1 behaved
identically (observed: frozen_steps=1 still re-evaluated at step 1
off a 1.8K biased cost estimate). Snapshot frozen before the
increment: k now freezes the first k boundaries.

Also exempt the one-shot bootstrap derivation from the freeze — it
sets the starting value the freeze pins, so blocking it under the
new default of 1 would strand no-initial_inflight runs at the floor.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: simplify frozen_steps docstring

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: cap hendrycks e2e configs at 1024 inflight

The duty-cycle gap (episodes spend ~35% of wall time outside an open
engine request) lets kappa compound the cap well past useful engine
load on the sanity envs - ceiling it at 1024.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: allow SignSGD with full optimizer offload

SignSGD is stateless, so it runs through the wrapper's generic
per-chunk CPU step path (plain GradientOffloadManager + _step_chunk)
with no AdamW-specific machinery. Halves per-rank CPU optimizer
state vs AdamW full offload by dropping both moment buffers.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: queue-overload HARD cut for agentic rollouts

Agentic rollouts overload inference by queueing, not preempting:
vLLM's admission control parks excess load in the waiting queue, so
the preemption HARD gate never fires (observed: 213 capacity-queued
vs 192 running, prefix-cache hit rate 0.06, num_preemptions_total 0,
and a 5x step-time blowup while the controller raised the cap on a
SOFT signal).

Classify HARD when capacity-queued requests exceed QUEUE_RATIO of
running for QUEUE_PERSISTENCE_POLLS consecutive polls (persistence
filters natural turn-completion bursts), and cut to just under what
the engines actually serve (0.9x running) instead of backing off
from inflated inflight. The metrics collector now ships running and
the by-reason waiting breakdown in EngineLoadSample; engines without
the breakdown fall back to total waiting.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: shed youngest episodes on overload cut

A cut only blocks new admissions, so the over-admitted episodes keep
thrashing the prefix cache until they finish at degraded throughput
(observed: 690 -> 320 cut took 20+ min to drain, with 10-18 min steps
and a 0.05 hit rate the whole way). Bind an on_overload hook from the
controller to the dispatcher: cut() reports the episode excess and
the dispatcher drops that many in-flight train episodes, youngest
groups first (least inference spend), reusing the off-policy
drop_group path so the sink finalizes partial groups.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: slew-limit cap growth to 1.25x per re-evaluation

A raise floods in fresh episodes whose fast finishers drag the cost
EWMA down, inviting a bigger raise (observed 256 -> 567 -> 690 while
the estimate fell 7.7K -> 6.3K). Limiting upward moves to 1.25x per
step turns the spiral into a ramp the queue-overload cut interrupts
after one increment. Cuts stay unlimited.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: cuts never raise the cap; unwire shed-youngest for now

The queue cut targets 0.9x running, but running can be inflated by
work the dispatcher no longer tracks — observed live: 'Increased
concurrency 231 -> 256 (queue overload)'. Clamp cut targets to the
current cap.

Unwire on_overload -> shed_youngest: cancelling the orchestrator task
does not abort the env-side rollout (3195 starts vs 2616 done after
shedding 489 episodes, none stopped Cancelled), so shedding leaves
zombies hitting inference while the freed permits admit new episodes
on top — total load rises. Keep the dispatcher method; rewire once
rollout abort propagates to the env server.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: floor the cost estimate with measured request cost

Completion-based estimates only see finished episodes; after a cap
raise the fast short episodes finish first and drag the estimate
down, inviting a bigger raise (observed 7.7K -> 6.3K -> 5.5K while
the cap spiraled 256 -> 690). The live request stream has no such
bias: every turn resends its episode's full context, so in-flight
episodes are counted at their current size the whole time they run,
and single-turn workloads are covered by the generation term.

The collector derives mean prompt+generation tokens per request from
the vLLM histogram deltas each poll; the controller folds them into
a request-weighted decayed mean and takes the max of it and the
completion mix. Drop frozen_steps in the e2e config to test that the
cold-start freeze is no longer needed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: size-bias the measured request cost

A plain per-request mean under-prices the in-flight pool: small
contexts take turns far more often than the large residents that
actually fill KV (observed: request mean 6.7K while resident cost
was 13.2K per running request, so the feedforward equilibrium sat
2x above true capacity and every ramp ended in a queue cut).
Weigh each request by its own token mass instead — E[X^2]/E[X]
from the prompt-histogram bucket deltas, midpoint-approximated,
+Inf bucket bounded by the engine max context. On the live GLM
distribution this reads 16.8K vs the 13.2K resident measure:
slightly conservative, and kappa growth learns back the slack.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: clock kappa growth on polls, not step boundaries

Step-clocked growth adapts at wildly different speeds across
workloads (steps range seconds to tens of minutes), and its binding
check sampled inflight at the boundary instant — exactly when
episode completions burst — so kappa stalled while the cap was
binding all step long (observed: kappa stuck at 1.13 for three clear
steps with the engine at 0.99 prefix hit). Grow kappa a small factor
per clear-and-binding poll instead; SOFT vetoes become per-poll for
free.

Also fall back to the observed request cost (not the pessimistic
engine max context) for envs without completions — the max-context
fallback made kappa's continuity init read a user-set start as an
intentional ~4x over-commit whenever step 1 completed before any
episode did.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: early growth brake and kappa ceiling memory

Thrash onset is a cliff, not a slope: prefix hit went 0.97 -> 0.06
within two minutes of kappa growing past the workload's true
over-commit (job 748: clean climb to kappa 1.51 / cap 380, then a
queue cut to 197). Two additions:

- Veto kappa growth on any poll with capacity-queued requests.
  Unlike generic waiting, capacity-queuing means KV blocks are full
  right now; the 2-poll waiting filter let growth feed the cap
  through the cliff between bursts.
- Remember the ceiling: an overload cut pins growth at 0.9x the
  kappa that overloaded, so the ceiling is rediscovered by a wobble
  instead of a fresh thrash episode every cycle (without memory the
  sawtooth re-pays the full discovery cost forever). A slow relief
  (~+2% per 10 min) lets a genuinely lightened workload re-probe.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: update adaptive concurrency for the measured-cost controller

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: clock the controller on pipeline turnovers, not steps

Step duration varies from seconds to tens of minutes across
workloads, so anything step-clocked adapts at workload-dependent
speed. Re-evaluate the cap every poll (with a 2% deadband against
estimate noise) and bound raises by the pipeline turnover: each
completion advances the clock by 1/inflight, so one turnover means
the in-flight pool has been replaced once regardless of scale — 100
completions at concurrency 10 buy 10x the raise budget of 100 at
concurrency 1000, matching how much less biased their estimates
are. Raises compound at most 1.25x per turnover; cuts and decreases
are never limited.

The turnover slew subsumes frozen_steps (the cap can never outrun
the pipeline's demonstrated stability), so the config field is
removed. Kappa now initializes on the first poll with real cost
data instead of the first step boundary; on_step shrinks to eval
bookkeeping and backoff reset.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: SOFT signal on high KV usage

Thrash onset is a cliff at full KV, and the queue-based signals only
fire once it is already happening. Live-request KV usage rises ahead
of it (measured ~0.53 at healthy load, ~1.0 at thrash), so treat any
decode engine above 0.8 as SOFT: growth stops while there is still
headroom to absorb in-flight context growth, cuts stay queue-driven.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: lower KV-usage SOFT threshold to 0.7

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: shed on overload now that rollout abort propagates

Bump verifiers to feat/rollout-abort (26eafc07): cancelling the
orchestrator-side task now aborts the env-side rollout, so
Dispatcher.shed_youngest no longer creates zombies — rewire it to
the controller's on_overload hook. An overload cut now sheds the
youngest in-flight episodes immediately instead of draining the
excess for tens of minutes at thrashed throughput.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: proportional kv-headroom trim

Cap moves alone cannot relieve pressure from episodes maturing in
place — they only block admissions. Observed on the kv-soft gate:
growth froze at usage 0.7 and the cap eased 371 -> 326, but the
admitted pool's contexts grew ~15%/step under it and crossed the
thrash cliff (prefix hit 0.05) within minutes anyway.

With rollout abort now propagating, trim the pool itself: above
KV_USAGE_TARGET (0.85), set the cap to inflight * target / usage and
shed the excess youngest episodes, on a short cooldown so each trim
propagates before the next is sized. Holds usage at the target
continuously instead of riding to the cliff and paying a full
queue-overload cut; the queue gate remains the backstop.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: kv-headroom trims re-derive kappa

A trim that lowers only the cap gets undone by the feedforward: the
slew allowance regrows per completion and the cap creeps back into
the trim zone, shedding ~8-16 young episodes every cooldown
(observed: 4 trims in 2.5 min). Re-derive kappa from the trimmed cap
the way cuts do; with growth already vetoed above KV_USAGE_SOFT this
yields a grow (<0.7) / hold (0.7-0.85) / trim (>0.85) usage band
instead of a shed loop.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: address PR review comments

- Treat the admitted unit as a black box in the controller docstring;
  docstring-style constants describing meaning only.
- Constants: ESTIMATE_ALPHA 1/1024, BACKOFF_FACTOR 0.8, KAPPA_MAX 8,
  QUEUE_PERSISTENCE_POLLS 6 (react within a minute).
- Rename RolloutDispatcher -> Dispatcher, inflight_permits ->
  current_inflight, shed_youngest -> cancel_inflight.
- Drop the out-of-vocab detokenization patch.
- Configs: initial_inflight = batch_size with a 2x max_inflight
  ceiling across the example and nightly configs.
- Docs: trim the adaptive-concurrency intro.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: weight the cost mix by live in-flight counts

The sampling-ratio weighting predicted the standing mix and needed
two corrections bolted on: duration weighting (admission mix vs
standing mix) and the eval-census interpolation (predicting the mix
through eval epochs). The dispatcher knows the standing mix exactly
— weight the per-env estimates by its live per-(kind, env) in-flight
counts instead. Train and eval need no separate treatment (eval
units enter the mix as they are admitted), so the census, its
interpolation, and the duration weighting are deleted; the
configured ratios remain only as the empty-pool fallback.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: hysteresis for kv-headroom trims

Trimming exactly to the trigger guarantees an immediate re-trigger
under monotonic pool growth (observed: trims every cooldown, 16-40
units each, while survivors grew ~15%/step). Trigger at 0.85 but
resize to 0.75, so each trim buys growth headroom before the next.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: lower kv-usage thresholds (soft 0.6, trigger 0.8, target 0.7)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat!: reduce the controller to measured AIMD

The feedforward kappa*C/G no longer controlled anything: the
turnover slew was the binding constraint on every ramp (raw targets
sat 2-5x above the cap), the usage trim overrides it on the way down
(it was added precisely because G-tracking is too slow for in-place
pool growth), and the gates own overload. Everything that computed G
existed to produce a number the other mechanisms clipped.

Replace it with AIMD on measured KV pressure, turnover-clocked:
grow the cap x1.25 per pipeline turnover while engines are clear,
usage < 0.6 and the cap binds; trim pool+cap to usage 0.7 above 0.8;
cut on preemptions (0.8x inflight) or persistent capacity-queueing
(0.9x running), cancel the excess, drain-latch, escalate to 0.5x if
overload survives a drain. The starting cap is user-set or
C / max_model_len — the only cost-like quantity left, read once.

Deleted: kappa and its ceiling/relief, both cost estimators (per-env
completion EWMAs and the size-biased request census with its
histogram parsing), cost_estimate/mix_cost, the inflight-mix hook,
the re-evaluation deadband, slew_allowance as a separate mechanism
(the growth law absorbs it), and on_step. ~480 -> ~280 lines with
no model of unit cost anywhere.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: align tests, configs and docs with the AIMD controller

Fix the hendrycks configs (high-eval start needs its ceiling at the
starting cap; freeze-era header comments), rewrite the adaptive
concurrency docs for the measured-AIMD design, and revert the
SignSGD full-offload allowance — SignSGD crashes with an async CUDA
illegal memory access on this stack, so the guard stays until that
is fixed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: min_inflight escape hatch

A hard floor on the adaptive cap (None auto-sets to 1). Setting
min_inflight = max_inflight pins the cap, recovering fixed-concurrency
behavior; not recommended in practice.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: address second review round

- Rename Dispatcher param max_inflight_episodes -> initial_max_inflight
  and document its relation to max_inflight_ceiling (starting value of
  the dynamic cap vs the configured hard maximum bounding out_q).
- Drop the dead n <= 0 guard in cancel_inflight (resize_down only
  calls it with a positive excess).
- Public hook attributes on the controller (set_limit, get_inflight,
  on_overload); single float-returning clamp; unconditional
  apply_limit on growth (it no-ops when unchanged).
- Gauges: capacity_tokens -> capacity; drop queue_overload_polls.
- Remove the stale detokenization NOTE in the vLLM server.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: revamp the concurrency e2e config matrix

Two workloads x four scenarios, all descriptively named and capped at
max_inflight = 1024:

- hendrycks (single node, 4 train + 4 infer GPUs, mirrors the
  hendrycks-sanity example; replaces the 2-GPU variants):
  initial-low (16, grow from near zero), initial-none (derived
  start), initial-high (1024, cut from overload), evals (256 + AIME
  avg@4 every 10 steps). gpu_memory_utilization = 0.2 shrinks the KV
  budget artificially so the controller operates below the ceiling
  instead of at huge concurrency.
- glm-air (2 nodes, replaces glm-air-swe): the same three initial
  scenarios plus evals (256 + 10-turn-capped SWE-Bench Verified
  every 10 steps). Each config uses its own sandbox label so
  parallel runs cannot delete each other's sandboxes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: slurm blocks for the hendrycks e2e configs

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: pin flash_attention_2 for the hendrycks e2e configs

R1-Distill-Qwen-1.5B resolves to the HF model impl, and attn=auto
resolves to flash_attention_3, which requires the custom impl — the
trainer refused to start.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: drop the initial-low e2e variants

The low start exercises the same turnover ramp as the derived start,
just from a lower anchor — the none variant covers it. Final matrix:
{none, high, evals} x {hendrycks, glm-air}.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: 4 API server processes for the hendrycks e2e configs

The initial-high run (1024 concurrent clients) killed vLLM's single
ApiServer process; the frontend needs to scale with the client
count.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: pin the hendrycks KV budget via num_gpu_blocks_override

Even at low gpu_memory_utilization the 1.5B model gets ~12.8M KV
tokens, putting the usage band above the max_inflight ceiling — the
derived start clamped to the ceiling and the none scenario
degenerated into the high one. Pin ~2.1M tokens so the derived start
(~256) and the band (~350-400) sit well below the ceiling.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: min_inflight is the only cap floor

Drop the implicit group_size floor: group episodes are admitted
individually, so a group trickles through in waves below its size —
nothing requires a group to fit in flight at once. min_inflight
(default 1) is now the single lower bound, and recovery from tiny
caps is fast in turnover terms (at inflight 1 every completion is a
full turnover).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: start hendrycks-initial-high at 700

Two attempts at a 1024 start died to vLLM ApiServer processes being
signal-killed under the client connection storm (with 1 and with 4
frontend processes). 700 is still decisively over the pinned ~350-400
usage band, so the overload-cut scenario is intact without stressing
the frontend.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: prime VM sandboxes for hendrycks-initial-high

The ApiServer deaths under the 1024 start were host thrash from 1024
subprocess-runtime episodes spawning local processes, not the client
connections. Run the high scenario on prime VM sandboxes and restore
the 1024 start.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: hold the drain latch until the engines settle

Cuts cancel episodes, so dispatcher inflight drops below the cap
almost immediately while the engines still churn through their own
backlog — preemption deltas from that stale churn re-triggered
escalated cuts every poll (observed cascade: 1024 -> 8, one halving
per 5s). Release the drain only when inflight is under the cap AND
the poll shows no preemptions or queue overload.

Also fix the hendrycks KV pin for 64-token blocks (32768 blocks gave
8.4M tokens, not 2.1M — the derived start clamped to the ceiling and
triggered the storm in the first place).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: say episodes, not units, in console logs

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Refund admission burst budget on episode completion

The burst window capped gross admissions at max(group_size, cap/10)
per 5s. For fast single-turn episodes the completion rate exceeds that
admission rate, so inflight equilibrates at admission_rate x duration
(observed: 24 at cap 58) and the cap never binds, locking out growth.
Completions now refund the window budget: the window meters net pool
growth, so ramps stay smoothed while steady-state replacement is
never throttled.

Also switch the hendrycks e2e configs to prime VM sandboxes and fix
num_gpu_blocks_override for 16-token blocks (FA2 backend), restoring
the intended 2.1M-token KV budget.

* Fix four controller/dispatcher bugs from review

- Growth was dead below cap 10: the permit is released before the
  completion hook fires, so the binding check read inflight <= cap - 1
  and 0.9 * cap was unsatisfiable for small caps. Count the completing
  episode back in.
- Queue cuts targeted 0.9 x engine running requests but the cap counts
  episodes; agentic episodes idle between turns, so this over-cut by
  the duty cycle. Cut in pool units like the preemption path.
- Escalation latched forever: it only reset on a CLEAR-poll drain
  release, but steady state post-cut sits in the SOFT usage band, so
  every later cut halved. Reset via a grace window of polls after the
  drain instead.
- Overload sheds count only live cancellations toward the excess;
  never-dispatched markers free no permits and made sheds undershoot.

Also expire the growth gate 15s after the poll that set it: if the
metrics path stalls (the very state runaway growth creates), growth
freezes instead of compounding blind. And skip growth on error-marker
completions (tokens <= 0) — they consumed no engine capacity, and a
slow-failing error storm otherwise grows the cap against idle engines.

* Drop cluster-specific node exclude from e2e configs

* Budget hendrycks e2e concurrency for the sandbox gateway

VM-sandbox runtimes hold one sandbox per in-flight episode, so peak
concurrency across concurrent runs must stay under ~1k or the gateway
429s. Cap the three runs at 400/300/256 and shrink the KV budget to
786K tokens (12288 blocks x 16-token FA2 blocks x 4 engines) so the
optimal band (~175) sits below every ceiling and each run still
exercises its intended path (cut down / grow up / absorb eval waves).

* Read KV capacity from kv_cache_size_tokens

The num_gpu_blocks label in vllm:cache_config_info does not reflect
num_gpu_blocks_override, so the derived capacity was 4x too high on
runs that pin the block count. kv_cache_size_tokens reports the
actual budget; keep the block product as a fallback for engines that
do not expose it.

* Adapt GLM-4.5-Air SWE example to a 4-node FP8 recipe

1 trainer node (sign-SGD full CPU offload, cp=4) + 3 FP8 inference
replicas with online quantization. The concurrency section is removed:
the controller runs on defaults, deriving its start from the measured
KV budget.

* Remove concurrency debug configs

The hendrycks/glm-air matrix configs were development scaffolding for
the e2e verification runs; the results live in the PR description.
The GLM-4.5-Air SWE example is the maintained recipe.

* Use fp8_per_block online quantization in the GLM-Air example

Matches the research-prod GLM recipe: the bf16 checkpoint is loaded
and quantized online, since NCCL weight broadcasts push bf16 trainer
weights into the engines on every update.

* Guard None raw tokens in logprobs detokenization

tokenizer.convert_ids_to_tokens returns None for ids outside the
tokenizer vocabulary. Models with embedding padding past the tokenizer
(e.g. R1-Distill-Qwen) can sample such ids; _restore_leading_spaces
then iterates None and the TypeError kills the AsyncLLM output loop
and the whole API server with it. Observed as recurring random
'ApiServer died with exit code None' crashes under sustained sampling.

* Revert "Guard None raw tokens in logprobs detokenization"

This reverts commit 0c1b5d4992eb99f1ea4c0a7c6a999daeca5cc95c.

* Order concurrency fields initial, min, max

* Route GLM-Air FP8 through DeepGEMM kernels

Without a block-wise FP8 GEMM backend the engine falls back to
torch._scaled_mm, which asserts on block-scale shapes during engine
init. Enable DeepGEMM and disable the FlashInfer block-scale GEMM,
matching the research-prod GLM recipe.

* Serve GLM-Air FP8 checkpoint with kernel-format weight transfer

The online fp8_per_block path crashes for glm4_moe on this stack (the
block-scale GEMM falls back to torch._scaled_mm and asserts), so the
example serves the native FP8 checkpoint instead. Weight updates then
need trainer-side quantization: implement convert_layer_to_vllm_kernel
for glm4_moe (standard GQA qkv fusion; the MoE handling mirrors
GLM-MoE-DSA, whose MoE layout is identical) and enable
quantize_in_weight_transfer.

The kernel copy path has no TP shard handling, so the engines run
EP experts + DP attention (data_parallel_size=8), matching the GLM
prod deployment shape. Trainer keeps the bf16 checkpoint; the
orchestrator addresses the served FP8 name.

* Disable MoE DP chunking for the FP8 GLM-Air engines

The cutlass FP8 MoE DP-chunking path under-sizes its permute scratch
for large profile/prefill batches (moe_permute asserts
n_token <= max_num_tokens), killing the engine at init. Same
mitigation as the GLM prod recipe.

* Serve GLM-Air FP8 via per-tensor online quantization

Both block-scale FP8 attempts crash for glm4_moe on this stack (the
blockscale GEMM asserts at engine init; the cutlass MoE DP-chunk
scratch under-sizes). Per-tensor online quant uses the standard
scaled_mm and fused-MoE FP8 kernels, keeps plain TP=8, and re-uses the
same quantize-on-load path for weight broadcasts.

* fix: stop metrics collector before finalizing monitors

The collector's poll loop outlived monitors.finalize() on clean exit,
so its next wandb.log hit the finished run and surfaced as a spurious
'Inference metrics poll failed: UsageError' warning. Stop it first;
the teardown's second stop() is a no-op.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Bump verifiers to a3188c06

Rollout-abort cleanup hardening: shielded sandbox create, strongly
referenced cancel tasks, and cancel drain on client close.

* Fix four review findings; drop unused glm4_moe kernel converter

- Overload signals read decode engines only: in P/D deployments a
  prefill queue or prefill preemption is normal flow and must not
  trigger cuts.
- Batch/group divisibility is checked after the batch-size default
  lands, so a config setting only group_size cannot pass with a
  non-divisible default.
- A group's age for youngest-first shedding is its oldest member's
  start; taking the newest made long-running groups look young and
  cancelled the most sunk cost.
- Admission-window refunds apply only to natural completions: refunding
  cancelled episodes handed a mass shed's worth of burst budget to the
  refill while the overload was still draining.

The glm4_moe kernel-format converter served the abandoned
quantize_in_weight_transfer experiment; the example now uses plain
online quantization, which needs no trainer-side support.

* Explain adaptive concurrency by intuition in the docs

Drop thresholds, constants, and the config listing from the docs
section; describe grow/trim/cut as probe-and-back-off against the
engines. Bump verifiers for the cancel-path race fixes.

* Drop unrelated changes from the branch

The detokenizer patch ships separately in #3304; the pydantic-config
pointer bump was an accidental sweep of local submodule state.

* Address review: config defaults and small cleanups

- max_inflight defaults to 1024: an unbounded default made the growth
  path's failure modes existential; None still removes the ceiling.
- min_inflight defaults to 1 instead of None-meaning-1, simplifying
  the bounds validator.
- Signal is a Literal instead of an Enum.
- Reword the admission-smoothing comment.

* Raise max_inflight in examples exceeding the new default ceiling

* a few minor tweaks

* Bump verifiers to 6bcedc76 (merge main into rollout-abort)

* Update lockfile for verifiers 0.3.1.dev57

* chore: cap CI RL runs at 512 inflight

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: dedupe concurrency block in wiki-search CI config

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Bump verifiers to main (rollout-abort merged)

feat/rollout-abort landed as PrimeIntellect-ai/verifiers#2396; the
submodule now tracks verifiers main.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 11:17:21 -07:00
Mika SenghaasandGitHub 5ed05cf6ac chore: bump workflow actions to latest versions (#3306)
checkout v5 -> v7, setup-uv v7 -> v10.0.1, upload-artifact v4/v5 -> v7,
download-artifact v6 -> v8, github-script v8 -> v9. All self-hosted
runners are on 2.336.0, above the 2.327.1 floor the node24-based
majors require. setup-uv stopped publishing floating major tags with
v8, so it now pins the exact release.

Also sync the CI ruff pin (0.13.0 -> 0.15.14) with uv.lock so CI
lints with the same ruff version as local runs.
2026-08-19 20:15:06 +02:00
1c0720d975 feat: sign-SGD support for full CPU optimizer offload (#3303)
Allow optim.type = "sign_sgd" with model.full_offload. SignSGD is
stateless, so full offload needs only 8 B/param of host RAM (FP32
master + FP32 accumulated gradient) instead of AdamW's 16 B/param
(master + two FP32 moments + accumulated gradient).

- Add a native multi-tensor CPU sign_sgd_step kernel mirroring the
  AdamW span kernel (BF16/FP32 grads, BF16/FP32 compute-param
  write-out, at::parallel_for). The kernel drops the gradient scale:
  sign(scale * g) == sign(g) for scale > 0.
- Generalize FullCPUOffloadOptimizer's native plumbing (bounded
  gradient manager, chunk stepping, sync fallback, checkpoint load,
  scheduler _opt_called marker) over a combined native-optimizer flag.
- Skip CPU optimizer state materialization for SignSGD everywhere:
  checkpoints carry only the FP32 masters.
- Relax the trainer/SFT config validators and setup_optimizer guard to
  accept sign_sgd; update docs and the start-run skill.
- Add a bit-exact parity test against the python SignSGD reference
  (BF16/FP32 grads, wd 0 and >0, zero grads, scalar-tail sizes).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 17:08:50 -07:00
Konstantin DunasandGitHub 61f2448d1d feat(orchestrator): add composable curricula (#3261) 2026-08-19 00:47:35 +02:00
c7a6573de5 chore: simplify ignore files to outputs/ (#3295)
* simplify artifact ignore rules to outputs/

Since the run-dir unification, every run artifact (logs, checkpoints,
weights, rollouts, evals, broadcasts, wandb, torchrun logs, sbatch
scripts) lives under output_dir, which defaults to outputs/. The
recursive **/<dir> patterns and their negations are redundant.

The **/wandb pattern also kept the wandb monitor source package out
of the docker build context (see #3292). Ignoring only outputs/
removes that class of bug.

Delete scripts/clean.sh: it mirrored the same recursive list, is
referenced nowhere, and rm -rf outputs/ replaces it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ignore .codex directory

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 10:52:22 -07:00
8b2819b4c7 fix(docker): re-include the wandb monitor package in the build context (#3292)
`**/wandb` (added in #3279) targets W&B's local run-output dirs, but it
also matches src/prime_rl/monitors/wandb/, which became a package in
#3275. `COPY src/ /app/src/` reads the filtered context, so the package
never reached the image and every entrypoint died at import:

    File "/app/src/prime_rl/monitors/__init__.py", line 19
      from prime_rl.monitors.wandb import WandbMonitor
    ModuleNotFoundError: No module named 'prime_rl.monitors.wandb'

monitors/__init__.py is imported unconditionally, so this took down the
orchestrator and trainer whether or not W&B was configured.

.gitignore already carries this exemption; mirror it here. The pair sits
above the bytecode patterns so those still strip __pycache__/*.pyc back
out of the re-included directory - last matching line wins.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 23:38:13 -07:00
1fd4fefd4a fix(tests): migrate full-offload SFT fixture to num-train-gpus (#3291)
PR #3256 renamed SFT deployment.num_gpus to num_train_gpus, but the
full-offload resume fixture from #3234 merged in parallel and kept the
old flag, failing config validation on main.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 20:22:33 -07:00
15d6c81974 feat: online evals during sft (#3256)
* Add online evals to the SFT entrypoint

The sft launcher now composes an inference server, one env server per
eval source, and a new evaluator process next to the trainer. The
handoff is the filesystem, not NCCL: the trainer writes HF weight
checkpoints at every step an eval env is due, and the evaluator points
the inference server at each stable checkpoint (/update_weights from
disk) before running the due evals, sequentially per checkpoint.

The evaluator reuses the orchestrator's eval components (EvalEnvs,
EvalSource, EvalSink, EvalRollouts) and logs eval/{env}/... metrics and
rollout traces exactly like RL, into the same W&B run as the trainer
(shared mode; the new WANDB_SHARED_PRIMARY env var selects the primary
process, defaulting to the previous orchestrator behavior).

Online evals are single-node only for now.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Harden the SFT online-eval launcher and evaluator

Address review findings on the initial implementation:

- Skip an eval step (with an error log) when the weight reload fails
  instead of killing the training run; drain the queued examples so they
  cannot leak into a later epoch with the wrong eval_step.
- Clean stale weights/step_N dirs at launch (all on fresh start, past
  the resume step on resume) so the evaluator never replays checkpoints
  from an abandoned run.
- Reconcile deployment.num_infer_gpus with inference.vllm TP/DP,
  mirroring RLConfig.auto_setup_deployment.
- Install a SIGTERM handler in sft_local (it now spawns GPU-holding
  children beyond torchrun), avoid busy-spinning while the evaluator
  drains final evals, and probe GPUs only when partitioning them so
  plain SFT keeps its old no-NVML behavior.
- Make the evaluator the shared-W&B primary - it exits last, so it must
  own run finalization.
- Warn when ckpt.keep_last/keep_interval can clean a checkpoint before
  the evaluator consumes it, and document the retention interplay and
  the standalone admin_base_url requirement.
- Fix pre-existing is_last_step off-by-one: resuming from a checkpoint
  at step >= max_steps no longer trains forever.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Add multi-node SFT online evals with decoupled SLURM jobs

With [eval] set on a multi_node deployment, the sft launcher submits
two independent SLURM jobs: the trainer (deployment.num_nodes) and an
eval job (deployment.num_infer_nodes) running the inference pool (one
vLLM engine per DP rank behind a router), one env server per eval
source, and the evaluator. The only coupling is weight checkpoints on
the shared filesystem, so the trainer job releases its allocation when
training finishes while the eval job keeps draining checkpoints and
exits after evaluating the final one. Any train x inference node
layout works.

The eval job is submitted first and the trainer depends on it having
started (--dependency=after), so the trainer joins the shared W&B run
the evaluator creates instead of timing out while the eval job pends;
a failed second submission cancels the first. On a clean evaluator
exit, node 0 publishes a job-scoped sentinel that releases the other
inference nodes, since a zero exit never trips --kill-on-bad-exit.

Also hardens the eval handoff paths: weight-checkpoint cleaning always
keeps the newest checkpoint (keep_interval-only cleaning used to
delete a non-aligned final checkpoint right after saving it, hanging
the evaluator), the evaluator skips abandoned STABLE-less checkpoints
instead of wedging on them, clean_stale_weights honors
NEVER_CLEAN_OUTPUT_DIR, and validate_output_dir sees ckpt.output_dir.

Verified e2e: Qwen3-30B-A3B-Thinking-2507 SFT on one node with AIME25
online evals on another; both jobs completed with exit code 0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Make the trainer own the shared W&B run

Split run creation from run finalization in shared W&B mode: the
WANDB_SHARED_PRIMARY process creates the run and the new
WANDB_SHARED_FINISHER process (defaulting to the primary) writes its
final state. The SFT trainer is now the primary in both the single-node
and decoupled multi-node online-eval deployments, so the run exists
even if the eval side never starts; the evaluator, which outlives the
trainer, stays the finisher so the run isn't marked finished while
final evals still log.

The decoupled submission order flips accordingly: the trainer job goes
first and the eval job depends on it having started, keeping the
joiner's bounded wandb-init retry window covering only startup lag.

Verified on a 2-node run: trainer inits with primary=True/
finisher=False, evaluator joins with primary=False/finisher=True, both
jobs exit 0, and the shared run ends in state "finished" with trainer
and eval metrics.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Add an SFT-flavored W&B overview view

The auto-provisioned overview saved view previously only had an RL
shape; SFT runs fell back to rollout-metric train panels that SFT
never logs. build_sections gains an "sft" flavor: the train section is
the loss and perplexity curves (train + validation) plus epoch
progress, the eval sections stay the rollout-based ones shared with
RL, and stability/performance show the metrics the SFT trainer
actually emits. The SFT trainer and the evaluator select the flavor
through setup_monitor.

The trainer now also logs loss/perplexity and val/perplexity
(exp of the mean loss, clamped to avoid overflow on divergence).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* address online-eval review findings

- Warn when an eval-due weight checkpoint was deleted by ckpt.keep_last
  / keep_interval cleaning before the evaluator could evaluate it, and
  advance past it instead of silently gapping the eval curve.
- Restore RL's enable_lora guard in the api_server_count DP fill, which
  the copy from RLConfig.auto_setup_deployment had dropped.
- Also clean stale rollout trace dirs at launch (clean_future_steps),
  not just weight checkpoints: the append-only trace files would
  otherwise mix two policies' rollouts under one step after a crash and
  resume.
- Parse sbatch job ids with --parsable; the human-readable output
  varies on multi-cluster setups and broke the dependency/cancel paths.
- Mention the evaluator log in the monitor-run skill.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* address pr review comments

- Rename SFT deployment.num_gpus to num_train_gpus, matching the rl
  launcher's num_train_gpus / num_infer_gpus API. Breaking: the old key
  fails as unknown.
- Flatten EvaluatorConfig.model to model_name and document how it is
  used: the served-model name on every eval request, auto-filled from
  model.name by the sft launcher; weights swap in place under one name,
  so per-step results are told apart by eval/{env}/policy_version.
- Trim the online-evals docs detail paragraph and fold the W&B overview
  mention into one clause covering RL and SFT runs.
- Drop the [eval] explainer comment from the reverse-text example.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* address self-review comments

- Rename multi-node deployment.num_nodes to num_train_nodes (matching
  the rl launcher). Breaking: the old key fails as unknown.
- Rename EvaluatorConfig.model_name to model and raise the default
  max_inflight_episodes to 128.
- Hardcode the evaluator's weights dir to <output_dir>/weights (it was
  always launcher-derived); with [eval] set, ckpt.output_dir is now
  rejected instead of silently pointing the evaluator elsewhere.
- Drop the online-evals bullet from the start-run skill.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* bring back the evaluator weights_dir field

Weight checkpoints follow ckpt.output_dir when checkpoints are
redirected to another volume, so a hardcoded <output_dir>/weights
cannot cover that deployment. The launcher fills weights_dir from the
checkpoint base again, and ckpt.output_dir is supported with [eval].

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix eval with redirected checkpoint dir and final-eval retrigger

The ckpt.output_dir rejection was meant to be removed when weights_dir
came back but the edit never landed (the format hook had reshaped the
raise and the scripted match failed silently) - remove it for real; the
evaluator watches <ckpt.output_dir>/weights via the launcher-filled
weights_dir.

Also force-fire every env when retrigger_on_resume resumes at the final
checkpoint (a crashed final eval was never retried when max_steps is
not interval-aligned), and trim a verbose comment.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* alias num_eval_gpus/num_eval_nodes for the infer deployment knobs

num_infer_gpus / num_infer_nodes stay canonical (rl-launcher parity)
and accept num_eval_gpus / num_eval_nodes via AliasChoices. The
deployment pre-validator collapses the alias onto the canonical key:
pydantic rejects a dict carrying both spellings, which is exactly the
common layering (canonical in the TOML, alias on the CLI).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix alias precedence via pydantic-config bump

The deployment pre-validator collapsed the num_eval_* aliases onto the
canonical keys with the alias always winning, which inverted
CLI-over-file precedence when the file used the alias and the CLI the
canonical spelling. The real gap was in pydantic-config:
_normalize_alias_keys never recursed into discriminated-union variants.
Bump the submodule to the fix (pydantic-config#23) and drop the
collapse - alias spellings now merge onto one key with normal
precedence in every layering.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* bump pydantic-config to v0.4.3 (merged alias fix)

Re-point the submodule from the PR-branch commit to the squash-merged
main commit, released as prime-pydantic-config 0.4.3.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* floor prime-pydantic-config at 0.4.3

The online-eval deployment aliases rely on 0.4.3's union-aware alias
normalization.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 17:41:34 -07:00
minh hoangandGitHub 4f5d943a15 fix(monitors): allow overriding the platform base URL via $PRIME_API_BASE (#3287)
The prime monitor's TrainRun hardcodes the production public API
(https://api.primeintellect.ai/api/v1/rft). Managed launches need to point
it at the platform's internal ingestion path instead, and non-prod
environments currently post metrics to prod (where their per-run tokens
401) — silently, since uploads are fire-and-forget.

$PRIME_API_BASE is taken verbatim when set (the platform already injects
it on managed orchestrator pods as {SERVICE_URL}/api/internal/rft);
otherwise the default is unchanged. Resolved once in __init__ and stored,
since the atexit _mark_failed hook must agree with the client.
2026-08-17 15:51:35 -07:00
572cc82e76 chore: bump verifiers to latest main (#3286)
Picks up 8 commits (91a267616..02cc940d8), notably the prime-sandboxes
0.2.37 floor (VM idle timeout + vm-opt-out validation) and the
intercepted-response replay gate (vf#2368). Adds a bounded harbor
cutoff mirroring deps/verifiers: verifiers pins harbor==0.21.0, which
the rolling exclude-newer window rejects.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 13:38:54 -07:00
d8f3d01016 perf(docker): split the uv dependency layer and add registry-backed build cache (#3279)
* perf(docker): cache the dependency sync independently of source edits

A one-line change under src/ currently busts the uv sync layer (source is
COPY'd before the sync) and re-downloads ~5 GB of wheels + recompiles
mamba-ssm. Split the sync in two:

- a manifests stage collects every pyproject.toml + uv.lock; the deps layer
  syncs against that skeleton with --no-install-workspace and the four path
  editables skipped, so it only busts when project metadata changes
- the source layer copies the real trees and reruns the original sync, which
  now only installs the first-party editables

Also fix the uv cache mount (UV_CACHE_DIR is /usr/local/share/uv/cache but
the mount targeted /app/.cache/uv, so it never cached anything) and add a
.dockerignore so local builds stop shipping .venv trees into the context
(packages/prime-rl-configs/.venv is 439 MB and was baked into local images
via COPY packages/). .git stays in the context: the pretend-version script
resolves submodule versions from .git/modules.

Validated: uv sync --locked --dry-run with the deps-layer flags against the
skeleton tree (linux, uv 0.11.9) resolves all 551 packages and plans 422
installs with no first-party editables and no lockfile errors.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* perf(ci): registry-backed BuildKit cache for image builds

setup-buildx-action creates a fresh builder per job, so every CI build is
cold even when nothing changed. Cache to ghcr buildcache-<arch> tags with
mode=max so the builder-stage dependency layer is reusable across runs;
blobs already present in GHCR are not re-uploaded.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* perf(docker): stop shipping .git in the cache and re-pushing immutable layers

Profiling the first warm build (run 31912669079) showed three avoidable
costs on top of the structural cache round-trip:

- the manifests stage COPY'd the full context into /ctx, so the ~735 MB
  .git landed in a layer that mode=max exports to the registry cache on
  every build; exclude it (it holds no pyprojects)
- the runtime stage copied the volatile /app remainder before the big
  immutable venv trees, so every code change re-executed and re-compressed
  the nvidia/torch/vllm/flash_attn copies; move the volatile layer last
- the "Remove unnecessary packages" step costs ~70s on the amd64 runner;
  only run it when the disk is actually tight

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(docker): condense build comments

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 22:33:54 -07:00
minh hoangandGitHub 7b97965bb3 fix(tests): migrate remaining --wandb.* flags to --monitors.wandb.* (#3280) 2026-08-16 10:01:07 -07:00
b8d9553c0f feat: overlap CPU optimizer with backward (#3234)
* feat: chunked per-layer optimizer step with stream-overlapped CPU offload

The CPUOffloadOptimizer now performs the optimizer.step() per-transformer-layer
instead of all-at-once. Each layer's optimizer states are moved to GPU, the step
runs for that layer only, and states are moved back to CPU before the next layer.

This bounds peak GPU optimizer-state memory to ~one layer's worth (plus one
prefetched layer for overlap) instead of the full model's, preventing OOM when
weight + grad + all_opt_states exceeds available VRAM.

H2D and D2H transfers are pipelined on dedicated CUDA streams so the next layer's
states are prefetched while the current layer computes, and the previous layer's
states are evicted while the next layer computes.

Pinned-memory D2H is fixed to pre-allocate the pinned destination and async-copy
into it, avoiding a race where pin_memory() reads a tensor whose async copy hasn't
completed.

Muon's per-group step counter is synced after all chunks complete, since the
param_groups are temporarily swapped during chunked stepping.

* feat: add on/off config for chunked offload and stream overlap

Add  and  config options
to independently toggle per-layer chunking and stream-overlapped H2D/D2H.

When stream is disabled, the chunked step uses a simple sequential
move→step→move loop with no CUDA stream logic, making the code path clearer
and easier to debug.

* chore: default optim_cpu_offload_chunked and optim_cpu_offload_stream to false

* fix: address bugbot review issues

1. Async D2H checkpoint corruption (HIGH): Add torch.cuda.synchronize()
   after _move_states('cpu') in state_dict() and in ckpt.py's
   AppState.state_dict() to ensure async pinned D2H copies complete
   before CPU tensors are read.

2. Incomplete stream dependency chain (MEDIUM): Replace wait_stream-only
   finish in _step_chunked_streamed with torch.cuda.synchronize() to
   block CPU. Add h2d_stream.wait_stream(d2h_stream) before prefetching
   chunk i+1 to prevent racing with the previous chunk's D2H into the
   same pinned CPU buffers.

3. First step OOM (HIGH): The init step now uses the same chunked path
   instead of a full optimizer.step() that materializes all states on
   GPU at once. States are created per-chunk and immediately evicted.

4. Defaults disagree (MEDIUM): Align setup_optimizer defaults for
   cpu_offload_chunked and cpu_offload_stream with config defaults
   (both False).

Also add torch.cuda.synchronize() at the end of _step_chunked (no-stream
path) to ensure async D2H completes before returning.

* fix: always sync step counters in _sync_step_counters

Remove the 'if step in group' guard so _sync_step_counters always writes
group['step'] = orig_step + 1. This handles optimizers that lazily create
the step key on per-chunk copies (e.g. Muon) where the original groups
might not have had the key set yet.

* fix: evaluate closure only once per chunked step (not per chunk)

Pass closure only to the first chunk's optimizer.step() and None to the
rest, so loss/grad recomputation happens once per training step rather than
once per layer.

* refactor: clean up CPUOffloadOptimizer for readability

- Remove redundant section separators and verbose docstrings
- Inline _build_chunk_param_groups into _step_chunk
- Inline _chunk_param_ids into _move_chunk_states
- Simplify _move_states to iterate values() directly
- Shorten comments to be targeted, not narrative

* fix: record_stream on D2H to prevent caching allocator race, align stream default

1. HIGH - Streamed D2H memory race: call record_stream on GPU tensors before
   replacing them during async D2H copy, so the caching allocator doesn't reuse
   their storage while the copy is still in flight on d2h_stream. Guard with
   is_cuda since some optimizer state tensors (e.g. AdamW step counter) live on CPU.

2. LOW - Stream default disagrees: change CPUOffloadOptimizer.__init__ stream
   default from True to False to match config and setup_optimizer defaults.

* fix: accurate docs for stream-mode GPU memory bound

Update docs, config docstring, and class docstring to say 'about one
layer's worth (two with stream overlap)' instead of 'a single layer's
worth', since stream overlap keeps up to ~3 layers resident on GPU
during the prefetch/D2H/compute overlap window.

* fix: restore param_groups in finally block to handle optimizer.step() errors

If optimizer.step() raises inside _step_chunk, the try/finally ensures
param_groups are restored to the original full set, preventing subsequent
steps from only updating a single chunk's parameters.

* revert: remove try/finally from _step_chunk per AGENTS.md philosophy

Let errors propagate — if optimizer.step() raises, training crashes
anyway and there's no point restoring param_groups.

* refactor: always use stream overlap when chunked, remove stream toggle

The stream path already caps GPU residency at 2 layers (prefetch waits for
eviction via h2d_stream.wait_stream(d2h_stream)), so the non-stream sequential
path and the stream config toggle are unnecessary. Removes optim_cpu_offload_stream
config field, the _step_chunked method, and the stream parameter from
CPUOffloadOptimizer and setup_optimizer.

* refactor: always chunk+stream when CPU offloading, remove chunked toggle

Removes optim_cpu_offload_chunked config field entirely. When
optim_cpu_offload is enabled, the optimizer step is always performed
per-transformer-layer with stream-overlapped H2D/D2H transfers (max 2
layers on GPU). This eliminates the non-chunked code path, the separate
_step_chunked_streamed method, and one config flag.

For large models (where offloading matters) chunked+stream is faster
than all-at-once because transfers overlap with compute. For small
models the absolute overhead is negligible.

* refactor: make stream param required in _move_chunk_states

Stream is always passed now — removes the None fallback, default_stream()
context manager, and all stream is not None guards.

* test: add parity tests for CPUOffloadOptimizer vs plain AdamW

Tests that per-layer chunked+stream stepping produces identical parameters
and optimizer states as all-at-once stepping, plus a state_dict round-trip
test.

* fix: remove redundant isinstance branch in test helper

* docs: remove chunked offload paragraph from scaling docs per review

* feat: make chunked optimizer offload opt-in per S1ro1 review

Adds optim_cpu_offload_chunked config flag (default False). When disabled,
CPUOffloadOptimizer uses the simple all-at-once path (move all states to
GPU, step, move back). When enabled, uses per-layer chunked stepping with
stream-overlapped H2D/D2H (max 2 layers on GPU).

Also adds torch.cuda.synchronize() to load_state_dict for async D2H safety.

* fix: reuse CUDA streams across steps to prevent memory leak

Creating new torch.cuda.Stream() on every step() caused the caching
allocator to hold onto memory via record_stream references on dead
streams. Streams are now created once in __init__ and reused.

* feat: stream FSDP gradients through CPU offload

* feat: fuse CPU offload with public FSDP hooks

* refactor: expose optimizer offload config

* refactor: always stream pinned offload transfers

* refactor: name CPU optimizer execution explicitly

* refactor: clarify CPU step config name

* chore: clarify offload runtime logging

* feat: run gradient-offloaded optimizer steps on CPU

* refactor: name fused optimizer offload full

* feat: restore gradient-only optimizer offload

* fix: keep GLM-5.2 weight broadcast within GPU memory at 4-node scale

With 4 train nodes the resident FP32 master shards are ~87 GiB/rank and the
per-layer broadcast (full expert gather + fp8 conversion) peaked ~49 GiB above
that, OOMing the post-step broadcast once training transients filled the cache.

- empty_cache() before broadcast so cached training pools are reusable
- drop consumed expert tensors eagerly and quantize into preallocated stacks
  instead of list+torch.stack copies (~49 -> ~31 GiB transient per layer)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: preallocate pinned gradient buffers before the first collective

The post-accumulate offload hook runs inside FSDP foreach_reduce on the
autograd thread; lazily cudaHostAlloc'ing the staging buffer there stalls
against the device while peer ranks' NCCL kernels spin waiting for this
rank's next collective — a distributed deadlock (faulthandler-confirmed:
autograd thread at optim.py empty_like(pin_memory=True) under
_fsdp_collectives foreach_reduce; deterministic at 78 layers, independent of
seq len, act-offload, hook design, or staging pageability). Pinning is only
safe before any collective exists, so allocate accumulator + staging for
every param at manager init.

Cost: the staging set is now always allocated (~equal to the accumulator
set) even for single-micro-batch steps; a config gate can refine this later.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: propagate dist timeout to device-mesh sub process groups

init_process_group applies the configured timeout only to the default PG;
device-mesh sub-groups fall back to torch's 10-minute module default, so
dist_timeout_seconds never reached the PGs doing the real work. Long
single-rank host phases (e.g. init-time pinned-buffer preallocation skew
across nodes) then trip peer watchdogs at 600s.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* perf: slab-allocate pinned gradient offload buffers

~800 per-param cudaHostAllocs (~1.4 TiB/node) took 10-20 minutes at init with
large node-to-node skew; one pinned slab per dtype for accumulators and one
for staging pins the same bytes in a handful of driver calls. Per-param
buffers become 256-byte-aligned views into the slabs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: overlap CPU optimizer with backward

* perf: fuse CPU gradient scaling into AdamW

* perf: add native CPU AdamW kernel

* perf: halve full-offload PCIe traffic

* harden native optimizer offload pipeline

* document optimizer offload handover

* chore(bench): add offload baseline configs and measured GLM-5 RAM feasibility

Config pack for the handover baseline matrix: Qwen3-30B-A3B four-variant
offload comparison and the GLM-5 one-node proxy, all validated with --dry-run.
Meta-device parameter counts show the 22-layer proxy (190.8B params, 2.78 TiB
CPU state) exceeds a 2 TiB node, and the four-node full-model job needs
2.71 TiB/node; handover.md updated with the measured feasibility numbers.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(bench): 8-GPU deployment and CPU thread budget for offload baselines

The SFT entrypoint defaults deployment.num_gpus to 1, and the launcher
defaults OMP_NUM_THREADS to 1, which serializes the CPU optimizer
(measured 15.7 s/step vs 6.5 s at 28 threads/rank on 8xH200).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: offload pipeline timing diagnostics and opt-in NUMA binding

Per-step wall-time counters for the bounded pipeline (D2H event wait, ring
slot waits, BF16-to-FP32 materialization, native Adam, post-backward drain),
logged at debug level. Profiling on 8xH200 showed the pipeline floor is
host-DRAM-bandwidth-bound: the Adam kernel takes ~3.4s/step against a ~0.4s
compute estimate and does not scale with OMP threads.

optim_cpu_offload.numa_bind pins each rank's CPUs to its GPU's NUMA node
before state allocation so first-touch keeps slabs and OMP threads local
(measured 6.39s -> 6.13s per step at seq 8K on Qwen3-30B-A3B).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: one-node 8xH200 offload baseline results in handover

Four-variant matrix and 2K-64K sweep for Qwen3-30B-A3B with bit-identical
losses throughout. The short-sequence pipeline floor is DRAM-bandwidth-bound;
with numa_bind, native full offload beats no-offload from 16K per-GPU sequence
upward while roughly halving peak HBM. Benchmark configs enable numa_bind.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: skip weight pre-download for random-init debug runs

pre_download_model fetched the full weight snapshot even when
debug.random_init never reads it — for GLM-5 that is ~1.4 TB pulled into
the shared HF cache. Random-init runs now fetch only config and tokenizer
files. GLM-5 proxy config drops to 20 layers to fit measured H200 node RAM.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: GLM-5 20-layer proxy results on one 8xH200 node

16K/32K/64K native full offload with numa_bind: ~18s/step CPU Adam for
21.4B params/rank, exposed drain shrinking from 17.4s at 16K to 6.9s at
64K. 20 layers is the RAM/HBM ceiling for a 2.95 TiB H200 node.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: GLM-5 8-layer no-offload vs full-offload comparison

10 layers OOMs an H200 with resident optimizer state at 16K; at 8 layers
full offload trails at 16K (38% TPS retained), wins outright at 32K (117%),
and is the only variant that runs at 64K. Halves peak HBM throughout.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: state full offload's BF16 gradient-rounding semantics

Gradients reduce in FP32 but FSDP2 materializes them in the sharded
parameter's dtype — BF16 for the full-offload compute model — so full
offload rounds each reduced gradient to BF16 once before the FP32 CPU
update. An FP32-transport option is structurally blocked (FSDP2 has no
grad-dtype override), so document the semantics in the config, the
training skill, and the handover, and point to state-only offload as
the gradient-bit-faithful mode.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: correct handover baselines — repo default is state offload

The 'no offload' rows measured the default state-offload path;
add the true GPU-resident baseline table (requires
--model.optim-cpu-offload None) and relabel accordingly.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat!: CPU optimizer offload is full offload only, disabled by default

optim_cpu_offload previously defaulted to state-only offload and carried
three modes (state-only, gradients, full) with separate streaming paths.
State-only streamed ~60 GiB/rank of optimizer state over PCIe every step
and cost ~45% of throughput at seq 8K against a GPU-resident baseline.

Now the option means one thing: full offload (FP32 masters, moments, and
gradients on CPU, optimizer overlapped with backward), enabled by setting
model.optim_cpu_offload, disabled by default so the baseline keeps
optimizer state on GPU. numa_bind defaults to true. Removes the GPU-
chunked step, state-move machinery, and per-mode branching; example
configs that enabled the old default drop the line.

Validated: config suite, dry-runs, full-native smoke with DCP checkpoint
at step 2 and resume (exact loss parity), torch-backend smoke, no-offload
default smoke.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Make CPU optim multithreading by overwriting num-thread but without oversubscring intra-op parallelsism threads

* chore(bench): drop the OMP_NUM_THREADS workaround superseded by auto thread budget

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: trim optimizer offload artifacts

* docs: trim optimizer offload scaling guide

* refactor trainer optimizer modules

* restore state-only optimizer offload

* revert unrelated GLM-5 changes

* fix conflicts with current main

* refactor: make full offload setup explicit

* refactor: rename full optimizer offload config

* fix: refresh offload masters on model-only resume

* refactor: simplify optimizer offload interface

* fix: return checkpoint state to CPU

* fix: adapt offload resume test to run dirs

* fix: preserve mixed dtypes in full offload

* fix: restrict full offload to AdamW

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Mario Sieg <mario.sieg.64@gmail.com>
2026-08-15 19:03:57 -07:00
9975d8868d feat: refactor monitors (#3275)
* feat!: refactor monitors into prime_rl.monitors

Replace the Monitor class hierarchy (ABC with five abstract methods,
NoOpMonitor, MultiMonitor) with a flat prime_rl.monitors module: only
log() is abstract, monitors register once per process, and module-level
functions fan out to them without ever raising. Construction is now
side-effect free - run registration and file handles move to init(),
and a monitor whose init() fails is disabled instead of crashing.

Sample logging becomes episode logging: PrimeMonitor regroups rollouts
into vf.Episodes and uploads one platform sample per episode, sharing
verifiers' build_samples with eval --push so training and eval samples
land identically (native episode in info.native_wrapper). The W&B
sample/eval tables and distribution logging are removed, and
PrimeMonitor now runs on the shared BackgroundAsync helper.

Config surface is grouped under [monitors]: monitors.wandb,
monitors.file, and orchestrator-only monitors.prime, replacing the
wandb / file_monitor / prime_monitor siblings and WandbWithExtrasConfig.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: wandb subpackage, finalize instead of final summary

Split the W&B monitor into monitors/wandb/{base,overview} for
readability. Rename save_final_summary to finalize - its real job is
finalizing the platform run (with the last metrics as summary); the
local final_summary.json files had no consumers and are no longer
written. Drop close() from the interface and registry: nothing called
it, and PrimeMonitor's shutdown (mark unfinalized runs failed, stop the
background loop) lives in __del__.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: track monitors/wandb package, drop prime monitor tests

The repo-wide **/wandb gitignore (W&B run dirs) silently swallowed the
new src/prime_rl/monitors/wandb/__init__.py, so CI imported the
subpackage as an empty namespace package. Negate the pattern for the
source directory.

The prime monitor unit tests mostly re-asserted the parquet column
mapping; drop them per the conservative-tests policy.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor!: loop-native monitor uploads, drop usage reporter

Rewrite PrimeMonitor's async plumbing: uploads are fire-and-forget
tasks on the orchestrator's event loop with short-lived httpx clients
(connect retries inside the transport), replacing the hand-rolled
background thread + event loop + fork handling and the per-request
retry/backoff helpers. Construction now takes only the monitor config;
runtime context moves to init(), whose kwargs each monitor names
itself.

Remove the usage reporter entirely (per-step training-token billing
posts, PI_USAGE_* env-gated) and with it background_async.py, which
has no users left.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: gate wandb-coupled paths on the registered monitor

The inference-metrics collector and the dispatcher's wandb flag were
gated on the config block, but they log to the global W&B session,
which only exists when WandbMonitor's init succeeded. A failed init
now disables the monitor instead of crashing, so the config gate let
the collector reach wandb.define_metric before any wandb.init. Gate
on monitors.get(WandbMonitor) instead.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix!: crash on monitor init failure

A configured monitor that cannot initialize (bad credentials, dead
platform) previously logged a warning and disabled itself, so the run
silently continued without its metrics. Let the exception propagate -
if monitoring was requested, losing it should stop the run.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* perf: offload episode serialization, atexit for failed-run marking

Move the parquet/JSON encode of episodes off the orchestrator's event
loop into the upload task via asyncio.to_thread - build_samples dumps
every episode's full model, and running it inline stalled dispatch on
every logging step (the one heavy call in finalize_train_batch not
already off-loop).

Replace PrimeMonitor's __del__ with an atexit hook for marking
unfinalized runs failed: __del__ can fire during interpreter teardown,
where httpx can no longer create a client, so the status PUT silently
died in 'Exception ignored' noise.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: sentinel-free non-finite JSON sanitizer

Test each child before recursing into it instead of signalling drops
through the recursive return value, which needed a module-global
sentinel object and dense sentinel-comparing comprehensions.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: type the JSON sanitizer, recurse via inner function

Rename drop_non_finite_json_values to sanitize with a recursive Json
type alias; the path-threading recursion moves into an inner walk()
so the public signature carries no recursion plumbing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: untype the sanitizer

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: sanitize returns dropped paths

Return (sanitized, dropped_paths) instead of filling a caller-supplied
list - call sites were allocating an empty list just to read it back.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: gather monitor configs into configs.monitors

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat!: slim the monitor config surface

- FileMonitorConfig.filename -> path (relative to output_dir, absolute wins)
- drop EpisodeLogConfig: episodes upload every step, all of them - the
  serialization is off-loop and the platform is the sample store, so
  interval/sampling knobs bought nothing but config surface
- hardcode the platform base URL and API key env var, resolve the
  frontend URL from the Prime CLI config; PrimeMonitorConfig shrinks to
  name + team_id, with run_name renamed to name to match wandb (still
  auto-set from run.name / the W&B run name)
- WandbConfig -> WandbMonitorConfig; the rl entrypoint's Shared*
  monitor configs move back next to RLConfig in rl.py

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: rename _SAMPLE_SCHEMA to SAMPLE_SCHEMA

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: move sanitize into utils

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: inline the prime monitor sanitize wrapper

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: drop prime monitor state flags and last-metrics replay

Register the atexit mark-failed hook only when this process created
the platform run and unregister it in finalize - the hook's presence
replaces the _registered/_finalized flags. Drop _last_metrics: every
step's metrics were already posted, so replaying the last dict as the
finalize summary was redundant; /finalize now gets an empty summary.
Use the BASE_URL constant directly instead of mirroring it on self.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: extract TrainRun owning the platform HTTP lifecycle

PrimeMonitor delegates create/log/finalize/status/sample-upload to a
small synchronous TrainRun that owns one persistent httpx client
(transport-level connect retries, connection reuse). The monitor keeps
episode grouping, parquet building, sanitization, and the
fire-and-forget task plumbing - each TrainRun call runs in a worker
thread via asyncio.to_thread. TrainRun is the seam the train SDK can
subsume later, the way wandb.Run backs the W&B monitor.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: TrainRun.create takes explicit fields

The OrchestratorConfig-to-payload mapping moves to the monitor;
TrainRun's surface is plain API fields, keeping it prime-rl-agnostic.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: rename init run_config param to config

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: type prime monitor init config as BaseConfig

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: polymorphic log, episodes through monitors, defaults on

monitors.log and Monitor.log accept either a metrics dict or a list of
vf.Episode with cohort coordinates (train/eval x all/effective); the
base class dispatches to log_metrics / log_episodes. The orchestrator's
trace-file writes move into FileMonitor (get_trace_path and
save_rollouts are inlined there), so all episode sinks share one entry
point: the streamed all cohort, the trained effective batch, and eval
epochs each fan out once, off-loop. group_episodes moves to
orchestrator utils and episode grouping happens at the source -
PrimeMonitor takes episodes and filters to the trained cohort.

The wandb and file monitors are now on by default (--no-monitors.wandb
/ --no-monitors.file to opt out), the registry list is MONITORS, and
wandb/base.py is renamed to wandb/monitor.py.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor!: PRL_RUN_ID is the run identity, drop monitor run ids

Rollout provenance is stamped with the launcher's $PRL_RUN_ID (or a
local uuid for standalone runs) instead of the monitor identity, so
Monitor.run_id and the monitors.run_id() helper go away. The RUN_ID
env handshake is removed with them: PrimeMonitor always creates a
platform run, and its id stays internal to TrainRun.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: singular episode overload, wandb log_episodes stub

log accepts a bare vf.Episode alongside dicts and episode lists (the
base dispatch wraps it); log_episodes is abstract now, so WandbMonitor
gets an explicit no-op.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: fully async monitors, TrainRun mirrors wandb exit behavior

The whole Monitor surface is async now (init/log/log_metrics/
log_episodes/finalize); the orchestrator awaits the fan-out directly
and the sync trainers wrap calls in asyncio.run. FileMonitor offloads
record serialization via asyncio.to_thread (awaited, so appends to one
trace file never interleave); PrimeMonitor's fire-and-forget goes back
to plain create_task since nothing submits cross-thread anymore.

TrainRun now owns its exit behavior the way wandb.Run does: create arms
an atexit hook that marks the run failed, finalize marks it completed
and disarms the hook. The orchestrator finalizes monitors only on a
clean exit, so a crashed run reports failed on the platform just like
it does on W&B.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: keep the platform mark-failed atexit path synchronous

asyncio.run at atexit dies with 'cannot schedule new futures after
interpreter shutdown': async httpx resolves DNS via run_in_executor,
and concurrent.futures marks itself shut down via
threading._register_atexit, which runs before module atexit hooks.
The failure PUT uses sync httpx; everything else on TrainRun stays
async.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: make wandb monitor init async

The async conversion missed WandbMonitor.init's multi-line signature,
so the registry awaited None and setup crashed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: finish the W&B run explicitly, align monitor logs

In (experimental) shared mode the SDK's atexit finish does not land the
run state, so even clean runs decayed to 'crashed' - WandbMonitor's
finalize now calls wandb.finish(exit_code=0) off-loop. Every monitor
logs one info line at init and finalize; per-step uploads only warn on
failure.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: task cache and parquet builder out of the monitor

TrainRun owns the fire-and-forget submit machinery; the episode
parquet builder becomes a module helper below both classes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: propagate monitor disables, shared prime block, drain on finalize

With the monitor sub-configs defaulting to enabled, the rl entrypoint's
--no-monitors.wandb / --no-monitors.file were silently ignored - the
CLI disable (the string 'None') now propagates to both sub-configs like
the enable does. [monitors.prime] joins the shared block, propagated to
the orchestrator only (no trainer platform integration yet), and
PrimeMonitorConfig loses team_id (the Prime CLI team applies).

TrainRun.finalize now drains in-flight uploads first, so the final
step's metrics and episodes land before the run is marked completed.
Also prunes FileMonitor's unreachable pre-init guard.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: fix stale TrainRun docstring

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: sample platform episode uploads to 10% capped at 128

All episodes every step overwhelms the platform's ingestion; sample
min(10% of the step's episodes, 128) instead. Lift once the prime
traces SDK is integrated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: take the first episodes instead of sampling

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: note monitor run names inherit run.name

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: wandb off by default, migrate integration test flags

The integration tests still passed the old --wandb.* flags, failing
config validation; and wandb-on-by-default would crash credential-less
environments at init. W&B is opt-in again (the file monitor stays on
by default); the tests use --monitors.wandb.*.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: sample platform episode uploads randomly

The effective batch is ordered by group finalization, so a prefix
over-represents early-finishing envs on multi-env runs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: restore the RUN_ID attach handshake

Managed launches pre-create the platform run and inject its id via
$RUN_ID; attaching instead of registering prevents duplicate runs.
RUN_ID stays a dedicated backend channel - PRL_RUN_ID can't signal
attachment because the rl launcher always mints one locally. Attached
runs skip the atexit failure marking (the backend owns that); finalize
still marks them completed on clean exit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: restore pre-refactor episode upload defaults

Every 10th step, unsampled - what log_extras defaulted to on main.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: episode upload cadence

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 17:39:40 -07:00
de626e934e chore: bump vllm-router wheel to v0.2.0 (#3274)
First release from the router's rebase onto upstream vllm-project/router
(PrimeIntellect-ai/router#51): upstream v0.1.15+18 with the re-ported
fork features (P/D routed-experts merge validated byte-identical against
a single-engine baseline, model-aware routing, phantom-load fixes,
validation 500->400 rewrite incl. vLLM 0.26 wording, per-run usage
metrics, JWT auth).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 12:36:30 -07:00
e56a8df198 feat!: remove the benchmark mode (#3272)
Remove the --bench flag from all entrypoints (RLConfig, SFTConfig,
TrainerConfig, OrchestratorConfig) along with BenchConfig, the
auto_setup_bench validators, the bench branches in the trainers and
orchestrator, and the rich benchmark table / JSON export helpers.

The benchmark CI keeps working: run_single_benchmark.py now runs a
normal short training (--max-steps, fake data) with the file monitor
enabled and aggregates throughput / MFU / step time / peak memory
from the run's metrics.jsonl. The output JSON schema is unchanged, so
the regression test, the aggregation script, and the stored baselines
are untouched.

Monitors no longer retain metric history: keep_full_history and the
history list are gone. The file and prime monitors keep only the last
metrics dict for the final summary, and the trainers track the peak
memory maximum locally for the end-of-run log.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 10:58:20 -07:00
68e0c50f6c feat: per-attempt log directories (#3271)
* never overwrite logs across launch attempts

Every launch of a run — fresh or resumed — writes its logs to its own
logs/attempt_<n>/ directory, with logs/latest symlinked to the current
attempt. Previously a resume reopened the same log files with mode "w"
and destroyed the previous attempt's logs. The SLURM templates compute
the attempt in bash the same way; readers (tmux.sh, log hints, tests)
go through logs/latest. Logs are the only clobbered artifact: the
step-keyed dirs are pruned deliberately on resume, and configs/ holds
the current attempt's resolved configs by design.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* route all template log paths through the attempt dir

The shared _launch_rank/_launch_router snippets and the multi-node SFT
template still wrote under $OUTPUT_DIR/logs/, so per-rank vLLM tees
targeted a directory that no longer exists and SFT resumes kept
overwriting trainer logs. Every sbatch template now computes the same
attempt block and writes only through $LOG_DIR; verified by rendering
all four entrypoint scripts and grepping for stale paths.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 21:53:06 -07:00
e26b505039 feat: run dir + resume from path (#3268)
* Add named run directories under output_dir

output_dir now groups related runs: each run writes all its artifacts
(logs, configs, checkpoints, weights, rollouts) to output_dir/run.name.
The new run.name field defaults to a random UUID, so every launch gets
a fresh run directory and concurrent runs no longer need a manually
unique output_dir. Set an explicit name to make the run directory
predictable, which is also what resume points back at.

Launching into a run directory that already contains run artifacts now
fails unless resuming or clean_output_dir is set; clean_output_dir
wipes only the run directory, not its output_dir siblings.

The rl entrypoint derives trainer/orchestrator output_dir from the run
directory, so sub-processes and standalone sub-configs are unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Add run id and propagate run identity everywhere

RunConfig gains an id (locally generated for now; the Prime SDK will
issue it once runs are registered there). The run identity now flows
to every surface that names or groups a run's artifacts:

- traces: the orchestrator stamps RunInfo with name + id (id prefers
  the monitor identity, falling back to run.id); requires the
  verifiers RunInfo.name companion (submodule bump)
- W&B: unset wandb.name inherits run.name; the shared W&B run id
  defaults to run.id
- Prime platform: unset prime_monitor.run_name inherits run.name
- sandboxes: env-server TOMLs carry sandbox_labels=[run.name], applied
  process-wide via verifiers' set_base_sandbox_labels, so every Prime
  sandbox of a run is labeled with the run name; runtime-config labels
  extend the base labels

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Bump verifiers for RunInfo ruff fix and rename

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Keep the run id out of config; inject identity

The run id is not user config: the rl entrypoint mints it (TODO: fetch
it from the Prime SDK once runs are registered there) and injects it —
with the resolved run name — as a launcher-managed [run] block into the
orchestrator and every env-server TOML. The orchestrator stamps it on
traces (monitor identity still preferred); env servers label every
Prime sandbox with the run name via set_base_sandbox_labels, now
imported from verifiers.v1.runtimes (the root export is gone).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Auto-generate readable run names; add run.dir

run.name now auto-generates as <train-envs>--<model>--<short-id> (SFT:
<dataset>--<model>--<short-id>, env names joined with +) instead of a
bare UUID, so default run directories and inherited W&B/platform names
read like the experiment they are while the short-id suffix keeps
launches collision-free. run.dir names the run directory and defaults
to run.name, for when the directory must differ from the display name.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Rename clean_output_dir to clean; lowercase names

The flag cleans the run directory, not the output directory, and now
matches the eval CLI's --clean. No alias for the old spelling; the
NEVER_CLEAN_OUTPUT_DIR escape hatch becomes NEVER_CLEAN. Auto-generated
run names are lowercased.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Use /tmp as the grouping dir in the dry-run example

* Split output_dir and run name in the GLM-5.2 example

* Carry the run id as PRL_RUN_ID, never in config

The run id is a runtime concept: the launcher sets $PRL_RUN_ID (once,
respecting an externally provided value — the future Prime SDK hookup
point) and every spawned process inherits it; the SLURM templates
export it job-wide the same way as the shared W&B id, which now
defaults to it. Configs carry only the run name. $PRL_RUN_ID is the
general vehicle for transporting runtime info between processes, so it
joins the protected env vars.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Retire WANDB_SHARED_RUN_ID in favor of PRL_RUN_ID

The shared W&B run id was always just the run identity under another
name; the monitor now reads $PRL_RUN_ID directly. WANDB_SHARED_MODE
(the toggle) and WANDB_SHARED_LABEL (the per-process label) carry
distinct information and stay.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Make resume a top-level config block

resume: ResumeConfig | None replaces ckpt.resume_step on the rl and
sft entrypoints: None (default) does not resume, a bare --resume (or
empty [resume] block) resumes from the latest checkpoint, and
--resume.step N resumes from step N — mirroring the eval CLI's
--resume. The block maps onto the sub-configs' internal resume_step
(-1 = latest), so trainer and orchestrator are unchanged. Also guard
--clean against a run.dir resolving outside output_dir (matches the
eval fix) and validate it in validate_run_dir.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Unify resume consumers on ResumeConfig

The sub-config checkpoint configs (trainer, orchestrator, SFT) carry
the same resume block as the entrypoints instead of an internal
resume_step with a -1 sentinel: step None means latest everywhere, and
the checkpoint managers and resume resolution read resume.step.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Bump verifiers for name-only eval resume

* Add resume.dir to fork an external checkpoint

--resume.dir points at another run's checkpoint step directory (e.g.
other/checkpoints/step_50) and forks it into this run: the step comes
from the directory name, the trainer and orchestrator load their state
from that path, and everything else (saving, weights, rollouts) stays
in this run's own directory. Mutually exclusive with resume.step.
Also bump verifiers: eval --resume is now a plain flag on the resolved
config, prl-style.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Bump verifiers for eval resume cleanup

* Bump verifiers for unified validate resume

* Bump verifiers for eval resume config hash check

* Carry the run name as PRL_RUN_NAME, drop RunInfoConfig

The whole run identity is now runtime-only: the launcher exports
$PRL_RUN_NAME next to $PRL_RUN_ID and every spawned process reads it
for trace stamping and sandbox labels; the multi-node template exports
it job-wide. Sub-configs carry no run info at all — components run
standalone simply have no run identity.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Bump verifiers for schema-level resume hash

* Bump verifiers for configs/ layout and digest check

* Move resume to the top level on trainer and orchestrator

resume sits next to ckpt on every config, not inside it — the same
shape at every level. The checkpoint managers take it as a parameter
instead of reading it off CheckpointConfig.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Write resolved configs as JSON

Machine-written configs (rl/sft/trainer/orchestrator/inference/env
server) become JSON: it keeps nulls, so explicit None overrides
round-trip exactly and to_toml_dict's "None"-string convention is
deleted. Hand-written configs stay TOML; the format split marks
intent vs resolved artifact. Aligns with verifiers' configs/<cli>.json
(submodule bumped).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Bump verifiers for gepa guard ordering

* Bump verifiers for logs/ run-dir layout

* Pin verifiers to main with #2358 merged

* Always construct checkpoint managers; fix skip-scheduler horizon

The checkpoint manager now always exists: resume decides whether it
loads, ckpt whether it saves. A standalone trainer or orchestrator
launched with --resume and no [ckpt] previously skipped the load path
silently; now it resumes (and saves no new checkpoints). The
resume-requires-ckpt validators are gone accordingly.

SFT's skip_scheduler sized the rebuilt schedule from resume.step,
which is unset for a bare --resume and for --resume.dir; it now uses
the resolved checkpoint step, so warmup/decay run on the remaining
steps.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Skip the HF weight load on any resume

loading_from_ckpt_later still required config.ckpt, so a resume
without [ckpt] loaded HuggingFace weights before the checkpoint
overwrote them — failing offline or OOMing on large models. The
resolved checkpoint step alone decides: resuming initializes an empty
model and loads from the checkpoint.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 20:54:25 -07:00
70caa7c61f chore: bump verifiers for prime vm runtime default (#3270)
* Bump verifiers for prime VM runtime default

vf#2356 makes the prime VM runtime the default agent runtime:
PrimeConfig now defaults vm=true, AgentConfig.runtime defaults to
PrimeConfig(), and prime auth is checked when a prime runtime or
tunnel is instantiated. Also picks up vf#2357 (stable task keys).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Drop vm = true from example configs

Prime sandboxes default to vm=true after the verifiers bump, so the
explicit flag in the example runtime sections is redundant.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Drop redundant prime runtime keys from example configs

The default agent runtime is now the prime VM sandbox, so
type = "prime" (pydantic_config falls back to the default union
variant when the tag is omitted) is redundant. The
idle_timeout = "None" lines go too: PrimeRuntime always drops
idle_minutes for VM sandboxes, so the key is a no-op there.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 17:13:31 -07:00
5a005de2d6 feat: warn when inference queue exceeds inflight-episode budget (#3269)
Poll-time check in InferenceMetricsCollector: when aggregate waiting
requests exceed 20% of max_inflight_episodes, inference is saturated
and rollout latency (and thus training throughput) suffers. Emit a
throttled warning (at most once per 60s) advising to wait if the
spike is intermittent and to lower max_inflight_episodes if it
persists.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 16:45:55 -07:00
AtirnaandGitHub 756afd40eb docs: remove retired zero-gradient metric (#3267) 2026-08-13 16:37:40 -07:00
c1674ac93c feat: dynamic pass-through vLLM inference metrics to W&B (#3240)
* feat: dynamic pass-through vLLM inference metrics to wandb

Replace the hand-curated inference metric allowlist with a dynamic
pass-through collector: every vllm:* Prometheus family is logged,
per-engine under inference/engine/{id}/ and cross-engine aggregations
(min/max/mean/median/sum) under inference/{agg|prefill|decode}/.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: drop InferenceMetricsConfig, keep collect_inference_metrics flag

Hardcode poll interval, aggregations, and per-engine logging in the
collector; config surface is unchanged from main (collect_inference_metrics
+ inference_metrics_roles).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Add inference health section to the overview view

Seven panels, each pairing the fleet aggregate (mean/sum) with the
cross-engine tail that flags a single sick engine - max for pressure
(KV usage, preemptions, waiting, prompt-token recompute), min for
health (prefix hit rate, generation throughput). A saturated engine
thrashing its KV cache hides inside fleet means; the tails surface it.

Also compute the prefix-cache hit-rate ratio per engine (not only
pooled over the fleet) so the min/max aggregations exist for it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Flatten metric keys to inference/{scope}/{metric}/{stat}

Drop the vllm: family prefix (the collector only admits vllm:* families,
so it carries no information), flatten per-engine series from
inference/engine/{id}/... to inference/{id}/..., and move scope-level
quantiles (:p50 -> /p50) and the pooled ratio (-> /pooled) into the
stat segment so every key reads inference/{scope}/{metric}/{stat}.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Add min series to KV usage and waiting panels

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 16:03:10 -07:00
halleriteandGitHub b1d4f2fa6c chore(ruff): pin path-dep import classification (#3263) 2026-08-13 19:14:25 +02:00
d43e0f329b perf!: remove the zero-gradient-ratio metric (#3249)
get_zero_gradient_ratio launched a device-scalar transfer and a
count_nonzero kernel per parameter plus two all-reduces and a sync every
step, serializing the post-backward path on models with many tensors: on
Qwen3-30B-A3B (8xH200, seq 8K) it cost 1.4 s of a 4.6 s step. The metric
also read 1.0 on every validation run, so it was likely not measuring
what it intended on FSDP2 DTensor gradients. Removes the metric, its
trainer call sites, and the Prometheus gauge.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 09:10:44 -07:00
8c1f196dd3 chore: bump verifiers for prime-sandboxes 0.2.36 (#3259)
* Bump verifiers for prime-sandboxes 0.2.36

prime-sandboxes 0.2.36 gives each live ACP process its own HTTP
transport (prime#831), fixing the h2 stream-cap deadlock that made
rlm rollouts fail with 'process stdin RPC failed (deadline_exceeded)'
above ~100 concurrency.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Repoint verifiers submodule to merged main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 16:43:09 -07:00
chethanukandGitHub 753a3fec0a docs(k8s): drop dead docs links and fix PVC name in Helm README (#3242)
k8s/README.md links to /prime-rl/kubernetes, /prime-rl/deployment and
/prime-rl/troubleshooting. All three return 404: those pages are not in
docs/ and have no entry in docs/mint.json. Drop the two Kubernetes links
and the troubleshooting bullet — the README's own sections are the chart
documentation — and retarget the deployment bullet at /prime-rl/scaling,
which is where the multi-node and SLURM content lives now.

The uninstall snippets also name the wrong PVC. templates/pvc.yaml names
it {{ .Release.Name }}-shared-data, so after the documented
`helm install my-exp`, `kubectl delete pvc prime-rl-shared-data` fails
NotFound and reads as if the data is already gone.

Closes #3054
2026-08-12 09:42:34 -07:00
3ad13dd0bc fix: skip weight pre-download for random-init debug runs (#3247)
pre_download_model fetched the full weight snapshot even when
debug.random_init never reads the weights — for large models that pulls
hundreds of GB (GLM-5: ~1.4 TB) into the shared HF cache before a fake-data
debug run. Random-init runs now fetch only config and tokenizer files.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 08:51:06 -07:00
ee06d333e4 chore: bump verifiers to latest main (#3246)
verifiers 42a6c95de..a506236ec:
- fix: compact harness runs without a container (#2329)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 20:02:42 -07:00
91d4b92597 chore: bump verifiers and prime-envs to latest main (#3245)
verifiers d53ab56f0..42a6c95de:
- feat: metadata-only overrides for config-plugged functions (#2323)
- feat(compact): one tool call per turn, notes-only carryover (#2313)

prime-envs 1f1f915a..b30aad36:
- feat!: add train/eval graph split to wikispeedia (#759)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 19:40:27 -07:00
82acb12ed7 fix: revert default DPPO masking thresholds to 0.2 (#3244)
Revert bb23623d6 (#3236). The tighter 0.1 trust region masks the few
high-leverage decision tokens once their probability moves >0.1 across
off-policy staleness, slowing LoRA convergence (reverse-text LoRA CI
smoke: 0.5-0.6 reward @ step 15 vs 0.8 with 0.2).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 19:35:13 -07:00
124f9694a6 chore: stop dumping resolved orchestrator config to control/ (#3243)
The orchestrator wrote its resolved config to <output_dir>/control/orch.toml,
a relict of the deprecated multi-tenant setup. The launcher already persists
resolved configs under the output directory.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 19:27:44 -07:00
4308fe3aba chore!: point at the renamed prime-envs repo (#3241)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 14:54:54 -07:00
minh hoangandGitHub da53d4c064 chore: bump renderers for Nemotron 3.5 (Lightning) renderer (#3239) 2026-08-11 12:23:08 -07:00
minh hoangandGitHub efe8e7fda8 feat: auto-resolve parsers for Nemotron 3.5 (Lightning) (#3237)
* feat: auto-resolve parsers for Nemotron 3.5 (Lightning)

* test: drop NVFP4 expectation, BF16 only

* clean up docstrings
2026-08-11 11:57:36 -07:00
bb23623d6e feat: change default masking thresholds to 0.1 (#3236)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 11:23:41 -07:00
03f12efbaf feat!: drop v0 env compat (#3226)
* feat!: drop v0 env compat from the orchestrator and configs

The verifiers legacy bridge is removed upstream, so every v0 code path
goes:

- configs: drop the [legacy] block, is_legacy, the legacy/env conflict
  validators, and resolve_legacy_env_kwargs from EnvConfig and
  EnvServerConfig; env-server TOMLs no longer carry a legacy section
- env-server entrypoint: always serve a taskset (no bridge fork)
- orchestrator: Env always loads its taskset client-side (info()/
  run_group()/task_idx addressing removed); requires_group_scoring and
  its consumers (variable permit costs, group-scored partial drops,
  run_group fan-out) are gone — one permit is one episode everywhere
- TrainSource rows always carry the task; the pending-draw head-of-line
  hold and per-env permit costs are gone (next_example takes no args)
- GroupState.task is required; task_idx derives from task.data.idx
- env taskset ids drop the -v1 suffix across configs, examples, docs,
  skills, and the workspace members (companion renames in verifiers and
  research-environments)
- port the qwen3-vl features-payload test from the v0 RendererClient to
  renderers.client.generate (the path the v1 train client drives)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers + research-environments to the rename branches and relock

deps/verifiers -> feat/legacy-package (6a8de86), deps/research-environments
-> feat/drop-v1-suffix (27ed790). Re-pin to the merged commits before landing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin to the reworked branch head

v0 code stays in place upstream; the branch now only removes the v1
legacy bridge and the -v1 suffixes (lock unchanged).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (v1 CLI simplifications)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (main merged, python floors)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (v1 drops on-demand Hub installs)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (v0 tree under verifiers.legacy, aliased)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (ID plain str, public alias names)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (ruff fixes)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (static-tooling fixes)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (gepa schema id fix)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (docs/legacy move)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin (hub installs restored in v1)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: pin verifiers to the merged main commit

deps/verifiers -> main 91d4f69e6 (#2303 merged); research-environments
-> the rename branch head with the automationbench_env collision fix.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: floor verifiers at 0.3.1.dev12

The first dev release carrying the v0 deprecation (verifiers#2303);
submodule follows main.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: verifiers submodule points at main head (the #2303 merge), not its parent

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: pin submodules to the merged mains and floor verifiers at 0.3.1.dev13

deps/verifiers -> f24b8ec0 (#2311), deps/research-environments ->
c0a0d1d7a (#754); 0.3.1.dev13 is the release cut from that verifiers
commit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers to main d53ab56f (0.3.1.dev14)

Picks up the model-catalog revert (verifiers#2314).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-10 21:54:01 -07:00
f2ead102d1 feat(laguna): support per-element attention gating (#3229)
Laguna's config carries a `gating` field that prime-rl's port dropped, so
g_proj was always sized for per-head gating:

    self.g_proj = nn.Linear(config.hidden_size, num_heads, bias=False)

That matches Laguna S (`gating = "per-head"`, g_proj [48, 3072]) and is wrong
for Laguna M (`gating = "per-element"`, g_proj [8192, 4096] = num_heads x
head_dim). Loading M.1 fails with

    ValueError: Size mismatch between saved torch.Size([8192, 4096]) and
    current: torch.Size([64, 4096]) for model.layers.0.self_attn.g_proj.weight

Carry `gating` on LagunaConfig and size g_proj from it, following upstream's
semantics exactly (poolside/Laguna-M.1 modeling_laguna.py):

    True / "per-element"  one gate per (head, head_dim) channel
    "per-head"            one gate per head, broadcast across head_dim
    False                 no gating

Note the default is `True`, not "per-head": a checkpoint that omits the field
gets per-element upstream, so defaulting the other way would silently mis-size
it. bool and str are both accepted for the same reason.

Verified against both checkpoints: g_proj matches [48, 3072] for S-2.1 and
[8192, 4096] for M.1, and the gate math is bit-identical to upstream in both
modes (max abs diff 0.0). End to end, a 4-node trainer probe loads the real
452GB M.1 checkpoint through load_dcp_from_hf with no size mismatch, where it
previously failed at model construction.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 21:41:50 -07:00
halleriteandGitHub c698bdeb2a chore: bump research-environments for the toolset register() fix (#3230) 2026-08-10 20:11:43 +02:00
6e33f3f82f chore: bump verifiers for the unbounded model-call timeout (#3227)
Bumps deps/verifiers 29e3a0f7 -> a298bcfe, picking up two commits:

  a298bcfe fix(v1): restore the unbounded model-call timeout (#2304)
  9ca7f5d6 Fix plain HTTP CONNECT for Docker framework routes (#2298)

verifiers#2218 had consolidated client construction into
build_async_openai/DEFAULT_TIMEOUT and, in doing so, replaced the relay
client's explicit `timeout=None` with a 600s read timeout mirroring the OAI
SDK default. That cap reached every model-call path, since DEFAULT_TIMEOUT
feeds clients/eval.py as well as build_async_openai, which judge.py and
clients/train.py use.

600s is fine for chat-shaped evals and wrong for RL: a single agentic turn on
a long SWE trajectory routinely runs past ten minutes, and when it does the
rollout dies as `ProviderError: Request timed out` even though the model was
still producing. Because it truncates the longest trajectories specifically,
the loss is biased rather than uniform. Seen on the laguna-s SWE RL run here.
#2304 restores unbounded read/write/pool and keeps connect at 5.0 so an
unreachable endpoint still fails fast.

No lockfile change: verifiers is an editable path dependency
(`source = { editable = "deps/verifiers" }`), and neither commit touches its
pyproject, so only the submodule pointer moves.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 21:41:10 -07:00
c282262e6e fix(slurm): export ORCH_PROCID so the orchestrator actually launches (#3225)
#3189 hoisted ORCH_PROCID out of the srun body into the outer batch script so
ORCH_ADDR could be derived from it. ORCH_ADDR was exported; ORCH_PROCID was
not.

The srun body is a quoted heredoc, so `$ORCH_PROCID` in

    if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then

is expanded per task, and a plain (unexported) shell variable never reaches
the task environment. The test becomes `[ "4" -eq "" ]`, which errors with
"integer expression expected" and evaluates false on every rank, so the block
that starts the orchestrator and both env servers is skipped entirely.

The failure is silent and expensive. Inference comes up, the trainer reaches
weight-broadcast init, and then the job sits there until the 3600s NCCL
watchdog fires on a 1-element ALLREDUCE, holding the whole allocation. There
is no error in the job log pointing at the orchestrator, and no
orchestrator.log to look at, because the `tee` that would create it is inside
the skipped block. Observed on a 6-node run: 20 minutes in, only
PRIME-RL::Trainer processes on the orchestrator node and no logs/envs/
directory, which the block's own `mkdir -p` would have created.

Export it. Verified by rendering multi_node_rl.sbatch.j2 and running the guard
with SLURM_PROCID=4: the branch is taken now and skipped before.

Audited the other templates for the same pattern — variables assigned in the
outer script but read inside a quoted heredoc. multi_node_sft, single_node_rl
and single_node_sft are clean. Two apparent hits are false positives:
HOSTNAMES is rebuilt inside the body from the exported HOSTNAMES_STR, and
inference.sbatch.j2's DP_PER_NODE is rendered directly into the body by Jinja.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 20:51:20 -07:00
289562d2ec feat: remove multi-tenant (#3189)
* feat(client): single-string base_url, remove elastic inference pool

The data plane is now a single endpoint (put a router in front for
multi-replica deployments); admin_base_url stays a list for per-server
admin operations (weight updates, health checks, NCCL rank offsets).
Removes ElasticInferencePool (DNS discovery + per-tenant adapter sync),
the InferencePool protocol/factory, and client-side load balancing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: orchestrator-side packing, single-tenant trainer, flat output dir

Removes the multi-tenant infrastructure:

- Bin-packing moves into the orchestrator (BatchPacker), which now ships
  per-DP-rank micro batches directly to the trainer — one transport hop
  instead of two (the rank-0 packer and its second filesystem write are
  gone). ZMQ data moves to port, READY barrier to port+1; the transport
  binds in the orchestrator process.
- MultiRunManager, run discovery, eviction, the control/orch.toml
  handshake, MultiPacker, MultiCheckpointManager, MultiLoRAOptimizer,
  MultiLoRAScheduler, per-run metrics, and trainer.max_concurrent_runs
  are deleted. A slim LoRAState in trainer/lora.py keeps single-tenant
  LoRA (RL + SFT) working: module registry, adapter state dicts, resets,
  and the shared lora_num_tokens/scaling tensors (n_adapters=1).
- The run_default nesting is gone: orchestrator.output_dir equals
  trainer.output_dir, with rollouts, broadcasts, checkpoints, and token
  exports in one flat experiment dir.
- RL LoRA optimizers now include modules_to_save params (matching SFT).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: always broadcast step-0 weights at startup

The trainer's startup broadcast of the incoming policy (v0 from scratch,
v{resume_step} on resume) now runs for every transport, not just the
in-memory ones, and the orchestrator's startup weight sync is
unconditional to match. This validates the broadcast path at startup
instead of after the first optimizer step and aligns fresh starts with
the restart flow. The orchestrator always waits for the startup weight
directory (default 1200s; ckpt.wait_for_weights_timeout overrides).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: assign base_url as str in auto_setup_inference_client

Leftover list assignment from before the base_url list[str] -> str
migration; pydantic doesn't validate assignment, so the list survived
until rl_local's urlparse crashed on it (sft-distill path only).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-08 19:49:42 -07:00
3ab5e04c4c feat: per-source env-server address via serve.address (#3218)
* feat(configs): per-source env-server address via serve.address

Setting serve.address on a train/eval source marks its env server
externally managed: the launcher neither writes its TOML nor spawns a
server for it, and the orchestrator connects to the given address.
Unset sources keep the derived loopback address, with indices still
positional across all sources.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: subclass vf.ServeConfig instead of mirroring its fields

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: consume vf.ServeConfig as-is

Companion verifiers bump makes ServeConfig.address optional with no
default, so the per-source serve block needs no prime-rl subclass.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers to merged optional-serve-address rev

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-08 16:38:07 -07:00
d1046b876c feat!: vllm pass-through inference config (#3202)
* feat!: flatten inference config into vLLM pass-through [vllm] section

Replace ModelConfig/ParallelConfig and the flat vLLM fields on
InferenceConfig with a single flat VllmConfig under [inference.vllm]
(standalone: [vllm]) that uses vLLM's own argument names and passes
unknown keys through to the server verbatim (extra="allow"), replacing
the vllm_extra escape hatch. to_vllm()'s rename table becomes a direct
to_namespace() dump.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test: pin VALID_VLLM_LORA_RANKS against vllm.config.lora.MaxLoRARanks

The constant stays hardcoded (prime-rl-configs has no vLLM dependency,
and importing vLLM costs ~5s per config-parsing process); a unit test
now fails on any vLLM bump that changes the accepted ranks.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: no apostrophe in the srun-quoted launch helper, guard with bash -n

The per-rank launch helper is rendered inside the single-quoted
`srun bash -c '...'` body, so the apostrophe in the new "can't be inlined
as CLI flags" comment ended the quoted body and the rest of the script was
parsed by the outer shell — every SLURM inference launch (single-node,
multi-node and disaggregated alike) died at parse time with
`syntax error near unexpected token ')'`.

Reword the comment, drop the quotes around printf's format string for the
same reason, and add a unit test that renders both sbatch templates across
the deployment shapes and runs `bash -n` on the output, so this class of
quoting bug fails CI instead of the cluster.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: feed srun launch bodies to bash on stdin via a quoted heredoc

The multi-node launch bodies were passed as a single-quoted `bash -c '...'`
argument, so a lone single quote anywhere inside them — including in the
shared _launch_*.sh.j2 includes, and including in a comment — ended the
quoted body and left the rest of the script to be parsed by the outer shell.
The apostrophe in this branch's "can't be inlined as CLI flags" comment did
exactly that and killed every SLURM inference launch at submit time with
`syntax error near unexpected token ')'`.

Deliver the bodies the way the cleanup block already does: `bash -s` with a
quoted heredoc, which srun broadcasts to every task and which passes the
script through verbatim, so no character in the body needs escaping. This
removes the hazard from inference, multi-node RL and multi-node SFT rather
than policing it, drops the `'"'"'` escape dance around
DECODE_COMPILE_CFG, and fixes the trainer log filter, whose sed script was
silently losing its backslashes to the outer shell.

Nothing in the bodies reads stdin, which would otherwise consume the rest
of the script.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test: drop the VALID_VLLM_LORA_RANKS pin against vllm.config.lora.MaxLoRARanks

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-08 10:50:41 -07:00
samsjaandGitHub 381df0a658 chore: bump version to 0.8.0 (#3209)
* chore: bump version to 0.8.0

* fix: revert accidental annotated-types version change in uv.lock
2026-08-07 10:20:28 -07:00
532d622b4c chore: bump verifiers to 0.3.0 (#3205)
* chore: bump verifiers + research-environments to latest main

verifiers d30a3f48e -> f940bf7a7 (0.2.2.dev76 -> dev91), floors follow.
research-environments f9c43a74f -> b10db7640 (adds mmk12-v1).

Adapts to vf#2244 (run info moved from Trace onto Episode): the
orchestrator stamps the run into each rollout's info instead of the
removed Trace.record_run, keeping per-trace records placeable.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat!: write traces.jsonl in verifiers' native episode format

One vf.Episode record per line, matching what verifiers' own eval CLI
writes and read_episodes loads. The run is stamped on the episode via
Episode.record_run, and prime-rl's orchestration metadata (env_name,
group_id, policy_version) lives in Episode.info; a multi-agent episode
is one line holding all its traces.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Revert "feat!: write traces.jsonl in verifiers' native episode format"

This reverts commit b5972ef9b16970420df558071e33bea63f9fddba.
traces.jsonl stays one trace record per line - the episode-native format
only pays off with the episode-first pipeline, which is not being taken.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: re-pin verifiers to run-info revert, drop the dev91 adaptation

deps/verifiers moves to vf#2264 (revert of vf#2244), which restores
Trace.record_run - the orchestrator code is untouched by the bump again.
Re-pin to verifiers main once vf#2264 merges.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: re-pin verifiers to main (vf#2264 merged)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers to dev102, enumerate used vf env members

verifiers eb2c3fe11 -> b23b5c2ca (0.2.2.dev102). The vf environments/*
workspace glob becomes an explicit list of the envs prime-rl trains or
tests on, so upstream examples with conflicting pins (nemo-gym-weather-v1
pins openai<=2.7.2 via nemo-gym against verifiers' openai>=2.9.0) never
enter the shared lock. Floors stay dev92 - nothing in the range is
API-required, and PyPI publishing lags main.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: pin verifiers to fix/interception-owned-clients for validation

One commit on top of main (dev102). Re-pin to main once it merges.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: re-pin verifiers to main (interception fix merged)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers to dev112 + renderers to 0.1.10.dev1 for 0.3.0 prep

verifiers 2efe0a138 -> 0a4d872f0 (0.2.2.dev112). renderers follows to main
(0.1.10.dev1, adds Laguna M.1) since vf now floors renderers>=0.1.9.
Re-pin to the 0.3.0 release tag and flip floors once it is published.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: floor verifiers at dev112 (published to PyPI)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: verifiers floors to 0.3.0 (released)

The submodule pin 0a4d872f0 is the v0.3.0 tag commit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: relock for the 0.3.0 floors

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: renderers floor to 0.1.9 (released)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 10:17:16 -07:00
minh hoangandGitHub ec92686fbc perf(docker): cut ghcr image build from 74m to 16m (#3160)
* fix(docker): pin prebuilt aarch64 flash-attn wheel instead of building from source

The arm64 image built flash-attn 2.8.3 from source on every build: 53m46s of the
1h13m arm64 job, 74% of it, and the critical path for the whole multi-arch build.

mjun0812/flash-attention-prebuild-wheels publishes the exact aarch64 counterpart of
the x86_64 wheel already pinned here — same flash-attn 2.8.3, cu128, torch 2.11,
cp312. Pin it behind a platform_machine marker and drop the source build.

GPU coverage is unchanged. The old source build and both wheels carry identical
fatbinaries: 288 entries, sm_80 / sm_90 / sm_100 / sm_120 with 72 kernels each. The
53-minute compile was reproducing what the wheel already shipped. Verified by
walking the fatbin entry headers of flash_attn_2_cuda.so in the old arm64 image
alongside both wheels; the .so sizes agree to within 0.013%.

Also drops the post-install script's side effects. It re-resolved without
--no-deps, re-downloading 897 MB and downgrading the image's cudnn from 9.22.0.52
to 9.19.0.56 relative to the lockfile, so arm64 now matches amd64 and the lock
again. Its flash-attn-cute reinstall existed only because the source build shipped
a flash_attn/cute stub that clobbered FA4; the wheel has no cute directory, so
arm64 takes the same install path as amd64.

Removes the local aarch64 build step from scripts/install.sh and the README too —
uv sync resolves flash-attn from the wheel there as well, so the 20-30 minute
compile and its "don't run uv sync afterwards or it gets uninstalled" caveat are
both gone.

The lock diff is large but mechanical: the second platform-forked URL makes uv
restate fork markers across the file. The resolved (name, version, source) set is
unchanged except for the one added aarch64 wheel.

* perf(docker): split the venv into parallel-compressible layers and push zstd

The image was 18 layers / 8.5 GB compressed, but a single layer held 7.76 GB of it —
the monolithic `COPY --from=builder /app /app` of the whole venv. BuildKit
compresses and pushes layers concurrently, so that one layer serialized the export
behind a single gzip stream: 562.7s of the amd64 job and 411.8s of the arm64 job,
plus 210.8s / 114.4s pushing.

Split the venv's largest trees (nvidia, torch, vllm, flash_attn, and the ~1 GB
flash_attn_2_cuda .so) into their own layers via `COPY --exclude`, and switch the
image export to zstd.

Measured on the first green build of this branch:

  exporting layers   amd64  562.7s -> 42.2s     arm64  411.8s -> 42.1s
  export + push      amd64    778s -> 100.1s    arm64    528s -> 85.2s
  image size         amd64   8.52  -> 7.04 GB   arm64   7.91  -> 6.64 GB

The size drop is zstd beating gzip on ratio here, and it also confirms the excludes
line up with the per-tree copies — a mismatch would have shipped the data twice and
grown the image. The registry shows 18 zstd + 5 gzip layers, the gzip ones being
base-image layers passed through untouched.

`COPY --exclude` needs Dockerfile syntax >= 1.19, hence the syntax directive. Keep
the excludes in sync with the per-tree copies that follow them. Excluding
`flash_attn` deliberately does not swallow `flash_attn_3`.

zstd is set without `force-compression` so base-image layers are reused as-is
instead of recompressed for nothing. Pulling zstd layers needs containerd >= 1.5 or
Docker >= 23. `push: true` is replaced by `push=true` inside `outputs` because the
two would otherwise register two image exporters and export the image twice. The
`digest` output the Summary step reads comes from the metadata file, so it is
unaffected.

Splitting also lets cluster nodes pull these layers in parallel.
2026-08-06 16:01:26 -07:00
samsjaandGitHub fb31b51e84 fix: disable dynamo on Ulysses all-to-all to prevent FSDP×compile NCCL deadlock (#3195)
When torch.compile is used with Ulysses context parallelism and FSDP,
the all-to-all collectives are traced into the compiled backward graph
while FSDP's reduce-scatter hooks fire eagerly via the autograd engine.
The compiler may reorder the all-to-all backward differently across
ranks, causing rank 0 to wait on reduce_scatter while rank 1 waits on
all_to_all — a classic collective ordering mismatch that deadlocks NCCL
after the 1-hour watchdog timeout (PR #3186, job 1578).

Wrapping _all_to_all_seq_to_head and _all_to_all_head_to_seq with
torch._dynamo.disable forces a graph break around the collectives so
they execute eagerly in the autograd engine, restoring a single
consistent backward ordering between the two collective systems.
2026-08-05 21:43:25 -07:00
samsjaandGitHub 33b7d19cb1 Revert "chore: release v0.8.0 (#3207)" (#3208)
This reverts commit 56a9402953.
2026-08-05 20:53:32 -07:00
samsjaandGitHub 56a9402953 chore: release v0.8.0 (#3207) 2026-08-05 20:42:26 -07:00
0c0b92f99c chore: remove padded vLLM input scrub (#3203)
The scrub from #2506 was a temporary mitigation for NaN logits caused by
stale padded decode inputs poisoning CUDA-graph replay. The root cause is
fixed in the pinned vLLM 0.26.0: the non-contiguous logits bug in the
native Triton top-k/top-p kernel (vllm-project/vllm#42739) is included,
and _preprocess now zeros the padded positions tail natively.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 15:53:27 -07:00
samsjaandGitHub 84ce4d6677 fix: add eval.retrigger_on_resume to re-fire evals at checkpoint step on resume (#3123)
On resume, the orchestrator defaults to assuming a clean exit where all
evals already completed. When a run crashes mid-eval, the user can set
eval.retrigger_on_resume=True to re-trigger interval-aligned evals
at the checkpoint step instead of the next interval boundary.

No changes to EvalSource — the existing first_trigger = not is_resumed
already skips the base eval on resume and just checks step % interval,
so passing resume_step to trigger() is sufficient.
2026-08-05 15:49:32 -07:00
01e959596a feat: auto-resolve parsers for Laguna, gpt-oss, and Trinity (#3201)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 15:06:50 -07:00
HubertandGitHub 738eb5016a fix(nemotron-h): use fla causal_conv1d for packed Mamba conv (#3192)
Both NemotronH Mamba paths built their packed-document metadata with a
`cu_seqlens.tolist()` and a Python loop over documents, once per Mamba
layer. On Super that is 40 host-device syncs per forward (80 with
activation recompute): each one blocks the Python thread until the CUDA
stream drains, so the CPU never runs ahead and, under context
parallelism, every rank re-synchronizes to its slowest CP partner at
every layer instead of absorbing jitter in queue depth.

Replace the per-document conv loop and the hand-built seq_idx with
fla's Triton `causal_conv1d` and `prepare_sequence_ids`, matching the
call shape already used for Qwen3.5 GDN in `trainer/model.py` and
`qwen3_5_moe`. Both fla helpers derive boundaries from `cu_seqlens`
directly and are `@tensor_cache`d by argument identity, so the 40
layers of a forward share one build.

fla is already a required dependency and its Triton backend needs no
arch-specific CUDA compilation, which was the stated reason for
avoiding a fused conv here.
2026-08-04 20:41:49 -07:00
06eb91d7c8 fix: accept seq_lens contract kwargs in GlmMoeDsaModel.forward (#3197)
* fix: accept seq_lens contract kwargs in GlmMoeDsaModel.forward

The fused LM head wrapper forwards seq_lens/seq_lens_are_pre_shard to the
inner model, but only GlmMoeDsaForCausalLM accepted them.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* review: drop inline comment above seq_lens kwargs

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 20:21:03 -07:00
327f378e07 feat!: standalone env servers (#3162)
* feat!: remove env-server sidecaring, launcher spawns at deterministic addresses

The orchestrator never spawns env servers anymore — it always connects to
each source's serve.address and polls until the server is up. Addresses
are assigned deterministically at config validation (tcp://127.0.0.1:5000+
across train then eval sources), so the launcher (local rl + multinode
sbatch template) spawns the servers in parallel with the orchestrator and
both sides agree on where each server lives from the config alone.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: docstring + test tidy

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor!: derive env-server addresses, require address on env-server config

Addresses are wiring, not intent — like the transport blocks, they are no
longer configurable on sources. The orchestrator derives each server's
address from the source's position in the config; the env-server entrypoint
takes a required address the launcher writes per source.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: env-server config mirrors verifiers' serve CLI, per-run base port

EnvServerConfig composes vf's env/serve/legacy blocks verbatim, so an
env-server TOML reads like a vf serve config. orchestrator.env_server_base_port
offsets the derived port range, giving concurrent runs on one host (e.g.
multi-run orchestrators) each their own 1:1 env server.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(configs): multi-env debug config (2 reverse-text train sources + eval)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: rename env server entrypoint to `env` (keep `env-server` alias), env_server_addresses -> env_addresses

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: env/ prefix for env server stop-event keys

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: rename env server naming to env throughout

EnvServerConfig -> configs/env.py:EnvConfig, source-level EnvConfig -> SourceConfig,
entrypoint moves to entrypoints/env.py, env_server_base_port -> env_base_port,
proctitle PRIME-RL::Env

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: trim env entrypoint row

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: drop the verifiers serve CLI, adopt vf.ServeConfig

Bumps deps/verifiers to PrimeIntellect-ai/verifiers#2237 (serve CLI removed,
ServingConfig renamed ServeConfig); prl's source-level ServingConfig follows suit

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: drop the removed serve CLI reference from EnvConfig

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: pin verifiers to main (serve CLI removal merged)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci: slim install imports configs.env

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* revert: keep env-server naming, validate env identity on EnvServerConfig

The env console script shadows coreutils env in activated shells — back to
env-server as the sole entrypoint (still at entrypoints/, orchestrator source
class stays EnvConfig as on main). EnvServerConfig regains the identity
validation the nested source config used to provide (missing env, mixed v0/v1)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(slurm): remove apostrophe from env-server launch comment

The multi-node srun body is one single-quoted bash -c string, so the
apostrophe in "source's" closed it early: every rendered sbatch failed to
parse with a syntax error near unexpected token '(' and the job died before
any component started. Reword the comment and note the constraint.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 16:48:48 -07:00
4aeca13870 chore: scope the jaxtyping lint ignores so F821 runs everywhere else (#3194)
* chore: scope the jaxtyping lint ignores so F821 runs everywhere else

F821 (undefined name) was disabled repo-wide for jaxtyping's shape
strings, so ruff could not report a missing import anywhere in prime-rl —
and style CI runs only ruff. Four modules actually use those annotations;
the ignore now names them.

The fifth file the rule fired on was not jaxtyping: rotary_emb annotated
a config it never imported, so the name resolved to nothing. Imported.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: trim the ignore comment

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 15:50:49 -07:00
minh hoangandGitHub 8ab86036b2 fix(ci): allow branch/commit refs in ghcr image build (#3126)
* fix(ci): allow branch/commit refs in ghcr image build

The `ref` input already advertises "Branch, tag, or commit to build",
but Resolve image vars rejected anything that wasn't main, v*, or *.dev*,
so dispatching a build off a feature branch failed.

Drop the allowlist (the ref is checked out — hence existence-validated —
before this step) and name non-tag builds with `git describe` so a
branch build tags as e.g. v0.7.1.dev55-3-gfea5aadcf-<branch>, carrying
the nearest release + commit distance + short sha and never colliding
with a clean release tag. Exact-tag refs still build under the tag
verbatim, and the commit-<sha> tag is kept since the platform pins it.

* ci: restrict manual image builds to maintain/admin

workflow_dispatch already requires write access, but that includes any
write-level collaborator. Add an authorize job that gates the build on
the dispatcher having maintain or admin (via the collaborator permission
API). Automated in-repo dispatches run as github-actions[bot] and are
allowed so devx_tag dev-image builds and the release build keep working.
prepare now needs authorize, gating the whole build + manifest chain.

* ci: gate only manual dispatches in authorize job

The authorize job ran for every trigger, including on:release. Scope the
permission check to workflow_dispatch (manual builds) so release/other
events pass through. Guard the step (not the job) so a skip still leaves
prepare's `needs: authorize` satisfied.
2026-08-04 12:46:29 -07:00
f0bc8f1fab fix: standalone inference at dp=1 EP (template) + poolside_v1 tool-call regex (#3184)
* fix: port dp=1 EP dense-style launch to standalone inference template

Same bug as #3094, same fix: the multi-node branch of inference.sbatch.j2
still passed external-LB DP args (data_parallel_rank/address) at dp=1
(e.g. tp=8 on 8-GPU nodes), which vLLM >=0.24 rejects with
'data_parallel_external_lb can only be set when data_parallel_size > 1'.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: accept poolside_v1 tool calls without newline after function name

Laguna S 2.1 emits <tool_call>name<arg_key>... with no newline; the
non-streaming func_detail_regex required one, so every tool call failed
detail parsing and leaked verbatim into content (finish_reason=stop).
Upstream vLLM >=0.25 accepts both forms; patch only the regex via the
shared vLLM plugin.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Revert "fix: accept poolside_v1 tool calls without newline after function name"

This reverts commit b054923274aecb39f82671b2f9eae22ef0590fb9.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 09:16:46 -07:00
756f217f22 fix: bump vf + fix lock (#3187)
* fix: relock uv.lock after research-environments bump

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: bump verifiers to 0.2.2.dev76 and rename ServingConfig to ServeConfig

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 18:34:18 -07:00
78cef2844f chore: bump research-environments to latest main (#3185)
Bump the deps/research-environments submodule pin 21a284618 -> f9c43a74 (latest
main), which includes research-environments #744 fixing senior_swe_bench_v1's stale
verifiers.v1.clients.config import (moved to verifiers.v1.configs.client) so
senior-swe-bench-v1 resolves against latest verifiers.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 17:26:39 -07:00
ef42886edc feat(orchestrator): multi-agent native metrics (#3165)
* feat(orchestrator): episode- and agent-level rollout metrics

Adapt to verifiers#2187 (Episode derived aggregates): episode.last_error
rename, submodule bump. Mirror the episode/trace hierarchy in the wandb
layout: count metrics read at the episode level (per-episode sums), and
a new {scope}/{subset}/<agent>/<metric>/<stat> level reports trace-level
metrics per agent, averaging in-episode fan-outs first.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers to vf#2187 head, episode wording cleanups

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(orchestrator): RolloutMetrics -> EpisodeMetrics, AgentMetrics -> TraceMetrics

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(orchestrator)!: trace-level metrics are agent-only, timing generation span renamed agent

Env level now carries only episode-level facts (count sums, pipeline
rates, eval scores); reward, truncation, errors, stop conditions, timing,
custom metrics and solve rates move under {scope}/{subset}/<agent>/.
Adapts to the vf span rename (Timing.agent, AgentSpan, split_agent_time)
and re-pins deps/verifiers. Overview reward/error/truncation panels match
the per-agent keys by regex.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(configs): agentic-judge reverse-text debug config

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(configs): deterministic two-call judge policy for the agentic-judge debug config

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers to vf#2187 head

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers to vf#2187 head (main merged)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers pin

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: re-pin verifiers to the vf#2187 merge commit

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers and research-environments to latest main

verifiers f646beb37 -> f6e420b99 (0.2.2.dev66, 17 commits) and
research-environments 6a2dee6fc -> ccb375ce5 (main + the scicode-v1
pin relax from research-environments#740).

Adaptations to the verifiers changes:
- Episode.error is now Episode.errors + a last_error property (vf#2187)
- verifiers.v1.loaders / verifiers.v1.push moved into
  verifiers.v1.utils.{loaders,platform} (vf#2204)
- verifiers floors bumped to 0.2.2.dev66 (root and prime-rl-configs)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump research-environments to latest main

ccb375ce5 -> 9a57c713c: research-environments#740 refreshed on current
main, picking up the ViRL39K v1 taskset (RE#689) and the taskset prompt
config fixes (RE#742). verifiers main is unchanged since f6e420b99.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers to 0.2.2.dev73 (per-rollout clients)

f6e420b99 -> 576506d66 (7 commits). vf#2218 builds one client per
rollout with a process-wide elastic renderer pool: TrainClientConfig
drops pool_size for a multiplex knob, and the config module moved from
clients.config to configs.client. The orchestrator config follows suit
(pool_size -> multiplex, None = client default). Floors to dev73.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore!: pin research-environments to the scicode merge commit, drop orchestrator.multiplex

deps/research-environments -> 21a284618 (research-environments#740 on
main). The orchestrator-level renderer knob (pool_size, briefly
multiplex) is removed instead of renamed: clients resolve inside env-
server workers, whose concurrency is already bounded per env by
serve.pool.multiplex (default 128, below the client-side renderer
default of 256), so each worker warms one renderer and the elastic pool
grows on demand.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(orchestrator)!: pipeline verdicts and eval scores are per-agent too

is_trainable / is_filtered / filters and avg@k / pass@k all score a
single trace, so they read per agent like every other trace-level
metric instead of pooling an episode's seats.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: drop the agentic-judge debug config from this PR

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: spell out the per-agent metric level in the monitor-run skill

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: eval's overview score is the per-agent avg@k

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(orchestrator): agent-level rates are flat over traces

is_truncated / is_completed rode the per-episode mean path with the
distributions, so an uneven fan-out — what the effective subset leaves
whenever a sibling errors — reweighted them away from the plain
fraction their siblings and the docs promise.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(orchestrator)!: agent-level metrics are flat over traces

One aggregation per level: the episode level sums an episode's traces,
the agent level takes each trace as a sample. Reward, avg@k and the
per-agent counts had been collapsing each episode's fan-out to a mean
first, which left them the odd ones out among the seat's own metrics and
made avg@k's k — a trace count — disagree with what it averaged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 16:04:14 -07:00
ed05a1418d fix: count unscored reward components as zero in rollout metrics (#3182)
* fix(metrics): count unscored reward components as zero

Verifiers now seeds expected reward/metric names with None when scoring
starts, so a scoring failure leaves seeded-unscored entries instead of an
empty dict. CustomMetrics counts unscored rewards as 0.0 (matching the
scalar reward, which sums them as 0) and keeps averaging metrics over the
rollouts that scored them, so all-subset per-key reward means no longer
collapse onto effective when scoring errors occur.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers submodule

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers submodule

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(metrics): count unscored metrics as zero too

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers to main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 15:25:25 -07:00
1ef8f1a843 chore: bump verifiers and research-environments to latest main (#3172)
* chore: bump verifiers and research-environments to latest main

verifiers f646beb37 -> f6e420b99 (0.2.2.dev66, 17 commits) and
research-environments 6a2dee6fc -> ccb375ce5 (main + the scicode-v1
pin relax from research-environments#740).

Adaptations to the verifiers changes:
- Episode.error is now Episode.errors + a last_error property (vf#2187)
- verifiers.v1.loaders / verifiers.v1.push moved into
  verifiers.v1.utils.{loaders,platform} (vf#2204)
- verifiers floors bumped to 0.2.2.dev66 (root and prime-rl-configs)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump research-environments to latest main

ccb375ce5 -> 9a57c713c: research-environments#740 refreshed on current
main, picking up the ViRL39K v1 taskset (RE#689) and the taskset prompt
config fixes (RE#742). verifiers main is unchanged since f6e420b99.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump verifiers to 0.2.2.dev73 (per-rollout clients)

f6e420b99 -> 576506d66 (7 commits). vf#2218 builds one client per
rollout with a process-wide elastic renderer pool: TrainClientConfig
drops pool_size for a multiplex knob, and the config module moved from
clients.config to configs.client. The orchestrator config follows suit
(pool_size -> multiplex, None = client default). Floors to dev73.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore!: pin research-environments to the scicode merge commit, drop orchestrator.multiplex

deps/research-environments -> 21a284618 (research-environments#740 on
main). The orchestrator-level renderer knob (pool_size, briefly
multiplex) is removed instead of renamed: clients resolve inside env-
server workers, whose concurrency is already bounded per env by
serve.pool.multiplex (default 128, below the client-side renderer
default of 256), so each worker warms one renderer and the elastic pool
grows on demand.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(orchestrator): read the agent timing span

vf#2187 renamed Timing.generation to Timing.agent (GenerationSpan ->
AgentSpan); the timing metrics group crashed every RL run's first
to_wandb. Metric keys follow (timing/agent, timing/agent/{model,
harness}). The unit fixture missed it because mk() duck-types Trace;
its namespace now mirrors the real field names.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 13:43:28 -07:00
e229a286f2 fix: checkpoint and resume the orchestrator train data position (#3164)
* fix(orchestrator): checkpoint and resume the train data position

Shuffle each finite env's task table with seed=epoch (1-indexed) so the
permutation is reproducible, snapshot per-env {epoch, cursor} into
Progress.data_positions at checkpoint time, and restore + log the
position on resume.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(orchestrator): track and fast-forward infinite taskset cursors on resume

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(orchestrator): drop old-checkpoint load compat

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(orchestrator): make the data position first-class checkpoint state

TrainSource is a torch Stateful (state_dict/load_state_dict) saved under
its own train_source key next to progress, mirroring the SFT dataloader.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: simplify orchestrator checkpoint table row

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(orchestrator): simplify TrainSource surface

Hardcode the env-choice seed, drop the torch Stateful base (nothing
consumes the protocol), log the restored position from ckpt.load, and
rename _shuffled to _shuffle.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(orchestrator): make the cross-env dispatch sequence reproducible

Advance the env-choice RNG exactly once per dispatched example - a draw
whose permit cost doesn't fit is held (head-of-line) instead of redrawn -
and checkpoint the RNG state and pending draw with the per-env positions.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(orchestrator): save the interval checkpoint on the event loop

state_dict() on a to_thread worker raced the dispatcher mutating
TrainSource; the payload is tiny, so snapshot and write synchronously.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 11:31:56 -07:00
2ffe374e02 fix(trainer): add B300/GB200/GB300 peak FLOPS for MFU (#3168)
B300 device names fell through to the A100 fallback (312 TFLOPS),
inflating reported MFU ~7x. Add dense BF16 peaks per NVIDIA datasheets:
GB200/GB300 superchips at 2.5 PFLOPS, HGX B200/B300 at 2.25 PFLOPS.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-01 21:51:18 +02:00
bbb90a1b41 chore(configs): expand inline TOML tables to sections (#3167)
Every checked-in config, example, and doc snippet now uses [section]
headers instead of key = { ... } inline tables. Purely stylistic: all
48 rewritten TOML files parse identically to their previous versions.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 15:24:35 -07:00
Matej SirovatkaandGitHub 9f0d41e23d chore(inference): bump vLLM to 0.26.0 (#3166) 2026-07-30 21:57:55 +02:00
e0638c7eb6 chore: adapt to the verifiers trace record cleanups (#3157)
* rename training environments to sources

* fix CPU test config fixtures

* rename evaluation environments to sources

* chore(orchestrator)!: rename max_inflight_rollouts to max_inflight_episodes

A dispatcher permit has always bought one episode, not one rollout: for a v1
env one `run` request is one episode (however many agents play it), and a
legacy group-scoring call reserves one permit per bridged v0 rollout, each of
which is its own single-agent episode. Name the knob what it counts.

`max_inflight_rollouts` still parses as an alias, as `rollouts_per_example`
does for `group_size`.

* feat(orchestrator)!: compose the verifiers env, serve and legacy blocks

verifiers split `EnvServerConfig` into three blocks, so an env entry composes
them instead of inheriting one class:

    [[orchestrator.train.source]]
    env    = { taskset = { id = "..." } }   # what runs
    serve  = { pool = { ... }, address, max_concurrent }   # how it's hosted
    legacy = { id, args }                   # a classic v0 env instead

`serve.pool` sizes the spawned server (was `pool`), `serve.address` points at an
external one (was `address`), and `serve.max_concurrent` bounds one worker's
episodes in flight — usually left unset, since `max_inflight_episodes` is the
run's bound. Each moved key raises with a pointer home, including the
`num_workers` shorthand the old validator migrated silently.

BREAKING: `pool` / `address` / `num_workers` on an env entry move under `serve`,
and a v0 env's `id` / `args` / `extra_env_kwargs` move under `legacy`.

TEMPORARY: `deps/verifiers` points at the `feat/one-agent-per-episode` branch
(PrimeIntellect-ai/verifiers#2157) so the two sides can be run together; re-pin
to a merged `main` commit before this lands.

* fix the source-config readers the compose commit missed

The Prime monitor still built its run-registration payload from `env.id`, which
the composed entry doesn't have — `AttributeError` at registration whenever
Prime monitoring is on. It reads `env_id` now, the property that spans both the
v1 and the v0 shape.

The packer's fixture still used the bare `id` shorthand, so its three runs were
rejected at config parse and skipped by `discover_runs`. Full CPU unit suite:
416 passed.

Re-pins `deps/verifiers` to the branch tip of verifiers#2157, which fixes the
same class of stale access on that side (`config.legacy.id`). Still a branch
commit — re-pin to a merged `main` before this lands.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* spell the env annotation out instead of vf.EnvField

verifiers dropped the `EnvField` alias, which was only ever
`SerializeAsAny[EnvConfig]` under a name that collided with `env_field()`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* declare the env default with the factory verifiers exports

`vf.env_field()` is gone: it only wrapped `Field(default_factory=...)`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* inline the legacy helpers, use the config class as the default

Follows verifiers dropping the three `configs/legacy.py` helpers and the
`single_agent_env_config` factory: `is_legacy` and `env_id` are one-liners here,
the mixed-run refusal is spelled out in `validate_env`, and the `env` default is
`vf.SingleAgentEnvConfig()`. `env.max_concurrent` now works as an alias for
`env.max_concurrent_agents`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* drop the serving-key pointers here too

The same call as verifiers a0ebc408: `num_workers` / `pool` / `address` on a source
entry now fail as an ordinary `extra_forbidden` instead of naming their new home.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* bump verifiers: no max_concurrent alias on the env block

`env.max_concurrent` used to bound a served worker's agent runs across episodes, so
accepting it as `max_concurrent_agents` multiplied it by the episodes in flight. It
errors now, like every other moved key. 416 unit tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* bump verifiers to 0.2.2.dev43 (merged main)

deps/verifiers d0bb0ffe5 -> fcb48822e, which is the squash-merge of the composed
env/serve/legacy config blocks (#2157) plus everything else since the last bump:
Harbor 0.20.0 (#2161), runtime-blamed box failures (#2156), standalone MCP clients
pinned to v1 (#2155), and the v1 test/E2E split (#2127).

Lock: harbor 0.14.0 -> 0.20.0, which drops claude-agent-sdk and datasets from its
own deps and adds filelock/platformdirs, so those move with it.

Replaces the temporary branch pin this PR carried.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix: spawn the env server again, and let a pip-only install resolve verifiers

Two CI failures from the compose commit.

The orchestrator stopped spawning env servers. It decides spawn-vs-connect by
`address is None`, and prime-rl's own field defaulted to None; `vf.ServingConfig`
defaults to `tcp://127.0.0.1:5000`, so every env looked external and the run waited
120s for a server nobody started. It now asks whether the address was *pinned*
(`model_fields_set`), so an unset `[serve]` spawns on a free port as before, and
pinning any address — including verifiers' own default — connects.

The slim `prime-rl-configs` wheel is installed from /tmp with no workspace context,
so `verifiers` resolves from PyPI, where `>=0.2.1` picks stable 0.2.1 — no
`SingleAgentEnvConfig`. Floor is `>=0.2.2.dev43` now, a pre-release specifier so the
dev release is eligible.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore: adapt to the verifiers trace record cleanups

Companion to PrimeIntellect-ai/verifiers#2172: record_* mutators, required
agent seat and RunInfo.id, last_error, and agent.name/.trainable reads.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: re-pin verifiers to merged main (f646beb37)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 10:34:53 -07:00
halleriteandGitHub 0b583306eb feat(orchestrator): hierarchical GRPO for proposer-solver envs (#3138) 2026-07-30 15:31:13 +02:00
halleriteandGitHub d612e23c1d chore(configs)!: remove every config shim (#3156) 2026-07-30 01:50:01 +02:00
halleriteandGitHub d135ed4c90 feat(orchestrator)!: rename env collections to sources, compose the verifiers config blocks (#3150) 2026-07-30 01:41:54 +02:00
1fd2d732c2 fix: read overview quality metrics from effective subset (#3159)
* fix: read overview quality metrics from effective subset

The all subset counts errored rollouts as zeros for num_branches,
num_turns, num_total_tokens, and is_truncated, which skews the
distributions and makes the panels uninterpretable. Point the wandb
overview panels and the eval success line at the effective subset;
has_error stays on all since effective drops errors by construction.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: reword zero-skew rationale, drop subset guidance from skill

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-29 16:36:13 -07:00
6a9969e61a chore: bump renderers to 0.1.9.dev9 (#3158)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-29 16:06:49 -07:00
1385e0722c fix: compute trainable rate over effective rollouts (#3152)
* fix(orchestrator): compute trainable rate over effective rollouts

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore: drop comment

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-07-28 23:52:21 -07:00
e2ad3beaaa feat(monitor): effective reward/score in wandb overview (#3153)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 23:40:39 -07:00
9551e20fa8 chore: single global router in front of engines for all deployments (#3105)
* chore: single global router in front of engines for all deployments

Every deployment shape now runs one client-facing router on server.port
with engines behind it on backend_port: local single-node runs spawn a
vllm-router in the inference entrypoint, and the SLURM templates collapse
per-replica routers into a single global router on inference node 0.
router/backend_port move to InferenceConfig top level; router = "None"
runs a bare engine (used for per-rank SLURM engine processes).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: finish single-node router integration

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-07-29 05:17:43 +02:00
6df90dc0aa feat: default rollout transport to zmq and inject host for multi-node (#3149)
* feat(config): shared [rollout_transport] propagated to trainer + orchestrator

Add rollout_transport as a shared RLConfig field (mirroring weight_broadcast /
ckpt / wandb), propagated to trainer.rollout_transport and
orchestrator.rollout_transport via propagate_shared_fields. A single
[rollout_transport] block configures both sub-configs.

auto_setup_rollout_transport (like auto_setup_weight_broadcast) resolves the
shared field from the sub-configs so the launcher's ZMQ host-injection gate is
correct whether transport is set via the shared block or directly on
trainer/orchestrator.rollout_transport (the documented fallback), and rejects
mismatched sub-config transports.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(launcher): inject rollout_transport.host for multi-node zmq transport

ZMQ rollout transport binds/connects a single rollout_transport.host (default
localhost). On multi-node trainer deployments the training-batch PUSH/PULL and
micro-batch PUB/SUB span nodes, so data ranks on non-head nodes connect to their
own localhost and hang at step 0. The launcher already injects
weight_broadcast.host=$MASTER_ADDR for nccl but had no equivalent for
rollout_transport.

When config.rollout_transport resolves to zmq, inject --rollout_transport.host
$MASTER_ADDR into the trainer torchrun and the orchestrator (mirrors the existing
weight_broadcast.host injection). Filesystem transport is unaffected.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(config): default rollout transport to zmq

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-29 04:43:50 +02:00
8372c37a15 fix: plot overview time panels on relative wall time (#3148)
* fix(monitor): plot overview time panels on relative wall time

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore: drop view_signature docstring

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-07-28 15:21:05 -07:00
15f5355f5f chore: bump verifiers + research-environments to latest main (#3147)
- deps/verifiers -> d0bb0ffe5 (network-policy alignment #2124, Codex MCP tools
  #2140, Ruff 0.16 / ty tooling, and everything since the last bump)
- deps/research-environments -> 6a2dee6fc (judges/swe agentic-judge setups #720,
  MMMU-Pro / CharXiv tasksets, wideseek verifiers-pin fix #731)
- uv.lock relocked (adds charxiv-v1, mmmu-pro-v1; bfcl-v3-v1 0.2.0 -> 0.3.0)

No code changes needed: the runtime-on-agent config addressing and Reward-record
metrics landed with the earlier bump (#3137).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 12:50:01 -07:00
JannikStandGitHub d1bfcbc636 chore(ci): enable nightly FFT cron (#3142) 2026-07-28 13:06:46 +02:00
f50ec5c4c8 feat(orchestrator): RAE — role-conditioned advantage estimation for self-play envs (SPIRAL) (#3136)
* feat(orchestrator): RAE — SPIRAL's role-conditioned advantage estimation for self-play envs

Add the `rae` algorithm (SPIRAL, arXiv:2506.24119): each trainable agent
keeps an EMA baseline of its own rewards, and every trace's advantage is
its reward minus its agent's pre-update baseline. Group-relative baselines
mis-credit multi-agent self-play — in a zero-sum game the group mean is ~0
whatever the policy does, and centering both agents against it turns any
structural asymmetry (first-mover edge) into permanent credit. Baselines
are keyed per (env, agent) — the paper's per (game, role) — and any
group_size works, including 1.

configs/debug/algo/rae.toml runs shared-policy Kuhn poker self-play
(kuhn-poker-v1, both agents late-bound to the run's model).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(tests): drop RAE unit tests

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-27 19:34:50 +02:00
9b944591c4 chore: bump verifiers to latest main; adopt runtime-on-agent, Reward records, textarena player (#3137)
* chore: bump verifiers to latest main; adopt runtime-on-agent, Reward records, textarena player

deps/verifiers b13ba60da → 295a06505 (+12: interleaving agents + kuhn-poker-v1,
runtime moves from the harness onto the agent (#2106), trace rewards become
Reward{score, weight} records (#2119), wordle-v1 rides the rewritten
TextArenaEnv, pluggable harness skills, agentic-judge grading knobs).

Adoption:
- every `env.<agent>.harness = { ..., runtime = ... }` config line splits into
  `harness = { ... }` + `env.<agent>.runtime = ...` (configs/, examples/, docs/,
  skills/)
- wordle configs address the textarena seat as `env.player`
- reward metrics read the weighted `Reward.value` (CustomMetrics gains a value
  extractor); unit-test trace builders record `vf.Reward(score=...)`
- uv.lock re-locked for verifiers 0.2.2.dev29

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(tests): adopt Reward records in prime-monitor rollout builder

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-27 18:26:18 +02:00
JannikStandGitHub 3b22dd951c fix(nightly-fft): restore auto-resolve latest v*.dev* when no image_tag input (#3134)
* fix(nightly-fft): restore auto-resolve latest v*.dev* when no image_tag input

The nightly's whole point is to catch regressions on tip-of-main, so a
plain 'gh workflow run "Nightly FFT"' must dispatch against the newest
built v*.dev* by default. #3133 removed that fallback and made no-input
dispatches emit an empty tag, which falls through to the platform's
default 'main' alias — currently baked ~50 commits stale — so the run
crashes on validation.

Restores the original behavior: no input → auto-resolve latest dev.
Explicit image_tag input still overrides (from #3132). Dispatch step
always passes --image-tag since the tag is always populated now.

* fix(ci): guard dev-tag resolver against pipefail

GitHub Actions runs the shell under `bash -eo pipefail` by default.
Two failure modes:
- `grep -E ...` returns 1 when no v*.dev* tags exist yet
- `head -n 10` closes the pipe after 10 lines, SIGPIPE-ing `sort`

Either aborts the step before the explicit no-candidates guard runs.
Wrap the pipeline in set +o pipefail / set -o pipefail.
2026-07-24 10:10:26 +02:00
JannikStandGitHub 13770289ef fix(nightly-fft): don't force --image-tag when no dispatch input (#3133)
* fix(nightly-fft): pin image_tag to commit-c505e07a1 in each config

The default 'main' image the platform validator ships is baked ~50
commits behind tip and predates cb74ae2be (which added the env.
wrapper on train.env entries). It rejects env.taskset with
'train.env[0].env — Extra inputs are not permitted' and doesn't know
the 'prime-qwen3' renderer name, so every nightly orchestrator
crash-loops on validation.

- Pin top-level image_tag = 'commit-c505e07a1' in each nightly-fft
  toml. c505e07a1 is post-cb74ae2be and accepts the current v1 shape.
- Workflow: when no dispatch input is set, emit an empty tag and skip
  --image-tag on prime train so the toml pin wins. Explicit
  workflow_dispatch image_tag still overrides.
- Drop this pin once v0.7.1+ (with the v1 schema) is released and the
  backend default resolves to it.

* revert: drop image_tag pin from nightly-fft configs

Keep the workflow change (only pass --image-tag when explicit input);
rely on prime-cli's built-in fallback: --image-tag > toml image_tag >
backend default. No commit-hash pin baked into the checked-in configs.
2026-07-24 06:59:43 +02:00
338 changed files with 25359 additions and 16463 deletions
+1
View File
@@ -0,0 +1 @@
../skills
+11
View File
@@ -0,0 +1,11 @@
# .git stays: docker-editable-pretend-versions.sh reads .git/modules via the bind mount.
outputs
**/.venv
**/__pycache__
**/*.py[cod]
**/.pytest_cache
**/.ruff_cache
**/.mypy_cache
.claude
.vscode
*.ipynb
+5 -5
View File
@@ -146,7 +146,7 @@ jobs:
id: artifact
run: echo "name=benchmark-${{ matrix.runner }}-$(echo '${{ matrix.model }}' | sed 's/\//--/')-${{ matrix.type }}-${{ matrix.lora_rank || 'full' }}-${{ matrix.num_gpus }}gpu-${{ matrix.ac }}-${{ matrix.attention }}-${{ matrix.seq_len }}-cp${{ matrix.cp }}-ep${{ matrix.ep }}" >> "$GITHUB_OUTPUT"
- name: Upload benchmark result
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v7
if: always()
with:
name: ${{ steps.artifact.outputs.name }}
@@ -163,16 +163,16 @@ jobs:
pull-requests: write
steps:
- name: Checkout repository # We can't use the image because then no git
uses: actions/checkout@v5
uses: actions/checkout@v7
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync
run: uv sync --all-extras
- name: Download all benchmark artifacts
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
path: /tmp/benchmark_artifacts
pattern: benchmark-*
+69 -18
View File
@@ -34,8 +34,42 @@ concurrency:
cancel-in-progress: false
jobs:
authorize:
name: Authorize dispatcher
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Require maintain or admin
# Gate MANUAL dispatches only; other events (e.g. release) are
# already privileged and pass through. Guard the step, not the job —
# a skipped job would skip `prepare` via `needs: authorize`.
if: github.event_name == 'workflow_dispatch'
env:
GH_TOKEN: ${{ github.token }}
ACTOR: ${{ github.triggering_actor }}
REPO: ${{ github.repository }}
run: |
# Restricted to repo members with maintain or admin. Automated
# in-repo dispatches (devx_tag dev-image builds, the release build)
# run as github-actions[bot] via GITHUB_TOKEN — allow those through.
if [ "$ACTOR" = "github-actions[bot]" ]; then
echo "Dispatcher is repo automation ($ACTOR); allowed."
exit 0
fi
role=$(gh api "repos/${REPO}/collaborators/${ACTOR}/permission" --jq '.role_name' 2>/dev/null || true)
echo "Dispatcher $ACTOR has repo role: ${role:-<none>}"
case "$role" in
admin|maintain)
echo "Authorized." ;;
*)
echo "::error::$ACTOR (role: ${role:-none}) is not allowed to trigger image builds; requires maintain or admin." >&2
exit 1 ;;
esac
prepare:
name: Prepare build
needs: authorize
runs-on: ubuntu-latest
permissions:
contents: read
@@ -69,7 +103,7 @@ jobs:
esac
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
ref: ${{ env.BUILD_REF }}
fetch-depth: 0
@@ -81,27 +115,30 @@ jobs:
INPUT_TAG: ${{ env.BUILD_TAG }}
PLATFORMS: ${{ env.BUILD_PLATFORMS }}
run: |
case "$INPUT_REF" in
main|v[0-9]*|*.dev[0-9]*) ;;
*)
echo "ref '${INPUT_REF}' not allowed for ghcr publish (must be main, v*, or *.dev*)" >&2
exit 1
;;
esac
if [ -n "$INPUT_TAG" ] && [ "$INPUT_TAG" != "$INPUT_REF" ] && [ "$INPUT_REF" != "main" ]; then
echo "custom 'tag' that differs from 'ref' is only allowed when ref=main; got ref='${INPUT_REF}' tag='${INPUT_TAG}'" >&2
exit 1
fi
raw_tag="$INPUT_TAG"
if [ -z "$raw_tag" ]; then
raw_tag="$INPUT_REF"
sanitize() {
echo "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//' | cut -c1-50
}
# A ref that is exactly a git tag builds under that tag verbatim;
# any other ref (branch / arbitrary commit) is prefixed with
# `git describe` so the tag carries the nearest release, commit
# distance and short sha (e.g. v0.7.0-42-g1a2b3c4d5-fix-my-branch)
# and can't collide with a clean release tag.
if [ -n "$INPUT_TAG" ]; then
tag=$(sanitize "$INPUT_TAG")
elif tag=$(git describe --tags --exact-match 2>/dev/null); then
:
else
tag="$(git describe --tags --always)-$(sanitize "$INPUT_REF")"
fi
tag=$(echo "$raw_tag" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | cut -c1-50 | sed 's/^-//;s/-$//')
if [ -z "$tag" ]; then
echo "Could not derive a valid image tag from '${raw_tag}'." >&2
echo "Could not derive a valid image tag from ref='${INPUT_REF}' tag='${INPUT_TAG}'." >&2
exit 1
fi
@@ -124,10 +161,16 @@ jobs:
steps:
- name: Remove unnecessary packages
run: |
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
# Deleting the preinstalled toolchains costs ~70s; skip unless disk is tight.
avail_gb=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
if [ "${avail_gb:-0}" -lt 80 ]; then
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
else
echo "Skipping cleanup: ${avail_gb}G available on /"
fi
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
ref: ${{ needs.prepare.outputs.ref }}
fetch-depth: 0
@@ -137,7 +180,7 @@ jobs:
run: |
if [ -f .gitmodules ]; then
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/pydantic-config deps/verifiers deps/renderers deps/research-environments
git submodule update --init --recursive -- deps/pydantic-config deps/verifiers deps/renderers deps/prime-envs
fi
- name: Log in to GitHub Container Registry
@@ -156,7 +199,15 @@ jobs:
with:
context: .
file: ./Dockerfile.cuda
push: true
# zstd compresses the multi-GB venv layers several times faster than gzip at a
# comparable ratio. No `force-compression`, so base-image layers are reused as-is
# rather than needlessly recompressed. Pulling zstd layers needs containerd >= 1.5
# or Docker >= 23.
outputs: type=image,push=true,compression=zstd,compression-level=3
# The per-job builder is ephemeral; mode=max caches builder-stage
# layers so warm builds skip the dependency sync.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
+155
View File
@@ -0,0 +1,155 @@
name: Build Kernels
# Builds the `prime-kernels` wheel for x86_64 and aarch64 from the deps/prime-kernels submodule.
# Runs on every bump of that submodule to catch build breakage, and with `release_tag` to
# attach the wheels to a GitHub release — which is how they are consumed (see the `kernels`
# skill).
#
# `tag-and-release.yaml` calls this for every release, before it promotes the draft, so a
# published release always carries the wheels its `[tool.uv.sources]` pin can point at.
# `workflow_dispatch` does the same by hand, for backfilling an already published release.
#
# No GPU is needed: nvcc cross compiles for the architectures kernels.toml declares.
on:
pull_request:
paths:
- "deps/prime-kernels"
- ".gitmodules"
- ".github/workflows/build_kernels.yaml"
push:
branches: [main]
paths:
- "deps/prime-kernels"
- ".gitmodules"
- ".github/workflows/build_kernels.yaml"
workflow_dispatch:
inputs:
release_tag:
description: "Existing release tag to attach the wheels to (e.g. v0.7.0). Empty = artifacts only."
required: false
type: string
ref:
description: "Ref to build the kernels from. Empty = the ref the workflow was started on."
required: false
type: string
workflow_call:
inputs:
release_tag:
description: "Release tag to attach the wheels to. The release may still be a draft."
required: false
type: string
ref:
description: "Ref to build the kernels from. Empty = the caller's ref."
required: false
type: string
env:
# Keep in sync with the CUDA the prime-rl image is built against (Dockerfile.cuda);
# the job container image below must be edited alongside it (no env context there).
CUDA_TAG: cu128
jobs:
build:
name: Build wheel (${{ matrix.arch }})
# Uploading the wheels to a release needs write; on workflow_call the caller
# must grant it too (tag-and-release.yaml does).
permissions:
contents: write
strategy:
fail-fast: false
matrix:
include:
- runner: image-builder
arch: x86_64
- runner: image-builder-arm-2204
arch: aarch64
runs-on: ${{ matrix.runner }}
container: nvidia/cuda:12.8.1-devel-ubuntu24.04
steps:
- name: Install build tooling
run: |
apt-get update
apt-get install -y --no-install-recommends git curl ca-certificates build-essential gh
- name: Checkout
uses: actions/checkout@v5
with:
submodules: false
ref: ${{ inputs.ref }}
# deps/prime-kernels is the prime-kernels submodule and carries every kernel's sources.
- name: Init the kernels submodule
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
git submodule update --init -- deps/prime-kernels
- name: Install uv
run: |
curl -LsSf https://astral.sh/uv/install.sh | env INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR=/usr/local/bin sh
uv --version
# The wheel only imports under the exact torch it was compiled against, so build
# against the torch prime-rl resolves rather than whatever is newest today.
- name: Create build environment
env:
UV_TORCH_BACKEND: ${{ env.CUDA_TAG }}
run: |
TORCH_PIN=$(grep -A1 '^name = "torch"$' uv.lock | sed -n 's/^version = "\([^"+]*\).*"$/\1/p' | head -n1)
if [ -z "$TORCH_PIN" ]; then
echo "Could not read torch's version from uv.lock" >&2
exit 1
fi
echo "Building against torch==$TORCH_PIN"
uv venv --python 3.12 /tmp/build-env
VIRTUAL_ENV=/tmp/build-env uv pip install "torch==$TORCH_PIN" setuptools wheel ninja
# torch C++ extensions are bound to the torch and CUDA they were compiled against, so
# the wheel carries both in its local version.
- name: Stamp ABI into the version
run: |
TORCH_VERSION=$(/tmp/build-env/bin/python -c 'import torch; print(torch.__version__.split("+")[0])')
LOCAL="${CUDA_TAG}torch${TORCH_VERSION}"
sed -i -E "s/^version = \"([^\"]+)\"$/version = \"\1+${LOCAL}\"/" deps/prime-kernels/pyproject.toml
grep '^version' deps/prime-kernels/pyproject.toml
- name: Build wheel
env:
VIRTUAL_ENV: /tmp/build-env
CUDA_HOME: /usr/local/cuda
PRIME_KERNELS_REQUIRE: "1"
MAX_JOBS: "8"
run: uv build --wheel --no-build-isolation --out-dir dist deps/prime-kernels
- name: Inspect wheel
run: |
ls -lh dist/
/tmp/build-env/bin/python - <<'PY'
import pathlib, zipfile
wheel = next(pathlib.Path("dist").glob("*.whl"))
extensions = [n for n in zipfile.ZipFile(wheel).namelist() if n.endswith(".so")]
assert extensions, f"{wheel.name} contains no compiled kernels"
print(wheel.name, *extensions, sep="\n ")
PY
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: prime-kernels-${{ matrix.arch }}
path: dist/*.whl
if-no-files-found: error
- name: Attach to release
if: inputs.release_tag != ''
env:
GH_TOKEN: ${{ github.token }}
# gh must not resolve the repo from the checkout: inside the container the
# workspace is owned by another uid, which git rejects as dubious ownership.
GH_REPO: ${{ github.repository }}
TAG: ${{ inputs.release_tag }}
run: |
gh release upload "$TAG" dist/*.whl --clobber
# The `[tool.uv.sources]` pin has to name the wheel exactly, ABI suffix and all.
WHEEL=$(basename dist/*.whl)
URL="https://github.com/${GITHUB_REPOSITORY}/releases/download/${TAG}/${WHEEL}"
echo "\`{ url = \"$URL\", marker = \"platform_machine == '${{ matrix.arch }}'\" },\`" >> "$GITHUB_STEP_SUMMARY"
+6 -6
View File
@@ -12,20 +12,20 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --extra flash-attn --all-packages --locked
run: uv sync --all-extras --all-packages --locked
- name: Run tests
env:
USERNAME_CI: CI_RUNNER
@@ -48,9 +48,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Create next .dev tag from latest release
uses: actions/github-script@v8
uses: actions/github-script@v9
with:
script: |
const { owner, repo } = context.repo;
+7 -10
View File
@@ -26,15 +26,15 @@ jobs:
apt-get install -y git
git config --global --add safe.directory "$GITHUB_WORKSPACE"
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run unit tests
@@ -84,9 +84,6 @@ jobs:
- test: reverse_text_moe
runner: vm
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: reverse_text_multi_run
runner: 4xa6000
pytest_args: "tests/integration/test_reverse_text_multi_run.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py"
@@ -97,15 +94,15 @@ jobs:
apt-get install -y git
git config --global --add safe.directory "$GITHUB_WORKSPACE"
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run integration tests
@@ -123,7 +120,7 @@ jobs:
run: uv run pytest -vvs ${{ matrix.pytest_args }}
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: ${{ matrix.test }}-logs
path: /tmp/outputs/**/*.log
+19 -11
View File
@@ -13,9 +13,9 @@ on:
required: false
default: ""
# Scheduled run at 3AM PST (11AM UTC) — disabled for now, enable once dry-run passes
# schedule:
# - cron: "0 11 * * *"
# Scheduled run at 3AM PST (11AM UTC)
schedule:
- cron: "0 11 * * *"
permissions:
contents: read
@@ -31,7 +31,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
@@ -70,7 +70,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
@@ -113,16 +113,24 @@ jobs:
exit 0
fi
# The GHCR versions API can list a tag before its manifest is
# actually pullable (build in-flight, or manifest step didn't
# finish). So: pull the top N candidate tags, then verify each
# with a manifest HEAD via the anonymous registry token flow;
# take the newest one that resolves.
# No dispatch input: auto-resolve the newest v*.dev* tag on
# GHCR (the point of a nightly is to catch regressions on
# tip-of-main). The GHCR versions API can list a tag before
# its manifest is actually pullable (build in-flight, or
# manifest step didn't finish), so pull the top N candidates
# and verify each with a manifest HEAD via the anonymous
# registry token flow; take the newest one that resolves.
# Disable pipefail locally: `grep` may exit 1 on no matches
# (empty tag list) and `head` may SIGPIPE `sort` after
# reading its 10 lines. Both would abort the step before the
# explicit no-candidates guard below runs.
set +o pipefail
candidates=$(gh api --paginate \
"/orgs/primeintellect-ai/packages/container/prime-rl/versions" \
--jq '.[].metadata.container.tags[]' \
| grep -E '^v[0-9]+\.[0-9]+\.[0-9]+\.dev[0-9]+$' \
| sort -Vru | head -n 10)
set -o pipefail
if [ -z "$candidates" ]; then
echo "No v*.dev* tag listed on GHCR." >&2
exit 1
@@ -151,7 +159,7 @@ jobs:
echo "tag=$tag" >> "$GITHUB_OUTPUT"
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
- name: Install prime CLI (latest)
run: uv tool install prime
+4 -4
View File
@@ -23,7 +23,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
@@ -73,15 +73,15 @@ jobs:
apt-get install -y git
git config --global --add safe.directory "$GITHUB_WORKSPACE"
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
+3 -3
View File
@@ -15,17 +15,17 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
# Submodules are excluded from ruff via pyproject.toml; no need to fetch them.
with:
submodules: false
- name: Run ruff
uses: astral-sh/ruff-action@v4.1.0
with:
version: "0.13.0"
version: "0.15.14"
args: "check --config=pyproject.toml"
- name: Run ruff format (check)
uses: astral-sh/ruff-action@v4.1.0
with:
version: "0.13.0"
version: "0.15.14"
args: "format --check --config=pyproject.toml"
+1 -1
View File
@@ -10,7 +10,7 @@ jobs:
trigger-docs-sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v7
- name: Validate mint.json pages exist
run: |
+40 -11
View File
@@ -29,7 +29,7 @@ jobs:
version: ${{ steps.tag.outputs.version }}
steps:
- name: Checkout main
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
fetch-depth: 0
@@ -113,9 +113,22 @@ jobs:
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
release-from-auto-tag:
# Wheels are attached while the release is still a draft, so it is never published without
# them — `[tool.uv.sources]` pins prime-kernels at a release asset, and an install that
# resolves to a wheel-less release would fall back to compiling CUDA from source.
kernels-from-auto-tag:
needs: auto-tag-on-main
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
permissions:
contents: write
uses: ./.github/workflows/build_kernels.yaml
with:
release_tag: ${{ needs.auto-tag-on-main.outputs.tag }}
ref: ${{ needs.auto-tag-on-main.outputs.tag }}
release-from-auto-tag:
needs: [auto-tag-on-main, kernels-from-auto-tag]
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
runs-on: ubuntu-latest
permissions:
contents: write
@@ -138,24 +151,23 @@ jobs:
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
tag-and-release:
resolve-release:
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
outputs:
tag: ${{ steps.release.outputs.tag }}
version: ${{ steps.release.outputs.version }}
steps:
- name: Checkout tagged release (dispatch)
if: github.event_name == 'workflow_dispatch'
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
fetch-depth: 0
ref: refs/tags/${{ inputs.tag }}
- name: Checkout tagged release (push)
if: github.event_name != 'workflow_dispatch'
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
fetch-depth: 0
@@ -207,11 +219,28 @@ jobs:
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
kernels-from-tag:
needs: resolve-release
permissions:
contents: write
uses: ./.github/workflows/build_kernels.yaml
with:
release_tag: ${{ needs.resolve-release.outputs.tag }}
ref: ${{ needs.resolve-release.outputs.tag }}
publish-release:
needs: [resolve-release, kernels-from-tag]
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
steps:
- name: Publish draft release
id: publish
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
TAG: ${{ needs.resolve-release.outputs.tag }}
run: |
STATE=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft --jq '.isDraft' 2>/dev/null || echo "missing")
if [ "$STATE" = "missing" ]; then
@@ -232,6 +261,6 @@ jobs:
if: steps.publish.outputs.published == 'true'
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
TAG: ${{ needs.resolve-release.outputs.tag }}
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
+3 -18
View File
@@ -1,26 +1,13 @@
.vscode/*
.claude/scheduled_tasks.lock
.claude/worktrees/
.codex/
*.ipynb
*.jsonl
configs/endpoints.py
# Artifacts
**/slurm
!src/prime_rl/slurm
!examples/slurm
!docs/slurm.md
**/torchrun
**/weights
**/checkpoints
**/broadcasts
**/rollouts
**/logs
**/wandb
**/evals
**/run_*/
!configs/**/evals
final_summary.json
# Run artifacts
outputs/
.pydantic_config
.chroma_db
deps/nixl_*
@@ -201,6 +188,4 @@ cython_debug/
debug_I2_zero_band
.idea
outputs/
third_party/
+6 -3
View File
@@ -4,9 +4,12 @@
[submodule "renderers"]
path = deps/renderers
url = git@github.com:PrimeIntellect-ai/renderers.git
[submodule "research-environments"]
path = deps/research-environments
url = git@github.com:PrimeIntellect-ai/research-environments.git
[submodule "prime-envs"]
path = deps/prime-envs
url = git@github.com:PrimeIntellect-ai/prime-envs.git
[submodule "pydantic-config"]
path = deps/pydantic-config
url = https://github.com/PrimeIntellect-ai/pydantic-config
[submodule "prime-kernels"]
path = deps/prime-kernels
url = https://github.com/PrimeIntellect-ai/prime-kernels
+49 -10
View File
@@ -1,5 +1,19 @@
# syntax=docker/dockerfile:1
# ^ `COPY --exclude` (used to split the venv into parallel-compressible layers) needs
# Dockerfile syntax >= 1.19; `docker/dockerfile:1` resolves to the latest stable 1.x.
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
# Every pyproject.toml + uv.lock, so the dependency sync below caches
# independently of source edits.
FROM nvidia/cuda:12.8.1-base-ubuntu24.04 AS manifests
# .git is ~735 MB, changes every commit, and would land in the registry cache.
COPY --exclude=.git . /ctx
RUN mkdir -p /manifests \
&& cd /ctx \
&& find . -name .git -prune -o -type f -name pyproject.toml -exec cp --parents {} /manifests/ \; \
&& cp uv.lock /manifests/
# Build stage - multi-arch base (supports amd64 + arm64)
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 AS builder
LABEL maintainer="prime intellect"
@@ -72,11 +86,23 @@ ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
# the runtime stage's `COPY /app`
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
# Install Python dependencies (The gradual copies help with caching)
# Install Python dependencies
WORKDIR /app
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# Third-party deps only — source edits don't bust this layer. First-party
# editables install in the source-layer sync below. No build-context bind
# mount here: .git would bust the cache every commit.
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
--no-install-package renderers \
--no-install-package prime-pydantic-config
COPY pyproject.toml /app/pyproject.toml
COPY uv.lock /app/uv.lock
COPY README.md /app/README.md
@@ -94,7 +120,7 @@ COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pr
# /app/.git/modules to the read-only context before resolving versions.
ARG VERIFIERS_PRETEND_VERSION
ARG RENDERERS_PRETEND_VERSION
RUN --mount=type=cache,target=/app/.cache/uv \
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
--mount=type=bind,source=.,target=/build-context,readonly \
if [ -d /build-context/.git/modules ]; then mkdir -p /app/.git && ln -s /build-context/.git/modules /app/.git/modules; fi \
&& \
@@ -106,7 +132,7 @@ RUN --mount=type=cache,target=/app/.cache/uv \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
@@ -128,11 +154,6 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
&& rm -rf /tmp/nixl /app/deps/nixl_cu12-*.whl; \
fi
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
ARG TARGETARCH
COPY scripts/docker-arm64-post-install.sh /app/scripts/docker-arm64-post-install.sh
RUN if [ "$TARGETARCH" = "arm64" ]; then /app/scripts/docker-arm64-post-install.sh; fi
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
# COPY ships only the trimmed result (~1.5 GB) instead of the full ~6.6 GB. Drops the math
# runtime libs (cublas/cusparse/cufft/cusolver/curand/npp/nvjpeg) and big static .a
@@ -217,14 +238,32 @@ RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.
USER appuser
ENV PATH="/usr/local/bin:$PATH"
WORKDIR /app
# Copy the application from the builder
COPY --from=builder --chown=appuser:appuser /app /app
# Copy the application from the builder, splitting the venv's largest trees into their
# own layers. BuildKit compresses and pushes layers in parallel, so shipping the whole
# ~20 GB venv as one layer serialized the export behind a single compressor. Splitting
# also lets nodes pull the image in parallel. Keep the excludes below in sync with the
# per-tree copies above, or the data lands in the image twice.
# The volatile /app remainder goes last so a source edit re-pushes one layer,
# not all of them.
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/nvidia /app/.venv/lib/python3.12/site-packages/nvidia
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/torch /app/.venv/lib/python3.12/site-packages/torch
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/vllm /app/.venv/lib/python3.12/site-packages/vllm
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn /app/.venv/lib/python3.12/site-packages/flash_attn
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so /app/.venv/lib/python3.12/site-packages/
COPY --from=builder /opt/ucx /opt/ucx
# Copy and set up entrypoint script
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
RUN chmod +x /app/docker-entrypoint.sh
COPY --from=builder --chown=appuser:appuser \
--exclude=.venv/lib/python3.12/site-packages/nvidia \
--exclude=.venv/lib/python3.12/site-packages/torch \
--exclude=.venv/lib/python3.12/site-packages/vllm \
--exclude=.venv/lib/python3.12/site-packages/flash_attn \
--exclude=.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so \
/app /app
# Place executables in the environment at the front of the path
ENV PATH="/app/.venv/bin:$PATH"
ENV UCX_HOME=/opt/ucx
+3 -12
View File
@@ -95,7 +95,7 @@ cd prime-rl
2. Initialize submodules
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
```
3. Install [uv](https://docs.astral.sh/uv/)
@@ -113,15 +113,6 @@ uv sync --all-extras
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
4.1. On aarch64 hosts: build flash-attn from source for your GPU
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`.
```bash
bash scripts/docker-arm64-post-install.sh
```
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
@@ -166,7 +157,7 @@ uv run trainer @ configs/debug/fake/rl.toml
5. Check that you can run the inference server (*this requires 1 GPU*)
```bash
uv run inference --model.name Qwen/Qwen3-0.6B
uv run inference --vllm.model Qwen/Qwen3-0.6B
```
6. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
@@ -227,7 +218,7 @@ Check out the [docs](docs) directory for in-depth guides on how to use prime-rl.
- [**Training**](docs/training.md) - RL, SFT, evals, checkpointing, observability, rules of thumb
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA, multi-tenant training
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA
- [**Development**](docs/development.md) - Test suite, pre-commit hooks, adding a new model
## Contributing
+113
View File
@@ -0,0 +1,113 @@
#!/usr/bin/env python3
"""
Time the routed-expert compute three ways: the fused MoE kernel (bf16 and mxfp8) against
the grouped-mm path a `model.moe_fused_kernel=false` run takes.
Forward and backward are timed separately, because only the forward is a kernel — the
backward is prime-rl's own closed-form bf16 gradients or, for mxfp8, autograd through the
grouped-mm reference. A speedup on the forward can be spent again on the backward.
uv run benchmarks/scripts/bench_fused_moe.py
uv run benchmarks/scripts/bench_fused_moe.py --tokens 16384 --num-experts 128
"""
from __future__ import annotations
import argparse
import torch
from prime_rl.trainer.models.layers.moe import _FusedMoE, _load_fused_moe_kernel, _run_experts_fused_reference
MODES = ("grouped_mm", "fused_bf16", "fused_mxfp8")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--tokens", type=int, default=8192, help="routed tokens (batch * seq)")
parser.add_argument("--dim", type=int, default=2048, help="model dim; must be a multiple of 256")
parser.add_argument("--hidden-dim", type=int, default=768, help="expert intermediate size; multiple of 128")
parser.add_argument("--num-experts", type=int, default=64)
parser.add_argument("--top-k", type=int, default=8)
parser.add_argument("--iters", type=int, default=20)
parser.add_argument("--warmup", type=int, default=5)
return parser.parse_args()
def make_inputs(args: argparse.Namespace) -> tuple[torch.Tensor, ...]:
torch.manual_seed(0)
randn = lambda *shape: torch.randn(*shape, device="cuda", dtype=torch.bfloat16)
x = (randn(args.tokens, args.dim) * 0.2).requires_grad_(True)
w1 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
w3 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
w2 = (randn(args.num_experts, args.dim, args.hidden_dim) * 0.05).requires_grad_(True)
logits = torch.randn(args.tokens, args.num_experts, device="cuda", dtype=torch.float32)
top_scores, selected = torch.softmax(logits, dim=-1).topk(args.top_k, dim=-1)
return x, w1, w2, w3, selected, top_scores.requires_grad_(True)
def run_forward(mode: str, inputs: tuple[torch.Tensor, ...], num_experts: int) -> torch.Tensor:
x, w1, w2, w3, selected, top_scores = inputs
if mode == "grouped_mm":
return _run_experts_fused_reference(x, w1, w2, w3, selected, top_scores, num_experts)
return _FusedMoE.apply(x, w1, w2, w3, selected, top_scores, num_experts, mode == "fused_mxfp8")
def time_mode(mode: str, inputs: tuple[torch.Tensor, ...], args: argparse.Namespace) -> tuple[float, float, float]:
"""Median forward ms, median backward ms, peak MiB."""
forward_ms, backward_ms = [], []
grad_out = torch.randn(args.tokens, args.dim, device="cuda", dtype=torch.bfloat16)
start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
torch.cuda.reset_peak_memory_stats()
for i in range(args.warmup + args.iters):
for tensor in inputs[:4] + (inputs[5],):
tensor.grad = None
torch.cuda.synchronize()
start.record()
out = run_forward(mode, inputs, args.num_experts)
end.record()
torch.cuda.synchronize()
if i >= args.warmup:
forward_ms.append(start.elapsed_time(end))
start.record()
out.backward(grad_out)
end.record()
torch.cuda.synchronize()
if i >= args.warmup:
backward_ms.append(start.elapsed_time(end))
median = lambda values: sorted(values)[len(values) // 2]
return median(forward_ms), median(backward_ms), torch.cuda.max_memory_allocated() / 2**20
def main() -> None:
args = parse_args()
if not torch.cuda.is_available():
raise SystemExit("no CUDA device")
kernel = _load_fused_moe_kernel()
for mxfp8 in (False, True):
reason = kernel.unsupported_shape_reason(args.dim, args.hidden_dim, mxfp8=mxfp8)
if reason is not None:
raise SystemExit(f"shape unsupported by the fused kernel: {reason}")
inputs = make_inputs(args)
print(
f"tokens={args.tokens} dim={args.dim} hidden_dim={args.hidden_dim} "
f"experts={args.num_experts} top_k={args.top_k} "
f"({args.iters} iters, {args.warmup} warmup, median)\n"
)
print(f"{'mode':<12} {'fwd ms':>9} {'bwd ms':>9} {'total ms':>9} {'speedup':>9} {'peak MiB':>10}")
baseline = None
for mode in MODES:
forward, backward, peak = time_mode(mode, inputs, args)
total = forward + backward
baseline = baseline or total
print(f"{mode:<12} {forward:>9.3f} {backward:>9.3f} {total:>9.3f} {baseline / total:>8.2f}x {peak:>10.0f}")
if __name__ == "__main__":
main()
+68 -11
View File
@@ -2,15 +2,18 @@
"""
Run a single benchmark configuration and output JSON results.
This script wraps the prime-rl training with --bench.output-json to get
metrics directly without parsing console output.
This script runs a normal short training (--max-steps) with the file monitor
enabled and aggregates throughput / MFU / step time / peak memory from the
run's metrics.jsonl.
"""
from __future__ import annotations
import json
import statistics
import subprocess
import sys
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
@@ -83,6 +86,8 @@ class BenchmarkConfig(BaseConfig):
timeout: Annotated[int, Field(description="Timeout in seconds")] = 3600
max_steps: Annotated[int, Field(ge=2, description="Training steps to run. The first step is warmup.")] = 4
micro_batches: Annotated[int, Field(ge=1, description="Number of micro batches")] = 2
ep: Annotated[int, Field(ge=1, description="Expert parallelism size (1 = no EP)")] = 1
@@ -115,7 +120,7 @@ class BenchmarkConfig(BaseConfig):
] = None
def build_command(config: BenchmarkConfig) -> list[str]:
def build_command(config: BenchmarkConfig, output_dir: Path) -> list[str]:
"""Build the benchmark command from config."""
# Determine training script
if config.type == "rl":
@@ -137,12 +142,18 @@ def build_command(config: BenchmarkConfig) -> list[str]:
str(config.seq_len),
"--model.attn",
config.attention,
"--bench.output-json",
str(config.output),
"--max-steps",
str(config.max_steps),
"--output-dir",
str(output_dir),
"--monitors.file.path",
"metrics.jsonl",
"--model.compile",
"--dist-timeout-seconds",
str(config.timeout),
]
if config.type == "sft":
cmd.extend(["--run.name", "bench"])
# Add activation checkpointing if enabled
if config.ac == "Recompute":
@@ -198,14 +209,61 @@ def dummy_metrics() -> dict:
}
def aggregate_metrics(metrics_path: Path) -> dict:
"""Aggregate per-step metrics from a run's metrics.jsonl.
Each metrics.jsonl line is one monitor.log call (``{"step": N, ...}``);
merge the lines per step, drop the first (warmup) step, and compute
mean/std/min/max per metric like the old --bench JSON export did.
"""
per_step: dict[int, dict] = {}
with open(metrics_path) as f:
for line in f:
row = json.loads(line)
per_step.setdefault(row["step"], {}).update(row)
steps = sorted(per_step)[1:] # Exclude first warmup step
columns = {
"perf/mfu": "mfu",
"perf/throughput": "throughput",
"time/step": "step_time",
"perf/peak_memory": "peak_memory",
}
series = {name: [per_step[step][key] for step in steps] for key, name in columns.items()}
def stats(values: list[float]) -> dict:
return {
"mean": statistics.mean(values),
"std": statistics.stdev(values) if len(values) > 1 else 0.0,
"min": min(values),
"max": max(values),
}
total_memory_gib = torch.cuda.mem_get_info()[1] / 1024**3
peak_memory_gib = statistics.mean(series["peak_memory"])
return {
"mfu": stats(series["mfu"]),
"throughput": stats(series["throughput"]),
"step_time": stats(series["step_time"]),
"peak_memory": {
"gib": peak_memory_gib,
"pct": peak_memory_gib / total_memory_gib * 100,
},
}
def run_benchmark(config: BenchmarkConfig) -> None:
"""Run a single benchmark and write results to output path."""
cmd = build_command(config)
output_dir = Path(tempfile.mkdtemp(prefix="benchmark-run-"))
cmd = build_command(config, output_dir)
print(f"Running: {' '.join(cmd)}")
if config.dry_run:
return
# The SFT entrypoint writes to output_dir/<run.name>, the RL trainer to output_dir directly
metrics_path = output_dir / "bench" / "metrics.jsonl" if config.type == "sft" else output_dir / "metrics.jsonl"
start_time = time.perf_counter()
try:
config.output.parent.mkdir(parents=True, exist_ok=True)
@@ -221,14 +279,13 @@ def run_benchmark(config: BenchmarkConfig) -> None:
config.success = False
config.error_reason = extract_oom_error_reason(output) or f"Non-zero exit code: {result.returncode}"
print(f"Process exited with code {result.returncode}: {output}")
if not config.output.exists():
if not metrics_path.exists():
config.success = False
config.error_reason = config.error_reason or extract_oom_error_reason(output) or "No JSON output written"
config.error_reason = config.error_reason or extract_oom_error_reason(output) or "No metrics.jsonl written"
print(f"Process exited with code {result.returncode}: {output}")
print("Benchmark completed but no JSON output was written")
print("Benchmark completed but no metrics.jsonl was written")
else:
with open(config.output) as f:
metrics = json.load(f)
metrics = aggregate_metrics(metrics_path)
lines = output.splitlines()
print("\n".join(lines))
except subprocess.TimeoutExpired:
+3 -2
View File
@@ -8,8 +8,9 @@ Configurations for running prime-rl.
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
- **`ci/`** — integration and nightly configs used by CI.
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
(per-algorithm smokes) and `fake/` (fake-data trainer/SFT smokes). Not guaranteed
functional or up to date.
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
(two reverse-text train sources + one eval source, one env server per source). Not
guaranteed functional or up to date.
```bash
uv run rl @ configs/basic/<env>/rl.toml
+8 -4
View File
@@ -11,7 +11,7 @@ num_infer_gpus = 1
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
[monitors.wandb]
project = "alphabet-sort"
name = "alphabet-sort"
@@ -32,10 +32,14 @@ group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 768
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # Checkpoint at the end of training
+8 -7
View File
@@ -10,7 +10,7 @@ num_infer_gpus = 1
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[wandb]
[monitors.wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
@@ -19,18 +19,19 @@ batch_size = 128
group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "math-env"
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
env.taskset.dataset_subset = "default"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.model]
seq_len = 16384
[inference.model]
[inference.vllm]
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+5 -4
View File
@@ -11,7 +11,7 @@ num_infer_gpus = 1
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
@@ -22,10 +22,11 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+19 -2
View File
@@ -1,9 +1,11 @@
# SFT warmup for reverse-text on 2 GPUs. Dev-sized mirror of examples/basic/reverse-text/sft.toml.
# SFT warmup for reverse-text on 2 GPUs (1 train + 1 infer for online evals).
# Dev-sized mirror of examples/basic/reverse-text/sft.toml.
max_steps = 100
[deployment]
num_gpus = 2
num_train_gpus = 1
num_infer_gpus = 1
[ckpt] # Checkpoint at the end of training
@@ -17,3 +19,18 @@ batch_size = 32
[optim]
lr = 2e-5
[eval]
interval = 25
num_examples = 32
[eval.sampling]
max_completion_tokens = 1024
[[eval.source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
+6 -5
View File
@@ -12,7 +12,7 @@ num_infer_gpus = 1
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
[monitors.wandb]
project = "wiki-search"
name = "wiki-search"
@@ -40,12 +40,13 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "wiki-search"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # Checkpoint at the end of training
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
+5 -4
View File
@@ -8,7 +8,7 @@ seq_len = 8192
num_train_gpus = 1
num_infer_gpus = 1
[wandb]
[monitors.wandb]
project = "wordle"
name = "wordle"
@@ -21,10 +21,11 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 128
group_size = 8
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "wordle"
env.player.harness.id = "null"
env.player.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
+1 -1
View File
@@ -3,7 +3,7 @@
max_steps = 20
[deployment]
num_gpus = 2
num_train_gpus = 2
[ckpt] # Checkpoint at the end of training
+13 -3
View File
@@ -19,13 +19,23 @@ lr = 1e-5
batch_size = 128
group_size = 8
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 384
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, task = { similarity_power = 4, power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 2
env.taskset.max_turns = 2
env.taskset.min_names_per_turn = 1
env.taskset.max_names_per_turn = 3
env.taskset.task.similarity_power = 4
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
@@ -2,7 +2,9 @@ max_steps = 20
seq_len = 2048
[ckpt]
resume_step = 15
[resume]
step = 15
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -13,29 +15,31 @@ lr = 5e-5
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[inference.vllm]
enable_lora = true
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "prime-qwen3"
@@ -12,29 +12,31 @@ lr = 5e-5
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[inference.vllm]
enable_lora = true
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "prime-qwen3"
@@ -22,20 +22,22 @@ impl = "custom"
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
gpu_memory_utilization = 0.7
[inference.model]
[inference.vllm]
max_model_len = 2048
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "default"
@@ -1,13 +0,0 @@
# Inference config for multi-run RL integration test
enable_lora = true
max_lora_rank = 8
max_loras = 4
gpu_memory_utilization = 0.7
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
max_model_len = 2048
[weight_broadcast]
type = "filesystem"
@@ -1,32 +0,0 @@
# Orchestrator config for multi-run RL integration test
# model.lora.name and output_dir are set via CLI
batch_size = 128
group_size = 16
seq_len = 2048
max_steps = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[optim]
lr = 3e-5
[train.sampling]
max_completion_tokens = 128
[[train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[ckpt]
interval = 10
resume_step = -1
[weight_broadcast]
type = "filesystem"
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[renderer]
name = "prime-qwen3"
@@ -1,21 +0,0 @@
# Trainer config for multi-run RL integration test
max_concurrent_runs = 2
enable_token_export = true
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
seq_len = 65536
fused_lm_head_token_chunk_size = 8192
optim_cpu_offload = false
[model.lora]
rank = 8
[model.ac]
freq = 1
[model.compile]
fullgraph = false
[weight_broadcast]
type = "filesystem"
@@ -16,7 +16,7 @@ type = "filesystem"
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "reverse-text-ci"
name = "ci-rl-opd"
@@ -24,12 +24,15 @@ name = "ci-rl-opd"
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.algo]
type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
[orchestrator.renderer]
name = "prime-qwen3"
@@ -37,10 +40,11 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -49,13 +53,16 @@ num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.4
@@ -16,7 +16,7 @@ type = "filesystem"
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "reverse-text-ci"
name = "ci-rl-sft"
@@ -24,13 +24,16 @@ name = "ci-rl-sft"
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -43,10 +46,11 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -55,13 +59,16 @@ num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.4
@@ -1,10 +1,9 @@
max_steps = 10
[ckpt]
resume_step = 5
[ckpt.weights]
save_adapter_separately = true
[resume]
step = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -2,9 +2,6 @@ max_steps = 5
[ckpt]
[ckpt.weights]
save_adapter_separately = true
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -0,0 +1,21 @@
max_steps = 6
[ckpt]
skip_optimizer = true
skip_scheduler = true
[resume]
step = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
optim_cpu_offload = false
full_offload = true
[optim]
lr = 0.0
[data]
name = "PrimeIntellect/Reverse-Text-SFT"
batch_size = 4
seq_len = 1024
@@ -1,7 +1,9 @@
max_steps = 10
[ckpt]
resume_step = 5
[resume]
step = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -8,7 +8,9 @@ seq_len = 2048
type = "filesystem"
[ckpt]
resume_step = 15
[resume]
step = 15
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -20,13 +22,17 @@ lr = 3e-6
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
@@ -19,13 +19,17 @@ lr = 3e-6
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
+13 -6
View File
@@ -5,7 +5,7 @@ seq_len = 2048
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
[monitors.wandb]
project = "alphabet-sort"
name = "alphabet-sort"
@@ -18,15 +18,22 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
[orchestrator.concurrency]
max_inflight = 128
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 768
[trainer]
[inference.parallel]
dp = 4
[inference.vllm]
data_parallel_size = 4
+16 -12
View File
@@ -4,7 +4,7 @@ max_steps = 5000
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
[monitors.wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
@@ -18,19 +18,26 @@ batch_size = 512
group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
[orchestrator.concurrency]
max_inflight = 128
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "math-env"
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
env.taskset.dataset_subset = "default"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "aime2024"
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
group_size = 32
env.taskset.id = "aime24"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer]
@@ -38,12 +45,9 @@ group_size = 32
seq_len = 16384
attn = "flash_attention_2"
[inference.parallel]
dp = 4
[inference.model]
[inference.vllm]
max_model_len = 8192
data_parallel_size = 4
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+8 -4
View File
@@ -5,7 +5,7 @@ seq_len = 2048
num_train_gpus = 1
num_infer_gpus = 1
[wandb]
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
@@ -18,10 +18,14 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
batch_size = 128
group_size = 16
[[orchestrator.train.env]]
[orchestrator.concurrency]
max_inflight = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 128
+10 -12
View File
@@ -5,7 +5,7 @@ seq_len = 4096
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
[monitors.wandb]
project = "wiki-search"
name = "wiki-search"
@@ -17,24 +17,22 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
group_size = 16
oversampling_factor = 2.0
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[orchestrator.concurrency]
initial_inflight = 128
max_inflight = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "wiki-search"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
[trainer]
[inference.parallel]
dp = 4
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
data_parallel_size = 4
+10 -7
View File
@@ -5,7 +5,7 @@ seq_len = 8192
num_train_gpus = 2
num_infer_gpus = 6
[wandb]
[monitors.wandb]
project = "wordle"
name = "wordle"
@@ -18,18 +18,21 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
[orchestrator.concurrency]
max_inflight = 128
[[orchestrator.train.source]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "wordle"
env.player.harness.id = "null"
env.player.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer]
[inference.parallel]
dp = 6
[inference.vllm]
data_parallel_size = 6
[orchestrator.renderer]
name = "prime-qwen3"
@@ -17,13 +17,18 @@ language_model_attr = "model.language_model"
batch_size = 256
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "color-codeword"
env.taskset = { id = "color-codeword-v1", images_per_turn = 1 }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "color-codeword"
env.taskset.images_per_turn = 1
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer]
+4 -4
View File
@@ -24,15 +24,15 @@ Needed for `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--server.port 8001 \
--gpu-memory-utilization 0.5 \
--model.enforce-eager
--vllm.gpu-memory-utilization 0.5 \
--vllm.enforce-eager
```
## Run the debug configs
Every config writes to the default `outputs/` directory, so running two back-to-back — or re-running one — fails with `FileExistsError`. Pass a distinct `--output-dir outputs/<algo>` per config (recommended for a sweep) or `--clean-output-dir` to wipe and restart.
Every config writes to the default `outputs/` directory, so running two back-to-back — or re-running one — fails with `FileExistsError`. Pass a distinct `--output-dir outputs/<algo>` per config (recommended for a sweep) or `--clean` to wipe and restart.
```bash
# GRPO (no frozen model)
+10 -10
View File
@@ -8,7 +8,7 @@ seq_len = 4096
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-echo"
@@ -24,20 +24,18 @@ type = "echo"
[orchestrator.algo.roles.user]
alpha = 0.1
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
# ECHO learns from observation tokens even when the GRPO advantage collapses
# to zero — keep zero-advantage rollouts in the batch.
[[orchestrator.post_batch_filters]]
type = "zero_advantage"
enforce = false
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
[orchestrator.renderer]
name = "prime-qwen3"
@@ -46,4 +44,6 @@ name = "prime-qwen3"
lr = 1e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+11 -7
View File
@@ -4,7 +4,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-rl"
@@ -21,10 +21,11 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -33,10 +34,11 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -44,4 +46,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+11 -7
View File
@@ -4,7 +4,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-max-rl"
@@ -21,10 +21,11 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -33,10 +34,11 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -44,4 +46,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+20 -19
View File
@@ -3,8 +3,8 @@
# ref_logprobs, GRPO samples don't, and both pack into the same micro batches.
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/mixed_grpo_opd.toml
@@ -14,7 +14,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-mixed-grpo-opd"
@@ -31,22 +31,20 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text-grpo"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text-opd"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.env.algo]
type = "opd"
[orchestrator.train.env.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
algo.type = "opd"
algo.teacher.name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
algo.teacher.base_url = "http://localhost:8001/v1"
[orchestrator.eval]
interval = 5
@@ -55,13 +53,16 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+14 -10
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/opd.toml
@@ -11,7 +11,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-opd"
@@ -24,7 +24,7 @@ type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
@@ -33,10 +33,11 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -45,10 +46,11 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -56,4 +58,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+14 -13
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/opd_lora.toml
@@ -11,7 +11,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-opd-lora"
@@ -24,7 +24,7 @@ type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
@@ -33,10 +33,11 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -45,10 +46,11 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 1e-4
@@ -56,10 +58,9 @@ lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+55
View File
@@ -0,0 +1,55 @@
max_steps = 20
seq_len = 4096
[model]
name = "Qwen/Qwen3-0.6B"
[monitors.wandb]
project = "algorithms-debug"
name = "debug-rae"
[orchestrator]
batch_size = 32
group_size = 1
[orchestrator.algo]
type = "rae"
[orchestrator.renderer]
name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.source]]
name = "kuhn-poker"
env.taskset.id = "kuhn-poker"
env.player0.harness.id = "null"
env.player0.runtime.type = "subprocess"
env.player1.harness.id = "null"
env.player1.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 512
[[orchestrator.eval.source]]
name = "kuhn-poker"
env.taskset.id = "kuhn-poker"
env.player0.harness.id = "null"
env.player0.runtime.type = "subprocess"
env.player1.harness.id = "null"
env.player1.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+11 -7
View File
@@ -10,7 +10,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-self-distill"
@@ -29,10 +29,11 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -41,13 +42,16 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+14 -10
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/sft_distill.toml
@@ -11,7 +11,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-sft"
@@ -25,7 +25,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -38,10 +38,11 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -50,10 +51,11 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -61,4 +63,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+14 -13
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/sft_distill_lora.toml
@@ -11,7 +11,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-sft-lora"
@@ -25,7 +25,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -38,10 +38,11 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -50,10 +51,11 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 1e-4
@@ -61,10 +63,9 @@ lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+139
View File
@@ -0,0 +1,139 @@
# Concurrency-controller debug run: GLM-4.5-Air on the v1 `scaleswe` SWE taskset,
# bash harness on a prime sandbox runtime, 1 train + 1 infer node, eval on 100
# SWE-Bench Verified instances. Concurrency is fully default: the controller
# derives its start from the measured KV budget and adapts from there — watch
# the concurrency/* gauges in W&B or the "Concurrency ..." lines in the
# orchestrator log.
#
# Inference serves FP8 via online per-tensor quantization of the bf16
# checkpoint; weight broadcasts re-quantize through the same path on every
# update. The trainer fits on one node via cp=4 (ulysses), full CPU optimizer
# offload with the stateless sign-SGD optimizer, plus the memory improvements
# from the GLM-5.1 prod run: LM-head token chunking, activation checkpointing
# (freq=1) + activation offloading (max_inflight=1), and skip-gather /
# skip-optimizer checkpointing. Router replay is enabled — GLM-4.5-Air is a
# glm4_moe model, which supports routed_experts.
#
# GRPO uses the linear length penalty with the input-token and turns
# coefficients set to 0.1.
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "debug-concurrency"
partition = "all"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "debug-concurrency" -y || true'
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
num_infer_replicas = 1
[monitors.wandb]
project = "swe-ablations"
name = "debug-concurrency"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
[resume]
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
optim_cpu_offload = false
full_offload = true
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "sign_sgd"
# --- Orchestrator ---
[orchestrator]
batch_size = 128
group_size = 8
max_off_policy_steps = 32
[orchestrator.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["debug-concurrency"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
num_examples = 100
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["debug-concurrency"]
env.agent.timeout.rollout = 3600
# --- Inference ---
[inference]
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
quantization = "fp8"
enable_return_routed_experts = true
+51
View File
@@ -0,0 +1,51 @@
# Minimal multi-env debug run: two reverse-text train sources + one eval source.
# The launcher spawns one env server per source at its derived address
# (tcp://127.0.0.1:5000-5002); the orchestrator connects to each.
max_steps = 10
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.renderer]
name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text-a"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text-b"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 5
num_examples = 64
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
Vendored Submodule
+1
Submodule deps/prime-envs added at 26dafdc958
Vendored Submodule
+1
Submodule deps/prime-kernels added at 2ceaf9eccb
+1 -1
+1 -1
+2 -14
View File
@@ -1,6 +1,6 @@
# Advanced
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, multi-tenant training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
## Table of Contents
@@ -11,7 +11,6 @@ This page covers the specialized features layered on top of the core training st
- [Enabling VLM Mode](#enabling-vlm-mode)
- [Limitations](#limitations)
- [LoRA Training](#lora-training)
- [Multi-Tenant Training](#multi-tenant-training)
- [Disaggregated Prefill/Decode Inference](#disaggregated-prefilldecode-inference)
## Custom Modeling
@@ -116,18 +115,7 @@ dropout = 0.0
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. To save the raw adapter alongside the merged HF weights:
```toml
[ckpt.weights]
save_adapter_separately = true
```
LoRA pairs naturally with [multi-tenant training](#multi-tenant-training) — each tenant gets its own adapter and the backbone is shared across all of them in trainer memory.
## Multi-Tenant Training
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/src/prime_rl/trainer/runs.py).
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
## Disaggregated Prefill/Decode Inference
+155 -54
View File
@@ -1,6 +1,6 @@
# Algorithms
This page covers the math and the configurable algorithmic components: the algorithm abstraction and its algorithms, how off-policy training works, the loss components and advantage functions, how to plug in your own, the filters applied between rollout and training, and how multi-turn rollouts get merged into training samples.
This page covers the math and the configurable algorithmic components: the algorithm abstraction and its algorithms, how off-policy training works, the loss components and advantage functions, curricula, and how multi-turn rollouts get merged into training samples.
## Table of Contents
@@ -17,9 +17,11 @@ This page covers the math and the configurable algorithmic components: the algor
- [Custom Loss](#custom-loss)
- [Advantage](#advantage)
- [Default Advantage](#default-advantage)
- [Hierarchical GRPO](#hierarchical-grpo)
- [Self-Play Advantage (RAE)](#self-play-advantage-rae)
- [Authoring an Algorithm](#authoring-an-algorithm)
- [Reference Scoring](#reference-scoring)
- [Filters](#filters)
- [Curricula](#curricula)
- [Multi-Turn Trajectories](#multi-turn-trajectories)
- [Extension Property](#extension-property)
- [Best-Effort Interleaving](#best-effort-interleaving)
@@ -33,7 +35,7 @@ A training algorithm in `prime-rl` is configured under `[orchestrator.algo]`, wh
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).
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, packer, or trainer hot path.
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, batch packing, or trainer hot path.
### Model References
@@ -45,7 +47,7 @@ type = "opd"
[orchestrator.algo.teacher] # opd's teacher: the frozen model it scores against
name = "Qwen/Qwen3-32B"
base_url = ["http://localhost:8001/v1"]
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.
@@ -67,6 +69,8 @@ type = "grpo" # the default
|---|---|---|---|
| `grpo` | policy | `rl` on actions | Standard group-relative RL. |
| `max_rl` | policy | `rl` on actions | MaxRL ([arXiv:2602.02710](https://arxiv.org/abs/2602.02710)): GRPO's centered reward normalized by the group **mean** instead of the standard deviation — the gradient is unbiased for the order-`group_size` truncation of the maximum-likelihood objective, upweighting hard examples like `1/p`. |
| `rae` | policy | `rl` on actions | RAE (SPIRAL, [arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): reward minus a per-agent EMA baseline of that agent's own rewards — the estimator for multi-agent self-play envs, where the group mean would mix the agents' opposite reward scales. See [Self-Play Advantage](#self-play-advantage-rae). |
| `hierarchical_grpo` | policy | `rl` on actions | GRPO for proposer-solver envs. Solvers are compared only with attempts on the same proposed problem; proposers are compared with the other proposals in the group. See [Hierarchical GRPO](#hierarchical-grpo). |
| `opd` | policy | `ref_kl` on actions | On-policy distillation ([Thinking Machines](https://thinkingmachines.ai/blog/on-policy-distillation/)): the policy samples, per-token reverse KL against a reference model as the gradient signal. Needs a `teacher`. |
| `sft` | *(the teacher)* | `ce` on actions | Hard distillation: a frozen model generates rollouts, the policy trains with CE on its tokens. Needs a frozen `sampling.source` (the teacher it samples from). |
| `opsd` | policy | `ref_kl` on actions | SDFT ([arXiv:2601.19897](https://arxiv.org/abs/2601.19897)): the model is its own reference, conditioned on an expert demonstration. The teacher *is* the live policy (the paper's setting, no extra deployment) — no model to configure. |
@@ -96,7 +100,9 @@ Echo also takes an optional user-supplied token filter that narrows the role sel
```toml
[orchestrator.algo.filter]
import_path = "my_module.drop_warnings"
kwargs = { patterns = ["WARNING"] }
[orchestrator.algo.filter.kwargs]
patterns = ["WARNING"]
```
```python
@@ -116,40 +122,44 @@ Both components resolve per environment. Each env inherits `[orchestrator.algo]`
[orchestrator.algo]
type = "grpo"
[[orchestrator.train.env]]
name = "math"
taskset = { id = "math-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
# inherits the top-level grpo
[[orchestrator.train.source]]
name = "math" # inherits the top-level grpo
env.taskset.id = "math"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "terminal"
taskset = { id = "terminal-v1" }
harness = { id = "bash", runtime = { type = "subprocess" } }
algo = { type = "echo" } # this env runs its own algorithm
env.taskset.id = "terminal"
env.agent.harness.id = "bash"
env.agent.runtime.type = "subprocess"
# this env runs its own algorithm
algo.type = "echo"
```
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_rl.orchestrator.sampler`) from the `sampling` component — the pool rollouts are generated from, and the home of future sampling strategies like replay buffers or branching — 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.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 |
|---|---|---|
| `grpo` | `GRPOAlgorithm` | `score_group`: group-norm credit (optional length penalty) |
| `echo` | `EchoAlgorithm` | `score_rollout`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
| `echo` | `EchoAlgorithm` | `score_episode`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
| `max_rl` | `MaxRLAlgorithm` | `score_group`: mean-normalized group credit |
| `opd` | `OPDAlgorithm` | `score_rollout`: own-context prefill under the teacher |
| `opsd` | `OPSDAlgorithm` | `score_rollout`: demo-conditioned prefill under the live policy |
| `sft` | `SFTDistillAlgorithm` | `score_group`: group-norm credit (feeds filters) |
| `rae` | `RAEAlgorithm` | `score_group`: per-agent EMA-baseline credit |
| `hierarchical_grpo` | `HierarchicalGRPOAlgorithm` | `score_group`: GRPO baseline per episode for solvers, per group for the proposer |
| `opd` | `OPDAlgorithm` | `score_episode`: own-context prefill under the teacher |
| `opsd` | `OPSDAlgorithm` | `score_episode`: demo-conditioned prefill under the live policy |
| `sft` | `SFTDistillAlgorithm` | no credit assignment; CE on sampled tokens |
Each class owns its hooks outright — reading one top to bottom reads the algorithm, and everything on the class is an override point. The two hooks are one scope-and-timing ladder — the wider scope is unlocked by a later barrier, so the two axes coincide. Each is handed the `Rollout` directly — the env's typed trace (`reward`, `nodes`, `num_turns`, ...) with `samples` attached, plus `assign_advantages` to write credit:
Algorithms operate on native verifier artifacts and annotate their message graphs directly:
- `async score_rollout(rollout)` — one rollout, **on arrival** (as it's tokenized, before its group is complete): rollout-local credit (`rollout.assign_advantages(...)`, scalar broadcast or per-token), observation ce weights, **or** model I/O — query a reference pool (e.g. `self.teacher_pool`, connected in `setup()` via `self.connect(...)`, or the live `self.policy_pool` for opsd) and attach per-token results (e.g. teacher logprobs) with bounded concurrency. No siblings. `echo` weights observation tokens here, identifying env-provided observation nodes by their non-sampled status and source step role attribution, applying the optional user filter, and writing the `ce_weights` stream. Model I/O runs *before* the pre-batch filters, so it pays compute on rollouts that may then be filtered out.
- `score_group(group)` — the cohort, **before filtering** (filters read the streams), synchronous: group-relative credit (GRPO/MaxRL baselines). `group` is a list of `Rollout`.
- `async score_episode(episode)` — rollout-local scoring as one episode arrives.
- `async score_group(episodes)` — group-relative scoring after the cohort completes.
The pipeline drives the hooks through two non-virtual methods it never looks inside: `algorithm.finalize_rollout(rollout)` per arrival (rollout-local scoring + reference I/O) and `algorithm.finalize_group(rollouts)` per group (scoring + wire stamping; after this the records are frozen — groups die at stamping). Sample construction (interleaving) is pure pipeline — observation-token provenance is available through structural attribution (`node.sampled`, `node.is_content`) for any algorithm that trains on env-provided tokens.
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 pool (`self.policy_pool`). 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.algo.advantage`.
## Async / Off-Policy Training
@@ -174,7 +184,7 @@ $$
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
$$
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the group-relative algorithms (`grpo`, `max_rl`, and `echo`'s action tokens).
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
@@ -245,7 +255,9 @@ Wire it up:
[trainer.loss]
type = "custom"
import_path = "my_module.ppo_clip_loss"
kwargs = { clip_eps = 0.2 }
[trainer.loss.kwargs]
clip_eps = 0.2
```
The dataclasses:
@@ -276,9 +288,11 @@ The per-token training signal is set by `algo.type` and the [algorithm](#the-alg
|---|---|---|
| `grpo` | `rl` | Group-norm: reward minus per-group baseline, optional length penalty. |
| `max_rl` | `rl` | Mean-normalized group credit (maximum-likelihood RL). |
| `rae` | `rl` | Reward minus a per-agent EMA baseline (SPIRAL's role-conditioned advantage estimation) — for multi-agent self-play envs. |
| `hierarchical_grpo` | `rl` | GRPO for proposer-solver envs: solvers are compared within one proposed problem, while proposers are compared across proposals. |
| `echo` | `rl` + `ce` | Group-norm on action tokens, plus weighted CE on env-provided tokens selected by message role (each role's `alpha` is its ECHO λ), optionally narrowed by a user filter. |
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream; `group_size` only fans out sampling. |
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream. |
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` and ship no advantage stream; `group_size` only fans out sampling. |
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` and ship no advantage stream. |
| `sft` | `ce` | Cross-entropy on the sampled tokens. Assigns no advantage — trains on every sampled token. |
### Default Advantage
@@ -297,33 +311,107 @@ type = "grpo"
type = "linear"
```
### Hierarchical GRPO
GRPO gives each rollout its reward minus the average reward of comparable rollouts. In an ordinary single-agent group, every rollout answers the same task, so one group average is enough.
A proposer-solver env is different. Starting from one source task, it produces several proposed problems, then runs several solver attempts on each problem:
```text
one source task
├── proposed problem A
│ ├── proposer trace
│ ├── solver attempt 1
│ └── solver attempt 2
└── proposed problem B
├── proposer trace
├── solver attempt 1
└── solver attempt 2
```
The solver attempts for A should not be compared with the solver attempts for B: the two problems may have very different difficulty. Proposer and solver rewards should not be compared either: they measure different jobs.
`hierarchical_grpo` therefore chooses the average separately for each role:
| Trace | Compared with | Why |
|---|---|---|
| Solver | Other solver attempts on the same proposed problem | They attempted the same problem. |
| Proposer | Other proposer traces in the group | They started from the same source task and proposed alternatives. |
For example, if three solvers receive rewards `[1, 1, 0]` on one proposed problem, their average is `2/3` and their advantages are `[1/3, 1/3, -2/3]`. Solver rewards from other proposed problems do not affect those values. The proposers are scored separately according to how useful their problems were for the solvers, then compared with the other proposers in the group.
Configure which roles are compared within a single proposed problem with `episode_agents`. For `proposer-solver`, that role is `solver`:
```toml
[orchestrator.algo]
type = "hierarchical_grpo"
episode_agents = ["solver"]
[[orchestrator.train.source]]
name = "proposer-solver"
group_size = 4 # proposed problems per source task
env.n = 4 # solver attempts per proposed problem
env.taskset.id = "proposer-solver"
env.proposer.harness.id = "null"
env.proposer.runtime.type = "subprocess"
env.solver.harness.id = "null"
env.solver.runtime.type = "subprocess"
```
`group_size` controls how many problems are proposed from each source task. `env.n` controls how many solvers attempt each proposed problem. If a comparison contains only one trace—for example, a solver when `env.n = 1`—its advantage is zero.
This algorithm is accepted only for proposer-solver envs. Use the env's `train_proposer` and `train_solver` settings if you want to train only one role.
### Self-Play Advantage (RAE)
Group-relative baselines assume the group is exchangeable attempts by one agent. A multi-agent self-play env breaks that: one episode yields one trace per agent, all trainable, and in a zero-sum game the rewards sum to ~0 whatever the policy does — the group mean carries no information, and centering against it converts any structural asymmetry (a first-mover edge) into permanent credit for 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]
type = "rae"
decay = 0.95
[[orchestrator.train.source]]
name = "kuhn-poker"
env.taskset.id = "kuhn-poker"
env.player0.harness.id = "null"
env.player0.runtime.type = "subprocess"
env.player1.harness.id = "null"
env.player1.runtime.type = "subprocess"
```
Both of `kuhn-poker`'s agents late-bind to the run's own model — shared-policy self-play against a continuously improving opponent. Pin one agent to a frozen endpoint (`env.player1.model = ...`) for asymmetric play; its traces are marked untrainable by the env and never reach the advantage computation. A single-agent env under `rae` degrades to REINFORCE with an EMA baseline.
### Authoring an Algorithm
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class. The hook receives the group's `Rollout`s (each the env's typed `verifiers.Trace` — turns, tool calls, metadata in `info` — with `samples` attached) and writes credit via `assign_advantages`:
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class:
```python
# 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
class MyAlgorithm(Algorithm):
async def score_group(self, group):
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
advantages = ... # one value per rollout
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
rollout.assign_advantages(advantage)
async def score_group(self, episodes):
traces = [trace for episode in episodes for trace in episode.traces]
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
advantages = ... # one value per trace
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
assign_advantages(trace, advantage)
```
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick the hook by *when* your signal is ready: `score_rollout` for per-arrival credit or credit that needs a model call (it's `async`), `score_group` for group-relative credit (GRPO/MaxRL). `assign_advantages` takes a scalar (broadcast over the rollout's trainable tokens — the common case) or a full-length per-token list aligned to the concatenated sample token_ids (process rewards, step-level credit; `0.0` off-mask).
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick `score_episode` for rollout-local work or model calls, and `score_group` for group-relative credit. `assign_advantages` takes a scalar or a list aligned to the trace graph's sampled tokens.
Each per-token list must match the rollout's completion-token count exactly — validated loudly when the view writes it. Advantage-based filters and metrics derive from the streams (the zero-advantage filter checks for all-zero streams; logged distributions use per-rollout means). Signals that depend on the live policy's weights (like OPD's reverse KL) cannot be precomputed here; those are reference-scoring algorithms, evaluated in the trainer.
Curriculum admission and metrics can inspect the resulting graph-native streams after group scoring.
### Reference Scoring
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_rollout`: as each rollout arrives they query a reference (the sample's own context for `opd`, the demo-conditioned context for `opsd`) and attach per-token reference logprobs to each sample. Rollouts are consumed serially by the orchestrator's main loop and each carries only a handful of samples, so the in-flight request count is naturally bounded — no explicit concurrency cap:
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_episode`: as each episode arrives they query a reference and attach sampled-token reference logprobs to its graph nodes:
- `opd` — score each sample's own context under the `teacher` (a frozen [model reference](#model-references)) via prefill; fills `ref_logprobs` for the `ref_kl` loss component (on-policy distillation). The `teacher` is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero).
- `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`).
@@ -334,34 +422,47 @@ type = "opsd"
demo_key = "demonstration"
```
Scoring runs at arrival, *before* the pre-batch filters, so a rollout that is later filtered still cost its reference compute — accepted for the simpler one-rollout-at-a-time shape (advantage-based filters never fire for opd/opsd anyway, since neither assigns an advantage).
Scoring runs before curriculum admission, so a rollout that is later rejected still costs its reference compute.
## Filters
By default, zero-advantage RL tokens are removed after a complete batch cohort has been collected and before its payload is packed for the trainer. This does not backfill the batch. Samples that still carry CE or reference-KL components are retained, while pure zero-advantage RL samples are not shipped. Removing an RL token also removes its trainer/inference mismatch-KL contribution. Set `orchestrator.train.filter_zero_advantages = false` to retain them.
Filters drop rollouts between scoring and training. Built-ins (composable):
## Curricula
| Filter | Effect |
|---|---|
| `gibberish` | Drops rollouts whose mean log-prob fall below a threshold — usually a sign of degenerate output. |
| `repetition` | Drops rollouts with high n-gram repetition. |
| `zero_advantage` | Drops rollouts whose advantage is zero, so the trainer doesn't waste tokens on them. |
Each training source has a `Curriculum` composed from one `TaskSampler` and any number of named `AdmissionGate`s. The sampler chooses tasks and observes every finalized `list[vf.Episode]`; each gate inspects the same native episodes. The group trains only if every gate admits it. Rejected groups remain observable while the orchestrator samples again to fill the batch.
The default `[orchestrator]` config registers all three in both filter slots: `post_batch_filters` enforce by default (flagged rollouts are recorded but not shipped to the trainer), while `pre_batch_filters` run in monitor mode (`enforce = false`); flip `enforce = true` there to drop matching rollouts before they consume a slot in the batch. Setting a slot replaces its defaults wholesale:
Samplers and gates can be stateful. Their `state_dict`, `load_state_dict`, and `metrics` methods are included in orchestrator checkpoints and logged under `curriculum/<env>/`.
Three small implementations are included:
- `StandardSampler` is the default: it advances the task iterator and cycles finite tasksets in source order.
- `DifficultyPoolSampler` samples finite tasksets with replacement and tracks each task's latest valid mean group reward. Each named pool has an inclusive reward threshold and a relative per-task sampling weight; weight `0` disables sampling from that pool. Unseen tasks use neutral weight `1.0`, so pool observations affect sampling immediately without waiting for a full taskset pass.
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in post-batch zero-advantage filtering, rejection requests replacement work. Groups without an advantage stream are admitted.
```toml
[[orchestrator.post_batch_filters]]
type = "zero_advantage"
[orchestrator.train.source.curriculum.sampler]
type = "difficulty_pool"
[[orchestrator.post_batch_filters]]
type = "repetition"
threshold = 0.4
[orchestrator.train.source.curriculum.sampler.pools.hard]
threshold = 0.25
weight = 0.2
[orchestrator.train.source.curriculum.sampler.pools.normal]
threshold = 0.75
weight = 1.0
[orchestrator.train.source.curriculum.sampler.pools.easy]
threshold = 1.0
weight = 0.2
[orchestrator.train.source.curriculum.gates.low_signal]
type = "advantage_range"
reject_min = -0.05
reject_max = 0.05
```
Filtered rollouts still appear in W&B distributions, just not in the trainer batch — useful for spotting whether filtering is doing its job.
## Multi-Turn Trajectories
Multi-turn rollouts (tool use, browser environments, long conversations) used to be stitched into a single fake "single-turn" sample, which silently corrupted the importance ratio when chat templates didn't roundtrip. Since [`verifiers` v0.1.8](https://github.com/PrimeIntellect-ai/verifiers/releases/tag/v0.1.8), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
For multi-turn rollouts (tool use, browser environments, long conversations), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
### Extension Property
+37 -30
View File
@@ -17,7 +17,7 @@ Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeInt
- [Optional Sub-Configs](#optional-sub-configs)
- [None](#none)
- [Discriminated Unions](#discriminated-unions)
- [Environments](#environments-orchestratortrainenv)
- [Environments](#environments)
- [Environment Variables](#environment-variables)
- [Examples](#examples)
@@ -50,18 +50,18 @@ CLI flags mirror the TOML tree using dots:
--max-steps 50 # top-level
--model.name Qwen/Qwen3-4B # nested
--trainer.optim.lr 1e-5 # double-nested
--inference.parallel.tp 4
--inference.vllm.tensor-parallel-size 4
```
> Field names are snake_case in TOML (`max_model_len`) and kebab-case on the CLI (`--max-model-len`).
> Renamed fields keep their old name as a validation alias — e.g. `rollouts_per_example` is still accepted in TOML and CLI after being renamed to `group_size`. Mixing the two names across sources is safe.
> A renamed field keeps no alias for its old name: the old spelling fails as an unknown key rather than being silently translated.
## Inspecting and Validating
```bash
uv run rl --help # full schema
uv run rl @ rl.toml --dry-run --output-dir /tmp/check # write resolved configs
uv run rl @ rl.toml --dry-run --output-dir /tmp --run.name check # write resolved configs (JSON) to /tmp/check/configs
```
## Syntax
@@ -71,12 +71,12 @@ uv run rl @ rl.toml --dry-run --output-dir /tmp/check # write resolved configs
CLI uses paired flags: bare `--flag` sets `True`, `--no-flag` sets `False`. TOML must be explicit:
```bash
uv run rl @ rl.toml --clean-output-dir # True
uv run rl @ rl.toml --no-clean-output-dir # False
uv run rl @ rl.toml --clean # True
uv run rl @ rl.toml --no-clean # False
```
```toml
clean_output_dir = true
clean = true
```
### Lists
@@ -93,20 +93,21 @@ uv run rl @ rl.toml --trainer.model.lora.target-modules '["q_proj", "k_proj", "v
target_modules = ["q_proj", "k_proj", "v_proj"]
```
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables (e.g. environments), see [Environments](#environments-orchestratortrainenv).
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables, see [Environments](#environments).
### Dicts
CLI takes a JSON literal. TOML uses a table or inline-table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
CLI takes a JSON literal. TOML uses a table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
```bash
uv run rl @ rl.toml --orchestrator.train.env.0.args \
uv run rl @ rl.toml --orchestrator.train.source.0.args \
'{"dataset_name": "openai/gsm8k", "dataset_subset": "main"}'
```
```toml
[[orchestrator.train.env]]
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
[[orchestrator.train.source]]
args.dataset_name = "openai/gsm8k"
args.dataset_subset = "main"
```
### Optional Sub-Configs
@@ -123,11 +124,11 @@ To **disable** a sub-config that's on by default, use `--no-<name>` on the CLI o
TOML has no `null`. Use the string `"None"`, which the loader coerces:
```toml
[inference.model]
[inference.vllm]
max_model_len = "None"
```
On the CLI: `--inference.model.max-model-len None`.
On the CLI: `--inference.vllm.max-model-len None`.
### Discriminated Unions
@@ -142,27 +143,32 @@ mu = 0.95
Omit `type` to keep the default variant.
### Environments (`[[orchestrator.train.env]]`)
### Environments
Training environments are an array of tables — set one per env, optionally with sampling weights:
Training and evaluation sources are arrays of tables. Set one source per environment; training sources can optionally carry sampling weights:
```toml
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "gsm8k"
env.taskset = { id = "gsm8k-v1", split = "train" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
ratio = 3 # 75% of batches
env.taskset.id = "gsm8k"
env.taskset.split = "train"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
ratio = 1 # default — 25% of batches
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "gsm8k-eval"
env.taskset = { id = "gsm8k-v1", split = "test" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "gsm8k"
env.taskset.split = "test"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
@@ -192,7 +198,7 @@ PYTORCH_CUDA_ALLOC_CONF = "expandable_segments:False"
VLLM_USE_DEEP_GEMM = "1"
[orchestrator.env_vars]
PI_USAGE_BASE_URL = "https://..."
PRIME_LOG_LEVEL = "debug"
```
The `rl` launcher applies these the same way in both single-node and multi-node (SLURM) runs. Precedence, low to high:
@@ -231,17 +237,18 @@ Start from a shipped base config, override two fields on the CLI, and dry-run:
```bash
uv run rl @ examples/basic/reverse-text/rl.toml \
--wandb.name my-experiment \
--monitors.wandb.name my-experiment \
--trainer.optim.lr 5e-6 \
--output-dir /tmp/reverse-dry \
--run.name check \
--dry-run
```
Then inspect the resolved config:
```bash
ls /tmp/reverse-dry/configs/
# rl.toml trainer.toml orchestrator.toml inference.toml
ls /tmp/reverse-dry/check/configs/resolved/
# rl.json trainer.json orchestrator.json inference.json
```
Each per-process TOML reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/configs/trainer.toml`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
Each per-process JSON reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/check/configs/resolved/trainer.json`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
+4 -4
View File
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
| Workflow | Trigger | What runs | Where |
|---|---|---|---|
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_multi_run`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
@@ -109,7 +109,7 @@ uv run sft \
--data.name PrimeIntellect/Reverse-Text-SFT \
--max_steps 200 \
--optim.lr 1e-4 \
--ckpt.weights
--ckpt
```
Then run the full RL stack on reverse-text:
@@ -118,8 +118,8 @@ Then run the full RL stack on reverse-text:
uv run rl @ configs/ci/integration/reverse-text-moe/start.toml \
--model.name samsja/mini-glm-moe \
--trainer.model.impl custom \
--inference.gpu-memory-utilization 0.7 \
--inference.model.max-model-len 2048
--inference.vllm.gpu-memory-utilization 0.7 \
--inference.vllm.max-model-len 2048
```
What to look for:
+66 -50
View File
@@ -12,6 +12,7 @@ This page covers the inference configuration and the supported features/deployme
- [P/D Disaggregation](#pd-disaggregation)
- [Router](#router)
- [Routing policies](#routing-policies)
- [Adaptive Concurrency](#adaptive-concurrency)
- [Advanced Configuration](#advanced-configuration)
- [KV Cache Offload](#kv-cache-offload)
- [Optimized P/D disaggregation deployment](#optimized-pd-disaggregation-deployment)
@@ -30,7 +31,9 @@ We support 3 distinct deployment shapes:
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `backend_port`, and a `[...deployment.router]` block, etc.
Every deployment shape has the same client-facing layout: a single global router listens on `inference.server.port` and fronts all vLLM engines, which listen on `inference.backend_port` (+ rank offset). Clients always talk to one URL, regardless of how many engines run behind it.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape and topology knobs such as `num_nodes` and `num_replicas`.
```toml
[inference.deployment]
@@ -40,7 +43,7 @@ type = "single_node" # or "multi_node" or "disaggregated"
To configure the inference server, you can use the `InferenceConfig` field. This is a config-field that allows you to set the inference server-specific knobs. Most of these are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
```toml
[inference]
[inference.vllm]
model = "PrimeIntellect/INTELLECT-3"
...
```
@@ -56,23 +59,23 @@ The single-node deployment is the default deployment shape. It runs the inferenc
type = "single_node"
```
The launcher starts a `vllm-router` on `inference.server.port` (default `8000`) fronting the vLLM engine on `inference.backend_port` (default `8100`). Clients connect to the router URL; admin operations (weight updates, health checks) bypass the router and hit the engine port directly — the RL entrypoint wires `orchestrator.model.client.admin_base_url` accordingly.
This deployment shape runs the inference server on a single node, if configured with NVLink enabled, it allows you more freedom in terms of parallelism configurations.
```toml
[inference]
[inference.vllm]
enable_expert_parallel = true # defaults to False
[inference.parallel]
tp = 2
dp = 4
tensor_parallel_size = 2
data_parallel_size = 4
[inference.deployment]
type = "single_node"
```
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required `orchestrator.max_inflight_requests`. Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required concurrency (see [Adaptive Concurrency](#adaptive-concurrency)). Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.enable_expert_parallel` or `inference.parallel.tp` to maximize the available GPU memory.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.vllm.enable_expert_parallel` or `inference.vllm.tensor_parallel_size` to maximize the available GPU memory.
You can also increase the available KV cache memory by enabling `inference.kv_cache_offload`. More details in the [Advanced Configuration](#advanced-configuration) section.
@@ -82,7 +85,7 @@ You can also increase the available KV cache memory by enabling `inference.kv_ca
This deployment shape branches into 2 sub-shapes:
- [Multi-replica](#multi-replica) - Runs the inference server on multiple nodes, but each node runs an independent vLLM replica. You can think of this as a for-loop over single-node deployments.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.vllm.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
### Multi-replica
@@ -94,35 +97,31 @@ Parallelism configuration is the same as the single-node deployment. The shape i
type = "multi_node"
num_nodes = 2
[inference]
[inference.vllm]
model = "PrimeIntellect/INTELLECT-3"
[inference.parallel]
tp = 2
dp = 4
tensor_parallel_size = 2
data_parallel_size = 4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a router instance running on the same node as the 1st replica — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[...deployment.router]` block. You can read more about the supported routing options in the [router](#router) section.
This configuration will run 2 independent vLLM replicas, each with `tensor_parallel_size=2` and `data_parallel_size=4`. Routing is handled by a single global router running on the first inference node, fronting the per-rank endpoints of all replicas — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[inference.router]` block. You can read more about the supported routing options in the [router](#router) section.
### Wide-EP
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.enable_expert_parallel = true`.
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.vllm.enable_expert_parallel = true`.
```toml
[inference.deployment]
type = "multi_node"
num_nodes = 2
[inference]
[inference.vllm]
model = "PrimeIntellect/INTELLECT-3"
enable_expert_parallel = true
[inference.parallel]
tp = 2
dp = 8
tensor_parallel_size = 2
data_parallel_size = 8
```
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tp = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tensor_parallel_size = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
## P/D Disaggregation
@@ -160,25 +159,31 @@ num_train_nodes = 4
num_infer_replicas = 3
```
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes and start 3 separate router instances.
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes, fronted by the single global router.
## Router
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
Every deployment fronts its vLLM engines with a single global router — it listens on `inference.server.port` and is the one URL clients connect to. The backend is configured via a discriminated `[inference.router]` block (`type = "vllm-router" | "llm-d"`):
```toml
[inference.deployment.router] # or [deployment.router] for the standalone inference entrypoint
[inference.router] # or [router] for the standalone inference entrypoint
type = "llm-d" # "vllm-router" (default) or "llm-d"
# llm-d-only knobs (all optional):
scorers = { "prefix-cache-scorer" = 3.0, "active-request-scorer" = 2.0 } # base, applied to every profile
prefill_scorer_overrides = { "queue-scorer" = 2.0, "kv-cache-utilization-scorer" = 2.0 } # merged onto the P/D prefill profile
decode_scorer_overrides = {} # merged onto the P/D decode profile
non_cached_tokens = 16 # below this many non-cached prompt tokens, skip remote prefill (P/D)
non_cached_tokens = 16 # llm-d only: below this many non-cached prompt tokens, skip remote prefill (P/D)
# llm-d only: base scorer weights, applied to every profile
[inference.router.scorers]
"prefix-cache-scorer" = 3.0
"active-request-scorer" = 2.0
# llm-d only: merged onto the P/D prefill profile (decode_scorer_overrides for decode)
[inference.router.prefill_scorer_overrides]
"queue-scorer" = 2.0
"kv-cache-utilization-scorer" = 2.0
```
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy. Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`. The only backend supported for single-node (local) deployments.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy (multi-node / disaggregated SLURM deployments only). Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
Both backends support the 2 most important things:
- Request routing - KV cache re-use and balanced routing
@@ -186,19 +191,23 @@ Both backends support the 2 most important things:
### Routing policies
The 2 policies you might want to configure are:
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - this works by hashing a request header to determine where to route the request to. You can configure what to hash by setting
`orchestrator.model.client.extra_headers_from_state` to the header the `router` expects to be set.
We set it to a sensible default, that works with all verifiers environments.
```toml
[orchestrator.model.client.extra_headers_from_state]
X-Session-ID = "trajectory_id" # this is the default - each rollout has a unique trajectory_id and router expects X-Session-ID
```
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - it hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica.
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
## Adaptive Concurrency
The orchestrator continuously sizes how many episodes run against the inference engines at once. A static cap cannot be right: too low starves the engines, too high crosses into KV thrash — the engines evict prefix cache, re-prefill the evicted work, and throughput collapses. The optimal value depends on the model, the deployment, and the workload's episode lengths, and it moves as training changes the policy.
The controller's idea is to treat the engines as ground truth and probe, instead of modeling episode cost: while the engines show headroom, admit a little more; when they show pressure, back off. Three behaviors, in increasing severity:
- **Grow**: while the engines look healthy and the current cap is fully used, raise it multiplicatively. Growth is clocked by the pipeline itself — the cap rises by a fixed factor each time the in-flight pool has turned over once — so a fast single-turn workload ramps in seconds while a slow agentic workload ramps at its own pace, with no tuning per workload.
- **Trim**: episodes grow their context *while running*, so a pool that fit comfortably an hour ago can outgrow memory without a single new admission. When KV usage nears the ceiling, the controller first lowers the cap and lets completions drain the pool naturally (soft — no work lost); only if usage keeps climbing despite the closed gate does it also cancel the youngest episodes (hard — least work lost).
- **Cut**: when the engines are demonstrably overloaded — requests being preempted, or piling up in the waiting queue — cut the pool hard, cancel the excess, and hold further cuts until the system settles.
The cap starts from a safe bound derived from the engines (KV capacity divided by the maximum context length), or from `initial_inflight` when a good value is known, and always stays within `[min_inflight, max_inflight]`.
## Advanced Configuration
### KV Cache Offload
@@ -251,34 +260,41 @@ For configuring various knobs with environment variables, we enable you to confi
[inference.deployment]
type = "disaggregated"
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip"}
[inference.deployment.prefill_env_vars]
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
[inference.deployment.decode_env_vars]
"VLLM_DEEP_GEMM_WARMUP" = "skip"
```
These are role-specific and layer on top of [`env_vars`](configuration.md#environment-variables) shared by all inference processes regardless of role.
### Other vLLM features
We support various other vLLM features. Some of those, such as `enable_dbo`, `enable_eplb` are exposed as a top-level config fields. For those that are not, you can configure them by setting `inference.vllm_extra` to the desired value.
The `[inference.vllm]` section is a pass-through: every key is forwarded to the vLLM server under vLLM's own argument name, whether prime-rl types it or not. Anything `vllm serve` accepts can be set here.
```toml
[inference.vllm_extra]
[inference.vllm]
headless = true
max_num_seqs = 256
```
On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (or `--vllm.max-num-seqs 256` for the standalone inference entrypoint); dict-valued arguments take a JSON string, e.g. `--vllm.compilation-config '{"cudagraph_mode": "NONE"}'`.
### Router Replay
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.enable_return_routed_experts = true`.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`.
```toml
[trainer]
enable_router_replay = true # this will also auto-set the inference.enable_return_routed_experts = true
enable_router_replay = true # this will also auto-set inference.vllm.enable_return_routed_experts = true
[inference]
[inference.vllm]
enable_return_routed_experts = true
```
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend increasing `orchestrator.*.env.num_workers` to allow for more parallelization on the verifiers side.
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
+5 -5
View File
@@ -10,9 +10,9 @@ A `prime-rl` RL run is three cooperating processes:
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/inference/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). We are trying to stay up-to-date with the latest vLLM features, you can read more about the supported features and deployment options in the dedicated [inference documentation](inference.md).
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, and LoRA. You can read more in the dedicated [training documentation](training.md).
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses ZMQ, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap the rollout link to the local filesystem (`rollout_transport.type = "filesystem"`) if you want rollouts persisted to disk. See [Scaling](scaling.md) for the deployment options.
## Installation
@@ -20,7 +20,7 @@ The three processes communicate through configurable transports — by default t
curl -sSL https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/main/scripts/install.sh | bash
```
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`research-environments`](https://github.com/PrimeIntellect-ai/research-environments) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`prime-envs`](https://github.com/PrimeIntellect-ai/prime-envs) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
You need at least one NVIDIA GPU (RTX 3090/4090/5090, A100, H100, H200, or B200). Single-GPU runs are supported for debugging; production RL is typically 1× inference node + 1+ trainer nodes.
@@ -32,7 +32,7 @@ Train an SFT-warmed `Qwen3-0.6B` on the `reverse-text` task — the env is bundl
uv run rl @ examples/basic/reverse-text/rl.toml
```
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into `outputs/logs/{trainer,orchestrator,inference}.log`. Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes and final HF-compatible weights land at `outputs/weights/step_20`.
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into the run directory at `outputs/<run_name>/logs/{trainer,orchestrator,inference}.log` (`run.name` auto-generates as `<envs>--<model>--<short-id>`; pass `--run.name <name>` for a predictable path). Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes with a final DCP checkpoint at `outputs/<run_name>/checkpoints/step_20`.
## Documentation
@@ -41,5 +41,5 @@ The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into
- **[Inference](inference.md)** — vLLM-backed server (or fleet) holding the current policy.
- **[Scaling](scaling.md)** — Single-GPU through multi-node clusters via FSDP / EP / CP and SLURM.
- **[Algorithms](algorithms.md)** — Async semantics, loss / advantage / filter plugins, trajectory merging.
- **[Advanced](advanced.md)** — Custom modeling, multimodal, LoRA, multi-tenant, P/D inference.
- **[Advanced](advanced.md)** — Custom modeling, multimodal, LoRA, P/D inference.
- **[Development](development.md)** — Test suite, pre-commit hooks, adding a new model.
+21 -32
View File
@@ -38,24 +38,25 @@ The `rl`, `sft`, and `inference` entrypoints all accept a `[deployment]` block (
uv run rl @ rl.toml \
--deployment.num-infer-gpus 6 \
--deployment.num-train-gpus 2 \
--inference.parallel.dp 6
--inference.vllm.data-parallel-size 6
```
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
For quick A/B ablations on the same node, run two RL instances side-by-side in separate tmux sessions, each pinned to half the GPUs and a separate inference port:
For quick A/B ablations on the same node, run two RL instances side-by-side in separate shells, each pinned to half the GPUs and a separate inference port, and track both in one dashboard:
```bash
# session 1, GPUs 0–1, default port 8000
bash scripts/tmux.sh -s exp1 -o outputs/exp1
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --output-dir outputs/exp1
# shell 1, GPUs 0–1, default port 8000
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --run.name exp1
# session 2, GPUs 2–3, port 8001
bash scripts/tmux.sh -s exp2 -o outputs/exp2
# shell 2, GPUs 2–3, port 8001
CUDA_VISIBLE_DEVICES=2,3 uv run rl @ rl.toml \
--inference.server.port 8001 \
--orchestrator.model.client.base-url http://localhost:8001/v1 \
--output-dir outputs/exp2
--run.name exp2
# watch both side by side
uv run dashboard outputs
```
#### SFT and Torchrun
@@ -69,7 +70,7 @@ uv run torchrun \
src/prime_rl/trainer/sft/train.py @ sft.toml
```
`--local-ranks-filter 0` keeps console output to rank 0 only; per-rank stdout/stderr is still captured in `<output_dir>/logs/trainer/torchrun/`.
`--local-ranks-filter 0` keeps console output to rank 0 only; per-rank stdout/stderr is still captured in `<run_dir>/logs/latest/trainer/torchrun/`.
### Multi-Node
@@ -86,7 +87,8 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
| `trainer.model.dp_replicate` | Number of dimensions to **replicate** instead of shard. Set to 2 to run 2-way DP replication × FSDP sharding within each replica — useful for very large clusters where pure FSDP communication dominates. |
| `trainer.model.reshard_after_forward` | If `true` (default), parameters are resharded after the forward pass to free memory; the backward pass re-gathers. Set `false` to keep params resident — faster but more memory. |
| `trainer.model.fsdp_cpu_offload` | Offload params + grads + optimizer state to CPU. Big memory win, large throughput hit. |
| `trainer.model.optim_cpu_offload` | Offload only optimizer state. Mid-ground — small throughput cost, decent memory savings, especially at low GPU count. |
| `trainer.model.optim_cpu_offload` | Offload optimizer state to CPU between steps. Enabled by default. |
| `trainer.model.full_offload` | Offload gradients, FP32 masters, and optimizer state and run the optimizer (AdamW or SignSGD) on CPU during backward. Disabled by default. |
### Expert Parallelism
@@ -137,14 +139,7 @@ targets = ["norm", "attn_proj"] # see Reference for the full list per architect
### Optimizer Offloading
Offloading optimizer states to CPU is enabled by default (`optim_cpu_offload = true`) — a near-free memory win at low GPU counts:
```toml
[trainer.model]
optim_cpu_offload = true # already the default
```
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training) — set `optim_cpu_offload = false` for multi-run. Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`. For full offload, set `model.optim_cpu_offload = false` and `model.full_offload = true`; this keeps BF16 compute weights on GPU and runs CPU optimizer chunks as gradients become ready during backward. Full offload only supports AdamW and SignSGD (`optim.type = "sign_sgd"`) and disables gradient clipping. SignSGD is stateless, so it halves the host RAM footprint versus AdamW (8 instead of 16 bytes per parameter: FP32 master + FP32 accumulated gradient, no moments).
### LM Head Chunking
@@ -199,9 +194,11 @@ Launch:
```bash
uv run rl @ base_rl.toml @ my_slurm.toml # submits via sbatch
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script + resolved config, exits
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes launcher/rl.sbatch + resolved config, exits
```
Every SLURM entrypoint stores its generated scripts and coordination files under `<run_dir>/launcher/`. SLURM stdout and stderr go to `launcher/logs/`. Local launches do not create `launcher/`.
### `[deployment]` Block
`[deployment]` is a discriminated union picked by `type` — `single_node` or `multi_node` for RL/SFT, with an extra disaggregated variant for inference. RL multi-node:
@@ -231,7 +228,7 @@ Full multi-node configs ship under [`examples/advanced/`](https://github.com/Pri
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), and the launcher prints one URL per node. Front the URLs with a router or point clients at any of them.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
### Custom Templates
@@ -245,22 +242,14 @@ The default templates live under [`src/prime_rl/templates/`](https://github.com/
## Benchmarking
Every entrypoint supports a `--bench` flag that runs a few warm-up + measurement steps with fake data and prints a rich-formatted throughput / MFU table:
To benchmark a parallelism config before committing a multi-day run, run a short training with fake data and a step cap, and read throughput / MFU / step time / peak memory from the logs:
```bash
# SFT trainer alone
uv run sft @ sft.toml --bench
uv run sft ... --data.type fake --data.length variable --bench # variable-length fake data
uv run sft @ sft.toml --data.type fake --max-steps 4
# RL trainer alone (no inference involved)
uv run trainer @ train.toml --data.fake --bench
# Inference alone — start the server normally, then bench the orchestrator
uv run inference @ infer.toml
uv run orchestrator @ orch.toml --bench
# Full RL stack (trainer with fake data, inference with real data from orchestrator)
uv run rl @ rl.toml --bench
uv run trainer @ train.toml --data.fake --max-steps 4
```
Persist results with `--bench.output-json`. Use this to compare parallelism configs before committing a multi-day run.
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `metrics.jsonl` to the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
+101 -70
View File
@@ -36,7 +36,8 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer + inference. |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at a derived loopback address); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
## RL Trainer
@@ -58,10 +59,10 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|---|---|
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | How many distinct policies may have contributed to one rollout before it's discarded (default 8). The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `errored_rollouts` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.env]]` | Training environments. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Environments](configuration.md#environments-orchestratortrainenv). |
| `[[orchestrator.eval.env]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
| `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.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). |
**Monitoring:**
@@ -69,17 +70,18 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|---|---|
| `log.level` | Process log level for trainer + orchestrator (`info` default; falls back to `$PRIME_LOG_LEVEL`). Set per-process via `trainer.log.level` / `orchestrator.log.level`, or globally on the `rl` entrypoint to propagate to both. |
| `orchestrator.log.vf_level` | Env-worker / [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) log level (`info` default; `debug` is noisy but useful for env debugging). |
| `--wandb` (+ `--wandb.project`, `--wandb.name`) | Enable Weights & Biases logging. See [Weights & Biases](#weights--biases). |
| `--orchestrator.prime-monitor` | Stream metrics to the Prime Intellect platform (Prime Lab). See [Platform monitoring](#platform-monitoring). |
| `--monitors.wandb` (+ `--monitors.wandb.project`, `--monitors.wandb.name`) | Enable Weights & Biases logging. See [Weights & Biases](#weights--biases). |
| `--monitors.prime` | Stream metrics and episodes to the Prime Intellect platform (Prime Lab). See [Platform monitoring](#platform-monitoring). |
**Run management:**
| Knob | What it does |
|---|---|
| `--clean-output-dir` | Wipe `<output_dir>` before starting. Useful when re-running an experiment with the same name during iteration. |
| `--output-dir outputs/<name>` | Per-run output directory. Always set this when running more than one experiment in parallel. |
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). Defaults to `$PRL_OUTPUT_DIR` if set, else `outputs`. |
| `--run.name <name>` | Run name, also the run directory name under `<output_dir>` (override the directory separately via `--run.dir`). Auto-generated as `<envs>--<model>--<short-id>` when unset, so every launch gets a fresh, readable run directory. Set an explicit name for a predictable path — required to resume the run later. |
| `--clean` | Wipe the run directory before starting. Useful when re-running a named run during iteration. |
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
| `--dry-run` | Resolve + validate the full config, write per-process TOMLs to `<output_dir>/configs/`, and exit without launching. The fastest way to debug a misbehaving config. |
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
### Algorithms
@@ -89,6 +91,8 @@ The RL entrypoint supports several training algorithms, switched via `[orchestra
|---|---|---|
| `grpo` (default) | None | Standard group-relative RL |
| `max_rl` | None | [MaxRL](https://arxiv.org/abs/2602.02710): GRPO with mean-normalized advantages (maximum-likelihood RL) |
| `rae` | None | [SPIRAL](https://arxiv.org/abs/2506.24119)'s role-conditioned advantage estimation: reward minus a per-agent EMA baseline, for multi-agent self-play envs (e.g. `kuhn-poker`) |
| `hierarchical_grpo` | None | GRPO for proposer-solver envs: compare solvers only with attempts on the same proposed problem, and compare proposers with the other proposals in the group |
| `opd` | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): the policy generates rollouts, the trainer minimizes per-token reverse KL to a reference model |
| `sft` | Required, any OpenAI-compatible endpoint | Hard-distill: a frozen model generates rollouts, the policy trains on its tokens |
| `opsd` | None — the live policy is its own reference (no deployment) | [SDFT](https://arxiv.org/abs/2601.19897): the model is its own reference conditioned on expert demonstrations |
@@ -100,7 +104,7 @@ Frozen models are declared inline on the algorithm, named where the model is use
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name <frozen-model> --server.port 8001
--vllm.model <frozen-model> --server.port 8001
```
The standalone `uv run sft` entrypoint is the more traditional SFT path — pure dataset-based, no orchestrator. Use the `sft` algorithm only when you want a frozen model to generate the supervision on the fly.
@@ -167,11 +171,54 @@ See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectorie
The minimal SFT run trains `Qwen3-0.6B` on the `reverse-text` SFT dataset:
```bash
uv run sft @ examples/basic/reverse-text/sft.toml --wandb
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)).
### 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:
```toml
[eval]
interval = 25
num_examples = 32
[[eval.source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
[deployment]
num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
#### Multi-Node (Decoupled Trainer and Inference Pool)
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two separate SLURM jobs**. `deployment.num_train_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2 # trainer job
num_infer_nodes = 1 # eval job (inference pool + evals)
[inference.vllm]
tensor_parallel_size = 8
[slurm]
job_name = "my-run"
```
The launcher submits the eval job after the trainer allocation starts. The trainer publishes its rank-0 hostname in the shared run directory, and the eval job uses it to join the NCCL weight-broadcast group. Each weight transfer is synchronous, but eval rollout execution overlaps with later training steps. After the final transfer, the trainer job releases its nodes while the eval job finishes the final epoch and exits. Without `max_steps`, the eval job never sees a final broadcast and holds its allocation until walltime. Trainer and evals log to one shared W&B run — the trainer creates it, and the evals process finalizes it. Any trainer-to-inference node layout works because `num_train_nodes` and `num_infer_nodes` are independent.
### SFT-Specific Knobs
| Knob | What it controls |
@@ -181,6 +228,7 @@ Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manag
| `data.seq_len` | Per-sample sequence length |
| `loss_mask.*` | Which roles contribute to loss (system / user / assistant / tool). |
| `val.interval` | Run validation every N steps; `val.data` mirrors `data` |
| `eval.interval` | Run online evals every N steps; see [Online Evals](#online-evals) |
### Important Metrics
@@ -188,15 +236,16 @@ Pulled from the console log and mirrored to W&B.
**Progress and loss:**
- `loss/mean` — main signal. Should decrease through the run.
- `val/loss` — validation loss when `[val]` is set, logged every `val.interval` steps.
- `loss/mean`, `loss/perplexity` — main signal. Should decrease through the run.
- `val/loss`, `val/perplexity` — validation metrics when `[val]` is set, logged every `val.interval` steps.
- `eval/{env}/...` — online eval metrics when `[eval]` is set, logged at each evaluated checkpoint step.
- `progress/epoch`, `progress/num_samples`, `progress/num_tokens` — dataset progress.
- `progress/<subset>/ratio_{samples,tokens}` — when training on multiple HF subsets/splits, the realized mixing ratio.
**Stability and optimization:**
- `optim/grad_norm` — spikes precede divergence.
- `optim/lr`, `optim/zero_grad_ratio` — LR schedule and the fraction of params that received zero gradients (high → dead path or wrong loss masking).
- `optim/lr` — LR schedule.
- For MoE: `max_vio/mean` (load-balancing violation), `routing_confidence/mean` — both are logged when non-zero.
**Performance:**
@@ -214,10 +263,9 @@ Checkpointing is split across processes because the orchestrator and trainer can
| Process | What's saved | Where |
|---|---|---|
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<output_dir>/checkpoints/step_N/trainer/` |
| Orchestrator | Step counter, total tokens / samples / problems | `<output_dir>/checkpoints/step_N/orchestrator/` |
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_N/trainer/` |
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_N/orchestrator/` |
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
| Trainer (HF weights) | HF-compatible weight snapshot for serving | `<output_dir>/weights/step_N/` |
### Enabling Checkpoints
@@ -232,34 +280,31 @@ uv run rl @ rl.toml --ckpt.interval 25 --ckpt.keep-interval 100 # …plus perma
### Resuming a Run
Re-run the same launch command and pass `--ckpt.resume-step <N>` (or `-1` for "latest"). Make sure `--max-steps` is at least the target final step, not the remaining delta:
Re-run the same launch command and pass `--resume` (latest checkpoint) or `--resume.step <N>`. Resuming reuses the run directory, so the run needs a name you can point back at — launch with `--run.name` (or pass the first run's auto-generated name). Make sure `--max-steps` is at least the target final step, not the remaining delta:
```bash
# First run: steps 1–10
uv run rl @ rl.toml --max-steps 10 --ckpt
uv run rl @ rl.toml --max-steps 10 --ckpt --run.name my-run
# Resume: continue to step 20
uv run rl @ rl.toml --max-steps 20 --ckpt.resume-step 10
# Resume from the latest checkpoint: continue to step 20
uv run rl @ rl.toml --max-steps 20 --ckpt --resume --run.name my-run
# ...or from a specific step
uv run rl @ rl.toml --max-steps 20 --ckpt --resume.step 10 --run.name my-run
# ...or fork another run's checkpoint into a fresh run
uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
--resume.dir outputs/my-run/checkpoints/step_10
```
### Serving Checkpoints
HF-compatible weight snapshots are written under `<output_dir>/weights/step_N/` whenever a full checkpoint runs (or you can write weights-only via `--ckpt.weights-only` for cheaper snapshots). Upload directly:
```bash
uv run hf upload <user>/<model>-RL outputs/weights/step_100
```
For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write the raw adapter alongside the merged weights — useful when serving the adapter through a separate `/load_lora_adapter` call.
## Observability
### Log Files
The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The full layout (single-node runs skip the `node_*.log` and `router_*.log` files):
The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>/` — every launch (fresh or resumed) gets its own numbered attempt directory, and `logs/latest` symlinks to the current one. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
```
<output_dir>/logs/
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
├── orchestrator.log # single instance, single file
├── inference.log # symlink → inference/node_0.log on multi-node
@@ -268,71 +313,57 @@ The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The f
│ └── torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log # per-rank
├── inference/
│ ├── node_*.log # per-node inference stdout (multi-node only)
│ └── router_*.log # vllm-router per replica (multi-node only)
└── envs/{train,eval}/<env_name>/
├── env_server.log
└── env_worker_<id>.log
│ └── router.log # the single global router (multi-node only)
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
```
Env worker logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
```bash
tail -F <output_dir>/logs/{trainer,orchestrator,inference}.log
tail -F <output_dir>/logs/trainer/node_*.log # multi-node only
tail -F <output_dir>/logs/inference/router_*.log # multi-node only
tail -F <run_dir>/logs/latest/{trainer,orchestrator,inference}.log
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
```
### Console Output
### Dashboard
`scripts/tmux.sh` opens a 4-pane tmux session that follows `trainer.log`, `orchestrator.log`, `inference.log`, and the union of env worker logs. Start it before launching:
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved configs, a rollout trace viewer with a per-token advantage/logprob view, merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
```bash
bash scripts/tmux.sh
# then in the Launcher window:
uv run rl @ ... --output-dir outputs/my-run
```
Pass `-s <session>` and `-o <output_dir>` to run multiple parallel experiments side-by-side in different sessions. The helper also works on a SLURM head node — `bash scripts/tmux.sh my-rl-job /shared/outputs/my-rl-job`.
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
### Weights & Biases
W&B is off by default. Enable with `--wandb`:
W&B is off by default (the file monitor, which writes `metrics.jsonl` and the per-step trace files to the run directory, is on by default):
```bash
uv run rl @ rl.toml --wandb # default project, random name
uv run rl @ rl.toml --wandb.project my-proj --wandb.name run-42
uv run rl @ rl.toml --no-wandb # force-disable even if the TOML enables it
uv run rl @ rl.toml --monitors.wandb # default project, random name
uv run rl @ rl.toml --monitors.wandb.project my-proj --monitors.wandb.name run-42
uv run rl @ rl.toml --no-monitors.file # disable the local metric/trace files
```
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `wandb.offline = true`.
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `monitors.wandb.offline = true`.
By default, every 10 steps each process also logs a sample of prompts/completions (with rewards and advantages) and reward/advantage/entropy distributions as W&B tables. Tune via `--wandb.log-extras.interval` and `--wandb.log-extras.sample-ratio`, or disable subsets:
```bash
uv run rl @ rl.toml --wandb \
--orchestrator.wandb.log-extras.interval 50 \
--no-trainer.wandb.log-extras.distributions
```
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, W&B mode **auto-creates an `overview` saved view** on the first run into a project — curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, every training run (RL and SFT) gets an **auto-created `overview` saved view** curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
### Platform Monitoring
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics, samples, and distributions to the platform dashboard. Bare flag uses defaults:
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics and episodes to the platform dashboard. Bare flag uses defaults:
```bash
uv run rl @ rl.toml --orchestrator.prime-monitor
uv run rl @ rl.toml --monitors.prime
```
Or set it in TOML:
```toml
[orchestrator.prime_monitor]
run_name = "my-experiment"
[monitors.prime]
name = "my-experiment"
```
Every 10th step the orchestrator uploads the step's episodes (full conversations with rewards and advantages) to the run's sample viewer.
Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted team. Currently internal-only.
## Rules of Thumb
@@ -340,5 +371,5 @@ Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted t
- **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.
- **Pin `output_dir` per run.** Sharing a directory across runs will mix rollouts and break resumes. `--output-dir outputs/<unique-name>` is the simplest discipline.
- **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.
+43 -37
View File
@@ -21,10 +21,12 @@ num_train_nodes = 2
num_infer_nodes = 1
num_infer_replicas = 4
[wandb]
[monitors.wandb]
project = "search-ablations"
name = "glm45air-search"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -32,7 +34,8 @@ timeout = 3600
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[resume]
[model]
name = "zai-org/GLM-4.5-Air"
@@ -49,7 +52,6 @@ attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
[trainer.model.ac]
@@ -59,7 +61,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
@@ -71,7 +72,10 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
[orchestrator.concurrency]
initial_inflight = 256
max_inflight = 512
[orchestrator.renderer]
name = "glm-4.5"
@@ -86,21 +90,21 @@ num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.0
[orchestrator.prime_monitor]
# --- Train: the search envs with usable training data (rlm `search` skill, prime sandbox) ---
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
# entry wholesale (keep `name`/`question_field`/`choices` in sync with the taskset defaults —
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "openseeker"
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.runtime.labels = ["glm45air-search"]
env.taskset.id = "openseeker"
[orchestrator.train.env.env.taskset]
id = "openseeker-v1"
[[orchestrator.train.env.env.taskset.task.judges]]
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
@@ -108,21 +112,23 @@ question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.env.env.taskset.task.judges]]
# [[orchestrator.train.source.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "redsearcher"
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.runtime.labels = ["glm45air-search"]
env.taskset.id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
[orchestrator.train.env.env.taskset]
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
[[orchestrator.train.env.env.taskset.task.judges]]
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
@@ -130,10 +136,10 @@ question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.env.env.taskset.task.judges]]
# [[orchestrator.train.source.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
@@ -142,36 +148,36 @@ choices = ["A", "B"]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "browsecomp"
num_examples = 500 # full set is 1266; cap eval at 500
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.env.env.taskset]
id = "browsecomp-v1"
task = { judge = { model = "Qwen/Qwen3-235B-A22B-Instruct-2507" } }
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.agent.timeout.rollout = 3600
env.taskset.id = "browsecomp"
env.taskset.task.judge.model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.eval.env.env.taskset.task.judges]]
# [[orchestrator.eval.source.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
[inference.vllm]
max_model_len = 131072
[inference.parallel]
tp = 8
tensor_parallel_size = 8
enable_return_routed_experts = true
+32 -29
View File
@@ -1,4 +1,4 @@
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, rlm harness on a prime sandbox
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
# a glm4_moe model, which supports routed_experts.
@@ -7,10 +7,13 @@
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
#
# 2 train + 4 infer nodes. Trainer uses cp=4 (ulysses) plus
# 1 train + 3 infer nodes. Inference serves the bf16 checkpoint as-is (no quantization). The trainer
# fits on one node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), optimizer
# CPU offload, and skip-gather / skip-optimizer checkpointing.
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
# skip-gather / skip-optimizer checkpointing.
# Concurrency is fully default: the controller derives its start from the measured KV budget and
# adapts from there.
max_steps = 1000
seq_len = 131072
@@ -28,14 +31,16 @@ pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y ||
[deployment]
type = "multi_node"
num_train_nodes = 2
num_train_nodes = 1
num_infer_nodes = 1
num_infer_replicas = 4
num_infer_replicas = 3
[wandb]
[monitors.wandb]
project = "swe-ablations"
name = "glm45air-scaleswe"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -43,10 +48,8 @@ timeout = 3600
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[model]
name = "zai-org/GLM-4.5-Air"
[resume]
# --- Trainer ---
@@ -54,13 +57,17 @@ name = "zai-org/GLM-4.5-Air"
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
optim_cpu_offload = false
full_offload = true
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
[trainer.model.ac]
@@ -70,11 +77,10 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
type = "muon"
type = "sign_sgd"
# --- Orchestrator ---
@@ -82,7 +88,6 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
[orchestrator.algo]
type = "grpo"
@@ -97,36 +102,34 @@ num_turns_weight = 0.1
name = "glm-4.5"
thinking_retention = "all"
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe"]
[orchestrator.prime_monitor]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
env.agent.timeout = { rollout = 3600 }
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe"]
env.agent.timeout.rollout = 3600
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
[inference.vllm]
max_model_len = 131072
[inference.parallel]
tp = 8
tensor_parallel_size = 8
enable_return_routed_experts = true
+41 -43
View File
@@ -22,10 +22,12 @@ num_train_nodes = 2
num_infer_nodes = 1
num_infer_replicas = 4
[wandb]
[monitors.wandb]
project = "terminal-ablations"
name = "glm45air-terminal"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -33,7 +35,8 @@ timeout = 3600
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[resume]
[model]
name = "zai-org/GLM-4.5-Air"
@@ -50,7 +53,6 @@ attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
[trainer.model.ac]
@@ -60,7 +62,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
@@ -72,7 +73,10 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
[orchestrator.concurrency]
initial_inflight = 256
max_inflight = 512
[orchestrator.renderer]
name = "glm-4.5"
@@ -87,29 +91,27 @@ num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.prime_monitor]
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "tmax"
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
[orchestrator.train.env.env.taskset]
id = "tmax-v1"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.runtime.labels = ["glm45air-terminal"]
env.taskset.id = "tmax"
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
# [[orchestrator.train.env.env.taskset.judges]]
# [[orchestrator.train.source.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.train.env.env.taskset.judges]]
# [[orchestrator.train.source.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# path = "deps/prime-envs/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
@@ -118,63 +120,59 @@ id = "tmax-v1"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swebench-verified"
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.env.env.taskset]
id = "swebench-verified-v1"
# [[orchestrator.eval.env.env.taskset.judges]]
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.agent.timeout.rollout = 3600
env.taskset.id = "swebench-verified"
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.eval.env.env.taskset.judges]]
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# path = "deps/prime-envs/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "terminal-bench-2"
group_size = 4 # avg@4
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
env.agent.timeout = { rollout = 3600 }
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.agent.timeout.rollout = 3600
env.taskset.id = "terminal-bench-2"
[orchestrator.eval.env.env.taskset]
id = "terminal-bench-2-v1"
# [[orchestrator.eval.env.env.taskset.judges]]
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.eval.env.env.taskset.judges]]
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# path = "deps/prime-envs/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
[inference.vllm]
max_model_len = 131072
[inference.parallel]
tp = 8
tensor_parallel_size = 8
enable_return_routed_experts = true
+33 -19
View File
@@ -6,22 +6,9 @@
output_dir = "/shared/outputs/glm5.2-16node-llmd"
enable_expert_parallel = true
gpu_memory_utilization = 0.75
enable_eplb = false
use_deep_gemm = true
enable_fp32_lm_head = true
[model]
name = "zai-org/GLM-5.2-FP8"
max_model_len = 91000
tool_call_parser = "glm47"
reasoning_parser = "glm45"
[vllm_extra]
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[kv_cache_offload]
type = "mooncake"
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
@@ -35,16 +22,43 @@ prefill_nodes_per_replica = 2
num_prefill_replicas = 4
decode_nodes_per_replica = 8
num_decode_replicas = 1
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
[deployment.router]
[deployment.prefill_env_vars]
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
[deployment.decode_env_vars]
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
[router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 }
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 }
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 }
non_cached_tokens = 128
[router.scorers]
"prefix-cache-scorer" = 3.0
[router.prefill_scorer_overrides]
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[router.decode_scorer_overrides]
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[slurm]
job_name = "glm5.2-16node-llmd"
partition = "all"
[vllm]
model = "zai-org/GLM-5.2-FP8"
max_model_len = 91000
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
+8 -8
View File
@@ -1,12 +1,4 @@
enable_expert_parallel = true
enable_eplb = false
use_deep_gemm = true
gpu_memory_utilization = 0.85
[model]
name = "zai-org/GLM-5-FP8"
tool_call_parser = "auto"
reasoning_parser = "glm45"
[deployment]
type = "disaggregated"
@@ -17,3 +9,11 @@ gpus_per_node = 8
[slurm]
job_name = "glm5"
partition = "cluster"
[vllm]
model = "zai-org/GLM-5-FP8"
tool_call_parser = "auto"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.85
enable_expert_parallel = true
enable_eplb = false
+54 -32
View File
@@ -1,12 +1,15 @@
max_steps = 10000000
seq_len = 131072
output_dir = "/shared/outputs/glm5-llmd" # FILL IN: point at your shared filesystem
clean_output_dir = true
output_dir = "/shared/outputs" # FILL IN: point at your shared filesystem
clean = true
[run]
name = "glm5-llmd"
[log]
level = "debug"
[wandb]
[monitors.wandb]
project = "glm5-llmd"
name = "base"
@@ -28,23 +31,53 @@ prefill_nodes_per_replica = 2
num_prefill_replicas = 4
decode_nodes_per_replica = 8
num_decode_replicas = 1
# skip warmup for faster start in cost of some jit overhead early
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
[inference.deployment.prefill_env_vars]
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
[inference.deployment.decode_env_vars]
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
# gives the most KV cache while keeping decent throughput, KV cache increase comes in from lower deep-ep LL static buffers
prefill_vllm_overrides = {"enable_dbo"=true}
decode_vllm_overrides = {"max_num_batched_tokens"=96, "max_num_seqs"=96}
[inference.deployment.prefill_vllm_overrides]
"enable_dbo" = true
[inference.deployment.router]
[inference.deployment.decode_vllm_overrides]
"max_num_batched_tokens" = 96
"max_num_seqs" = 96
[inference.router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 } # need some prefix-cache routing, however due to shared mooncake pool do low prio
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 } # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 } # decode doesn't really create queue, it fills in KV cache fast, give 4.0
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[inference.vllm]
model = "zai-org/GLM-5.1-FP8"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[slurm]
job_name = "glm5-llmd"
partition = "all" # FILL IN: set to your cluster's partition
@@ -60,7 +93,6 @@ attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
ep = 8
optim_cpu_offload = true
[trainer.model.quantization]
type = "fp8"
@@ -81,9 +113,12 @@ weight_decay = 0.0
[orchestrator]
batch_size = 256
group_size = 16
max_inflight_rollouts = 2048
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
[orchestrator.concurrency]
initial_inflight = 256
max_inflight = 512
[orchestrator.model]
name = "zai-org/GLM-5.1-FP8"
@@ -93,34 +128,21 @@ clear_thinking = false
[orchestrator.train.sampling]
temperature = 1.0
extra_body = {chat_template_kwargs = {clear_thinking = false}}
[orchestrator.train.sampling.extra_body.chat_template_kwargs]
clear_thinking = false
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "r2e"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "rlm", runtime = { type = "prime", labels = ["glm5-llmd"] } }
env.taskset.id = "r2e-gym"
env.agent.harness.id = "rlm"
env.agent.runtime.labels = ["glm5-llmd"]
[inference]
enable_expert_parallel = true
# <0.80 because glm5 layers are too large for 0.85
gpu_memory_utilization = 0.75
enable_eplb = false
use_deep_gemm = true
enable_fp32_lm_head = true
[inference.model]
name = "zai-org/GLM-5.1-FP8"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
# Speed up GLM-5.1 weight load: EP weight filtering + safetensors prefetch.
[inference.vllm_extra]
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
# Mooncake distributed CPU KV store: 1TB/node shared pool across all inference nodes.
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
+15 -20
View File
@@ -3,7 +3,7 @@ seq_len = 131072
[log]
level = "debug"
[wandb]
[monitors.wandb]
project = "glm5-pd-disag"
[weight_broadcast]
@@ -23,10 +23,15 @@ type = "disaggregated"
prefill_nodes_per_replica = 4
decode_nodes_per_replica = 4
[inference.vllm]
model = "zai-org/GLM-5-FP8"
tool_call_parser = "glm47"
gpu_memory_utilization = 0.80
enable_expert_parallel = true
enable_eplb = false
[slurm]
job_name = "glm5-pd-disag"
[ckpt]
interval = 100
@@ -38,7 +43,6 @@ name = "zai-org/GLM-5"
impl = "custom"
attn = "flash_attention_2" # dsa is skipping flash attn anyway
fused_lm_head_token_chunk_size = 2048
optim_cpu_offload = true
ep = 8
[trainer.model.ac]
@@ -51,42 +55,33 @@ max_inflight_activations = 1
[trainer.ckpt]
skip_optimizer = true
skip_gather_master_weights = true
[trainer.optim]
type = "adamw"
lr = 1e-6
weight_decay = 0.1
[orchestrator]
batch_size = 4096
group_size = 16
oversampling_factor = 3
max_off_policy_steps = 16
[orchestrator.concurrency]
initial_inflight = 4096
max_inflight = 8192
[orchestrator.model]
name = "zai-org/GLM-5-FP8"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] } }
[[orchestrator.post_batch_filters]]
type = "gibberish"
enforce = true
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm5-pd-disag", "swe-bench-verified"]
[inference]
enable_expert_parallel = true
# we need <0.85 bc glm5 layers are too large for 0.85
gpu_memory_utilization = 0.80
enable_eplb = false
use_deep_gemm = true
[inference.model]
name = "zai-org/GLM-5-FP8"
tool_call_parser = "glm47"
+43 -31
View File
@@ -20,7 +20,7 @@ job_name = "swe-qwen30b"
[ckpt]
interval = 100
[wandb]
[monitors.wandb]
project = "intellect-3.1"
[trainer.model]
@@ -45,58 +45,70 @@ weight_decay = 0.01
[orchestrator]
batch_size = 2048
oversampling_factor = 2
[[orchestrator.train.env]]
[orchestrator.concurrency]
initial_inflight = 4096
max_inflight = 4096
[[orchestrator.train.source]]
name = "swe"
ratio = 0.3
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe"] } }
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
env.taskset.id = "r2e-gym"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["intellect-3.1", "swe"]
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "deepdive"
ratio = 0.2
env.taskset = { id = "deepdive-v1" }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] } }
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
env.taskset.id = "deepdive"
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.runtime.labels = ["intellect-3.1", "deepdive"]
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "math"
ratio = 0.3
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
env.taskset.id = "i3_math"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "logic"
ratio = 0.2
env.taskset = { id = "i3_logic_v1", filter = { max = 0.874 } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
env.taskset.id = "i3_logic"
env.taskset.filter.max = 0.874
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "code"
ratio = 0.2
env.taskset = { id = "i3_code_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
env.taskset.id = "i3_code"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] } }
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["intellect-3.1", "swe-bench-verified"]
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "aime2025"
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference.parallel]
tp = 8
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[inference.vllm]
tensor_parallel_size = 8
[orchestrator.renderer]
name = "default"
+14 -12
View File
@@ -20,7 +20,7 @@ job_name = "swe-minimax"
[ckpt]
interval = 100
[wandb]
[monitors.wandb]
project = "minimax-swe"
[trainer.model]
@@ -45,26 +45,28 @@ weight_decay = 0.01
[orchestrator]
batch_size = 2048
oversampling_factor = 2
max_off_policy_steps = 16
[orchestrator.concurrency]
initial_inflight = 4096
max_inflight = 4096
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "swe"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe"] } }
env.taskset.id = "r2e-gym"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["minimax-swe", "swe"]
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] } }
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["minimax-swe", "swe-bench-verified"]
[inference.parallel]
tp = 8
# PrimeIntellect/MiniMax-M2.5-bf16 — template-identical to MiniMaxAI/MiniMax-M2.5 (mapped).
[inference.vllm]
tensor_parallel_size = 8
[orchestrator.renderer]
name = "minimax-m2"
+26 -22
View File
@@ -18,10 +18,12 @@ num_train_nodes = 4
num_infer_nodes = 1
num_infer_replicas = 4
[wandb]
[monitors.wandb]
project = "nemotron-3-super"
name = "nemotron-3-super-swe"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -29,7 +31,8 @@ timeout = 3600
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[resume]
[model]
name = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
@@ -46,7 +49,6 @@ cp = 8
cp_style = "ulysses"
ep = 8
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
[trainer.model.ac]
@@ -56,7 +58,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
@@ -66,7 +67,10 @@ type = "adamw"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 1536
[orchestrator.concurrency]
initial_inflight = 1536
max_inflight = 1536
[orchestrator.algo]
type = "grpo"
@@ -81,30 +85,30 @@ num_turns_weight = 0.1
name = "nemotron-3"
truncate_history_thinking = false
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
[orchestrator.prime_monitor]
env.taskset.id = "scaleswe"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.runtime.labels = ["nemotron-3-super-swe"]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
env.agent.timeout = { rollout = 3600 }
env.taskset.id = "swebench-verified"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.runtime.labels = ["nemotron-3-super-swe"]
env.agent.timeout.rollout = 3600
[inference]
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
enable_prefix_caching = true
enable_expert_parallel = true
enable_return_routed_experts = true
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
enable_prefix_caching = true
[inference.model]
max_model_len = 131072
[inference.parallel]
tp = 8
+14 -10
View File
@@ -20,7 +20,7 @@ job_name = "math-qwen30b"
[ckpt]
interval = 100
[wandb]
[monitors.wandb]
project = "qwen30b-math"
[trainer.model]
@@ -42,24 +42,28 @@ lr = 1e-6
[orchestrator]
batch_size = 512
oversampling_factor = 2
max_off_policy_steps = 8
[orchestrator.concurrency]
initial_inflight = 1024
[orchestrator.train.sampling]
max_completion_tokens = 32768
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "math"
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "i3_math"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "aime2025"
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference.parallel]
tp = 8
[inference.vllm]
tensor_parallel_size = 8
+14 -10
View File
@@ -20,7 +20,7 @@ job_name = "swe-qwen30b"
[ckpt]
interval = 100
[wandb]
[monitors.wandb]
project = "qwen30b-swe"
[trainer.model]
@@ -43,21 +43,25 @@ lr = 1e-6
[orchestrator]
batch_size = 512
oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.train.env]]
[orchestrator.concurrency]
initial_inflight = 1024
[[orchestrator.train.source]]
name = "swe"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] } }
env.taskset.id = "r2e-gym"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["qwen30b-swe", "swe"]
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] } }
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["qwen30b-swe", "swe-bench-verified"]
[inference.parallel]
tp = 8
[inference.vllm]
tensor_parallel_size = 8
+11 -10
View File
@@ -9,7 +9,7 @@ type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[wandb]
[monitors.wandb]
project = "general-agent-debug"
name = "qwen3-30b-a3b-rlm"
@@ -35,16 +35,17 @@ batch_size = 512
group_size = 16
max_off_policy_steps = 32
[[orchestrator.train.env]]
env.taskset = { id = "general-agent-v1", task = { tools = { colocated = true } }, min_tier = 1 }
env.agent.harness = { id = "null", runtime = { type = "modal" } }
[[orchestrator.train.source]]
env.taskset.id = "general-agent"
env.taskset.min_tier = 1
env.taskset.task.tools.colocated = true
env.agent.harness.id = "null"
env.agent.runtime.type = "modal"
[inference]
gpu_memory_utilization = 0.85
[inference.model]
[inference.vllm]
max_model_len = 32768
[inference.parallel]
dp = 2
tp = 4
data_parallel_size = 2
tensor_parallel_size = 4
gpu_memory_utilization = 0.85
+18 -20
View File
@@ -1,6 +1,6 @@
# Alphabet Sort
In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to sort names alphabetically using LoRA. Unlike other examples, this task doesn't require SFT warmup as the base model already understands the conversation format. We proceed directly to multi-turn RL against the `alphabet-sort-v1` taskset.
In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to sort names alphabetically using LoRA. Unlike other examples, this task doesn't require SFT warmup as the base model already understands the conversation format. We proceed directly to multi-turn RL against the `alphabet-sort` taskset.
> This example runs on a single H100 GPU.
@@ -9,12 +9,13 @@ In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to sort na
The taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import alphabet_sort_v1"
uv run python -c "import alphabet_sort"
```
Start the tmux session:
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
```bash
bash scripts/tmux.sh
uv run dashboard
```
## Task
@@ -31,14 +32,14 @@ We use non-default settings to balance the difficulty: 3 fixed turns (instead of
Start the inference server:
```bash
# In the `Inference` pane
uv run inference --enable-lora --model.name Qwen/Qwen3-4B-Instruct-2507
# Run this in the inference terminal
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507
```
Evaluate the base model:
```bash
# In the `Trainer` pane
uv run eval alphabet-sort-v1 --harness.id null \
# Run this in the other terminal
uv run eval alphabet-sort --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
-n 20 \
@@ -91,17 +92,14 @@ We train with LoRA (rank 32, alpha 64) for 100 steps.
*Check out the logs on [W&B](https://wandb.ai/primeintellect/alphabet-sort-4b-lora/workspace?nw=nwuserandrewpi).*
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run rl @ examples/basic/alphabet-sort/rl.toml \
--wandb.project ... \
--wandb.name ...
--run.name rl \
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
This will write a weight checkpoint in `outputs/weights/step_100`. Upload it to HF to be able to use it as the final model for evaluation.
```bash
uv run hf upload <user>/Qwen3-4B-Instruct-AlphabetSort-RL outputs/weights/step_100
```
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_100`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL`](https://huggingface.co/PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL).
@@ -109,13 +107,13 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetS
Let's see how our final RL checkpoint performs on the eval set.
```bash
# In the `Inference` pane
uv run inference --enable-lora --model.name PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
# Run this in the inference terminal
uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
```
```bash
# In the `Trainer` pane
uv run eval alphabet-sort-v1 --harness.id null \
# Run this in the other terminal
uv run eval alphabet-sort --harness.id null \
-m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL \
--client.base-url http://localhost:8000/v1 \
-n 20 \
+8 -4
View File
@@ -7,7 +7,7 @@ seq_len = 2048
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
[monitors.wandb]
project = "alphabet-sort"
name = "alphabet-sort"
@@ -31,9 +31,13 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 768
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference] # Default inference config
+2 -2
View File
@@ -12,6 +12,6 @@ Schedule training locally on a node with 8 GPUs
```bash
uv run rl @ examples/basic/hendrycks-sanity/rl.toml \
--wandb.project your-project \
--wandb.name your-run
--monitors.wandb.project your-project \
--monitors.wandb.name your-run
```
+12 -10
View File
@@ -1,6 +1,6 @@
max_steps = 5000
[wandb]
[monitors.wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
@@ -16,27 +16,29 @@ batch_size = 512
group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "math-env"
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
env.taskset.dataset_subset = "default"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "aime2024"
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
group_size = 32
env.taskset.id = "aime24"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.model]
seq_len = 16384
[inference.model]
[inference.vllm]
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+33 -49
View File
@@ -1,33 +1,33 @@
# Reverse Text
We demonstrate how to train `Qwen3-0.6B` to reverse a small chunk of text. We will use a SFT warmup to learn the skill of text reversal on longer documents and then a quick RL run on the `reverse-text-v1` taskset. We use a similar setup in our CI and for development.
We demonstrate how to train `Qwen3-0.6B` to reverse a small chunk of text. We will use a SFT warmup to learn the skill of text reversal on longer documents and then a quick RL run on the `reverse-text` taskset. We use a similar setup in our CI and for development.
> The commands in this example were designed to be run on 2 GPUs (one trainer and one inference GPU). It is possible to run on less or more GPUs using different deployment strategies. If you run on a different setup, you may need to adjust the start commands.
## Setup
The `reverse-text-v1` taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
The `reverse-text` taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import reverse_text_v1"
uv run python -c "import reverse_text"
```
First, let's start a `tmux` session which we will use throughout the experiment.
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
```bash
bash scripts/tmux.sh
uv run dashboard
```
Let's check how well `Qwen3-0.6B` does out-of-the-box on the `reverse-text` environment.
```bash
# Run this in the `Inference` pane
uv run inference --model.name Qwen/Qwen3-0.6B
# Run this in the inference terminal
uv run inference --vllm.model Qwen/Qwen3-0.6B
```
```bash
# Run this in the `Trainer` pane
uv run eval reverse-text-v1 --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
# Run this in the other terminal
uv run eval reverse-text --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
This is of course just a quick vibe check and no full-fledged evaluation, but we can see that the model struggles with this task. In this specific instance, we got an **average reward of ~0.05** across the 20x3 rollouts. Let's do some training!
@@ -41,29 +41,26 @@ We will fine-tune `PrimeIntellect/Qwen3-0.6B` ([HF](https://huggingface.co/Prime
To train on a single GPU, run
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run sft @ examples/basic/reverse-text/sft.toml \
--wandb.project ... \
--wandb.name ...
--run.name sft \
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
To train on multiple GPUs, run
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run torchrun \
--local-ranks-filter 0 \
--nproc-per-node ... \
src/prime_rl/trainer/sft/train.py @ examples/basic/reverse-text/sft.toml \
--wandb.project ... \
--wandb.name ...
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
This should write a weight checkpoint in `outputs/weights/step_100`. Upload it to HF to be able to use it as the base model for RL.
```bash
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT outputs/weights/step_100
```
This should write a DCP checkpoint in `outputs/sft/checkpoints/step_100`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT).
@@ -74,18 +71,15 @@ For the RL we will only do 20 steps at 8x16 rollouts, for a total batch size of
*Check out the logs of the RL run on [W&B](https://wandb.ai/primeintellect/examples?nw=yxjwjc556do).*
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run rl @ examples/basic/reverse-text/rl.toml \
--model.name ... \
--wandb.project ... \
--wandb.name ...
--run.name rl \
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
This will write a weight checkpoint in `outputs/weights/step_20`. As before, let's upload it to HF.
```bash
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-RL outputs/weights/step_20
```
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_20`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL).
@@ -94,13 +88,13 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL`
Let's see how our final RL checkpoints perform on the `reverse-text` environment.
```bash
# Run this in the `Inference` pane
uv run inference --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
# Run this in the inference terminal
uv run inference --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
```
```bash
# Run this in the `Trainer` pane
uv run eval reverse-text-v1 --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
# Run this in the other terminal
uv run eval reverse-text --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
Way better! Now we get an **average reward of ~0.8**.
@@ -131,18 +125,8 @@ Exec into the trainer pod and run SFT:
```bash
kubectl exec -it my-exp-trainer-0 -- bash
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs
# This will save checkpoints to /data/outputs/weights/step_100
```
Upload the checkpoint to HuggingFace or use it directly from shared storage:
```bash
# Option 1: Upload to HuggingFace (from within the pod)
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT /data/outputs/weights/step_100
# Option 2: Use local checkpoint path in RL config
# Update the model.name in the RL configs to point to /data/outputs/weights/step_100
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs --run.name sft
# This will save DCP checkpoints to /data/outputs/sft/checkpoints/step_100
```
### Step 3: Deploy RL Training
@@ -210,11 +194,11 @@ kubectl exec -it my-exp-trainer-0 -- bash
# If inference server isn't running with the RL model, start it in another terminal:
kubectl exec -it my-exp-inference-0 -- bash
uv run inference --model.name /data/outputs/weights/step_20
uv run inference --vllm.model /data/outputs/weights_hf/step_20
# Back in trainer pod, run evaluation
uv run eval reverse-text-v1 --harness.id null \
-m /data/outputs/weights/step_20 \
uv run eval reverse-text --harness.id null \
-m /data/outputs/weights_hf/step_20 \
--client.base-url $INFERENCE_URL \
-n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
@@ -223,8 +207,8 @@ uv run eval reverse-text-v1 --harness.id null \
```bash
helm uninstall my-exp
# Optionally delete shared data:
kubectl delete pvc prime-rl-shared-data
# Optionally delete shared data. The PVC is named <release-name>-shared-data:
kubectl delete pvc my-exp-shared-data
```
**What the Helm chart provides:**
+5 -4
View File
@@ -4,7 +4,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
@@ -15,10 +15,11 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+21 -2
View File
@@ -8,7 +8,26 @@ name = "PrimeIntellect/Qwen3-0.6B"
[data]
name = "willcb/R1-reverse-wikipedia-paragraphs-v1-1000"
seq_len = 4096
batch_size = 32
batch_size = 32
[optim]
lr = 2e-5
lr = 2e-5
[eval]
interval = 25
num_examples = 32
[eval.sampling]
max_completion_tokens = 1024
[[eval.source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
+20 -22
View File
@@ -16,7 +16,7 @@ In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to answer
The taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import wiki_search_v1"
uv run python -c "import wiki_search"
```
Set up the credentials for the configured reference judge:
@@ -25,10 +25,10 @@ Set up the credentials for the configured reference judge:
export OPENAI_API_KEY=your_api_key_here
```
Start the tmux session:
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
```bash
bash scripts/tmux.sh
uv run dashboard
```
## Task
@@ -69,15 +69,15 @@ Key configuration highlights:
Start the inference server:
```bash
# In the `Inference` pane
uv run inference --enable-lora --model.name Qwen/Qwen3-4B-Instruct-2507 --model.tool_call_parser hermes
# Run this in the inference terminal
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507 --vllm.tool-call-parser hermes
```
Evaluate the base model:
```bash
# In the `Trainer` pane
uv run eval wiki-search-v1 --harness.id null \
# Run this in the other terminal
uv run eval wiki-search --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
-n 20 \
@@ -91,10 +91,11 @@ uv run eval wiki-search-v1 --harness.id null \
Train with the unified config file:
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run rl @ examples/basic/wiki-search/rl.toml \
--wandb.project your-project-name \
--wandb.name your-run-name
--run.name rl \
--monitors.wandb.project your-project-name \
--monitors.wandb.name your-run-name
```
The unified config file automatically configures:
@@ -102,24 +103,20 @@ The unified config file automatically configures:
- **Orchestrator**: Rollout generation with tool calling enabled
- **Inference**: vLLM server for Qwen3-4B-Instruct-2507 with tool parsing enabled
This will write weight checkpoints in `outputs/weights/step_*`. Upload the final checkpoint to HuggingFace:
```bash
uv run hf upload <user>/Qwen3-4B-Instruct-WikiSearch-RL outputs/weights/step_500
```
This will write DCP checkpoints in `outputs/rl/checkpoints/step_*`.
## Evaluation
Evaluate your trained model:
```bash
# In the `Inference` pane
uv run inference --enable-lora --model.name <user>/Qwen3-4B-Instruct-WikiSearch-RL --model.tool_call_parser hermes
# Run this in the inference terminal
uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSearch-RL --vllm.tool-call-parser hermes
```
```bash
# In the `Trainer` pane
uv run eval wiki-search-v1 --harness.id null \
# Run this in the other terminal
uv run eval wiki-search --harness.id null \
-m <user>/Qwen3-4B-Instruct-WikiSearch-RL \
--client.base-url http://localhost:8000/v1 \
-n 20 \
@@ -133,10 +130,11 @@ uv run eval wiki-search-v1 --harness.id null \
The V1 taskset fixes the question bank and searchable corpus. You can replace its reference judge in `rl.toml`:
```toml
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wiki-search"
taskset = { id = "wiki-search-v1", task = { judges = [{ id = "reference", model = "openai/gpt-5.4-nano" }] } }
harness = { id = "null", runtime = { type = "subprocess" } }
taskset = { id = "wiki-search", task = { judges = [{ id = "reference", model = "openai/gpt-5.4-nano" }] } }
harness = { id = "null" }
runtime = { type = "subprocess" }
```
## Notes
+10 -11
View File
@@ -8,7 +8,7 @@ num_infer_gpus = 6
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
[monitors.wandb]
project = "wiki-search"
name = "wiki-search"
@@ -32,24 +32,23 @@ target_modules = [
[orchestrator]
batch_size = 512
group_size = 16
oversampling_factor = 2.0
[orchestrator.concurrency]
initial_inflight = 1024
[orchestrator.model.lora]
name = "qwen3-4b-wiki-search"
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
env.taskset.id = "wiki-search"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # Checkpoint at the end of training
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
+25 -31
View File
@@ -1,6 +1,6 @@
# Wordle
In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This will require a SFT warmup to learn the format and, finally, multi-turn RL against the `wordle-v1` taskset to improve performance.
In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This will require a SFT warmup to learn the format and, finally, multi-turn RL against the `wordle` taskset to improve performance.
> The commands in this example were designed to be run on 2 GPUs (one trainer and one inference GPU). It is possible to run on less or more GPUs using different deployment strategies. If you run on a different setup, you may need to adjust the start commands.
@@ -9,27 +9,27 @@ In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This w
The taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import wordle_v1"
uv run python -c "import wordle"
```
Start the pre-layouted `tmux` session which we will use to run all experiments and view logs conveniently
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
```bash
bash scripts/tmux.sh
uv run dashboard
```
Before training, we want to get a baseline score and test how well `Qwen3-1.7B` does out-of-the-box in the `wordle` environment so that we quantify our training effect. To do so, first start a local inference server to serve `Qwen3-1.7B`.
```bash
# Run this in the `Inference` pane
uv run inference --model.name Qwen/Qwen3-1.7B
# Run this in the inference terminal
uv run inference --vllm.model Qwen/Qwen3-1.7B
```
Then, use the `eval` entrypoint to evaluate the model in the `wordle` environment. We evaluate on the 20 evaluation examples which are distinct words not appearing in the training set of the environment. We constrain the response length to 1024 tokens as this should be more than enough to play a full game.
```bash
# Run this in the `Trainer` pane
uv run eval wordle-v1 --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
# Run this in the other terminal
uv run eval wordle --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
We got an **average reward of ~0.2** across the 20x3 rollouts. From the summary, we can see that the most of the reward is coming from format and partial rewards. In fact, the model does not guess the correct word within any game, leading to a win rate of **0%**. Looking at some samples, it is evident repeatedly submitting guesses in the wrong format and is not able to revise its strategy from the environment feedback. Let's do some SFT warmup to get the model to learn the format of the environment.
@@ -43,29 +43,26 @@ We will fine-tune `PrimeIntellect/Qwen3-1.7B` ([HF](https://huggingface.co/Prime
To train on a single GPU, run
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run sft @ examples/basic/wordle/sft.toml \
--wandb.project ... \
--wandb.name ...
--run.name sft \
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
To train on multiple GPUs, run
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run torchrun \
--local-ranks-filter 0 \
--nproc-per-node ... \
src/prime_rl/trainer/sft/train.py @ examples/basic/wordle/sft.toml \
--wandb.project ... \
--wandb.name ...
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
After training completes, you will find the final weight checkpoint in `outputs/weights/step_20`. Upload it to HF to be able to use it as the base model for RL we will do in the next section.
```bash
uv run hf upload <user>/Qwen3-1.7B-Wordle-SFT outputs/weights/step_20
```
After training completes, you will find the final DCP checkpoint in `outputs/sft/checkpoints/step_20`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-SFT).
@@ -77,18 +74,15 @@ Finally, we will do multi-turn RL against the `wordle` environment using the mod
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run rl @ examples/basic/wordle/rl.toml \
--model.name ... \
--wandb.project ... \
--wandb.name ...
--run.name rl \
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
This will write a weight checkpoint in `outputs/weights/step_100`. As before, let's upload it to HF.
```bash
uv run hf upload <user>/Qwen3-1.7B-Wordle-RL outputs/weights/step_100
```
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_100`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-RL).
@@ -97,13 +91,13 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](http
Let's see how our final RL checkpoint performs on the eval set.
```bash
# Run this in the `Inference` pane
uv run inference --model.name PrimeIntellect/Qwen3-1.7B-Wordle-RL
# Run this in the inference terminal
uv run inference --vllm.model PrimeIntellect/Qwen3-1.7B-Wordle-RL
```
```bash
# Run this in the `Trainer` pane
uv run eval wordle-v1 --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
# Run this in the other terminal
uv run eval wordle --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
Way better! Our model now wins **~60%** and gets an average reward of **~1.5**.
+7 -8
View File
@@ -5,7 +5,7 @@ seq_len = 8192
num_train_gpus = 2
num_infer_gpus = 6
[wandb]
[monitors.wandb]
project = "wordle"
name = "wordle"
@@ -18,19 +18,18 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
env.taskset.id = "wordle"
env.player.harness.id = "null"
env.player.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer] # Default trainer config
[inference.parallel]
dp = 6
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
[inference.vllm]
data_parallel_size = 6
[orchestrator.renderer]
name = "prime-qwen3"
+32
View File
@@ -0,0 +1,32 @@
# Standalone SWE evals: SWE-bench Verified + Terminal-Bench 2, one epoch each,
# against DeepSeek V4 Flash on Prime Inference.
#
# export PRIME_API_KEY=<your Prime Inference key>
# uv run evals @ examples/evals/swe.toml
#
# The tasksets run in prime sandboxes (the default runtime), so the key also
# authenticates sandbox creation. External API endpoints expose no vLLM
# /metrics, so adaptive concurrency has no load signal - the band must be
# pinned (min_inflight = max_inflight) or the evals process refuses to start.
model = "deepseek/deepseek-v4-flash"
[eval.client]
base_url = "https://api.pinference.ai/api/v1"
api_key_var = "PRIME_API_KEY"
[eval.concurrency]
min_inflight = 32
max_inflight = 32
[[eval.source]]
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
[[eval.source]]
name = "terminal-bench-2"
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600

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