Compare commits

...
Author SHA1 Message Date
minh hoangandGitHub 96fa737c35 fix(docker): keep the editable verifiers when installing the prime CLI (#3705)
## Summary

Published prime-rl images since #3635 (2026-09-22) ship the PyPI
`verifiers==0.2.0` wheel instead of the submodule editable, and the
orchestrator and env-server entrypoints fail at import as a result. This
installs the prime CLI with its verifiers requirement overridden so the
editable stays, and asserts that at build time.

## What's wrong

`Dockerfile.cuda` installs the prime CLI after the lockfile sync (`uv
pip install 'prime>=0.7'`). Every prime release since 0.6.30 (prime#879,
2026-08-31) pins `verifiers==0.2.0`, so that install uninstalls the
editable verifiers (0.3.x, pretend version `0.3.2.dev137`) and replaces
it with the 0.2.0 wheel. Observed on a pristine `v0.9.1.dev128` pod on
telus:

```
$ uv run --no-sync orchestrator --help
  File ".../prime_rl/configs/orchestrator.py", line 160, in EnvConfig
    env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
AttributeError: module 'verifiers.v1' has no attribute 'SingleAgentEnvConfig'

$ uv run --no-sync env-server --help
  File ".../prime_rl/entrypoints/env_server.py", line 9, in <module>
    from verifiers.v1.runtimes import set_base_sandbox_labels
ImportError: cannot import name 'set_base_sandbox_labels' from 'verifiers.v1.runtimes'
```

`uv pip check` on the image reports 107 incompatibilities, all `...
requires verifiers>=0.3.1, but 0.2.0 is installed`.

Runs that install a Hub env at pod start survive by accident: `prime env
install` pulls an env that requires `verifiers>=0.3.1`, which drags
verifiers 0.3.x from PyPI back in before the orchestrator imports it.
Runs on baked envs get no such repair. The nightly FFT configs are all
baked envs, and nightly FFT has failed every day since 9/24.

An older CLI is not an option: the last release without the pin (0.6.29)
needs a prime-sandboxes API that 0.3.0 removed, and prime-rl itself
requires `prime-sandboxes>=0.3.0`.

## Fix

- Install the CLI with `--overrides` on a one-line file containing
`verifiers`, so its `verifiers==0.2.0` requirement is ignored and the
editable is left alone. Everything else the CLI needs (prime-traces,
prime-sandboxes, openai, …) still installs as before.
- Assert in the same `RUN` that `verifiers` imports from
`/app/deps/verifiers`, so a regression fails the build rather than the
orchestrator.
- **This is a workaround, marked `FIXME(prime#940)` in the Dockerfile.**
The real fix is the prime CLI dropping verifiers as a dependency,
PrimeIntellect-ai/prime#940. Once that ships, remove the overrides file
and the `--overrides` flag here and in `scripts/docker-entrypoint.sh` on
#3686, which replays this step with the same override for the runtime
source overlay. Keep the import assertion.

## Verified

- The override was exercised on telus pods against the
`v0.9.1.dev127-4-gba81f7c5b-feat-runtime-source-overlay` image (whose
entrypoint runs the identical command after re-syncing the editables):
verifiers stays at `0.3.2.dev137` from `deps/verifiers`, `prime
--version` and `uv run --no-sync prime env install
primeintellect/wordle` work, `orchestrator --help` and `env-server
--help` start, `uv pip check` drops from 107 incompatibilities to 7 (six
pre-existing lockfile inconsistencies plus the intentional `prime
requires verifiers==0.2.0`). A full hosted run (reverse-text, 20 steps)
completed on that venv.
- This Dockerfile change itself: image build dispatched from this
branch, result below.

Build from this branch: dispatched, result pending.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes Docker venv composition for a dependency that prime-rl
entrypoints rely on; mitigated by a build-time import-path assertion,
but image builds and baked-env runs depend on the override staying
correct.
> 
> **Overview**
> Published CUDA images broke **orchestrator** and **env-server**
because installing `prime>=0.7` after `uv sync` pulled PyPI
`verifiers==0.2.0` over the repo’s editable under `deps/verifiers`
(0.3.x APIs).
> 
> The **prime CLI install step** in `Dockerfile.cuda` now writes a
one-line `uv pip install --overrides` file (`verifiers`) so the CLI’s
pinned verifiers requirement is ignored while other CLI deps still
install. A **build-time assert** checks `verifiers` resolves under
`/app/deps/verifiers`. Comments mark this as a temporary
**FIXME(prime#940)** until the CLI drops verifiers; the entrypoint
overlay in `scripts/docker-entrypoint.sh` is called out as needing the
same cleanup later.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
22c9bfd1c9907da4662665f225ca10c3cdf6a930. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-27 16:53:54 -07:00
35aa06fbfa feat(eval): allow any config override on resume (#3690)
## Summary

`uv run eval --resume` used to compare the resolved config against the
interrupted attempt's `eval.json`. It refused any change outside a short
allowlist, which left out the solver `model`, everything under
`source.*.env` (including where each judge is served) and
`tasks_per_minute`. So a paused eval couldn't move to a new endpoint
serving the same weights under another name, such as a self-hosted
router becoming a hosted API. The only way out was `--clean`.

This PR removes that validation (`RESUMABLE`, `config_diff`,
`check_config`, `previous_config`), so any field can be overridden on
resume. It's up to whoever resumes to keep the measurement consistent.
The resolved config is still written beside each attempt's episodes
(`stamp_config`), so every attempt records what it ran with.
`docs/eval.md` still says a resume that changes the model, sampling or
env stops with the differing paths. That's no longer true and needs a
follow-up.

## Test plan

- Removed the tests for the deleted functions. `pytest tests/unit/eval`
passes (7 tests).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Resume can now mix previously landed episodes with a different model,
sampling, or env configuration, which can invalidate eval comparability
if operators override carelessly.
> 
> **Overview**
> **`uv run eval --resume` no longer compares the new resolved config to
the interrupted attempt's stamped `eval.json`.** The allowlist-based
guard (`RESUMABLE`, `config_diff`, `check_config`, `previous_config`) is
removed, so fields like model, sampling, env/judge endpoints, and source
layout can all change when resuming instead of forcing `--clean`.
> 
> Resume still loads landed episodes from the trace stream and stamps
the current config per attempt via `stamp_config`; only the validation
step in `Eval.run` is dropped. Module docs now state that **any config
may be overridden** and consistency is the operator's responsibility.
> 
> Unit tests for config checking and `previous_config` lookup were
removed; remaining resume tests (`plan`, `take_landed`, trigger
integration) are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
06482534d862782e1a844ea9f8d5c3f5c37310ac. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 14:43:05 -07:00
718635b2ca feat: treat timed-out rollouts as their own outcome (#3702)
## Summary

Companion to PrimeIntellect-ai/verifiers#2693, which stops a rollout
whose stage deadline expires as `<stage>_timeout` with
`Trace.is_timeout` set (scored, not errored).

- Training keeps main's semantics: the dispatcher records a `Timeout`
error on a timed-out train trace, so it stays out of the batch and
counts under `has_error`. Eval keeps the timeout as a scored outcome.
- Metrics: `is_timeout` joins the trace rates
(`<scope>/{all,effective}/<agent>/is_timeout/mean`) next to
`is_truncated`; `EpisodeMetrics.is_timeout` over the full cohort feeds
the console summary lines (`... | Truncation 0.0% | Timeout 100.0%`) for
train, online eval and standalone eval.
- W&B overview and dashboard metric sections plot
`all/<agent>/is_timeout/mean`.
- Trace index rows carry `timeout` (the episode's `is_timeout` or any
trace's); the dashboard series expose it.
- Dashboard: yellow (`--timeout`) marks for timed-out episodes on the
overview tile (`timeout rate`), episode cells, swarm points,
timing/token strips, episode table rows (with a `timed out (<stop>)`
title), trace tabs and the timeline state; the trace meta panel shows
`is_timeout`.
- Dispatcher: a timed-out eval trace with zero turns stays a timeout
instead of being promoted to an `EmptyTrajectory` error; it is scored
and counted under `is_timeout`.
- Bumps `deps/verifiers` to verifiers `main` with #2693 merged.

## Breaking

- In evals, a rollout that hits its `timeout.rollout` (or
setup/finalize/scoring) budget no longer counts under `has_error`: it
lands `ok` with `stop_condition = "<stage>_timeout"`, is scored, and
enters the `effective` subset like a truncated rollout does. Training is
unchanged: a timed-out rollout is still an error (now typed `Timeout`,
with `is_timeout` set alongside).

## Verification

Ran off this branch with the verifiers companion on `PYTHONPATH`:

```
uv run eval gsm8k -n 4 -r 1 -c 4 -m alibaba/qwen3.5-flash --env.agent.harness.id null --env.agent.runtime.type subprocess --env.agent.timeout.rollout 2
```

Before the dispatcher change: `Error 100.0% | Truncation 0.0% | Timeout
0.0%`, every trace re-labelled `EmptyTrajectory`. After: `Error 0.0% |
Truncation 0.0% | Timeout 100.0%`, metrics `is_timeout/mean = 1.0`,
`stop_condition/agent_timeout = 1.0`, index rows `ok=true,
stop_condition=agent_timeout, timeout=true`. A control run with the
default budget lands `agent_completed`, `timeout=false`, `Timeout 0.0%`.

Dashboard driven headlessly with playwright against both runs: `timeout
rate` tile `100%` in `rgb(255, 209, 102)`, every episode cell/row class
`timeout`, rows titled `timed out (agent_timeout)`, trace meta
`is_timeout true` / `ok true`; the control run shows `0%` and no marks;
no page errors.

`tests/unit/orchestrator`, `tests/unit/eval` and
`tests/unit/test_dashboard_timeline.py` pass.


## Screenshots

Eval with `--env.agent.timeout.rollout 2`: the overview tile and episode
cells read yellow, the traces table marks each row's edge yellow, and
the trace viewer lists the timed-out episodes with `is_timeout true` /
`ok true`.


![overview](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/assets/is-timeout/timeout-2s-overview.png)

![traces](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/assets/is-timeout/timeout-2s-traces-table.png)
![trace
viewer](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/assets/is-timeout/timeout-2s-traces.png)

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Eval cohort semantics change (timeouts move off `has_error` onto
`is_timeout`), and the dispatcher path that promotes empty trajectories
to errors now explicitly exempts timed-out eval traces—worth validating
against downstream dashboards and monitors that assumed timeouts were
errors.
> 
> **Overview**
> Rollouts that hit a stage deadline (`<stage>_timeout`) are now a
**distinct outcome** from errors and truncation, with **`is_timeout`**
tracked alongside **`is_truncated`** in orchestrator metrics, console
summaries, W&B/dashboard metric panels, and docs.
> 
> **Training vs eval:** On **train**, the dispatcher still drops
timed-out traces from the batch by attaching a **`Timeout`** error and
marking the trace **`ok=false`** (same exclusion as before, now typed).
On **eval**, timeouts stay **`ok`** and scored; zero-turn timeout traces
are no longer relabeled as **`EmptyTrajectory`** errors.
> 
> **Observability:** Trace index rows and eval series expose
**`timeout`**; the dashboard uses yellow styling for timeout rate,
episode cells, swarm dots, tables, timeline state, and trace meta
**`is_timeout`**. Eval success logs and standalone eval runner output
add a **Timeout** percentage next to truncation/error.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
83c0ce4c920aa0fb55eea97c251db18ec763053f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 13:12:08 -07:00
f557d7593f feat: shared env block for train and eval sources (#3695)
## Summary

- **Group `env` block**: `[orchestrator.train]`, `[orchestrator.eval]`,
the `[eval]` block of `sft`, and the top level of `uv run eval` each
take an `env` block. Every source of the group inherits it through
`vf.merge_env_defaults`, and a source's own `env` values win.
- **Only shared knobs**: the block is typed as `vf.SharedEnvConfig`. It
takes `retries`, `timeout`, `max_concurrent_agents`, `interception`,
`taskset.task`, and `taskset.system_prompt`. Env ids, taskset ids, and
agent roles stay on each source and are rejected in the group block. So
one group can mix single-agent and multi-agent envs.
- **Eval shorthands**: `<taskset-id>` and `--env.<field>` keep their
single-source meaning. Next to a TOML that defines `[[source]]` blocks,
`--env.<field>` now sets the shared block instead of erroring, e.g. `uv
run eval @ sources.toml --env.retries.max-retries 3`.
- Pin `deps/verifiers` to the merged
[verifiers#2690](https://github.com/PrimeIntellect-ai/verifiers/pull/2690),
which adds `SharedEnvConfig` and `merge_env_defaults`. Raise the
`verifiers` minimum to `0.3.2.dev143`, its first release, in both
`pyproject.toml` files, so the slim `prime-rl-configs` install gets it.
- Update `docs/eval.md` and `docs/configuration.md`.

## Verification

- Composed `configs/basic/reverse-text/rl.toml` with an overlay that has
two train and two eval sources. Each group's `env` block sets
`retries.max_retries`, `retries.include`, `timeout.episode`,
`max_concurrent_agents`, and `taskset.system_prompt`. One source per
group overrides `retries.include` and `timeout.episode`. The other
source got every group value. The overriding source kept its two values
and inherited the rest. The same held after re-validating the resolved
`OrchestratorConfig` dump.
- Repeated the check with the same blocks in a `uv run eval` TOML, plus
a `proposer-solver` source. The multi-agent source inherited the shared
values and kept its `proposer` settings. The resolved `eval.json`
re-validates to the same dump.
- `--env.retries.max-retries 5 --env.retries.include A B` next to that
TOML reached every source, except that the overriding source kept its
own `include`.
- A group block with `id`, `agent.*`, `taskset.id`, or a misspelled
field fails with one error at `env.*`.
- `uv run eval gsm8k --env.agent.harness.id bash --env.taskset.split
test` still configures the single source.
- `pytest tests/unit/eval tests/unit/test_configs.py`: 202 passed.
- Built the `prime-rl-configs` wheel and installed it in a clean venv,
as the slim-install job does. It resolved `verifiers 0.3.2.dev143`, and
the configs imported with no heavy deps.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how train/eval env configs are merged at parse time, so
misconfigured shared blocks or invalid shared-only fields could affect
every source in a group; scope is config/CLI rather than training logic
itself.
> 
> **Overview**
> Adds a **group-level `[env]` block** on orchestrator train/eval source
groups (and standalone eval) so shared knobs—retries, timeouts,
concurrency caps, interception, shared taskset fields—apply to every
source, with per-source `env` still winning on conflict. Config
validation layers defaults through `merge_group_env` and verifiers’
`SharedEnvConfig` / `merge_env_defaults`.
> 
> **Eval CLI behavior** changes for multi-source TOMLs: `--env.*` now
targets the shared block instead of being rejected (single-source
`<taskset-id>` shorthands are unchanged and still cannot mix with
`[[source]]` TOMLs). Docs and unit tests cover the new TOML shape and
shorthand routing.
> 
> Pins **verifiers** to `>=0.3.2.dev143` in the root and
`prime-rl-configs` packages (lockfile updated).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8aef01e0cdd6baaf1275e06f33bf0091c548913a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 13:02:01 -07:00
f87fd0eb33 fix(examples): set group_size=8 in GRPO recipes (#3693)
## Summary

- Set `orchestrator.group_size = 8` in the INTELLECT-3.1 and Qwen3
math/SWE standalone RL examples.
- Prevent GRPO's default group size of 1 from giving every rollout a
zero group-relative advantage.
- Keep existing explicit group sizes, including GLM base configs used by
overlays.

## Verification

- Parsed each changed TOML through `RLConfig.model_validate`; all three
resolve to group size 8 for every train source.
- `git diff --check` passed.

Co-authored-by: Konstantin Dunas <git@hallerite.com>
2026-09-27 00:27:04 -07:00
Mika SenghaasandGitHub 12001f3167 fix: update eval dependency pins (#3694)
## Summary

- Pin verifiers to `6a82e5d`, which includes the [Bash/Null certifi
fix](https://github.com/PrimeIntellect-ai/verifiers/pull/2614) and the
[nano-rlm certifi
pin](https://github.com/PrimeIntellect-ai/verifiers/pull/2688).
- Pin prime-envs to `647ff7a`, which includes the [GPQA judge
fix](https://github.com/PrimeIntellect-ai/prime-envs/pull/845), [DeepSWE
missing-test
scoring](https://github.com/PrimeIntellect-ai/prime-envs/pull/847), and
[Apex Compose host
images](https://github.com/PrimeIntellect-ai/prime-envs/pull/842).
- Refresh `uv.lock`. Exclude `tau2-bench` from the shared workspace
because its new Tau2 dependency requires LiteLLM below 1.82.7, while
Harbor requires 1.92.0 or newer.

## Breaking

- `uv sync --all-packages` no longer installs `tau2-bench`. Install and
run it in a separate environment until its Tau2 and Harbor LiteLLM
requirements can share one lock.

## Verification

- `uv lock --check` and `uv sync --all-packages --all-extras --locked
--dry-run --quiet` passed.
- The five-source Intellect 4 GLM-5.3 eval composition resolved with the
intended model, max reasoning effort, harnesses, group sizes, and
rollout timeouts.
- `uv run --no-sync eval @ configs/debug/eval/multi-env.toml --dry-run`
passed.
- `uv run --no-sync rl @ configs/basic/wordle/rl.toml --dry-run` passed.
- A one-task `pi-terminal-bench-2` financial-document rollout on
`internal/glm-5.3-fast` completed with reward 1.0, 55 turns, and 0.0%
error.
- `git diff --check` passed.

Apex remains excluded from prime-rl's shared workspace because it pins a
separate verifiers git revision. Its new Compose host images still need
an Intellect 4 rollout check before Apex rejoins that suite.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking for anyone relying on `uv sync --all-packages` to install
`tau2-bench`; they must use a separate environment until LiteLLM
constraints align.
> 
> **Overview**
> **`tau2-bench` is removed from the shared `uv` workspace** so `uv sync
--all-packages` can keep Harbor’s **`litellm>=1.92.0`** without fighting
Tau tasksets’ **`litellm<1.82.7`**. The workspace **`exclude`** list now
includes `deps/prime-envs/environments/tool_use/tau2_bench`, and the
comment documents that split (alongside the existing Apex / tau2_synth /
tau3 exclusions).
> 
> **`uv.lock` is refreshed** accordingly: `tau2-bench` and the git
**`tau2`** package drop out of the lock, along with their former
transitive stack (e.g. gymnasium, matplotlib, langfuse, redis). Several
editable prime-envs packages show **patch version bumps** in the lock
(Lean/math envs, `gpqa`, `lean-common`, etc.) as part of the same
dependency refresh.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5f1504314e8e97d8e8bae5ebc49381cc30822106. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-26 22:43:55 -07:00
1cf683267d chore: drop CLAUDE.md in favor of native AGENTS.md (#3691)
## Summary

- Delete `CLAUDE.md`. It only imported `@AGENTS.md`, and Claude Code
reads `AGENTS.md` natively since v2.1.277
([docs](https://code.claude.com/docs/en/memory.md#agents-md)).
- Update the skills line in `AGENTS.md` to name both the
`.claude/skills` (Claude Code) and `.agents/skills` (Codex) symlinks.
Neither tool reads the other's skills folder, so both symlinks stay.

## Breaking

- Claude Code sessions older than v2.1.277 read only `CLAUDE.md`, so
they no longer load the repo instructions. On Bedrock or with telemetry
disabled, the minimum is v2.1.281. Migration: update Claude Code.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation-only agent config changes with no runtime or application
code impact; the only caveat is older Claude Code versions losing loaded
instructions.
> 
> **Overview**
> Removes **`CLAUDE.md`**, which only re-exported **`AGENTS.md`** via
`@AGENTS.md`, so agent instructions live in a single file now that
Claude Code reads **`AGENTS.md`** natively.
> 
> The **Skills** section in **`AGENTS.md`** now documents both symlink
targets: **`.claude/skills/`** for Claude Code and **`.agents/skills/`**
for Codex, since each tool only loads its own folder.
> 
> **Breaking:** Claude Code builds before native **`AGENTS.md`** support
(v2.1.277+, v2.1.281+ on Bedrock/telemetry-off) no longer pick up repo
instructions unless upgraded.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
205ca092421609d40c938a16c78a75051c67ec2e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 18:59:04 -07:00
Xuan-Phi NguyenandGitHub b944873248 fix(trainer): measure MoE violation per EP group and microstep (#3684)
## Summary

`max_vio` is intended to capture the largest expert routing violation
for each training microbatch across an entire EP group. The metric uses
expert token counts, not the number of tokens allocated to an EP rank.
For each microbatch, we take the maximum across MoE layers and EP
groups; `max_vio/mean` and `max_vio/max` then summarize those microbatch
maxima within the logged optimizer step.

### Why the old numbers depended on topology

The router records selections for every expert on each rank before
dispatch, but the original `get_load_balance_stats` computed violation
from that rank's **local** counts. With CP, each rank sees only a
sequence shard. At fixed EP, changing CP or DP changes the local token
population and the number of rank readings. SFT averaged layer
violations locally, took a world maximum, and averaged it over gradient
accumulation; RL's `/mean`, `/median`, `/std`, and `/max` summarized all
local layer/rank/microbatch readings. Those reductions did not describe
one EP group's routed traffic, so equal EP degrees could report
substantially different values.

### What changed

- Sum per-expert token counts and routing-confidence sums within the EP
group **before** computing per-layer violation and confidence. Reset
both buffers after reading them. Remove the unused `reset_stats` and
`try_to_avoid_padding_experts` switches while keeping their previous
default behavior.
- In RL and SFT, read routing statistics after **each microbatch**
through the shared `get_global_moe_stats` helper. Take the maximum
violation across layers, then across the `dp_cp` mesh. This preserves a
short-lived imbalance instead of pooling counts across microbatches.
- Aggregate those per-microbatch global maxima into `max_vio/mean` and
`max_vio/max` for each optimizer step. RL also retains the other
distribution statistics supplied by `Tensors.compute_stats`; SFT now
publishes `/max` alongside `/mean`.
- Clear SFT validation routing buffers before the next training step.

### Validation: same EP, more trainer replicas

These RL runs used Qwen3-30B-A3B-Thinking-2507, EP=4, CP=1, sequence
length 32,768, group size 8, and learning rate 1e-6. The experiment
configs were temporary; the tracked `math.toml` is restored and
`math2.toml` is not included in this PR.

| Run | Topology | `orchestrator.batch_size` | Average `max_vio/mean` |
Average `max_vio/max` |
| --- | --- | ---: | ---: | ---: |
|
[math1-v1](https://wandb.ai/primeintellect/qwen30b-math/runs/a2da2577b6c54320bc1d997022b0ebe7)
| 8 GPUs total: 4 train + 4 inference; one EP group, `dp_replicate=1` |
16 | 6.7774 | 7.7035 |
|
[math2-v1](https://wandb.ai/primeintellect/qwen30b-math/runs/d69f377a0cb5425b99b455e6c8101118)
| 16 GPUs total: 8 train + 8 inference; two EP groups, `dp_replicate=2`
| 32 | 6.8707 | 7.7897 |

Values are arithmetic averages of the logged metrics over the **shared
steps 1–99**, read from W&B. The two-group run is 1.38% higher on
`/mean` and 1.12% higher on `/max`. Its rollouts are different, so this
is a comparability check, not a paired-input equality test. This
comparison does not exercise CP. The shared-helper refactor followed
these runs and preserves their reduction arithmetic.

Relative to the original `examples/advanced/qwen3-30b-a3b/math.toml`,
the experiments used:

- **Math1:** single-node deployment with 4 train and 4 inference GPUs
instead of 2 train and 2 inference nodes; EP 4 instead of 8;
`orchestrator.batch_size` 16 instead of 512; inference TP 4 instead of
8.
- **Math2:** 1 train and 1 inference node instead of 2 each; EP 4
instead of 8; `dp_replicate=2`; `orchestrator.batch_size=32` instead of
512; inference TP 4 and DP 2 instead of TP 8. Its Slurm job name was
`math2-qwen30b` instead of `math-qwen30b`.
- **Both:** added `max_steps=400`, `orchestrator.group_size=8`, Slurm
partition `all`, and a run-specific `VLLM_CACHE_ROOT`; changed
`orchestrator.concurrency.initial_inflight` from 1024 to 64 and added
`max_inflight=128`. Other settings followed the original config.

### Remaining topology effects

At fixed EP, equal violation readings are not guaranteed. For
fixed-length packed SFT, the per-microbatch token population in one EP
group is `micro_batch_size × (EP / CP) × seq_len`. Increasing CP makes
that population smaller, and the relative count imbalance noisier,
unless `micro_batch_size` scales with CP. Increasing trainer nodes at
fixed EP creates more EP groups (`trainer_world_size / EP`); taking the
maximum over more groups tends to raise both logged `/mean` and `/max`
slightly through an order-statistics effect. With fixed CP and global
SFT batch size, adding DP ranks also reduces gradient accumulation steps
and the number of microbatch samples in each logged step.

For a stricter fixed-EP comparison, keep tokens per microbatch per EP
group constant (`micro_batch_size` proportional to CP) and scale the
global batch size with trainer world size. For example, double batch
size when trainer world size doubles, whether the added ranks come from
DP or CP. RL can still vary with actual sequence lengths and rollout
contents.

Checks: `uv run --no-sync pytest tests/unit/train/models/test_moe.py -q`
(15 passed), `ruff check`, `ruff format --check`, and `git diff --check`
passed for the PR changes.
2026-09-26 10:11:07 -07:00
c28afbbae2 fix: keep workstation blackwell on fa2 in auto-attn (#3681)
## Summary

- Gate `attn='auto'` → FA4 on SM10x/SM11x (`major in (10, 11)`) instead
of `major >= 10`. FA4's own interface uses the same families for its
native tcgen05/TMEM Blackwell path.
- B200/GB200 (SM100) and B300/GB300 (SM103) keep FA4, so the goal of
#3655 stays intact. Hopper keeps FA3.
- Workstation Blackwell (SM12x, e.g. RTX PRO 6000) resolves to FA2
again. #3655 sent it to FA4 as a side effect.
- Update the `attn` comment in `docs/scaling.md`.

| GPU | CC | `attn: auto` |
|---|---|---|
| H100/H200 | SM90 | FA3 |
| B200/GB200 | SM100 | FA4 |
| B300/GB300 | SM103 | FA4 |
| RTX PRO 6000 | SM120 | FA2 (main: FA4) |

## Verification

5 steps of `configs/ci/integration/reverse-text/start.toml` on 2x RTX
PRO 6000 (SM120), same venv (vllm 0.29):

**Before (main `b963ceda3`)**: `Auto-resolved attn='auto' to
'flash_attention_4' (SM120)`
```
Step 1 | Mismatch KL 0.2967 | Grad. Norm nan
Step 2 | Loss nan | Entropy nan | Mismatch KL nan | Grad. Norm nan   (run then stalls: NaN weights reach inference)
```

**After (this branch)**: `Auto-resolved attn='auto' to
'flash_attention_2' (SM120)`
```
Step 1 | Mismatch KL 0.0008 | Grad. Norm 0.8843 | Reward 0.19
Step 3 | Mismatch KL 0.0012 | Grad. Norm 0.8779 | Reward 0.15
Step 5 | Mismatch KL 0.0013 | Grad. Norm 1.6303 | Reward 0.46
Training finished!
```

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Small, targeted change to GPU-architecture gating at model setup;
lowers risk on SM12x by avoiding an incompatible FA4 path rather than
altering auth or data handling.
> 
> **Overview**
> **`attn='auto'` no longer picks Flash Attention 4 on every SM10+
GPU.** Resolution now uses FA4 only when the compute capability major is
**10 or 11** (datacenter Blackwell, e.g. B200/B300), keeps **FA3 on
Hopper (SM90)**, and uses **FA2 for everything else**—including
workstation Blackwell (**SM12x**, e.g. RTX PRO 6000), which lack the
tcgen05/TMEM path FA4 expects.
> 
> The **`resolve_auto_attn`** docstring and the **`attn`** comment in
**`docs/scaling.md`** are updated to match this split so docs and
runtime behavior stay aligned.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ab27534ec84dba23a2043dc65235e6b7ea57b41c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 15:58:24 -07:00
b963ceda3c perf(deepseek_v4): dynamic sparse attention slot count, no recompiles, per-query tile skipping (#3644)
The DSv4 sparse attention kernels compiled one kernel per gather width,
and HCA's width tracks the longest
document in the packed row, so every new width stalled training while
TileLang compiled. The kernels now
compile once per process and skip slot tiles no query can reach.

- `topk` was a compile key, so each new gather width recompiled; kernels
now take `Indices` as a free view
  `(B, S, G, n_tiles, tile)` with only `n_tiles = K / tile` dynamic.
- The tile size stays fixed so in-tile offsets stay provable; a fully
dynamic `topk` slowed the backward 24-29%.
- Each query loops only over tiles up to its last valid slot; the
skipped tiles are fully masked, so this is exact.

End to end, DeepSeek V4 Flash SFT on 8 B300 nodes (full model, 256k,
cp8/ep8, bf16, 20 steps, fresh compile
caches per arm). Real data packs 4-9 documents per row; fake data is one
document per row.

| data | arm | median step, 6-20 | total, steps 2-20 | MFU |
|---|---|---|---|---|
| real (scaleswe) | main | 19.20 s | 440.1 s | 46.7% |
| real (scaleswe) | this PR | 17.81 s (-7.2%) | 346.8 s (-21%) | 53.6% |
| fake | main | 16.87 s | | 57.5% |
| fake | this PR | 16.76 s (-0.7%) | | 57.8% |

On real data, main recompiles mid-run and spends 27-30 s on 8 of 19
steps; this PR compiles 28 TileLang
kernels in step 1 versus 356 for main, and losses match to 1e-4.

![Before/after timeline of a recompile
step](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/78da67f7cc8f89dec8032ea322ce488d5181b8c8/benchmarks/fp8_grouped_gemm/dsv4_attn_dynamism_stall.png)

Rank 0, step 5 of a traced 8-step run on a 6-layer one-node proxy with
real data
([config](https://github.com/PrimeIntellect-ai/prime-rl/blob/b339e8eafed9f39d832a5da0d2eae9a5a91b0b7a/benchmarks/fp8_grouped_gemm/sft_1n_scaleswe.toml)),
aligned at the step start.
On main the GPU idles 5.6 s and 4.2 s inside the sparse attention
forward and backward while TileLang compiles
new widths (cache file times: 4-7 compiles in 6 of the 7 steps after
step 1, versus none for this PR).
The untraced full-model numbers above are the timing claim.

Before:
[main@33e02a7](https://github.com/PrimeIntellect-ai/prime-rl/commit/33e02a7a183002aca0864c5afc1c2f5a50e48e37).
After: [real-data
config](https://github.com/PrimeIntellect-ai/prime-rl/blob/b339e8eafed9f39d832a5da0d2eae9a5a91b0b7a/benchmarks/fp8_grouped_gemm/sft_scaleswe.toml),
[fake-data
config](https://github.com/PrimeIntellect-ai/prime-rl/blob/b339e8eafed9f39d832a5da0d2eae9a5a91b0b7a/benchmarks/fp8_grouped_gemm/sft.toml).
Both real-data arms carry #3544's tool-call fix (`c7ba105d5`), which the
dataset needs.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 11:10:03 -07:00
samsjaandGitHub 3cc565eecb feat(eval): add a BetterStack heartbeat to eval runs (#3664)
## Summary

The trainer, sft, and orchestrator already beat a Better Stack
heartbeat; evals (and the sft online-eval, which shares the
`EvalRunner`) were invisible to it. This gives the eval its own
`heartbeat` config: one ping per landed episode.

There is deliberately no startup ping: the first landed episode is the
first beat. The gap between run start and the first episode (pool boot,
env servers, the first episode's full duration) would otherwise sit
inside the ping stream as an abnormally long silence that flips a
healthy run stale. Until the first beat, the heartbeat has simply never
been pinged.

When episodes stop landing, the pings stop and Better Stack flips the
heartbeat stale after its grace period. Size that period + grace above
the longest legitimate gap between episodes. The `Heartbeat` never runs
more than one ping in flight (a `beat()` while one is pending is
dropped), so continuous landings cost at most ~one request per
round-trip.

The orchestrator keeps its existing per-batch heartbeat; nothing there
changes.

## Usage

```toml
[heartbeat]
url = "https://uptime.betterstack.com/api/v1/heartbeat/<token>"
```

Set it on the `eval` config (also available to the sft online-eval via
its `[eval]` block).

## Validation

- `ruff check` + `ruff format` clean.
- `uv run pytest tests/unit/test_configs.py
tests/unit/eval/test_cli.py`: identical to the unmodified tree (67
pre-existing failures in this env from missing verifiers hub plugins;
126 pass).
- Live 30-minute run against a real Better Stack heartbeat URL using the
exact `Heartbeat` class: 60 pings at a 30s cadence, all HTTP 200 (RTT
126-344ms); silence after stop, as the dashboard's staleness window
expects.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Optional observability hook with no change to eval logic, auth, or
data paths when `heartbeat` is unset.
> 
> **Overview**
> Eval and SFT online-eval (shared `EvalRunner`) can now opt into Better
Stack uptime monitoring via an optional **`heartbeat`** block on
**`ServedEvalConfig`**, matching trainer/orchestrator/SFT.
> 
> When configured, **`EvalRunner`** creates a **`Heartbeat`** at setup
and pings **once per successfully landed episode**—not on dispatch
failures or cancellations, and **not at startup**. The first beat is the
first landing so long boot/first-episode gaps do not look like stale
silence in Better Stack; if episodes stop (dead inference, hang, or
clean exit), pings stop and the monitor goes stale after grace.
> 
> Configure with `[heartbeat] url = "..."` on the eval config (or SFT
`[eval]`); size Better Stack period + grace above the longest gap
between landed episodes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
75add6ed9027ef8b2f2aab2a63c945db38633655. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-25 10:59:31 -07:00
samsjaandGitHub f52f6a69df add sft example glm5 (#3666)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Documentation and example TOML only; no changes to training, auth, or
runtime code paths.
> 
> **Overview**
> Adds **supervised fine-tuning (SFT)** to the GLM-5.3 advanced example
alongside the existing RL/inference guides.
> 
> New TOML overlays under `sft/h200/` target **8-GPU H200 nodes** (8
training nodes, `cp`/`ep` = 8, 131k `seq_len`): **`base.toml`** wires
`zai-org/GLM-5.3-BF16`, custom MoE training settings, `sign_sgd`, and
Slurm; **`math-10k.toml`** points at
`PrimeIntellect/INTELLECT-3-SFT-10K` (math split); **`fake.toml`** swaps
in fake data for dry runs.
> 
> The README **SFT** section documents composing configs with `uv run
sft @ ...` and notes the existing dashboard can monitor SFT runs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
81d7877b4e06ec9f3865006f6b309ac0b0e95aff. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

## Layout

The SFT overlays live under `examples/advanced/glm-5.3/sft/h200/` — an
`h200/` subfolder marks them as tuned for 8-GPU H200 nodes, and the
files drop the `sft-` prefix since the parent folder already says SFT:

- `sft/h200/base.toml` — base SFT config: `zai-org/GLM-5.3-BF16` on 8
training nodes with the same large-scale knobs as RL (custom impl,
`cp`/`ep` = 8, 131k context, AC offloading, `sign_sgd`, SLURM job
`glm53-sft`).
- `sft/h200/math-10k.toml` — data overlay:
`PrimeIntellect/INTELLECT-3-SFT-10K` (math split).
- `sft/h200/fake.toml` — fake-data overlay with `force_balanced_routing`
for dry runs.

Launch:

```bash
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml
```

The README SFT section documents the command, the fake-data variant, and
the dashboard. Both compositions validate with `sft --dry-run`.
2026-09-25 10:58:54 -07:00
Mika SenghaasandGitHub 9cc215df69 chore: bump prime-envs to latest main (#3672)
## Summary
- Bump the `deps/prime-envs` submodule from `1213b7336` to `b677502a2`
(latest `main`). Pulls in:
-
[prime-envs#818](https://github.com/PrimeIntellect-ai/prime-envs/pull/818):
separate original OfficeQA from repaired PI-OfficeQA (new
`pi-officeqa-pro-v2` env).
-
[prime-envs#832](https://github.com/PrimeIntellect-ai/prime-envs/pull/832)
(+ [#835](https://github.com/PrimeIntellect-ai/prime-envs/pull/835),
[#836](https://github.com/PrimeIntellect-ai/prime-envs/pull/836)):
switch `swebench_pro` to SWE-bench Pro V2, constraining image repository
choices.
-
[prime-envs#824](https://github.com/PrimeIntellect-ai/prime-envs/pull/824):
SWE-Atlas Harbor environments (new `swe-atlas-qna`, `swe-atlas-rf`,
`swe-atlas-tw` envs).
-
[prime-envs#811](https://github.com/PrimeIntellect-ai/prime-envs/pull/811):
PI-DeepSWE while preserving original DeepSWE (new `pi-deepswe` env).
-
[prime-envs#801](https://github.com/PrimeIntellect-ai/prime-envs/pull/801):
APEX-Agents 1.1 with its reference harness and Harbor grading (new
`apex-agents` env).
-
[prime-envs#810](https://github.com/PrimeIntellect-ai/prime-envs/pull/810):
`pi-terminal-bench-2` with repaired QEMU task images.
-
[prime-envs#829](https://github.com/PrimeIntellect-ai/prime-envs/pull/829):
agentic Lean tasksets on a shared `lean-common` base (new cambench,
combibench, discover-and-prove, formalmath, kimina, matholympiadbench,
minif2f, numina, proofnet, proverbench, putnambench tasksets; removes
`deepseek-prover` and `goedel-pset`).
-
[prime-envs#838](https://github.com/PrimeIntellect-ai/prime-envs/pull/838):
raise Verifiers dev requirements to 0.3.2.dev137, matching our vendored
`deps/verifiers` pin.
- Relock `uv.lock`: new workspace members are auto-discovered via
`deps/prime-envs/environments/*/*`; `lean-common` joins as an editable
path source.
- Exclude `apex-agents` from the workspace: it pins `verifiers` as a git
rev (`328c0b1`), which conflicts with the editable workspace member —
same lock-conflict pattern as `tau2_synth` and `tau3_bench`.

## Validation
- `uv lock` and `uv lock --check` pass (581 packages resolved).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Large dependency-graph churn and benchmark harness upgrades (e.g.
SWE-bench Pro V2) can affect eval/training env selection, though changes
are confined to workspace packaging and the lockfile.
> 
> **Overview**
> Updates the monorepo lockfile and workspace rules after advancing
**`deps/prime-envs`**, so newly added Harbor/SWE/Lean/search env
packages resolve alongside the editable **`verifiers`** pin.
> 
> **`pyproject.toml`** documents why **`apex-agents`** is excluded from
the uv workspace (it pins **`verifiers`** to a git rev, same conflict
pattern as **`tau2_synth`** / **`tau3_bench`**) and adds that path to
**`tool.uv.workspace.exclude`**.
> 
> **`uv.lock`** registers many new auto-discovered workspace
members—including **`lean-common`**, agentic Lean tasksets (e.g.
**`cambench`**, **`proofnet`**, **`putnambench`**), PI variants
(**`pi-deepswe`**, **`pi-officeqa-pro-v2`**, **`pi-terminal-bench-2`**),
and **`swe-atlas-*`**—while dropping **`deepseek-prover`** and
**`goedel-pset`**. Several existing packages bump versions and tighten
**`verifiers`** requirements to **`>=0.3.2.dev137`** (notably
**`deep-swe`**, **`swebench-pro`**, and the migrated Lean envs).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5d592eccccbb09ad765d6663e12a91399a49e29b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-25 10:21:37 -07:00
NeoandGitHub 13c82f0551 Mario/increase moe mfu split size tensorize (#3665)
<html>
<head>

</head>
<body>

<p class="p1">This PR changes the split representation to use CPU
tensors.</p>

<h3><span class="s1"><b>Performance</b></span></h3>

<p class="p4">Benchmarked on Qwen3-30B-A3B with 8× H200, EP 8, balanced
routing, bf16, and no activation checkpointing.</p>



Version | Step time (3–30) | Tok/s/GPU | MFU (head_dim 128)
-- | -- | -- | --
main (job 1426) | 7.59s | ~8,635 | ~32.8%
CPU-tensor splits, this PR (job 1434) | 6.95s | ~9,430 | ~35.9%
torchtitan (job 1422) | 6.58s | ~9,960 | 37.8%




<p class="p1">Compared with <code>main</code>, this PR reduces step time
from <span class="s1"><b>7.59s to 6.95s</b></span> (~8.4% reduction),
increases throughput from <span class="s1"><b>~8,635 to ~9,430
tok/s/GPU</b></span> (~9.2% improvement), and raises MFU from <span
class="s1"><b>~32.8% to ~35.9%</b></span>.</p>

</body>
</html>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Logic for split sizes is unchanged; this only alters tensor
layout/device timing for a performance path in distributed MoE routing.
> 
> **Overview**
> Improves **MoE expert-parallel token dispatch** in
`TorchTokenDispatcher` by building `input_splits` and `output_splits`
together and moving them to **CPU once** before the all-to-all.
> 
> Instead of two separate GPU reductions, the change **stacks** the
per-rank token counts from local and grouped expert histograms, sums
them, and calls `.cpu()` up front so `all_to_all_single` can read split
sizes (via `.tolist()`) **without an extra device sync** on the hot
path. Dispatch/combine still use the same split semantics; only where
the tensors live and when they are transferred changes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e61d0bfdda7fe7ec7170b20eb60096d3552daa7a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-25 04:18:29 +02:00
7d25aaa0d2 docs: drop the standalone RL trainer entrypoint from the docs (#3634)
## Problem

`uv run trainer` calls `prime_rl.trainer.rl.train` directly, outside
torchrun, so the `env://` rendezvous has no
`RANK`/`WORLD_SIZE`/`MASTER_ADDR`/`MASTER_PORT` and the process dies
before any training starts:

```
ValueError: Error initializing torch.distributed using env:// rendezvous:
environment variable RANK expected, but not set
```

Every documented use of that entrypoint was therefore broken. Scott hit
it during onboarding on the README's own validation steps (#3633).

## Fix

Rather than defaulting the rendezvous env for a single-process group
(#3633), drop the standalone trainer from the docs — per the thread, it
isn't a path we want people on:

- **`README.md`** — removed "Validate your environment setup" step 4
(`uv run trainer @ configs/debug/fake/rl.toml`) and renumbered the
following steps. The remaining step 5 (`uv run rl @
configs/basic/reverse-text/rl.toml`) already exercises the trainer
end-to-end.
- **`docs/training.md`** — dropped the `uv run trainer` row from the
entrypoints table, and reworded the `uv run orchestrator` row that
pointed at a "separately-launched trainer".
- **`docs/scaling.md`** — the trainer-alone benchmark now launches under
torchrun, the way the `rl` launcher and
[`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py)
(what the CI benchmark matrix runs) already do.

Docs only — no code or config changes, and the `trainer` entrypoint
itself is untouched.

## Follow-up, not in this PR

`k8s/README.md`, `k8s/prime-rl/values.yaml` (the `trainer.command`
example), and the k8s section of `examples/basic/reverse-text/README.md`
still drive the trainer pod with `uv run trainer`, and hit the same
failure — the chart sets no rendezvous env on the trainer StatefulSet.
Fixing that means changing how the chart launches the trainer, not just
the prose, so it wants its own PR from someone who can run the
deployment.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation-only edits with no runtime or config changes.
> 
> **Overview**
> Documentation no longer recommends **`uv run trainer`**, which fails
on startup without torchrun/`RANK` because it invokes the RL trainer
outside distributed launch.
> 
> The README **environment validation** checklist drops the standalone
RL trainer step and **renumbers** the inference and full **`uv run rl`**
checks. **`docs/training.md`** removes the trainer row from the
entrypoints table and updates the **`uv run orchestrator`** note so it
no longer assumes a separately launched trainer. **`docs/scaling.md`**
changes the “RL trainer alone” benchmark to **`torchrun …
src/prime_rl/trainer/rl/train.py`**, matching how the **`rl`** launcher
and CI benchmarks run it.
> 
> The **`trainer`** CLI entrypoint is unchanged; this is prose-only.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
cb2aa3805b8e77dbb9e334961349c42a1c7462db. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 16:05:26 -07:00
samsjaandGitHub 5a0c80e54a docs(readme): drop stale FA3 source-build step; flash_attn_3 comes from prebuilt wheels (#3648)
## Why

Section 3.1 of the README ("Optional: Install Flash Attention 3")
claimed FA3 "has no wheels prebuilt" and instructed a manual source
build from the `hopper` subdirectory. This is stale — **prime-rl already
installs FA3 as a prebuilt wheel from the lockfile**:

- `pyproject.toml` resolves `flash_attn_3 = { index =
"pytorch-cu130-test" }` → `https://download.pytorch.org/whl/test/cu130`
- `uv.lock` pins `flash-attn-3 == 3.0.0` from that index (real compiled
wheels: `flash_attn_3-3.0.0-cp39-abi3-manylinux_2_28_x86_64.whl`, ~402
MB, plus an aarch64 build)
- `uv sync --all-extras` (step 4 of the same install section) pulls it
in via the `flash-attn-3` extra — same as `Dockerfile.cuda` (`--extra
flash-attn-3`)
- This has been the case since at least May (the source was
`pytorch-cu128-test` before `70117046a` moved it to `cu130-test`)

Since step 4 already installs FA3, the section documents a step that
must not be followed: building from git would fight the lock (its "uv
sync will uninstall the package" warning was describing a self-inflicted
problem).

## What

- Remove section 3.1 entirely. Nothing is lost: `flash_attn_3` arrives
prebuilt with `uv sync --all-extras`, and the `flash_attention_3`
backend / `attn="auto"` picks it up on Hopper GPUs.

Docs-only change, no code touched.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> README-only edit with no runtime or dependency behavior changes.
> 
> **Overview**
> Removes **README Manual Setup subsection 3.1**, which told Hopper
users to build Flash Attention 3 from the Dao-AILab git source and
warned that **`uv sync` / `uv run` would uninstall** that manual
install.
> 
> That guidance is outdated for this repo: **`flash_attn_3` is already
pulled in via the lockfile and `uv sync --all-extras`** (optional extra
from the PyTorch test index), so the extra source-build step conflicted
with the pinned wheel and described a problem users only hit if they
bypassed the lock.
> 
> Docs-only; install flow in step 4 is unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
921c72d02f42ab0a58fe4b10cd8fb227f1a3543f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-24 16:05:09 -07:00
e48c943c48 fix(orchestrator): save final checkpoint before finalizing the run (#3642)
## Problem

`Orchestrator.start()` writes the orchestrator's own final checkpoint in
its `finally` block **after** `monitors.finalize()`. Finalize is what
tells the launcher the run is done: on the fft k8s path, the platform
marks the run COMPLETED and uninstalls the release. So the
orchestrator's final checkpoint races teardown.

## Fix

Save the final checkpoint first, then finalize. Clean and forced exits
both still save; only the order relative to `monitors.finalize()`
changes.

## Scope

This PR first also made the orchestrator wait for the trainer's final
checkpoint. Per review, waiting for both components is the launcher's
job, as the SLURM template already does with `.trainer.done` /
`.orchestrator.done`, so that part was dropped. The k8s launcher side is
platform#5817 + fft#92 (Linear ENG-6341): the platform marks a run
COMPLETED and tears it down only once both the trainer and the
orchestrator have finished.

With those in place, teardown already waits past the orchestrator's
finalize, so this change is **defense-in-depth** there. It still matters
for any launcher that tears down on finalize alone, and it makes the
orchestrator's own "I'm done" signal truthful.

## Testing

- `uv run pytest tests/unit -m "not gpu"` (as in `cpu_tests.yaml`,
x86_64, `--all-extras`): 616 passed, 1 skipped. CI CPU tests pass on
this head.
- Not exercised on k8s with an image built from this branch; the telus
runs for ENG-6341 used the stock prime-rl image. The GPU integration
tests (which run the orchestrator end to end from this branch) are the
coverage for the reordering.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 15:56:03 -06:00
e521297df6 perf(deepseek_v4): fused in-place interleaved RoPE for DeepSeek-V4, matching vLLM (#3645)
Eager interleaved RoPE was a large share of each DeepSeek-V4 attention
layer: every site widened the
tables with `repeat_interleave`, rotated a copy of the 64 rope channels,
and rebuilt the whole
512-channel head with `torch.cat`. All five RoPE sites (q, kv,
compressed kv, indexer q, and the
inverse rotation of the attention output) now run one out-of-place
Triton kernel, adapted from
Megatron-LM and bit for bit with vLLM's `rotary_embedding`, making the
end-to-end SFT step 13-14%
faster on B300.

- RoPE tables were built every forward in bf16. They are now one static
fp32 `[cos | sin]` cache in
  vLLM's layout, indexed by position inside the kernel.
- q was normed and rounded to bf16, then rotated and rounded again.
`dsv4_q_norm_rope` does both in
fp32 with one rounding: exact matches with vLLM rise from ~69% of rope
channels to 99.9997%.
- `dsv4_rope` is a functional custom op whose backward is the inverse
rotation. An in-place version
needs an `autograd.Function` wrapper, because `register_autograd`
rejects mutating ops.
- Passing fp32 tables through `PackedContext` failed multi-node: FSDP's
`cast_forward_inputs` cast
them to bf16. Hence the cache lives on one rotary module that every
attention layer shares.

DeepSeek V4 Flash SFT on 8 B300 nodes, full model, bf16, 256k tokens,
cp8/ep8, selective AC. Median step
over steps 6-20 of 20, which skips the sparse-attention recompiles both
real-data arms hit (removed by
#3644). tok/s/GPU is the 32,768 packed positions each GPU processes per
step, padding included, over that
median. Losses match `main` to 1.5e-3 on identical samples:

| Per step, 8 B300 nodes | Fake: main | Fake: this PR | Real: main |
Real: this PR |

|----------------------------------|------------|---------------|------------|---------------|
| Median step time | 16.896 s | 14.641 s | 19.203 s | 16.474 s |
| tok/s/GPU | 1939 | 2238 | 1706 | 1989 |
| MFU | 57.4% | 66.2% | 46.7% | 53.2% |
| Peak reserved GPU memory, rank 0 | 244.0 GiB | 246.6 GiB | 246.7 GiB |
247.0 GiB |

Fake data is one 256k document per row; real data is the scaleswe SFT
set, 4-9 documents per row.

![Before/after main-stream kernels in one DeepSeek-V4 layer's attention
block](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/1210bc4eaea568a0247d04d79ca425a21051ee6c/benchmarks/ds-v4-rope-profile-v2.png)

**Figure:** Kernels on rank 0's main GPU stream during layer 2's
forward, in the last of five
`torch.profiler` steps of a 1-node, 6-layer run (256k tokens, cp8/ep8,
bf16). Both arms start at the
layer's first kernel, and the dashed line marks the end of its attention
block at the MoE router. The two
~7 ms `torch.cat` blocks per layer, which rebuild the heads around q's
RoPE and around the inverse
rotation of the attention output, are gone, shortening the block from
94.1 ms to 72.3 ms. The bottom panel
sums each kernel category over the whole step: `torch.cat` -180 ms and
the RoPE path's elementwise ops and
copies -145 ms, against +7 ms for the fused kernels, for -307 ms of
main-stream kernel time. The profiled
run explains the mechanism; the unprofiled full-model runs in the table
are the timing claim.

Before: [`main`
33e02a7](https://github.com/PrimeIntellect-ai/prime-rl/commit/33e02a7a183002aca0864c5afc1c2f5a50e48e37).
After:
[`04f7b8a`](https://github.com/PrimeIntellect-ai/prime-rl/commit/04f7b8a94e7d6482843eb871e938ded9f71427fb),
the in-place version this PR began as, with the
[fake](https://github.com/PrimeIntellect-ai/prime-rl/blob/2c671d77ed8fe639a568976c832e4ed00995542f/benchmarks/fp8_grouped_gemm/sft.toml),

[real](https://github.com/PrimeIntellect-ai/prime-rl/blob/2c671d77ed8fe639a568976c832e4ed00995542f/benchmarks/fp8_grouped_gemm/sft_scaleswe.toml)
and
[profiling](https://github.com/PrimeIntellect-ai/prime-rl/blob/2c671d77ed8fe639a568976c832e4ed00995542f/benchmarks/fp8_grouped_gemm/sft_1n_256k.toml)
configs. Real-data runs add #3544's tool-call fix

([`c7ba105`](https://github.com/PrimeIntellect-ai/prime-rl/commit/c7ba105d58b1d825c3f411bcaf6bd6c85db57ddd))
to both arms.
The out-of-place rewrite was checked only in per-kernel benchmarks,
where it is net ~90 µs faster per
layer forward than in-place, and has not been re-run end to end.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 17:26:14 -04:00
Konstantin DunasandGitHub 1556db6ca7 chore: bump verifiers to latest main (#3663)
Advance the `deps/verifiers` submodule from `9e7ec2746` to `69cc0f948`,
the latest verifiers `main`, on top of prime-rl `origin/main`.

This picks up interrupted completion stream retries and the follow-up
refactor to tenacity. Dependency metadata is unchanged, so no lockfile
update is needed.

Validation: `uv lock --check --offline` passed. All four upstream
stream-retry regression cases passed with `uv run --no-sync pytest
--noconftest
deps/verifiers/tests/v1/test_e2e.py::test_chat_harness_preserves_streamed_reasoning
-q`. Shared integration fixtures were disabled because the local
environment lacks `prime_runs`. `git diff --check` passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Submodule pointer-only change with no prime-rl code or lockfile edits;
upstream behavior is limited to streaming/retry handling in verifiers
and was exercised by targeted tests.
> 
> **Overview**
> Updates the **`deps/verifiers`** git submodule from `9e7ec2746` to
**`69cc0f948`** (current verifiers `main`). There are **no changes to
prime-rl source or lockfiles**—only the pinned submodule commit moves.
> 
> The new verifiers revision adds **retries for interrupted completion
streams** and a follow-up refactor to use **tenacity** for that retry
logic. prime-rl still consumes verifiers the same way (CI initializes
the submodule; v1 config types extend `verifiers.v1`).
> 
> Validation noted in the PR: `uv lock --check --offline`, targeted
stream-retry e2e tests under `deps/verifiers/tests/v1/test_e2e.py`, and
`git diff --check`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c23df2e4bfaa88decca20bdb1a26d4fe5f9bd23c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-24 11:10:10 -07:00
Mika SenghaasandGitHub f984dee559 fix: pre-download data before trainer ranks (#3659)
## Summary

- pre-download Hub data in the SFT launcher, beside model predownload,
before trainer ranks start
- call data predownload only for SFT data, and skip generated fake data
in the launcher
- store the snapshot in the configured Hub cache and pass its local path
to the trainer
- log skipped local paths and download duration like model predownload
- add optional `data.revision` and honor it when loading data directly

## Verification

- before: research-prod debug job 1400 failed before its first step when
concurrent ranks received HTTP 429 from the Debug data tree API
- after: called the predownload utility with the pinned Debug data and
confirmed it resolved to the local snapshot
- ran Ruff lint and formatting checks on the changed Python files

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes SFT startup and mutates in-memory data config before
subprocesses start; low security impact but affects all real-data SFT
runs’ I/O behavior.
> 
> **Overview**
> **Pre-downloads Hugging Face SFT datasets in the launcher** (alongside
model pre-download) so a single process hits the Hub before
`torchrun`/SLURM ranks start, avoiding concurrent dataset API traffic
that caused HTTP 429 failures.
> 
> Adds `pre_download_data`, which no-ops for non-SFT/`fake` configs and
existing local paths, uses `snapshot_download` with optional
`HF_HUB_CACHE`, **rewrites `data.name` to the cached snapshot path**,
and logs timing like model pre-download. The launcher calls it for train
and validation data when not in `dry_run`.
> 
> Adds optional **`data.revision`** on `SFTDataConfig` and threads it
through `load_dataset` when data is loaded directly (revision is ignored
for local paths).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6aa6aa6e37a3e777bfd61ec835f02ee7f1a360cd. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-24 11:01:21 -07:00
Mika SenghaasandGitHub c1c1fe7e14 chore: update verifiers for buffered streams (#3656)
## Summary

- Advance the `deps/verifiers` submodule from `9cf0df2` to `9e7ec27`,
the last VF main commit before Matej's retry fix.
- Include buffered SSE keepalives and retry replay from
[verifiers#2650](https://github.com/PrimeIntellect-ai/verifiers/pull/2650),
the empty-tools fix from
[verifiers#2669](https://github.com/PrimeIntellect-ai/verifiers/pull/2669),
and Prime job-output recovery from
[verifiers#2670](https://github.com/PrimeIntellect-ai/verifiers/pull/2670).
- Include the nano-rlm default revision bump from
[verifiers#2672](https://github.com/PrimeIntellect-ai/verifiers/pull/2672).
- Keep Matej's stream-consumption retry PR
[verifiers#2654](https://github.com/PrimeIntellect-ai/verifiers/pull/2654)
out of this pin. VF main merged it during this load test.

## Breaking

- VF streams now send keepalives while they buffer a model turn. They
send the completed response after the turn commits. Consumers that need
live provider token deltas must connect to the provider directly.

## Verification

- `uv sync --all-extras --all-packages --locked` completed. Both eval
configs passed `uv run --no-sync eval @ ... --dry-run`.
- Served `poolside/Laguna-S-2.1-FP8` on eight H200 nodes. Each node ran
one ETP=8 replica behind the default vLLM router with a four-hour
request timeout.
- Ran AIME26/null and Terminal-Bench 2 `fix-git`/Bash together on VF
`1e0b660`, the direct parent of the pinned `9e7ec27`. The intervening VF
diff changes only the optional nano-rlm harness default. Neither tested
harness uses nano-rlm.
- Each eval had 2,000 rollouts, fixed 2,000 inflight concurrency, and a
900-second rollout cap. Bash used 20 maximum turns. No eval-side rate
limiter was set.

The table excludes sandbox-creation HTTP 429 rollouts. It counts the
configured 900-second cap as **no error**.

| Eval | No error | Other infrastructure errors | Stream errors |
| --- | ---: | ---: | ---: |
| AIME26/null | 1,770/1,772 | 2 | 0 |
| TB2 fix-git/Bash | 1,857/1,859 | 2 | 0 |
| Combined | 3,627/3,631 | 4 | 0 |

- AIME had 779 cap exits. Its other failures were one sandbox missing
`dockerImage` and one terminated sandbox. Its 996 model calls had no
recorded call error. Of its fully completed calls, 339 exceeded 600
seconds; the longest lasted 894 seconds.
- Fix-git had 37 cap exits. Its other failures were one sandbox missing
`dockerImage` and one sandbox setup `apt-get` I/O error. Its 27,874
model calls had no recorded call error. Six fully completed calls
exceeded 600 seconds.
- Found zero terminal stream-disconnect signatures in trace errors,
model-call errors, or eval and environment logs. Both eval commands
exited successfully.
2026-09-24 10:37:00 -07:00
samsjaandGitHub bdaafc35ab chore(deps): bump dion to 6f9242d (uneven FSDP shards) (#3658)
## Summary

Bumps the dion pin from `99e5f7e` to `6f9242d`, picking up samsja/dion#4
(merged into `sami/fix-ep`):

- **Uneven and empty FSDP shards in Muon**: local shards are padded to a
uniform peer-transfer size for the all-to-all and trimmed back
before/after orthogonalization, so the update is exactly the unpadded
Muon update. Previously the optimizer asserted the sharded dim is
divisible by the optimizer world size — full Muon failed on the first
step for matrices with e.g. 4 or 24 rows on a 64-rank FSDP group.
- **Partitioned-matrix fix**: per-row learning rates are now sliced with
chunk offsets matching DTensor's `Shard` (`torch.chunk`) layout;
`torch.tensor_split` disagrees with it at world size ≥ 3 and could
silently misassign or crash when a partition boundary fell inside an
uneven shard.
- Padding now uses `torch.nn.functional.pad` (no-op fast path when
shards are already uniform).

## Compatibility

- `Muon`'s constructor signature is unchanged; the call site in
`src/prime_rl/trainer/optim/__init__.py` is unaffected.
- The pinned tree is byte-identical to the dion branch validated with:
exact (`rtol=0, atol=0`) parity vs unsharded Muon across
uneven/empty/3D/partitioned shapes at world sizes 2 (NCCL) and 3 (gloo),
plus 170 pure-CPU padding round-trip cases.

## Changes

```
pyproject.toml | 2 +-
uv.lock        | 4 ++--
```

Note: `uv lock` in a fresh clone needs the `deps/` submodules
initialized **with tags** (`git submodule update --init`, then ensure
tags are fetched) — `verifiers` and `renderers` derive versions from git
tags via hatch-vcs, and a tagless shallow checkout resolves them as
`0.0.1.dev1`, which fails workspace resolution.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Pins a new git revision of the distributed Muon optimizer used on
Linux GPU training; behavior changes in FSDP edge cases but no in-repo
code edits.
> 
> **Overview**
> Updates the **dion** git pin from `99e5f7e` to `6f9242d` in
`pyproject.toml` and `uv.lock` only—no prime-rl source changes. Training
still wires **Muon** through `src/prime_rl/trainer/optim/__init__.py`
under the `gpu` extra.
> 
> The new revision pulls in upstream fixes for **FSDP-sharded Muon**:
uneven or empty local shards are padded for all-to-all peer transfer and
trimmed so updates match unsharded Muon (avoiding first-step failures
when matrix rows aren’t divisible by optimizer world size), and per-row
learning rates are sliced with **DTensor**-consistent chunk offsets
instead of `tensor_split` (which could misassign rates at world size ≥
3).
> 
> **Risk:** dependency-only bump, but it changes distributed optimizer
numerics/behavior on large FSDP runs where the old pin could assert or
silently wrong-rate parameters.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9ca26a11e000fb7ca8a374537af6a3858c1b1aed. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 22:40:17 -07:00
samsjaandGitHub 48aa99fbb5 feat(trainer): expose the torch.compile mode (reduce-overhead) in the compile config (#3657)
## Summary
`CompileConfig` only exposed `fullgraph`, so there was no way to opt
into `torch.compile`'s lower-overhead modes. This adds a `mode` field
that mirrors the `torch.compile` `mode` kwarg, and forwards it to each
layer's `.compile()` call in `apply_compile`.

- Accepts `reduce-overhead` (records CUDA graphs to cut kernel launch
overhead), `max-autotune`, `max-autotune-no-cudagraphs` (tune Triton
kernels, longer compile) and `lite`.
- `mode = None` (default) keeps the current behavior — layers compile
with PyTorch's default mode.
- CUDA-graph modes re-record on new input shapes, so runs with highly
variable shapes pay recompile churn.

## Usage

```toml
[trainer.model.compile]
mode = "reduce-overhead"
```

or on the CLI: `--trainer.model.compile.mode reduce-overhead`.
2026-09-23 22:39:07 -07:00
samsjaandGitHub 94dff2ca54 fix(trainer): b300 fallback to FA4 (#3655)
## Problem

Two GPU-capability gates in `src/prime_rl/trainer/model.py` matched
`(10, 0)` exactly, but B300/GB300 are **SM103** (compute capability
10.3, per https://developer.nvidia.com/cuda-gpus):

1. **`resolve_auto_attn`**: `attn: auto` on B300/GB300 resolved to
`flash_attention_2` instead of FA4, silently losing the Blackwell-native
attention kernels on every default-config B300 run.
2. **`apply_quantization` (MXFP8 gate)**: MXFP8 quantization raised
`requires SM100 (Blackwell)` on B300 even though Blackwell Ultra
supports it.

## Fix

Use `major >= 10` in both places, matching the existing Blackwell checks
in `fp8_utils.py` and `fp8_grouped_gemm.py`.

## Behavior after this PR

| GPU | CC | `attn: auto` | MXFP8 |
|---|---|---|---|
| H100/H200 | SM90 | FA3 (unchanged) | n/a |
| B200/GB200 | SM100 | FA4 (unchanged) | allowed (unchanged) |
| B300/GB300 | SM103 | **FA4 (was FA2)** | **allowed (was rejected)** |
| Other SM100+ parts | SM110+ | FA4 | allowed |

Note the previous code kept workstation Blackwell (SM120/121, e.g. RTX
PRO 6000) on FA2; with the simple `major >= 10` check those now
auto-resolve to FA4 too. If FA4 kernels aren't available on such a host,
set `attn` explicitly.

## Notes

- Verified SM103 device capability via NVIDIA's CUDA GPUs page; FA4 runs
on B300 with the pinned `flash-attn-4` rev (`0251105`), which is past
the SM103 JIT-compile-churn fixes reported in
Dao-AILab/flash-attention#2635/#2699.
- B300 runs can confirm the old behavior by grepping trainer logs for
`Auto-resolved attn='auto' to 'flash_attention_2' (SM103)`.
- No behavior change on Hopper or B200 hosts.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes GPU-specific attention backend auto-selection and MXFP8
eligibility at trainer setup; mis-gating could pick unsupported kernels
on some SM10x parts.
> 
> **Overview**
> **Fixes B300/GB300 (SM103) being treated as non-Blackwell** because
capability gates in `model.py` matched compute capability `(10, 0)`
exactly.
> 
> For **`attn: auto`**, `resolve_auto_attn` now picks **flash attention
4** when the device **major** compute capability is **≥ 10**, instead of
only SM100. SM103 runs get FA4 rather than silently falling back to FA2.
> 
> For **MXFP8** in `apply_quantization`, the same **`capability[0] <
10`** rule replaces the exact SM100 tuple check, and the error text now
refers to **Blackwell (SM100+)**.
> 
> Docstrings for auto attention resolution are updated to describe
**SM100+** (including SM103) rather than datacenter-only SM100 vs
workstation SM120 wording tied to the old `(10, 0)` branch.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fbd7387af8a54df4cb3829b29dcfbbc24c1a7d27. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 21:00:12 -07:00
Mika SenghaasandGitHub 4723b0ee5a fix: increase default router timeout to four hours (#3654) 2026-09-24 04:48:24 +02:00
Mika SenghaasandGitHub b695a0aeda fix(inference): align DeepSeek V4 request tool placement (#3646)
## Summary

- attach request-level tools to the first existing DeepSeek V4 system
message
- preserve vLLM's existing synthetic-system behavior when a request has
no system message
- cover both paths and ensure the caller's messages are not mutated

vLLM 0.29's Python DeepSeek V4 tokenizer prepends a synthetic tool-only
system message even when the request already has a system prompt. That
differs from DeepSeek's reference encoder, vLLM's Rust renderer, and
prime-rl's training renderer, producing a different token prefix at
inference time.

This is a temporary compatibility patch for
[vllm-project/vllm#51856](https://github.com/vllm-project/vllm/pull/51856)
(upstream commit `2909ad8f`). That fix is expected to ship in vLLM 0.31,
at which point this monkey patch can be removed.

## Tests

- `pytest tests/unit/inference/test_deepseek_v4_tokenizer_patch.py -q` —
2 passed
- `ruff check src/prime_rl/inference/patches.py
tests/unit/inference/test_deepseek_v4_tokenizer_patch.py`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Inference-only tokenizer shim with idempotent guards; behavior is
covered by reference-encoding unit tests and should be removable after a
vLLM upgrade.
> 
> **Overview**
> Adds a temporary vLLM monkey patch so **DeepSeek V4 inference prompts
match the reference encoder and training renderer** when requests
include tools plus an existing system message.
> 
> On vLLM 0.29, the Python tokenizer **prepends a synthetic system block
for request-level tools**, putting `## Tools` before the caller’s system
text. The patch wraps `get_deepseek_v4_tokenizer` and
**`apply_chat_template`**: if the conversation already has a system
role, it shallow-copies the conversation, **attaches `tools` to the
first system message**, clears top-level `tools` so vLLM does not insert
the extra system message, and leaves **no-system** requests on stock
behavior. It is registered in **`apply_shared_vllm_patches`** and is
meant to be removed once the vLLM pin includes upstream **#51856**
(~0.31).
> 
> Unit tests assert rendered prompts match **`encode_messages`**, that
only one `## Tools` section appears, and that **input `messages` are not
mutated**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1acca7c9d1c503d0d497f05638d50e687ec714c8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 15:14:15 -07:00
753cfb5a42 fix: mark dashboard episodes failed by ok, not by carried errors (#3649)
## Summary
- The dashboard marks an episode as failed only when `ok` is false.
Retry history no longer turns a successful episode red: the episode
table row, the rollout list item, the error-rate tile on the eval
overview, and the server's `errors_only` filter all read `ok` alone.
- Episode errors and trace errors render in different places, each
tagged with its scope. A failed episode's own errors sit above the agent
and branch selectors, since they belong to the whole episode. A failed
trace's errors sit at the top of that trace's transcript, only on its
tab, and the tab is red. A failure recorded on both the episode and its
trace shows once, as the trace's.
- Errors an ok episode or ok trace carries render as a collapsed
`recovered from N episode|trace errors in earlier attempts` list in the
same two places, each entry with its traceback. The table row and
rollout list item get a dotted left edge with the recovery count in
their tooltip.

## Why
Verifiers retries a whole episode when a retryable error such as
`SandboxError` ends an attempt, and on success it prepends the earlier
attempts' errors to the final record: `final.errors[:0] = history`, with
the comment "success is the `ok` stamp, never errors-emptiness". The
agent-level retry does the same on the trace. An episode that hit the
sandbox creation limiter once and then completed cleanly therefore lands
with `ok = true`, a full trace, and the limiter error in `errors`. The
dashboard treated `num_errors > 0` as failure, so such episodes showed a
red row, an error banner over a clean transcript, and inflated the error
rate, which is what a user saw after a run with `retries.include =
["SandboxError", ...]`. Episode errors also rendered inside the open
trace, so a multi-agent episode showed a red banner over a green agent's
transcript.

## Verification
A synthetic eval run was built from a real 4-episode gsm8k stream and
served by an isolated dashboard on this branch, driven headlessly with
Playwright:

| Line | Shape | Before | After |
|---|---|---|---|
| 1 | episode failed; trace `solver` failed with `SandboxError`, trace
`judge` ok | red row, `error` badge, both banners inside the solver
transcript, episode banner inside the judge transcript | red row; the
`episode error` banner above the tabs on both; the `trace error` banner
only in the solver transcript; `solver` tab red |
| 2 | episode ok after a retry; episode and trace carry `SandboxError`
as history | red row, `error` badge, red banner over the clean
transcript | plain `done` row with a dotted edge and a "recovered from 1
error" tooltip, no banner, collapsed "recovered from 1 trace error in
earlier attempts" list holding the SandboxError and its traceback |
| 3, 4 | plain ok | `done` | `done` |
| error-rate tile | 2 failures counted | 50% | 25% |
| `errors_only=true` | | lines 1 and 2 | line 1 |

No console errors in either state.

## Screenshots
Episode table: line 1 failed (red edge), line 2 recovered (dotted edge),
lines 3 and 4 plain.

![episode
table](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/table.png)

Line 2, recovered after a retry: no banner, the SandboxError in the
collapsed recovered list (expanded here), `ok = true`.

![recovered
episode](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/recovered.png)

Line 1, `solver` tab: the episode error above the selectors, the failed
trace's error at the top of its transcript, the tab red.

![failed episode, solver
tab](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/failed_solver.png)

Line 1, `judge` tab: the episode error stays above the selectors; the
judge's transcript carries no banner because that trace completed.

![failed episode, judge
tab](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/failed_judge.png)

Screenshots live on the `assets/dashboard-retry-errors` branch.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dashboard display and filtering only; no changes to training, eval
recording, or auth paths.
> 
> **Overview**
> Aligns the eval dashboard with Verifiers’ retry semantics: **success
is `ok`, not empty errors**. Episodes that recovered after retryable
failures no longer look failed or inflate error metrics.
> 
> **Failure detection** now keys off `ok` only—the episode table,
rollout list, swarm **error-rate** tile, and server **`errors_only`**
filter no longer treat `num_errors` on successful episodes as failures.
Recovered episodes get a **dotted “retried”** row style and tooltips
instead of red error styling.
> 
> **Error UI** splits episode vs trace scope: episode-level failures
render in a new **`#tm-episode-errors`** strip above agent/branch tabs;
trace failures stay at the top of that trace’s transcript, with failed
agent tabs highlighted. **`scopedErrors`** dedupes episode/trace
duplicates (trace wins) and separates **failed** errors from
**recovered** history on ok records, shown as collapsible “recovered
from N … errors” sections. **`resetTranscript`** clears the episode
error strip whenever the transcript is replaced.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c4f6e242745c085c4bac60388dfb8c775e7b65f4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 14:29:47 -07:00
Biswa PandaandGitHub 33e02a7a18 fix(trainer): preserve Nemotron Mamba parameter dtype (#3557)
## Summary

- Initialize Nemotron Mamba `A_log` and `D` parameters with the active
default dtype so FSDP units do not mix float32 and bfloat16 storage.
- Keep the existing float32 state-space computation by casting at use
time.
- Add a focused bfloat16 parameter-dtype regression test.

## Validation

- `ruff check src/prime_rl/trainer/models/nemotron_h/mamba.py
tests/unit/train/models/test_nemotron_h.py`
- Focused in-cluster GPU probe: `A_log=torch.bfloat16`,
`D=torch.bfloat16`
- One-step Nemotron 3.5 Super VLM + MATH + Dynamo run: optimizer
completed and policy v1 was applied over NCCL.
- Three-step Kubernetes run: all optimizer steps completed; policies v0
through v3 applied to Dynamo; Job succeeded.
- Trainer mismatch KL by step: `0.0274`, `0.0344`, `0.0309`.

W&B: https://wandb.ai/test232/nemotron35-vlm-rl/runs/jq06zl0l
2026-09-23 13:35:34 -07:00
94f359e8d6 feat: scope verifiers limiters by run id and bump verifiers to main (#3641)
## Summary
- Bump the verifiers submodule to main (`9cf0df22b`), which includes
PrimeIntellect-ai/verifiers#2657: creation limiters wait on backlog
instead of raising past 300s, and their bucket is scoped by
`$VF_RUN_ID`. `uv.lock` is regenerated; verifiers dropped its `lean`
extra.
- The env-server entrypoint sets `VF_RUN_ID` from `PRL_RUN_ID`, minting
a uuid only when neither is set. Its pool workers inherit it.
- The multi-node SFT SLURM script exports `PRL_RUN_ID` and
`PRL_RUN_NAME` unconditionally, as the RL script does. Only the W&B
shared-mode variables stay behind the wandb condition, now named
`wandb_shared` in the template.

## Why
With the bump, a run whose sandbox creation outpaces `creates_per_min`
throttles instead of failing every rollout past the 300s backlog.
Scoping the bucket by run id keeps one run's backlog from delaying
another.

The env server is the one prime-rl process that creates sandboxes, and
every launcher hands it `PRL_RUN_ID`: the `rl`, `sft`, and `eval`
entrypoints export it before spawning, and the SLURM scripts export it
at the top of the sbatch script, which `srun` propagates to the `uv run
env-server` tasks. Deriving `VF_RUN_ID` there covers every launch path
with one line. The SFT script previously exported the run id only for a
shared W&B run, so its online-eval env servers would otherwise each have
minted their own scope.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes run-id propagation for SLURM-launched env servers and sandbox
creation throttling behavior; mis-set env vars could affect multi-run
cluster behavior but not auth or data integrity.
> 
> **Overview**
> Aligns prime-rl with verifiers’ run-scoped sandbox **creation
limiters** (keyed on `$VF_RUN_ID`) so throttling and backlog are per run
instead of shared across jobs.
> 
> The **env-server** entrypoint now sets `VF_RUN_ID` from `PRL_RUN_ID`,
or mints a UUID when launched standalone, so pool workers inherit the
same scope on every launch path.
> 
> **Multi-node SFT** previously exported `PRL_RUN_ID` only when shared
Weights & Biases logging was enabled, which left online-eval env servers
without a consistent run id. The SLURM template now always exports
`PRL_RUN_ID` and `PRL_RUN_NAME` (matching RL), while W&B shared-mode env
vars are gated on a new `wandb_shared` flag passed from `sft.py`.
> 
> **Lockfile** metadata drops the removed `lean` extra from the bumped
verifiers dependency.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
364f0b58699ad556746116a1bf6208e37b5afc6b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 13:34:19 -07:00
Matej SirovatkaandGitHub cf400e7db9 perf: reduce DSV4 indexer stalls and overlap CP gathers (#3643)
Packed sequence lengths were causing repeated FP8-indexer autotuning
during training. Other DP groups then arrived late at the layer-4 FSDP
prefetch, making a normal ~1–3 ms parameter gather appear to take 1.78
s. Together with narrower checkpoint state, avoiding a query-layout
copy, and overlapping CP communication, the matched BF16 benchmark
improves from **22.741 s / 40.23% MFU** after #3638 to **18.999 s /
47.79% MFU**.

- Bucket the indexer's autotune key by compressed-key length, also
keying on head count and dimension. Exact key lengths still control
addressing and masks. An all-rank trace showed the last rank arriving
1.718 s late and completing the gather in 1.34 ms; it had been
benchmarking the first CSA indexer.
- Register the FP8 indexer as an opaque operation and make its final
int32 selection a mandatory checkpoint save. This preserves the top-k
replay requirement while retaining compact IDs and skipping indexer
scoring on replay.
- Apply query RoPE directly in the sparse kernel's `(batch, tokens,
heads, dim)` layout, removing the transpose/contiguous round trip in
attention and the indexer.
- Launch the main KV CP gather with PyTorch's asynchronous functional
collective before query/compressor computation, and wait just before
consuming KV. Its registered backward performs the corresponding sum
reduce-scatter. Compilation stays enabled; communication uses NCCL's
existing stream.

### SAC configuration

Exact configuration for the measured run:

```toml
[model.ac]
mode = "selective"
freq = 1
targets = [
  "prime_rl::dsv4_sparse_attn",
  "prime_rl_collectives::all_to_all_single_equal",
  "aten::sort.stable",
]
```

`prime_rl::fp8_indexer` is saved automatically by the mandatory policy
in both full and selective checkpointing. The qualified stable-sort
overload matters: `aten::sort` does not match `aten::sort.stable`.

### Measurements

| Variant | Mean step time | Logged tokens/s | Logged MFU |
| --- | ---: | ---: | ---: |
| PR #3638 only (job 653) | 22.741 s | 86,890 | 40.23% |
| Indexer tuning buckets, full AC (665) | 20.718 s | 95,043 | 44.01% |
| Buckets + sparse-attention/EP-count SAC (675) | 20.042 s | 97,636 |
45.21% |
| All changes + SAC above (691) | **18.999 s** | **103,210** |
**47.79%** |

This is a **1.197× step-time speedup** over #3638 alone and **1.055×**
over the prior SAC run. Peak rank-0 reserved memory is **232.5 GiB /
267.7 GiB**. All five losses are finite. These are short benchmark
results, not a long-run convergence measurement. Measurements use the
pinned job-492 environment; this branch is rebased onto current main,
whose touched modeling files were identical to that baseline.

### Validation

- CPU checkpoint-policy tests: 4 passed on the PR branch, including
mandatory indexer retention under custom SAC targets. Ruff lint and
formatting checks passed for all changed files.
- Existing FP8-indexer GPU correctness cases: 2 passed. Changing key
lengths 1060 → 1064 → 1073 reused one autotune entry (2.015 s initial
tuning, then 0.919 ms and 0.634 ms).
- Existing sparse/eager attention parity cases: 9 passed, covering CSA,
HCA, sliding attention, packed documents, and empty compression.
- Existing CP packing checks: 6 passed across CP2/CP4 and all three
attention types; rerun successfully after inlining the gather and wait
calls directly in attention forward.
- Two-rank async-collective probe: outputs and input/weight gradients
passed with full/selective checkpointing, eager execution and
`torch.compile(fullgraph=True)`.
- Compiled two-rank BF16 attention checks: all three attention types
passed under full/selective checkpointing against the blocking
implementation; maximum relative L2 difference across outputs and
gradients was 0.026%. The sliding cases ran in a separate process after
the combined test harness reached its compiled-variant limit.
- Query-layout microcheck: bitwise-equal outputs and input gradients in
BF16/FP32, including the production query shape.



<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes touch CP collectives, compile/custom-op boundaries, and SAC
correctness for non-replayable top-k; numerics are covered by existing
kernel and CP tests but production timing depends on NCCL stream overlap
behavior.
> 
> **Overview**
> This PR targets **DeepSeek V4 training step time** by cutting FP8
indexer autotune churn, overlapping context-parallel communication, and
tightening activation-checkpoint behavior around sparse indexing.
> 
> The **FP8 Lightning indexer** is registered as `prime_rl::fp8_indexer`
and added to the **mandatory** selective-activation-checkpoint save list
so replay keeps the final int32 top-k without re-running scoring. Triton
autotune now keys on **`next_power_of_2(S_k)`** plus head count and
dimension so packed batches with slightly different compressed-key
lengths reuse one tuned config.
> 
> In **attention**, queries stay in **`(batch, tokens, heads, dim)`**
through RoPE and into `dsv4_sparse_attn`, dropping the
transpose/contiguous path. Under CP, **KV all-gather** starts
asynchronously via `_c10d_functional.all_gather_into_tensor` before
query and compressor work, with **`wait_tensor`** immediately before KV
is consumed.
> 
> Tests assert mandatory checkpoint retention for the new op and extend
CP parity mocks for the async gather path.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6449f9212c3430c812b9623a1b5bd274e350b780. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 16:07:21 -04:00
samsjaandGitHub 8da21f16b8 feat(eval): make task dispatch rate configurable (#3602)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Optional config with default unchanged; reuses existing orchestrator
dispatch rate limiting with no auth or data-path changes.
> 
> **Overview**
> Eval runs can now cap how fast episodes are dispatched via a new
**`tasks_per_minute`** setting on **`ServedEvalConfig`** (shared by
standalone eval and SFT online eval). **`None`** keeps the previous
behavior with no rate limit; a positive value throttles dispatch through
the existing **`Dispatcher`** **`AsyncLimiter`**, intended to pace
sandbox provisioning during autoscaling.
> 
> The eval **`runner`** passes **`config.tasks_per_minute`** into the
dispatcher instead of hard-coding **`None`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
31f8041b908234dc4c45f128540af8e4daa6435b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 09:30:15 -07:00
ae37b35a34 fix(trainer): match vLLM's per-token FP8 activation quantization bit for bit (#3623)
RL compares trainer and inference logprobs token by token, so any
disagreement between the two FP8
quantizers is model-independent noise. The trainer's per-token
activation cast is now bit-identical to
vLLM's production CUDA op, `torch.ops._C.per_token_group_fp8_quant`.

- Three kernels in `fp8_utils.py` floor `amax` at `1e-10` and use
`tl.math.div_rn` for scale and quotient.
Triton's `/` lowers to multiply-by-reciprocal, one fp32 ULP off the
correctly rounded value.
- The weight kernel is untouched: vLLM's weight path is itself a
reciprocal-multiply and already matched.
- A new GPU test pins the equality against the CUDA op; the trainer
still imports vLLM nowhere.

Share of 128-wide groups whose scale is bitwise equal to vLLM's, and
share of elements whose fp8 byte
is, on four 4096x4096 bf16 activation tensors on an H200:

| tensor | scales: before | after | bytes: before | after |
|---|---|---|---|---|
| randn x0.02 | 42.8329% | 100.0000% | 98.1890% | 100.0000% |
| randn x1.0 | 41.0797% | 100.0000% | 99.8822% | 100.0000% |
| randn x30.0 | 43.6028% | 100.0000% | 99.8869% | 100.0000% |
| randn heavytail 16ch x50 | 42.7979% | 100.0000% | 99.8999% | 100.0000%
|

Every pre-fix mismatch was exactly one e4m3 step, so weights stay at
100% and dequantization error is
unchanged. Agreement with vLLM's Triton fallback drops to about 42% on
scales, which is forced since
vLLM's two backends are not bit-identical to each other and only the
CUDA op runs in production. Costs
3.1% of quant-kernel time at 4096x4096 and 8.7% at [8192, 7168].
Verified on sm90 with
`use_ue8m0=False`; sm100 takes a different vLLM kernel.

## Effect on training gradients

The old floor applied to the scale, not to `amax`, so any 128-wide group
with `amax < 0.0448` was
quantized against an inflated scale: its values were squeezed into a
corner of the e4m3 range
instead of spanning it, and everything below `1e-7` rounded to zero.
Forward activations sit above
that threshold; gradients do not, and both the input-gradient (dgrad)
and weight-gradient (wgrad)
paths cast `grad_output` through these kernels. The error is one-sided
toward zero, so it shrinks
gradients rather than adding noise.

Measured end to end: a 131k-context SWE RL run with an FP8 trainer on
pre-fix code logged
`optim/grad_norm` averaging 0.0079 over 100 steps, against 0.0465 and
0.0528 for otherwise
identical runs with a bf16 trainer. A rerun of that config on the fixed
kernels is at 0.0421 over
its first 17 steps, where the pre-fix run read 0.0094 and the bf16
reference 0.0468 over the same
window. Mismatch KL is blind to all of this, since it depends on the
forward alone: lr = 0 probes
read 0.0089 before the fix and 0.0091 after.

### Why the floor's location matters

Per 128-element group:

```
# before
amax  = max(|x|)
scale = max(amax / 448, 1e-4)      # floor on the SCALE
y     = x / scale

# after
amax  = max(max(|x|), 1e-10)       # floor on the AMAX
scale = div_rn(amax, 448)
y     = clamp(div_rn(x, scale), -448, 448)
```

A floor exists only to keep an all-zero group from dividing by zero. The
correct scale, `amax / 448`,
maps the group's largest element to exactly 448 and spans the full e4m3
range. Pinning the scale at
`1e-4` makes it too large whenever `amax < 0.0448`, and a scale that is
too large makes `y = x / scale`
too small, so the group occupies a corner of the range.

Take a gradient group with `amax = 1e-5`:

- correct scale is `1e-5 / 448 = 2.2e-8`, giving `y_max = 448`, the full
range
- old scale is `1e-4`, giving `y_max = 0.1`, a sliver of it
- e4m3's smallest subnormal is `2^-9 = 0.00195`, so any `|y|` below
about `0.001` rounds to zero
- that is every `|x|` below `1e-7`, which is 1% of this group's maximum
- at `amax = 1e-6` the same `1e-7` cutoff erases everything below 10% of
the maximum

Two properties make this worse than rounding noise. It is one-sided,
always toward zero, so it biases
the gradient short rather than jittering it. And it is non-uniform:
groups above `0.0448` are exact
while groups far below it are gutted, so the surviving gradient also
points in a different direction.
AdamW's per-parameter normalization absorbs much of the magnitude loss,
which is why a run carrying
this bug trains through it while looking healthy.

## Launch-config retune

This PR also reconfigures the kernel launch specs for perf (for H200).

Measuring the cost of correct rounding exposed a separate problem: these
kernels were already launched
at block sizes that spill registers. The per-channel cast used a `[128,
128]` fp32 tile, and
`div.rn.f32` needs more live temporaries than `div.full.f32`, which is
why correct rounding looked
expensive there. Retuning `BLOCK_M`, `BLOCK_N` and `num_warps` in five
host wrappers, with no kernel
body change, recovers more than correct rounding costs.

Measured on an H200 at this model's dimensions (hidden 4096, MoE
intermediate 2048, 8 local experts
with ragged routing), 102 configs against a noise-control arm:

| kernel | wins | regressions | noise | best delta |
|---|---|---|---|---|
| `grouped_per_channel` k-major | 24 | 0 | 2 | -54.1% |
| `grouped_per_channel` row-major | 21 | 0 | 5 | -35.3% |
| `per_token` transposed | 6 | 0 | 6 | -44.8% |
| `grouped_per_token` | 7 | 0 | 19 | -12.0% |
| `per_token` | 3 | 0 | 9 | -12.4% |

Ragged expert groups gain more than equal ones: at K=4096 with 4096
tokens per rank, the k-major
per-channel cast is -28.5% on an equal split and -54.1% under realistic
routing. A launch config cannot
change the arithmetic, so bit identity against the CUDA op is
unaffected.

## Verification

```
uv run --no-sync python -m pytest tests/unit/train/models/test_fp8_utils.py -q
```

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 11:14:43 -04:00
Matej SirovatkaandGitHub 77788ba020 fix: retain two reduce-scatter input buffers for FP32 MoE routers (#3638)
FP32 MoE routing uses a separate FSDP unit. Its post-backward hook can
request a reduce-scatter input buffer while the expert reduction is
still in flight; FSDP's default limit of one inserts a compute-stream
wait before attention backward can run.

Set `set_reduce_scatter_max_input_buffers(2)` on that router unit
immediately after sharding. FSDP resolves the shared buffer limit to the
maximum across its units, allowing the router to pack gradients while
the expert reduction completes. This adds two lines on top of main, with
no new configuration or numerical dtype changes. The tradeoff is
additional memory for in-flight reduction inputs.

### Measured timings

Same saved packed tokens and checkpoint, GLM-5.3 EP8/CP8 on 32 B300
GPUs, FP32 routing, full activation checkpointing, and activation
offloading enabled in both runs. Two warmup passes followed by one
profiled forward/backward; no optimizer update.

| Metric | One buffer | Two buffers |
| --- | ---: | ---: |
| Warm forward + backward, median across 32 ranks | 14.699 s | 12.649 s
|
| Profiled forward + backward, median across 32 ranks | 14.808 s |
12.717 s |
| Expert reduce-scatter overlap with main-stream compute, rank 0 | 11.1%
| 93.7% |
| Maximum reserved GPU memory across ranks/passes | 204.49 GiB | 205.29
GiB |

Warm forward/backward is **13.9% shorter**, equivalent to **16.2% higher
throughput**, at **0.80 GiB** more peak reserved memory in this run.

### Timeline of the stall

Actual CUDA kernel intervals for layer 77, rank 0. Each panel is aligned
independently to that layer's expert reduce-scatter launch. Blue is
other main-stream compute, green is attention backward, and orange is
expert gradient reduce-scatter.

![Measured one-buffer versus two-buffer reduce-scatter
overlap](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/1bebf826b530cb7c52d18d8cf92d562174a7efbe/reduce-scatter-overlap.png)

With one buffer, the router's post-backward hook queues a compute-stream
wait while the **4.5 GiB expert reduction** is in flight. This creates a
**40.7 ms main-stream compute gap**. The router's own reduction is only
**6 MiB / 0.66 ms**. Attention backward starts **48.87 ms** after the
expert reduction launch; with two buffers it starts at **8.15 ms**
instead. The layer's expert-reduction overlap rises from **7.3% to
96.3%**. These layer-specific percentages differ from the aggregate
values in the table.

These are single-run comparisons, not repeated statistical benchmarks.
The measured experiment set the cap at the root; this PR applies the
same effective shared cap through the router unit. Ruff and `git diff
--check` pass; this exact main-based patch has not had a new distributed
run.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Two-line FSDP scheduling tweak in MoE setup only; no numerical or API
changes, with modest extra peak memory for reduction buffers.
> 
> **Overview**
> When **FP32 MoE routers** are sharded as their own FSDP unit
(alongside expert-parallel expert shards), backward can stall: the
router’s post-backward reduce-scatter needs an input buffer while the
much larger expert gradient reduction is still using FSDP’s default
single buffer, forcing a **compute-stream wait** before attention
backward can proceed.
> 
> Right after `fully_shard` on `block_mlp.router`, the PR calls
**`set_reduce_scatter_max_input_buffers(2)`** so the router can queue
its small reduction without blocking on the in-flight expert
reduce-scatter. FSDP’s shared limit becomes the max across units—same
effective behavior as raising the cap at the root, but scoped to the
router shard path. **Tradeoff:** slightly more memory for in-flight
reduction inputs; no new config or dtype changes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
51a9e3daef8a53a254d7e7ff35d1ee3c8afce18c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 17:02:46 +02:00
Scott CabrinhaandGitHub ab85b3b369 fix(docker): install the Prime CLI into the image venv for hosted-run env bootstrap (#3635)
## Problem

Since #3585 removed the `prime` CLI as a prime-rl dependency ("Stop
installing the `prime` CLI with prime-rl. Run `uv tool install prime`
when the CLI is needed"), the published GHCR images ship no `prime`
executable. That breaks Hosted Training runs on these images at
bootstrap:

The platform's env-server and orchestrator pods prepend an
**authenticated** Hub env install to their pod command,

```
uv run --no-sync prime env install '<owner/name>' && ... && uv run --no-sync env-server @ config
```

because verifiers' own `ensure_installed` resolver fetches the Hub
**unauthenticated** and 404s on private environments — the pre-install
into the pod's venv is what makes v1 Hub tasksets resolvable at boot
(envs baked into the image never hit this path).

With the executable absent from `/app/.venv/bin`, every pod dies at
spawn and the run wedges at `CREATING`. Observed on
`ghcr.io/primeintellect-ai/prime-rl:v0.9.1.dev100` dispatching a run
with a Hub taskset:

```
error: Failed to spawn: `prime`
```

(the orchestrator's entire log is two lines: the no-checkpoints warning,
then that spawn failure).

## Fix

Install the CLI into the image venv at build time — **not** as a project
dependency, so #3585's "CLI as a separate tool" boundary stands for
library code; the image just ships the executable and its runtime deps
so the platform bootstrap can run.

- One `RUN` after the main `uv sync`, using the same uv cache mount as
the rest of the file.
- `prime>=0.7` — pure-Python CLI, few MB; most deps
(httpx/pydantic/etc.) are already in the venv.
- The runtime stage copies `/app` wholesale, and `PATH` already puts
`/app/.venv/bin` first, so `uv run --no-sync prime env install ...` and
direct `prime` calls both resolve.

## Alternatives considered

- Reverting #3585's dependency removal: rejected — keeps the boundary;
the image need, not the library, is what broke.
- Platform-side init container with a dedicated prime-cli image (cleaner
long-term: keeps the CLI out of the framework image entirely) — worth
tracking on the platform side; this PR is the minimal unblock for hosted
Hub-env runs today.

## Verification

- `VIRTUAL_ENV=<venv> uv pip install 'prime>=0.7'` smoke-tested locally
(CLI 0.7.0 boots).
- Placement reviewed against the builder stage: runs after the locked
sync chain, before the optional NIXL block; nothing downstream
overwrites the venv.
2026-09-22 19:06:08 -06:00
Mika SenghaasandGitHub de5cdb8bae fix: read serialized dashboard token counts (#3632)
## Summary

- pin Verifiers `main` at the merge of [Verifiers
#2652](https://github.com/PrimeIntellect-ai/verifiers/pull/2652),
including the computed fields from [Verifiers
#2651](https://github.com/PrimeIntellect-ai/verifiers/pull/2651)
- read serialized token counts directly from completed episode and live
trace records
- remove dashboard-specific token reconstruction and prompt-token
summation

The previous implementation summed every full prompt in a multi-turn
trace.
This counted the shared conversation once per request and inflated long
rollouts.

## Verification

Before this change, a two-turn trace with prompt usages of 100 and 150
tokens
reported 250 input tokens. After this change, the serialized record and
both
dashboard paths report 130 input tokens and 50 output tokens.

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

## Validation

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

## Note on "no timeout"

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

## Validation

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

## Validation

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

## Validation

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

<!-- CURSOR_SUMMARY -->
---

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

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

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


<!-- CURSOR_SUMMARY -->
---

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

---------

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

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

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

---------

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

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

## Why

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

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

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

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

## Test plan

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

## Why

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

## Validation

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

Depends on PrimeIntellect-ai/renderers#156.

<!-- CURSOR_SUMMARY -->
---

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation and example path updates only; no training, inference,
or runtime code changes.
> 
> **Overview**
> Renames the advanced GLM example from **`glm-5.2`** to **`glm-5.3`**
and updates every inbound link and launch snippet so docs match the
presets that target GLM-5.3.
> 
> **README**, **docs** (`advanced.md`, `configuration.md`,
`scaling.md`), and **examples/README** now point at
`examples/advanced/glm-5.3/` and describe **`GLM-5`/`GLM-5.3`** instead
of 5.2. The **glm-5.3** walkthrough updates `uv run rl` / `uv run
inference` paths; **`infer/pd-llmd.toml`** only fixes its launch comment
to the new path (config content such as `GLM-5.2-FP8` model IDs is
unchanged).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fb2d99039d8719ff2bcdf2ac1e2c7baaa6f49946. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Johannes Hagemann <johannes@Johanness-MacBook-Pro.local>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 00:22:35 -07:00
samsjaandGitHub a9005aba8e fix(examples): express GLM-5.2 SWE shared model as a [model] table (#3591)
## Summary
PR #3588 centralized the model id for
`examples/advanced/glm-5.2/swe.toml` as a top-level
string (`model = "zai-org/GLM-5.3-BF16"`), but `RLConfig.model` is a
`SharedModelConfig`
table, so no config class could parse the file and CPU tests on `main`
failed
(`test_load_configs[examples/advanced/glm-5.2/swe.toml]`).

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

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

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

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

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

## Test plan

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

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

## Breaking

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

## Verification

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

---------

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

## Verification

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

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

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

After:

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

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

---------

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

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

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

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

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

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

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

## Changes

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

## Validation

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

**Eval Overview**

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

**Eval Metrics**

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

**Train Overview**

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

**Train Metrics**

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

---------

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

## Context

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

## Verification

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

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

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


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

## Validation

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

<!-- CURSOR_SUMMARY -->
---

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

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

## Verification

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

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

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

## Verification

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## Verification

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

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

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

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

---------

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

---------

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

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

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

## Verification

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

Why:

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

Important:

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

Examples:

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

## Breaking

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

## Verification

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

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking CLI and config renames affect existing scripts; env-server
address discovery replaces fixed ports across `rl`, `sft`, and `eval`
launch paths.
> 
> **Overview**
> **Replaces `uv run evals` with `uv run eval`** as the standalone
evaluation entrypoint, sharing the orchestrator eval pipeline
(per-source env servers, adaptive or pinned concurrency, file/W&B/Prime
monitors). Config is **flattened** (`[[source]]`, `[client]`,
`[concurrency]` at top level); **`--resume`** continues from the trace
stream instead of a `[ckpt]` cursor; SFT **online eval** is renamed and
typed as `SFTOnlineEvalConfig` (no public `[online]` block).
> 
> **Env server wiring changes:** fixed `env_server_base_port` ranges are
removed—launcher-managed servers bind **OS-assigned loopback ports** and
publish addresses via **`address_file`** /
`configs/.../envs/<split>/<name>.address`. Training **`ratio`** and
online-eval **`interval`** are scoped to the right source types only.
> 
> **Docs and examples** add `docs/eval.md`, per-example `eval.toml`
files, and `configs/debug/eval/*` smokes; **`configs/evals/swe.toml` is
deleted**. CI adds a **gsm8k eval** integration test on VM runners.
> 
> **Dashboard** gains live rollout APIs and eval-centric metrics
(plan-driven progress, platform links, eval run status), renames
**`evals.log` → `eval.log`**, and tightens static asset revalidation.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
82f2f0eda7628c874be6dcfcda700cab26fd4442. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 11:04:24 -07:00
xianzheng shanandGitHub 0d372c1fd6 fix(inference):Fix native disk KV cache offload tier type (#3538)
## Summary

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

## Problem

The inference configuration emitted a secondary tier of the form

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

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

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

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

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

## Changes

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

## Validation

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

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

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

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

---------

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Build-only Dockerfile alignment with pyproject extras; no application
or dependency logic changes beyond fixing the sync command.
> 
> **Overview**
> Repairs **CUDA Docker image builds** that broke after the `gpt-oss`
optional extra was removed from `pyproject.toml` (#3424).
> 
> Both `uv sync` steps in `Dockerfile.cuda` (the cached third-party
layer and the full workspace sync after sources are copied) no longer
pass `--extra gpt-oss`. **`uv` was failing** on an undefined extra; the
remaining extras (`gpu`, flash-attn variants, `disagg`, `quack`,
`kernels`, `mamba-ssm`, etc.) are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b340617baed2ffb69a2a1adc800e9264f4c32ba2. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Johannes Hagemann <johannes@Johanness-MacBook-Pro.local>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 22:03:42 -07:00
samsjaandGitHub eff12f2483 chore: glm-4.5-air swe example to muon + 2 trainer / 4 inference nodes (#3546)
## Summary

Updates the GLM-4.5-Air `scaleswe` advanced example to mirror the
research-prod air ablation base config (research-prod PR #198): 2
trainer nodes with Muon instead of the single-node sign-SGD setup, and 4
one-node inference replicas. Router replay, `max_off_policy_steps`, and
the length-penalty weights stay unchanged.

## Changes

- **Deployment**: `1 train + 3 infer replicas` -> `2 train + 4 infer
replicas` (one-node replicas)
- **Optimizer**: `sign_sgd` -> `muon`; drop the sign-SGD-era
`optim_cpu_offload = false` / `full_offload = true` and `[trainer.ckpt]
skip_optimizer` (optimizer state is checkpointed again, so runs can
resume)
- **Trainer memory**: `fused_lm_head_token_chunk_size` (8192) and
`optim_cpu_offload` (true) use their defaults (per review); keep cp=4
(ulysses) and activation checkpointing + offloading
- **Orchestrator**: unchanged (`batch_size = 256`, `group_size = 16`,
`max_off_policy_steps = 32`, linear length penalty with
`num_output_tokens_weight = 0.0`, input/turns weights 0.1)
- **Router replay**: unchanged, stays enabled
(`trainer.enable_router_replay` +
`inference.vllm.enable_return_routed_experts`)
- **Inference**: added `enable_expert_parallel = true` and
`gpu_memory_utilization = 0.85` (TP=8 + EP)

## Validation

- `uv run rl @ examples/advanced/glm-4.5-air/swe.toml --dry-run`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Example TOML only; no application code, auth, or data-path changes.
> 
> **Overview**
> Updates **`examples/advanced/glm-4.5-air/swe.toml`** to match the
research-prod air ablation base (research-prod PR #198) instead of the
old single-node sign-SGD layout.
> 
> **Deployment** scales to **2 trainer nodes** and **4 inference
replicas** (was 1 train / 3 infer). **Training** switches the optimizer
from **`sign_sgd` to `muon`**, drops sign-SGD-only trainer settings
(`full_offload`, explicit LM-head chunk size, **`skip_optimizer`**
checkpointing), so **optimizer state is saved again** and jobs can
resume. Comments now describe Muon + two-node training and default
LM-head chunking / CPU optimizer offload.
> 
> **Inference** adds **`enable_expert_parallel = true`** and
**`gpu_memory_utilization = 0.85`** alongside existing TP=8 and router
replay. GRPO batch/group sizes, length-penalty weights, and router
replay behavior are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
91c71d25ac6b277aa1ddd5631384e40fb080f53f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-14 17:18:28 -07:00
e0886c152d chore(trainer): unify context-parallel setup across models (#3533)
Unifies all context parallel setup so that a single frozen `CPContext`
dataclass is shared by all cp-aware modules, stored under a
`self.cp_contex: CPContext` attr.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 14:03:40 -04:00
9ef21a64f1 docs(examples): restore launch READMEs, add vlm section, slim advanced examples (#3537)
## What

Related changes to `examples/` and `configs/`:

### 1. Launch walkthroughs for the advanced examples

`#3085` restructured `examples/` into `basic/` + `advanced/` and dropped
the per-example READMEs — the step-by-step launch guides. Since then the
advanced folders had no how-to-start documentation. This PR restores
them, rewritten against current usage (not copied from history):

- **`examples/advanced/glm-4.5-air/README.md`** — config-by-config table
(train/eval sources, node topology), sandbox setup (Prime Intellect
Sandboxes by default, swap `env.agent.runtime` for your own),
`SERPER_API_KEY` forwarding, launch via `uv run rl @ ...` with built-in
sbatch submission, `uv run dashboard` how-to, resume/export.
- **`examples/advanced/glm-5.2/README.md`** — 32-node RL configs, the
llm-d + Mooncake variant, the `infer/` pre-flights; documents that
`swe.toml` declares **no train source** and must be composed with a
source overlay.
- **`examples/advanced/qwen3-30b-a3b/README.md`** — same format: math
(subprocess runtime, no sandbox), SWE (sandbox), tool use (Modal
runtime, `modal setup`).

Why rewritten and not resurrected: `scripts/tmux.sh` was removed
(`#3351`, replaced by `uv run dashboard`), the `.env` auto-sourcing is
gone, `--wandb.*` became `--monitors.wandb.*`, and HF weight upload was
replaced by DCP checkpoints + `tools/convert_dcp_to_bf16.py`. Every
claim was checked against the configs on `main` and `docs/training.md` /
`docs/scaling.md`.

### 2. Refined `examples/README.md`

Proper `basic/`, `extra/`, and `advanced/` sections with per-example
one-liners (domains, node counts, context length), a where-to-start
pointer (reverse-text first), and a related-configs section.

### 3. `extra/` section

`dynamo/` (external Dynamo inference + NCCL weight updates) and the VLM
SFT configs (moved from the `examples/` root, `vlm_sft`/`vlm_sft_moe`)
now live in **`examples/extra/`** — material that doesn't follow the
basic eval → SFT → RL walk-through pattern. `basic/` keeps only the
core-environment walk-throughs.

### 4. Config-only folders move to `configs/`

- `minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`:
`examples/advanced/` → **`configs/advanced/`** — frontier configs
without tutorials are configs, not examples.
- `examples/evals/` → **`configs/evals/`** — standalone evals (`uv run
evals @ configs/evals/swe.toml`) are configs too; the reference in
`skills/training/start-run/SKILL.md` is updated.

All other references updated: root `README.md` (advanced list:
Qwen3-30B-A3B, GLM-4.5-Air, GLM-5), `examples/README.md`,
`configs/README.md`, `docs/configuration.md`, `docs/scaling.md`. Moves
are pure `git mv`; no config content changed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation and config path reorganization only; VLM loss-mask TOML
changes are equivalent defaults with clearer comments.
> 
> **Overview**
> Restores **step-by-step launch READMEs** for
`examples/advanced/glm-4.5-air`, `glm-5.2`, and `qwen3-30b-a3b` (SLURM
launch, sandboxes/Modal, dashboard, resume/export), and **reorganizes**
`examples/README.md` into `basic/`, `advanced/`, and new **`extra/`**
(`dynamo/`, `vlm/`).
> 
> Frontier configs **without** walkthroughs move from
`examples/advanced/` to **`configs/advanced/`** (`minimax-m2.5`,
`nemotron-3-super`, `deepseek-v4-flash`); standalone evals move to
**`configs/evals/`** (e.g. `swe.toml` path in comments and docs).
Cross-links update in the root README, `configs/README.md`,
`docs/configuration.md`, and `docs/scaling.md` (Nemotron/MiniMax now
point at `configs/advanced/`; advanced list trimmed/relabelled for
GLM-5).
> 
> Adds **`examples/extra/vlm/README.md`** and tightens VLM SFT TOMLs
with explicit `[data.loss_mask] assistant = true` (replacing the full
mask table in the MoE config). **`dynamo`** launch path updates to
`examples/extra/dynamo/rl.toml`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ed086f6797af9755e61acce6b672df50387f3b6d. 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: samsja <samsja@users.noreply.github.com>
2026-09-12 19:35:47 -07:00
samsjaandGitHub 1e7c6888b6 feat(trainer): add optional IcePop loss (#3526)
## Summary

Add IcePop as an explicit, opt-in RL loss while preserving IPO as the
default.

```toml
[trainer.loss]
type = "icepop"
ratio_low = 0.2
ratio_high = 5.0
```

Accepted tokens use the importance-weighted policy-gradient term; tokens
outside the inclusive trainer/inference ratio band are dropped. IcePop
has no separate KL term. `adv_tau` remains configurable.

The acceptance test is performed in log space and masked ratios are
replaced before exponentiation. This is mathematically equivalent for
accepted tokens while preventing a rejected extreme ratio from producing
`0 * inf = NaN` in the loss or gradient.

Addressing review feedback: the rl losses are now loss objects
(`IPOLoss`, `IcePopLoss`, `CustomLoss`) initialized from their loss
config, satisfying a structural `Loss` protocol with an explicit
`.loss()` method (no `__call__`), and `setup_rl_loss_fn` builds the
right object from `[trainer.loss]` via a class-pattern `match` statement
(review suggestions from @hallerite). The IcePop paper (Ring-1T
technical report, [arXiv 2510.18855](https://arxiv.org/abs/2510.18855))
is linked from `docs/algorithms.md`.

This PR intentionally contains no DPPO, cache-salt, or experiment
configuration changes.

## Verification

- `176 passed` in `tests/unit/test_configs.py`
- CPU loss/gradient checks passed for inclusive `0.2` and `5.0`
boundaries
- CPU loss/gradient checks passed for a rejected extreme ratio
(`exp(100)` case)
- CPU checks passed for the loss-object dispatch: `setup_rl_loss_fn`
builds `IPOLoss` / `IcePopLoss` / `CustomLoss`, and unsupported configs
raise `TypeError`
- CPU checks passed for the `Loss`-protocol `.loss()` path through
`compute_loss` (rl component, ipo + custom loss)
- Ruff formatting and lint checks pass

GPU unit coverage for the same boundary and numerical-safety cases is
included for CI.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes the core RL loss implementation and adds a new training
objective path; incorrect masking or numerics would directly affect
policy gradients, though IPO/default behavior is preserved and tests
cover boundary and NaN cases.
> 
> **Overview**
> Adds **IcePop** as an opt-in `[trainer.loss]` variant (`type =
"icepop"`) while **IPO remains the default**. IcePop keeps only tokens
whose trainer/inference importance ratio lies in an inclusive band
(`ratio_low` / `ratio_high`, defaults 0.2–5.0), applies the usual
importance-weighted policy-gradient term on accepted tokens, and **drops
IPO’s separate KL penalty**; `adv_tau` is still configurable.
> 
> The RL loss path is refactored from free functions into callable
**`IPOLoss`**, **`IcePopLoss`**, and **`CustomLoss`** objects wired
through `setup_rl_loss_fn`. IcePop evaluates the acceptance band in log
space with a **detached** mask and zeroes rejected log-ratios before
`exp` so extreme off-policy ratios cannot yield `0 × inf` NaNs in loss
or gradients. Config adds `IcePopLossConfig` with pydantic validation
that `ratio_low ≤ ratio_high`.
> 
> Docs (`docs/algorithms.md`, config skill) describe enabling IcePop;
unit tests cover ratio boundaries, gradients, the extreme-ratio safety
case, and config parsing.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f69d2e69ad4802ce6fdb2e48fb9fd7d0c87f88c8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-12 17:51:42 -07:00
815d1c0cad chore(examples): drop empty [monitors.prime] sections (#3536)
## What

Removes the bare `[monitors.prime]` sections (empty tables, no keys)
from the example configs:

- `examples/advanced/glm-4.5-air/search.toml`
- `examples/advanced/glm-4.5-air/swe.toml`
- `examples/advanced/glm-4.5-air/terminal.toml`
- `examples/advanced/nemotron-3-super/swe.toml`

## Why

An empty `[monitors.prime]` table silently enables Prime Lab platform
monitoring (streaming metrics/episodes to the platform) for anyone who
starts a run from these examples. Dropping the section keeps the
examples monitoring-free apart from W&B, matching the other examples
(`glm-5.2`, `intellect-3.1`, `minimax-m2.5`, `qwen3-30b-a3b`, and all
`basic` examples), which never declare it.

Users who want platform monitoring can re-enable it with
`--monitors.prime` or the section itself (see `docs/training.md` ->
Platform monitoring).

## Notes

- Pure deletion of 8 lines across 4 files; all files still parse as
valid TOML.
- `configs/debug/concurrency.toml` also declares `[monitors.prime]`;
left untouched since this PR is scoped to examples.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Example-only TOML deletions; default monitoring behavior for runs
started from these four configs changes from implicit Prime Lab on to
off, with no runtime or training logic changes.
> 
> **Overview**
> Removes bare **`[monitors.prime]`** blocks (empty tables with no keys)
from four advanced example training configs: GLM-4.5-Air **search**,
**swe**, and **terminal**, plus **nemotron-3-super** SWE.
> 
> Those sections were enough to turn on **Prime Lab platform
monitoring** (metrics/episodes streaming) for anyone launching from the
examples, even though only **`[monitors.wandb]`** was intentionally
configured. After this change, the examples match the rest of the tree
(W&B only unless users opt in via **`--monitors.prime`** or a populated
**`[monitors.prime]`** section).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2fb5bd42edfef2ea4ed67951352a0519a9964e57. 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: samsja <samsja@users.noreply.github.com>
2026-09-12 17:20:05 -07:00
Matej SirovatkaandGitHub 28bb83bea7 fix(qwen3.5): address follow-up review cleanup (#3534)
Follow up on Garrett's review of #3429. Composite MoE models store
expert counts in `text_config`, so `is_tt_moe_model` missed them and the
trainers skipped their load-balancing statistics. Resolve the text
config before checking expert counts, with a CPU check covering
dense/MoE text and VLM configs.

Remove the unused-argument `del` statements while preserving the public
signatures. Drop the zero-initialization assertion and the two-rank GDN
test that ordinary CI always skipped, as requested in review. Keep the
native forward/backward, packing, vision, MRoPE, and router replay
coverage.

Retain the existing compiler disable for CP convolution and link its
exact upstream bug. Two-rank H200 testing on PyTorch 2.13.0+cu130 / FLA
a954753 reproduces a Dynamo `copy_` shape error without the disable: the
functional collective returns `[6, 8192]`, while FLA supplies a stacked
`[2, 3, 8192]` output buffer. The same operation works eagerly; an
isolated compiled collective using a concatenated buffer followed by
reshape also passes.

Upstream status checked September 12: FLA main (`516143e`) still has the
identical communication helper. PyTorch issues
[#138795](https://github.com/pytorch/pytorch/issues/138795) and
[#155632](https://github.com/pytorch/pytorch/issues/155632) remain open.
The matching [fix
#177205](https://github.com/pytorch/pytorch/pull/177205) closed without
merging, and current PyTorch main still lacks the reshape. FLA's
[graph-capture RFC
#1155](https://github.com/fla-org/flash-linear-attention/issues/1155#issuecomment-5354945885)
defers CP; no exact FLA fix was found.

Validation:

- H200 Slurm 486: Qwen3.5 and shared MoE suite, **33 passed**. CPU MoE
suite: **15 passed**. Ruff check/format and whitespace checks pass.
- Standalone GDN probes use two H200 ranks and `torch.compile` with
default settings (graph breaks allowed), two packed layouts, native
unsharded output/input-gradient comparisons, and finite parameter
gradients. These isolate the convolution boundary; they do not establish
full trainer or image+CP compilation support.

| CP convolution disable | Selective AC | Result | Slurm job |
|---|---|---|---|
| Present | Off | Both layouts pass on both ranks | 484 |
| Removed in probe | Off | Dynamo collective shape error | 485 |
| Present | On | Both layouts pass on both ranks | 487 |
| Removed in probe | On | Both layouts pass on both ranks | 488 |

The checkpointed probe passing does not make removal safe: the supported
non-checkpointed configuration still fails. The isolated
stacked/concatenated collective comparison passed its expected failure
and parity checks (Slurm 489). Probe scripts and logs are retained
outside the repository under
`/home/matej/prime-rl-verify/qwen35-review-20260912/`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Targeted config lookup and test/doc cleanup; MoE detection fix reduces
risk of missing load-balance metrics on composite MoE models.
> 
> **Overview**
> **MoE detection** now reads expert counts from `text_config` when
present, so Qwen3.5 MoE VLMs are recognized and trainers collect
load-balancing stats instead of treating them as dense models. A CPU
parametrized test covers dense/MoE text and VLM config classes.
> 
> Review cleanup removes unused `del` stubs on public APIs
(`from_config`, RoPE helpers), drops CI-skipped Qwen3.5 tests (zero-init
norm assertion and two-rank gated-delta-net CP parity), and tightens the
comment on why context-parallel `causal_conv1d` stays outside
`torch.compile` (Dynamo all-gather vs FLA buffer layout,
[pytorch#155632](https://github.com/pytorch/pytorch/issues/155632)).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0520d09809547dfb8e982f2590702eee079c7e4f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-12 21:09:58 +02:00
Matej SirovatkaandGitHub 534888b77d feat(models): add native Qwen3.5 family implementation (#3429)
## Summary

Unify Qwen3.5 dense, MoE, and VLM training under a native
implementation, including the Qwen3.8 checkpoint that uses this
architecture. Remove the separate MoE package and global Transformers
model patches.

- Keep `Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL)` shared by the
backbone and causal LM; remove unused Transformers TP/PP plans,
split-module metadata, cache arguments, and redundant initialization.
Modules own their initialization, including zero-centered RMSNorm.
- Use Prime's shared attention and MoE runtime. Gated full attention
consumes the fused QKV projection with the correct doubled query width;
configured MoE load balancing allocates its router selection bias.
- Own packed DeltaNet, zero-centered RMSNorm, MRoPE, and the vision
encoder. Hybrid layers support Ulysses CP through FLA boundary-state
exchange; full attention uses common attention dispatch.
- Convert official fused MoE expert weights to Prime's split projections
and back, excluding MTP weights.
- Keep the narrow compiler boundary for FLA CP convolution, whose
collective layout fails Dynamo tracing. Vision FlashAttention has no
compiler disable and uses each backend's declared return format
directly.

Qwen tests live under `tests/unit/train/models/qwen3_5/`:
`test_model.py` parametrizes initialization, context-parallel setup, and
forward/backward/packing checks over dense and MoE configs;
`test_vlm.py` groups vision tests with CPU MRoPE checks. MoE router
replay remains a dedicated check. Tests use native configs and models
without Transformers reference models, HF weight comparisons, or Hub
downloads. Public model helpers use
`AutoModelForCausalLMPrimeRL.from_config` with the trainer's shared
auto-attention resolver, without hardcoded backends or private attention
config writes. Remove the class/source-introspection test and duplicate
shared-attention checks. Remove the blanket BF16 optimizer/reduction
restriction for RL VLMs; FP32 defaults remain unchanged and FSDP still
computes in BF16.

Text and vision consume Prime's resolved `model.attn` configuration
directly, including under Ulysses CP. Remove Qwen constructor
fallback/propagation logic, the forced vision SDPA override, and its
unused vision branch.

MTP and video training are outside this runtime's scope.
`scripts/mini_moe.py` is unchanged from main and is outside this PR's
validation.

## Math KL validation

Both checkpoints completed 20 steps on `math-env`
(`PrimeIntellect/Hendrycks-Math`, train split), with **batch size 64**.
Every step-mean KL is below **0.015**.

| Checkpoint | Steps | Mean KL over 20 steps | Highest step-mean KL |
|---|---:|---:|---:|
| `Qwen/Qwen3.8-27B` | 20 | 0.000359685 | 0.000953884 |
| `Qwen/Qwen3.5-35B-A3B` | 20 | 0.000208713 | 0.000462048 |

Runs executed concurrently on separate H200 nodes using `uv run rl @
<config>`, with four trainer and four inference GPUs per model. Both
Slurm jobs completed with exit code 0: dense job 387, MoE job 386.
Tested commit: `9983e7bed`.

Settings: main's `debug` algorithm with constant per-token advantage
1.0; original task sampler; math-verify scoring without the optional LLM
judge; Prime VM runtime enforcing the task network policy; sequence
length 4096, maximum completion length 2048, group size 8, learning rate
1e-6, compilation, selective activation checkpointing, FlashAttention 3,
and NCCL weight updates. MoE additionally uses EP=4 and router replay.
Inference uses `max_num_seqs=64`. Optimization and reduction dtypes
retain their FP32 defaults.

All 20 batches per model contained 64 trainable episodes, and all
gradient norms were finite. These are asynchronous E2E measurements of
`mismatch_kl/all/mean`; the summary averages the 20 step means and
includes normal policy staleness. The debug algorithm exercises training
with synthetic advantages, so this is a correctness check, not a
learning-quality benchmark. These 20-step runs use text inputs; packed
image-conditioned validation is recorded below.

<details>
<summary>All 20 step-mean KL values</summary>

| Step | Dense mean KL | MoE mean KL |
|---:|---:|---:|
| 1 | 0.000087817 | 0.000103068 |
| 2 | 0.000133938 | 0.000132430 |
| 3 | 0.000112734 | 0.000115124 |
| 4 | 0.000193951 | 0.000099179 |
| 5 | 0.000205668 | 0.000214333 |
| 6 | 0.000359477 | 0.000348763 |
| 7 | 0.000838096 | 0.000161281 |
| 8 | 0.000150568 | 0.000207813 |
| 9 | 0.000190916 | 0.000158351 |
| 10 | 0.000246897 | 0.000258552 |
| 11 | 0.000492465 | 0.000462048 |
| 12 | 0.000236148 | 0.000177551 |
| 13 | 0.000311170 | 0.000316216 |
| 14 | 0.000953884 | 0.000286797 |
| 15 | 0.000817523 | 0.000233271 |
| 16 | 0.000320892 | 0.000184788 |
| 17 | 0.000567697 | 0.000175972 |
| 18 | 0.000280278 | 0.000164684 |
| 19 | 0.000264224 | 0.000196673 |
| 20 | 0.000429352 | 0.000177372 |

</details>

## Packed VLM validation

Both models completed five packed image RL updates on MMMU Math dev,
with batch size 32 and an 8192-token trainer packing limit. All 160
samples per model included images.

| Model | Steps | Mean KL | Maximum step-mean KL | Images per packed
microbatch |
|---|---:|---:|---:|---:|
| Qwen/Qwen3.8-27B | 5 | 0.000501153 | 0.000729994 | 5–6 |
| Qwen/Qwen3.5-35B-A3B | 5 | 0.000346154 | 0.000458347 | 5–6 |

| Step | Dense KL | MoE KL |
|---:|---:|---:|
| 1 | 0.000231250 | 0.000167199 |
| 2 | 0.000387219 | 0.000343682 |
| 3 | 0.000553381 | 0.000360291 |
| 4 | 0.000729994 | 0.000401253 |
| 5 | 0.000603919 | 0.000458347 |

Native models; trainable vision encoder; FA3; compiled decoder blocks
and selective activation checkpointing; FP32 optimization and gradient
reduction; CP1; MoE EP4 and router replay; debug advantages; group size
8; maximum completion length 1024; inference context 4096; NCCL weight
broadcasts. These are correctness smokes on four repeated diagram
questions, not learning-quality benchmarks.

Packed MRoPE exactly matched individual-document MRoPE for all 320
training samples, and image-grid/pixel-patch counts matched each
document’s image-token spans. Both Slurm jobs exited 0 (dense 400, MoE
399). MoE needed allocator retries at the H200 memory limit.

Image+CP+compile remains separately unresolved; these E2E runs use CP1.

Tested runtime contents: `dcdf770df` (subsequent commits only change
tests). Run configs and detailed batch/position evidence are under
`/home/matej/prime-rl-verify/pr3429-20260910/`.

## Other validation

- Attention cleanup at `a2173601f`: H200 Qwen suite 24 passed, one
skipped; official dense/MoE model loading preserves configured attention
for text and vision at CP sizes 1 and 2. An additional compiled image/CP
backward check exposed `Autograd not support dtype: Int` with selective
activation checkpointing; the same error reproduces using the previous
SDPA vision path. Compiled image/CP validation remains unresolved. The
completed math runs above use CP=1.

- Native-only H200 Qwen suite: **20 passed, one expected single-rank CP
skip**, with `HF_HUB_OFFLINE=1` and `TRANSFORMERS_OFFLINE=1` (Slurm 407;
consolidated dense/MoE suite). Existing config suite: **175 passed**.
Ruff check/format pass. Both dense and MoE run the shared
packed-versus-unpacked comparison. MoE replays identical expert
selections to isolate document boundaries; ordinary routing
forward/backward remains covered.
- CI at `9983e7bed`: CPU unit tests, Ruff, slim install, and CodeQL
pass. GPU CI passes the Qwen tests; its five failures are in unchanged
DeepSeek V4 tests (three packed-batch assertions reproduced on
unmodified main `bad80b1a3`, two FP8 architecture failures). GPU CI: 66
passed, 82 skipped, 599 deselected, five failed.
- Two-rank H200 compiled packed DeltaNet output and input-gradient
checks passed with the CP convolution compiler boundary.
- Exact official checkpoint key/shape conversion and reverse conversion
passed: dense 1,199 source keys to 1,184 runtime keys; MoE 1,811 source
keys to 1,066 runtime keys after excluding MTP.
- Full H200 unit suite: 737 passed, 12 skipped, three DeepSeek V4
failures also reproduced on unmodified main. The weight-transfer test
imports the unified model.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Large change to core training models (hybrid attention, MoE weight
conversion, packed multimodal RL) with removed Transformers workarounds;
regressions would affect Qwen3.5/3.8 RL and VLM correctness rather than
peripheral code.
> 
> **Overview**
> Replaces the split **Qwen3.5 dense + MoE packages** and **Transformers
runtime monkey-patches** with one **native PrimeRL implementation**
under `models/qwen3_5/`. Dense text, MoE text, and composite VLMs all
dispatch to **`Qwen3_5ForCausalLM`**, driven by local configs
(`Qwen3_5TextConfig`, `Qwen3_5MoeTextConfig`, vision/composite configs)
and updated **`AutoConfig` / VLM registration**.
> 
> The rewrite drops the HF-backed text stack in favor of **Prime
`FlashAttention`**, **packed varlen GatedDeltaNet** (FLA + Ulysses CP),
**zero-centered RMSNorm**, **MRoPE**, a **custom vision encoder**, and
**MoE layers** with HF↔Prime **expert weight conversion** (MTP dropped).
VLM prep keeps dummy vision runs for FSDP symmetry and shards
**`routed_experts`** under CP. **`model.py`** no longer applies Qwen3.5
checkpoint/MRoPE/varlen patches or forces vision SDPA under CP.
> 
> **Trainer/config cleanup:** removes the **VLM must use bfloat16**
validator and the duplicate check at model load; **`parallel_dims`**
treats MoE on nested **`text_config`**. Ring/Ulysses patching no longer
lists Qwen-specific attention classes because **`Qwen3_5Attention`
subclasses `FlashAttention`**.
> 
> **Tests/docs:** deletes HF-comparison tests and the old `qwen3_5_moe`
tree; adds **`tests/unit/train/models/qwen3_5/`**
(forward/pack/CP/VLM/MRoPE). **`development.md`** points VLM authors at
the unified package.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d9162ce07425b56e01f6b62d3b24b141a8ff4a51. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-12 17:08:22 +02:00
43b4e2bd13 feat(deepseek_v4): support context parallelism (#3508)
Adds `ring` style CP support to deepseek v4.

The comms requirements are a bit different than those of other models
currently supported. As a point of comparison, for GLM which also has
key/value compression, the key/value creation is embarrassingly parallel
along the seq dim and the compressed key/values can be created from
cp-rank-local data. Comms are of the form `gather_for_cp(kv_cp_shard)`.

For deepseek v4 attention layers there are two general components:
sliding-window parts and compressed attention parts. The SWA treatment
is embarrassingly parallel and handled analogously to GLM. The
compressor components are not embarrassingly parallel and require
different handling. The compression step involves pooling along seq
dimension, which is what removes the embarrassingly parallel property
and necessitates cross cp-rank communication prior to kv formation. This
means that the `gather_for_cp` needs to occur at a comparatively earlier
step than in GLM, say: we never create a sharded version of `kv` (for
the compressed component) and instead use `gather_for_cp` to gather the
tensors required to create the unsharded `kv` directly.

A more memory optimized approach would only pass small windows of tokens
across CP ranks and then all-gather the small, post-compression tensors,
but we re-use `gather_for_cp` and go for simplicity here.

---------

Signed-off-by: Garrett Goon <44747910+garrett361@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-09-11 09:03:10 -04:00
550beb6f43 chore(deepseek_v4): production attention path cleanup (#3517)
Moves the eager-model helpers off the production path and into the eager
impl file for cleaner prod code. Also fixes a previous CI breakage where
we asserted on batch size == 1 which broke packing equivalence tests,
and performs other minor cleanup.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 12:39:44 -04:00
Matej SirovatkaandGitHub bad80b1a30 feat(models): add native Nemotron-H implementation (#3426)
Nemotron-H now runs as a native PyTorch module through PrimeRL Mamba-2,
shared attention, and unified MoE layers. Both Nano (regular MoE) and
Super (latent MoE) layouts are retained. Packed convolution and SSD
reset at document boundaries, and Mamba owns the full-sequence/head
redistribution required by Ulysses context parallelism. Checkpoint
conversion maps official per-expert and latent-expert weights into the
canonical runtime layout.

Updated against main (`daa72a91d`), retaining current fusion,
normalization, and CP interfaces. Restored LoRA adapter `mixer` names
and installed Mamba SSD through the GPU extra. The pinned upstream
source uses Triton without requiring the optional selective-scan CUDA
extension. Configuration guards and HF execution comparisons were
removed; existing packed-boundary tests exercise real GPU kernels.
Router compute follows `trainer.model.moe_router_dtype` (`float32` by
default, optionally `bfloat16`); the model does not force an override.

`NemotronHModel` and `NemotronHForCausalLM` both inherit
`NemotronHPreTrainedModel`, following the existing pattern used by other
architectures. The shared Nemotron base retains the config type and
architecture-specific conversion/CP hooks. Unused TP/PP plans, no-split
metadata, checkpointing flags, redundant attributes, and obsolete
`use_mamba_kernels` handling are removed. Shared model construction,
LoRA, LM-head patching, and weight-transfer code remain unchanged.
Broader removal of the model abstractions is deferred to a follow-up PR.

Garrett's config-docstring and unused-HF-attribute comments are
addressed. The broader context-parallel setter refactor and additional
gradient tests remain deferred.

## Validation

All GPU validation used Slurm-allocated Hopper H200s. Current revision
`f6d7a4033` restores the shared Nemotron base while retaining the
attribute cleanup. Ruff lint/format checks, factory
construction/dtype/inherited-hook checks, and all **15 existing model
tests** passed (Slurm job 343).

- Full unit suite: **699 passed, 11 skipped**, rerun after the nn.Module
cleanup (Slurm job 336).
- Targeted Nemotron, packed-boundary, and KL tests: **15 passed**, rerun
after removing the router override.
- H200 checks verified gate GEMM and weight-gradient dtypes for both
BF16 and FP32 router settings.
- Compiled two-GPU Mamba Ulysses: output, input-gradient, and reduced
parameter-gradient checks passed.
- Fused QKV + compiled selective activation checkpointing:
forward/backward and meta-buffer initialization passed.
- Eight two-GPU checkpoint-resume combinations: exact weights,
CPU-offloaded AdamW state, and next update across fused/unfused QKV and
FSDP shard placements.
- Official Nano checkpoint: exact key/shape conversion round trip,
**6,243 → 401 → 6,243 tensors**.
- `uv sync --all-extras --all-packages`, Ruff lint, and format checks
passed.

The 20-step run below was completed at `a7f798048` (Slurm job 339),
before restoring the original shared base. The preceding revision
`00746d6d2` was also validated: direct inheritance and the original
factory passed construction checks; compiled two-GPU Mamba and fused-QKV
selective-AC checks passed again (job 341). All 15 targeted unit tests
passed (job 340). The two-step end-to-end Nano run completed (job 342),
with mismatch KL **0.00475226** and **0.00522814**, finite gradients,
and three successful NCCL weight updates including startup. Compiled
Mamba/selective-AC and eight checkpoint-resume probes also passed again
on this code (jobs 337–338). The end-to-end run used
`nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16` on eight Slurm-allocated
H200s: four trainer GPUs with EP=4 and four inference replicas. The
native trainer used FlashAttention 3, compilation, selective activation
checkpointing, and NCCL weight updates. Reverse-text used batch size 64,
group size 8, sequence length 1024, and maximum completion length 512.
Optimization and reduction dtypes retained their defaults.

Launched with `uv run rl @ rl-module-cleanup.toml`. The config sets
`trainer.env_vars.TRITON_CACHE_DIR` to node-local `/tmp` to avoid
shared-home artifact read failures; no diagnostic hooks are present in
this run.

The automated review requests a math-environment table. This run uses
reverse-text and does not satisfy that environment-specific requirement:
the current math task requires a policy-aware container runtime, which
is unavailable on the validation nodes.

**20/20 steps completed**, with **21 successful NCCL weight reloads**
(startup plus every update). Mismatch KL: mean **0.0059826873**, maximum
**0.0076148757**, final **0.0071559078**. All step KL values and
gradient norms were finite. Super latent behavior was exercised by small
model tests and distributed probes; no full-size Super run was
performed.

| Step | Mean mismatch KL |
| ---: | ---: |
| 1 | 0.0061262716 |
| 2 | 0.0044362689 |
| 3 | 0.0046579577 |
| 4 | 0.0057872585 |
| 5 | 0.0052399668 |
| 6 | 0.0067561148 |
| 7 | 0.0045683677 |
| 8 | 0.0047115656 |
| 9 | 0.0063753380 |
| 10 | 0.0065832101 |
| 11 | 0.0062584030 |
| 12 | 0.0072330278 |
| 13 | 0.0066353143 |
| 14 | 0.0060227909 |
| 15 | 0.0053012762 |
| 16 | 0.0066529727 |
| 17 | 0.0055223401 |
| 18 | 0.0060145170 |
| 19 | 0.0076148757 |
| 20 | 0.0071559078 |

CI at `a7f798048`: Ruff, slim install, and CodeQL passed; remaining jobs
were running or queued at the last check. On the previous commit
(`a60d27578`): all 15 Nemotron tests passed. The GPU unit job had five
failures in unchanged DeepSeek-V4 tests (packed-batch assertions and
unsupported FP8 kernels on that runner); CPU unit tests, Ruff, slim
install, and CodeQL passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Large rewrite of a hybrid MoE/Mamba training path, checkpoint layout,
and distributed Mamba CP, with dependency pins that affect the whole GPU
stack.
> 
> **Overview**
> Replaces the Hugging Face–wrapped Nemotron-H stack with a **native
hybrid model**: one `NemotronHDecoderLayer` per block type (Mamba,
attention, MoE), a first-party **`NemotronHMamba2`** that uses FLA
packed causal conv plus **`mamba_ssm` Triton SSD**, and Ulysses CP via
**sequence↔head all-to-all inside the Mamba module** (the shared
`cp_mamba` helper is deleted).
> 
> **Checkpoint and config:** `NemotronHConfig` is realigned to current
HF field names and `layer_types`; conversion is **explicit per layer
type** instead of inferring from key presence (the old router-bias
`MapValue` shift is gone). Install/docs now pull **`mamba-ssm` from a
pinned git rev** through the **gpu** extra, with **`tilelang==0.1.12`**
pinned for vLLM compatibility; trainer init no longer disables
`use_mamba_kernels` or monkey-patches HF Mamba.
> 
> Tests drop HF parity checks and instead exercise native packed
boundaries, CP wiring on `NemotronHMamba2`, and existing KL/conversion
coverage.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f6d7a403332bd90d26efa3dcb4c8358a5e95f92e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-10 14:04:38 +02:00
samsjaandGitHub aa3a6522b4 feat(algo): add debug advantage algorithm (#3521)
## What

Adds a `debug` algorithm (`[orchestrator.algo] type = "debug"`) that
assigns the same constant advantage (default `advantage = 1.0`) to every
sampled token of every clean trainable trace, ignoring rewards entirely.

## Why

Purely a debugging feature for infra work: with constant advantages
every admitted rollout is trainable and every action token carries
gradient signal, so the full RL path — advantage transport, importance
ratios, trust region, trainer loss, optimizer, weight update — can be
exercised regardless of the reward function (e.g. to rule out "all-zero
advantages / nothing trainable" when smoke-testing a pipeline). The
config validator rejects `advantage = 0`, the exact failure this tool
exists to rule out.

## How

Follows the existing "a new credit-assignment scheme is a new named
class" pattern:

- `DebugAlgoConfig` in `prime_rl.configs.algorithm` (discriminated-union
member, `action_loss_type = "rl"`, nonzero-advantage validator)
- `DebugAlgorithm` (`score_episode` — the signal is rollout-local, no
group-relative work needed) registered in `ALGORITHM_CLASSES`

Intentionally not documented in `docs/` or the skills — it is a debug
tool, and the code docstrings are the reference.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Opt-in debug algorithm only; no changes to existing algo behavior or
production defaults.
> 
> **Overview**
> Adds a **`debug`** training algorithm for pipeline smoke tests: set
`[orchestrator.algo] type = "debug"` to assign the same constant
per-token advantage (default **1.0**) on every clean trainable trace,
**ignoring rewards**, so admitted rollouts always produce RL gradient
through the full stack (advantage transport, ratios, trust region,
trainer, optimizer).
> 
> **Config:** `DebugAlgoConfig` joins the `AlgoConfig` discriminated
union with `action_loss_type = "rl"` and a validator that rejects
`advantage = 0` (the “nothing trainable” case this mode is meant to rule
out). **Runtime:** `DebugAlgorithm` implements `score_episode` via
`iter_trainable_traces` + `assign_advantages`, registered in
`ALGORITHM_CLASSES` like other algorithms. Docstrings mark it as
infra-only—not a real training signal.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ce6ca60585b3f259780492b892157b356b0569cf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-10 00:19:14 +02:00
3f0c2e3b5a feat(trainer): select MoE compute by layer (#3518)
Select the model layers that use the configured MoE compute backend with
`model.moe.compute.apply_to`:

- `"all"` (default): all routed-expert groups.
- `"85%"`: the first 85% of model layers, rounded down; 48 layers
selects indices 0–39.
- `[0, 1, 2, 3]`: explicit zero-based model layer indices. `[]` selects
none.

Non-MoE blocks in hybrid models count toward indices and percentages.
Other expert groups use BF16 compute and transport while retaining the
configured dispatch backend and expert parallelism. Out-of-range indices
and invalid percentages fail early. Dense linear quantization is
unchanged.

```toml
[trainer.model.moe.compute]
type = "mxfp8"
apply_to = "85%"
```

BF16, DeepGEMM FP8 and MXFP8 configs inherit the common selector. NVFP4
inherits it in #3511. Inference precision remains configured separately.

First PR in the stack: main → #3518 → #3515 (filter flag) → #3513 (vLLM
upgrade) → #3511 (NVFP4).

Validation: 62 focused MoE/config tests passed on this main-based
branch, including all three forms through CLI/config round trips,
percentage rounding, hybrid-layer indexing, and invalid indices. Ruff
lint/format and whitespace checks passed. GB200 mixed DeepGEMM-FP8/BF16
forward/backward passed with an exact BF16 fallback output and unchanged
parameters/checkpoint keys. EP2 with layer-index selection verified
MXFP8 transport for the selected group, BF16 transport for the excluded
group, both forwards, and BF16 fallback backward. MXFP8 backward has a
separately reproduced CuTe TMA-alignment compiler failure in the
existing kernel; that kernel is unchanged here.

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Per-layer MoE precision and transport wiring affects forward/backward
numerics and expert-parallel paths; misaligned trainer vs inference
precision could skew RL logprobs if rollout config is not matched
manually.
> 
> **Overview**
> Adds **`model.moe.compute.apply_to`** so BF16, DeepGEMM FP8, and MXFP8
routed-expert backends can target **all layers**, a **leading
percentage** (e.g. `"85%"`, rounded down), or **explicit zero-based
layer indices** (including `[]` for none). Shared
**`MoEComputeConfigBase`** validates inputs and **`resolve_layers`**
maps selections to layer sets; out-of-range indices fail at resolve
time.
> 
> **`configure_moe_runtime`** maps selection onto language-model
**`layers`** (including VLM via **`get_language_model`**): selected MoE
modules get the configured grouped GEMM; others **fall back to BF16**
compute and matching token dispatch alignment. **MXFP8 torch transport**
is used only when that layer’s grouped GEMM is actually
**`MXFP8GroupedGemm`**, so excluded layers no longer take MXFP8
all-to-all when compute is partial. Startup logging reports selected vs
total MoE layers.
> 
> Docs describe hybrid-layer counting, dense-quant independence, and RL
rollout/inference precision alignment. Unit tests cover config/CLI
round-trips and BF16 fallback without loading MXFP8 backends when
nothing is selected.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f367d4866ddcc0debd53faebe8944f096eb3ba44. 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: matejsirovatka <matejsirovatka@users.noreply.github.com>
2026-09-10 00:11:35 +02:00
6b0d9e504b fix(deepseek_v4): hardware guards for unrunnable gpu CI tests (#3512)
Custom deepseek v4 flash attention requires more SMEM than some gpus
(like the current CI runners) have. Skip the tests in those cases.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 11:06:46 -04:00
751a235af8 perf(deepseek_v4): score the Lightning Indexer with the fused FP8 kernel (#3504)
Second of three stacked PRs, builds on #3479.

Scores the DeepSeek V4 Lightning Indexer with `fp8_indexer`, the fused
Triton kernel GLM DSA already runs, dropping the eager float32 `(batch,
seq_len, heads, entries)` intermediate.

The indexer now rejects a batch larger than 1 instead of looping over
the batch axis: the entry ranges it hands the kernel are built from
sample 0's causal thresholds, so every other sample would have been
scored against the wrong range.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 10:51:22 -04:00
Matej SirovatkaandGitHub daa72a91d8 feat(models): add native GPT-OSS implementation (#3424)
## Summary

Replace the Transformers/hub-kernel GPT-OSS runtime with a Prime-owned
model, FA4 attention with learned sinks, and canonical grouped experts.
BF16 GPT-OSS checkpoints load through lossless expert-layout conversion;
inference policy updates route prepared expert and sink tensors through
vLLM's registered parameter loaders.

This branch targets `main` and supports runtime QKV and gate/up fusions,
canonical checkpointing, and the CP capability interface. Main's
dependency pins are retained; the obsolete `gpt-oss` hub-kernel extra is
removed.

## Supported configuration

- `model.impl = "auto"` selects native GPT-OSS. Validated checkpoint:
`unsloth/gpt-oss-20b-BF16`. Original MXFP4 checkpoint loading is outside
this change.
- Direct FA4 calls preserve learned sinks, sliding/full attention, and
packed-document boundaries. FA4 explicitly returns `(output, lse)`;
FA2/FA3 default calls return a tensor.
- Ring and Ulysses CP preserve sink gradients; common expert parallelism
and runtime fusions are supported.
- Hopper is the validation target. The vLLM loader patch handles
prepared expert and sink tensors with the pinned vLLM.

GPT-OSS and shared FA4 attention no longer use `torch._dynamo.disable`.
There is no forwarding wrapper around the native FA4 function. Native
configuration/input guards and HF GPT-OSS execution-comparison tests are
removed; checkpoint conversion and CP checks remain. There are no
example or skill changes relative to main.

## Context-parallel attention

Every CP helper replaces an attention compute method. GPT-OSS's ring
adapter is separate because the shared ring custom operators have no
learned-sink input or sink-gradient output. It uses differentiable K/V
gathers and FA4 to preserve those gradients. Its Ulysses adapter passes
the model's FA4 function, scale, and sinks into the shared sink-aware
Ulysses implementation. That thin adapter is an organizational choice;
directly assigning the existing generic closure would omit these
arguments.

## Validation

- H200 full unit suite after cleanup: **701 passed, 11 skipped**. After
the final direct-FA4 assignment, the targeted checkpoint roundtrip and
compiled attention/CP checks passed again.
- Cold `torch.compile(fullgraph=False)` forward/backward and
eager-output agreement passed for GPT-OSS and shared FA2/FA3/FA4
attention.
- Two-GPU eager and compiled GPT-OSS ring/Ulysses output and
Q/K/V/sink-gradient checks passed. Compiled shared FA4 Ulysses output
and Q/K/V gradients passed on both ranks.
- The CP tests reuse one process group across cases, avoiding
teardown/reinitialization reconnect failures.
- Earlier integration validation covered eight checkpoint/resume
combinations and a real 20B export matching all 411 checkpoint
keys/shapes and sampled tensor values.
- Ruff lint/format and git whitespace checks passed.

## Final 20-step H200 RL run

After all code changes, `uv run rl @ config.toml` completed through the
standard Slurm launcher on eight H200 GPUs: four trainer and four
inference GPUs, `unsloth/gpt-oss-20b-BF16`, reverse-text, batch 64,
group 8, sequence length 1024, completion budget 512, EP=4, QKV/gate-up
fusions, compilation, selective activation checkpointing, and NCCL
policy reloads. Rollout concurrency starts at 32 and is capped at 64.

Slurm job **326 completed with exit code 0**, in 24m42s. All **20
optimizer steps** completed and inference acknowledged **21 successful
reloads** (startup plus 20 updates). Rollout errors were 0%. The short
completion budget truncates most reasoning; this validates numerical
consistency and pipeline operation.

The table reports `mismatch_kl/all/mean` on commit `c3fe30c29`.

Completed steps: 20
Mean of step means: 0.0014423477
Min: 0.0007825278
Max: 0.0027635854

| Step | Mismatch KL |
| ---: | ---: |
| 1 | 0.0007825278 |
| 2 | 0.0008648058 |
| 3 | 0.0010610037 |
| 4 | 0.0015761884 |
| 5 | 0.0012348450 |
| 6 | 0.0023151361 |
| 7 | 0.0016181732 |
| 8 | 0.0012400812 |
| 9 | 0.0010534789 |
| 10 | 0.0017238446 |
| 11 | 0.0027635854 |
| 12 | 0.0023905332 |
| 13 | 0.0015134896 |
| 14 | 0.0014993388 |
| 15 | 0.0011815884 |
| 16 | 0.0012801469 |
| 17 | 0.0012795344 |
| 18 | 0.0012338012 |
| 19 | 0.0011749482 |
| 20 | 0.0010599031 |

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches core training attention/MoE and vLLM weight loading for a new
architecture; mistakes could affect numerics or checkpoint load, though
conversion and CP tests mitigate this.
> 
> **Overview**
> Replaces the Transformers / hub-kernel GPT-OSS path with a
**Prime-owned** `gpt_oss` stack: custom config, packed-batch forward
(`seq_lens`), grouped MoE, and **FlashAttention 4** attention with
**learnable sink** parameters wired through ring and Ulysses context
parallelism (including sink gradients).
> 
> **Training/runtime:** Drops Hopper-only checks and explicit hub-kernel
enablement; hub kernels stay disabled globally. Shared FA4 call sites
now handle `(output, lse)` returns and drop `torch._dynamo.disable`
wrappers. Ulysses varlen attention gains optional `learnable_sink`
sharding.
> 
> **Inference:** Registers a vLLM startup patch to load prepared BF16
MoE expert and **`.sinks`** tensors via weight loaders until upstream
vLLM catches up.
> 
> **Packaging/docs:** Removes the `gpt-oss` optional extra (`kernels`
dependency); docs point at BF16 checkpoints (e.g.
`unsloth/gpt-oss-20b-BF16`) and SM90/SM100+ for FA4 sinks. Tests add
2-GPU ring/Ulysses CP checks and drop HF MoE parity.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c3fe30c2956c167563821a0542ec587069704b00. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-09 16:33:45 +02:00
dad79d1ce8 feat(inference): add Dynamo admin plane integration (#3491)
## Overview

Add a minimal Dynamo admin-plane integration for Prime-RL weight
synchronization. Prime-RL discovers and pins one Dynamo inference
worker, routes administrative operations directly to it, propagates
configured authentication to the worker client, and uses the existing
custom NCCL sender and receiver for policy updates.

This PR is intentionally limited to a singleton text-model RL training
loop. It excludes managed Dynamo process launch, multi-worker or
multi-rank topology, multimodal training, routed-expert transfer, and
LoRA. Managed process launch is the stacked follow-up #3493; the
unrelated `skip_gather` compatibility fix remains isolated in #3492.

## Changes

- Add optional Linux-only Dynamo dependency support and compatibility
metadata for the upstream Pydantic bound.
- Add `orchestrator.model.client.dynamo` with `enabled` and optional
`discovery_url`.
- Derive an omitted discovery URL from the OpenAI base URL by stripping
its path and incrementing its explicit non-default port.
- Discover exactly one model-matching worker and pin its instance
identity and private admin origin.
- Propagate static headers, environment-derived headers, and a non-empty
API-key bearer token to Dynamo discovery and worker administration.
- Initialize Prime-RL's existing NCCL communicator through Dynamo
collective RPC and transfer policy weights without adding another
transport protocol.
- Preserve existing filesystem and NIXL behavior outside the
Dynamo-specific NCCL path.
- Add `examples/basic/dynamo/rl.toml` and a runnable README with
loopback-safe commands, endpoint checks, GPU isolation, trusted-network
guidance, and the Prime-RL command.
- Keep the `uv.lock` conflict resolution isolated from upstream source
changes.

## Validation

### Local

- `uv lock --check` — passed at functional source head
`55d8f2f658b543aea08d13b4ce53bb6ec91ab82d`.
- `uv run --frozen pytest -q tests/unit/inference/test_dynamo.py` — 15
passed.
- Ruff lint and format checks — passed for all five changed Python
files.
- `git diff --check origin/main...HEAD` — passed.
- Signed conflict-resolution commit
`dc1e7910977e8a847d6081ceb204f779081ebe36` changes only `uv.lock` (39
additions, 2 deletions in that commit).
- `git merge-tree --write-tree HEAD origin/main` — passed without
conflicts at current head.
- The current `uv.lock` PR delta against main is 139 additions and 17
deletions.

### Kubernetes

- The exact functional source head
`1cdcaff56972aab55ed1456a2829555052285099`, with the separate #3492
`skip_gather` compatibility overlay required by the installed vLLM-RS
build, completed a five-step Qwen3-0.6B Math run in `bis-rl-3` over SSH.
- Trainer and orchestrator completed steps 1 through 5; vLLM received
startup policy `v0` and updates `v1` through `v5`; every step reported
0% rollout errors and 0% truncation; post-update generation succeeded;
the runner exited zero.
- The subsequent authentication change at
`dec4f82b66c3a231f56f8b759c1c4dcb20685a8b` was also exercised in the
stacked #3493 managed-Dynamo five-step run, which completed 1,001
generation requests and policy updates `v0` through `v5`.
- Current-head commits after that runtime validation modify only
`uv.lock` and one trailing blank line; no production behavior changed.

## Operational notes

- Keep Dynamo discovery and worker administration on a trusted loopback
or private network.
- The Dynamo frontend must expose the native generate route with
`DYN_VLLM_ENABLE_INFERENCE_V1_GENERATE=1`.
- The included vLLM-RS recipe uses `top_k = 0` because that backend
rejects Verifiers' default `top_k = -1`.

---------

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-09-08 21:03:02 -07:00
dd2dd5461b prime-runs (#3459)
Replaces `monitors/prime.py`'s`TrainRun` with `pr.init(kind="train",
...)`.

## What moved where

| was in prime-rl | now |
| --- | --- |
| `TrainRun.create` / `$RUN_ID` attach | `pr.init(kind="train", model=,
environments=, training=pr.TrainingSpec(...), config=, ...)` /
`pr.init(kind="train", id=$RUN_ID)` |
| `TrainRun.log_metrics` (fire-and-forget task per POST) |
`run.log_metrics(values, step=)` — a queue put; the SDK's uploader owns
retries, `Retry-After`, backpressure |
| `episodes_to_parquet_bytes` + `SAMPLE_SCHEMA` + presign→PUT→confirm |
`prime_runs.projection` + the SDK's training samples sink (same schema,
same flow) |
| the `step % 10` cadence in `log_episodes` | the sink
(`step_interval=10`), keyed on each episode's `run.work.step` — the
`TrainRunInfo` the dispatcher stamps |
| `finalize` → `POST /finalize`, fallback `set_status` | `run.finish()`
— drain, then an idempotent finalize; 409 on the failure path is treated
as already-closed |
| atexit `_mark_failed` | the SDK's atexit hook reports **crashed**
(with a message); an attached run's failure marking stays with the
launcher, as before |

The `kind == "train" and subset == "effective"` cohort filter stays
here. The monitor keeps `sanitize()` so dropped non-finite metric paths
are still named in the log (the SDK would drop them silently).
`$PRIME_API_BASE` still works — it historically points at
`…/api/v1/rft`, so the monitor strips what the SDK re-adds.

## Decisions

- **Step keying.** The samples sink keys each episode by the step it was
*dispatched* at (`run.work.step`), not the batch step; the platform
keeps one Parquet object per upload and the viewer unions every object
under a step, so an off-policy episode landing in a later batch adds an
object rather than replacing one, and each object numbers its
`sample_id`s in its own range (SDK side, `aba26790`). "Step N" in the
sample viewer therefore means dispatched at N, while the metrics at N
describe the batch trained at N.
- **Run identity.** The orchestrator keeps the launcher's `PRL_RUN_ID`
(or a local uuid) as the run identity for episodes, W&B and sandbox
labels, exactly as on `main`. The SDK keys every uploaded record to the
platform run (`run.id` / `run.type` on the uploaded copy, `work` kept),
so Prime Traces documents carry the id the dashboard shows without the
orchestrator learning it.

## Dependency

`prime-runs[train]>=0.1.1` from PyPI
([0.1.1](https://pypi.org/project/prime-runs/0.1.1/),
PrimeIntellect-ai/prime#896); the lock carries `prime-runs 0.1.1` +
`prime-traces 0.0.3` from the registry. The monitor's own unit tests run
in CI; there is no GPU-free end-to-end path for the training seam, so
the RFT contract was verified by reading the platform's `/api/v1/rft/*`
and `/api/internal/rft/*` routes against the SDK's calls.

## Hosted managed runs

Since PrimeIntellect-ai/platform#4885, hosted managed runs start the
orchestrator with `--monitors.prime.name`, `RUN_ID`, a per-run token in
`PRIME_API_KEY` and `PRIME_API_BASE=<platform>/api/internal/rft`.
prime-runs 0.1.1 (PrimeIntellect-ai/prime#895) addresses that internal
router and sends the run's token in `x-api-key`, the header it
authenticates on; 0.1.0 only spoke `/api/v1` with a Bearer header and
would have left those runs silently unmonitored. This monitor's
`_base_url()` passes `$PRIME_API_BASE` minus the trailing `/rft`, which
0.1.1 accepts, so the floor bump is the whole change. External runs
(prime-rl launched outside the platform) were never affected.

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

https://claude.ai/code/session_01Fk5fBAAaTiPfJ5UpNyqxXR


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how training runs register and upload to the Prime platform
(including hosted `$RUN_ID` / internal RFT paths); misconfiguration now
fails launch instead of silently skipping monitoring, but orchestrator
run identity for W&B stays unchanged.
> 
> **Overview**
> **Replaces** the in-repo `TrainRun` HTTP/Parquet implementation in
`PrimeMonitor` with **`prime-runs[train]>=0.1.1`**, so run registration
(or `$RUN_ID` attach), metrics streaming, episode sample uploads,
finalize, and crash reporting are owned by the SDK uploader instead of
custom `httpx` + fire-and-forget tasks.
> 
> The monitor layer is now a thin adapter: `pr.init(kind="train", …)` on
startup, `run.log_metrics` / `run.log_episodes` via `asyncio.to_thread`,
and `run.finish()` with a **60s** drain timeout. Local behavior kept
where it matters: non-finite metrics are still **sanitized with named
warnings**, only **train / effective** episodes are forwarded, and
**`$PRIME_API_BASE`** is normalized for the SDK. Episode
**every-10th-step** upload cadence moves into the SDK sink (keyed on
dispatch step on `run.work`).
> 
> **Docs** in `training.md` describe the SDK, team allowlisting,
**`PRIME_RUNS_MODE=disabled`**, and **`RUN_ID`** attach.
**Lock/pyproject** add `prime-runs` and transitive **`prime-traces`**,
with fast-track resolver entries.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
aed9bbfb509367d7cad1fb8cd869c2b835fa8860. 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-09-08 20:06:21 -07:00
cea63f9ef3 feat(deepseek_v4): sparse attention kernels (#3479)
Adds a TileLang implementation of the flash-attention style kernel for
DS V4. Based on the similar kernel used for GLM. The kernel is wired
through the DS V4 model and the attention arguments are refactored to
naturally adapt to the shape expected by the efficient kernel (e.g. no
more `attention_mask` realization).

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 21:11:30 -04:00
6a360c3029 feat(trainer): add runtime gate/up and qkv fusions (#3451)
## Summary

Adds runtime parameter fusions, on by default: `model.fusions` packs
parameters that are always computed together into one tensor, turning
several GEMMs into one. Fusions are runtime-only — checkpoints keep the
canonical parameter names and shapes, so a run can enable or disable one
at any point and still load its own checkpoints.

```toml
[trainer.model.fusions]
enabled = ["gate_up", "qkv"]   # default; [] disables
raise_on_fail = false          # default: a fusion no module supports logs a warning
shard_fused_on_dim1 = false    # default; experimental zero-copy checkpointing, see Notes
```

- **`gate_up`** — each gated MoE expert's `gate_proj` and `up_proj`
become one `[num_experts, 2 * intermediate_size, hidden_size]` weight.
The forward is a single grouped GEMM whose transpose and chunk are
views; there is no weight reshape.
- **`qkv`** — an attention layer's `q_proj`, `k_proj` and `v_proj` (and
their biases) become one `nn.Linear`. `FlashAttention.project_qkv` is
shared with `LagunaFlashAttention` so both support it.

## Review fixes and verification (2026-09-08)

Review found and fixed three previously unchecked checkpoint cases:

- **Exports and model-only resume:** DCP returns `{}` when no optimizers
are supplied. Both fusion optimizer-state translators now preserve that
empty dictionary instead of raising `KeyError: 'state'`.
- **AdamW resume with optimizer-state CPU offload:** packed parameters
restored their moments but lost scalar state, including AdamW's step
counter. The write-back now restores scalar tensors and non-tensor state
as well as packed moments.
- **Full CPU offload checkpoint save:** splitting packed CPU optimizer
tensors requires CPU collectives. Both training entrypoints now enable
Gloo alongside NCCL when full offload is enabled.

Verified on H200s through Slurm job **232**:

- The complete existing unit suite and Ruff checks passed.
- All **32 distributed checkpoint combinations** passed: AdamW/Muon,
fused/unfused save and load, default/dimension-1 sharding, and
optimizer-state CPU offload on/off. Canonical weights, optimizer state,
and the next update with identical gradients were bitwise exact.
- Full CPU offload completed model-only resume/save and optimizer
resume/save. All **311 model tensors** were exact after model-only
resume; **931 model/master/step tensors** were checked across optimizer
resume, with unchanged weights and correctly incremented counters.
- Expert outputs and matrix-weight gradients, and QKV projections
with/without bias, were exact. BF16 input-gradient relative differences
were about 0.29%; bias-reduction variation also occurred in repeated
unfused calculations.
- All **11 RL/SFT training, resume, and export checks** passed (6 SFT, 5
RL). BF16 and FP8 exports reload in HF, and direct DCP-to-FP8 matches
chained conversion byte-for-byte. RL completed 20 steps with final
reward **0.8362** and passed its mismatch-KL checks.

The dashboard browser checks cannot install OS dependencies on this
cluster because they require sudo. The prior A6000 benchmark CI job was
cancelled without executing any steps; its hardware-specific baseline
was not validated on H200. Blackwell-only MXFP8 was not exercised.

Verification artifacts: `/home/matej/prime-rl-verify/pr3451-20260908/`.
This review changes only the fusion helpers and RL/SFT distributed
initialization; it adds no tests or skill changes.

## Design

A fusion is a function that replaces some of a module's parameters with
one `PackedParameterSpec`, which owns the split sizes, the packing
dimension, and the canonical names it stands in for. Everything else
falls out of that description, so a new fusion adds no machinery:

- **Checkpoints** — state-dict hooks registered alongside the packing
swap the packed entry for its canonical entries on the way out and back
on the way in. The canonical entries are views of the packed storage
when the packing dimension is unsharded (`gate_up`: experts shard on dim
0, pack on dim 1); a DTensor sharded along the packing dimension (`qkv`:
FSDP shards dim 0) is unsharded by the split, so those entries are
replicated copies. Anything that loads into the state dict in place
therefore packs the loaded entries back explicitly
(`write_back_loaded_packed_parameters` after the HF weight load,
`write_back_loaded_packed_optimizer_state` /
`join_loaded_optimizer_state_for_runtime` on resume). DCP therefore
writes `gate_proj`/`up_proj` and `q_proj`/`k_proj`/`v_proj` and never
sees the packed layout. The optimizer has no equivalent hook (its
`state_dict()` hooks fire while state is still keyed by integer param
ids, before DCP maps them to FQNs), so the same translation is applied
explicitly around `get_state_dict` in `AppState`.
- **Muon** — `PackedParameterSpec.muon_matrix_partitions` yields the
split sizes when the packing is on the output dimension. Those go to
Dion's new `matrix_partitions` argument, which orthogonalizes each
logical matrix separately on the one physical parameter, with a
per-partition learning-rate adjustment. A packed parameter therefore
trains exactly as the parameters it replaces would — including
per-projection scaling for grouped-query attention — while keeping a
single momentum tensor. Uses the merged matrix-partition support in the
pinned `samsja/dion@99e5f7e` (samsja/dion#3).

Modules advertise fusions through `supported_fusions`; requesting one
that no module supports logs a warning, or fails at startup with
`raise_on_fail = true`. Fusions are skipped when LoRA is enabled, since
it targets the unfused projections.

## Performance

Qwen3-30B-A3B, 8×H200, EP=8, `seq_len=8192`, torch EP dispatch,
selective AC, compile, no offload. Mean throughput over steps 3–6:

| precision | unfused | fused | |
|---|---|---|---|
| BF16 | 37636 tok/s (MFU 13.3%) | 37352 tok/s (MFU 13.2%) | −0.8% |
| FP8 (`quantization.type=fp8` + `moe.compute.type=deepgemm_fp8`) |
30594 tok/s (MFU 10.8%) | 34062 tok/s (MFU 12.0%) | **+11.3%** |

BF16 is unchanged, as expected: the separate GEMMs already read the same
activation, so there is nothing to save. The gain is under FP8, where
each GEMM quantizes its activation independently — unfused casts the
same tensor 3× for q/k/v and 2× for gate/up, fused casts it once. Peak
memory is unchanged (101.8 → 102.0 GiB).

## Validation

Correctness, on GPU:

- Forward output and all weight gradients of the fused grouped experts
are **bitwise identical** to the unfused module; the packed q/k/v
projections are bitwise identical to the separate ones. Only the MoE
input gradient differs (max abs `1.5e-5` on a `2.4e-3` scale), by one
bf16 accumulation rounding from doing one `[T, 2I]` dgrad instead of two
`[T, I]`.
- Muon updates on a packed parameter are **bitwise identical** to
updating the parameters it replaces, over multiple steps, for both
fusions.
- All four fused/unfused optimizer checkpoint round trips are exact,
including the next optimizer update after each. For `gate_up` the
checkpoint entries alias the packed storage; for `qkv` under FSDP they
are replicated copies of the q/k/v weights and their optimizer state,
materialized transiently on every rank at load and checkpoint time (~1
GB bf16 weights + ~2 GB fp32 Muon momentum for Qwen3-30B-A3B).
`shard_fused_on_dim1 = true` (experimental, default off) shards fused
2-D parameters along dim 1 via FSDP2's `shard_placement_fn`, so the
split stays a local view: the q/k/v weight entries alias the packed
storage and `model.state_dict()` holds 0.1 MiB extra instead of 72 MiB
on the mini model (0 / 144 → 72 / 72 weight entries aliasing; biases
stay copies, having no second dimension). It is not a correctness fix on
its own — biases would still load as zero and the optimizer-offload
resume path replaces its state tensors after the template is built, so
the explicit write-back stays in place with the flag on or off.
Constraints: `hidden_size % dp_shard == 0` (FSDP2 raises otherwise) and
an extra chunk-cat per all-gather of dim-1 shards. #3486 measured the
placement alone and is closed in favour of this flag.
- DCP metadata for a fused EP=2 checkpoint contains 94 `gate_proj` and
94 `up_proj` entries and zero `gate_up_proj` entries.

End to end on SLURM (2 GPUs, EP=2, compiled, Muon, both fusions unless
noted):

| run | result |
|---|---|
| BF16 fake-data training + checkpoint save | ✅ |
| resume: fused ckpt → fused runtime | ✅ |
| resume: fused ckpt → **unfused** runtime | ✅ |
| resume: unfused ckpt → **fused** runtime | ✅ |
| optimizer-state CPU offload, save + resume | ✅ |
| DeepGEMM FP8 expert compute | ✅ |
| pretrained `mini-glm-moe` RL run with vLLM weight reload | ✅ mismatch
KL `0.0001` at both steps |

Plus `ruff format`/`ruff check`, and `pytest tests/unit/train/models
tests/unit/test_configs.py` (`215 passed, 3 skipped`), including a new
`tests/unit/train/models/test_fusions.py`.

## Notes

- `pyproject.toml` and `uv.lock` pin `samsja/dion@99e5f7e`, which
contains the merged matrix-partition support from samsja/dion#3.

## Verification on merged `main` (2026-09-04)

Branch merged with `main` (no conflicts) and re-verified on 8×H200 nodes
via SLURM. `ruff check`/`ruff format --check` clean; `pytest tests/unit
-m "not gpu"`: 536 passed, 1 skipped; `pytest tests/unit -m gpu`: 81
passed, 8 skipped.

**Numerics against an fp32 reference** (`samsja/mini-glm-moe`, single
GPU, no FSDP, 512 random tokens; reference is HF `Glm4MoeForCausalLM` in
fp32 eager). Whole-model outputs are not bitwise identical between fused
and unfused bf16 — the packed GEMMs take a different accumulation path —
but the fused model is exactly as close to fp32 as the unfused one:

| model (bf16) | logits mean abs diff vs fp32 | KL(fp32 ‖ model) | grad
rel. err vs fp32: q/k/v · experts gate/up · rest |
|---|---|---|---|
| unfused | 7.64e-3 | 3.97e-5 | 4.52e-2 · 4.96e-2 · 4.48e-2 |
| fused `qkv` | 7.64e-3 | 3.82e-5 | 4.14e-2 · 4.81e-2 · 4.12e-2 |
| fused `gate_up` | 7.22e-3 | 3.83e-5 | 4.52e-2 · 5.19e-2 · 4.51e-2 |
| fused both | 7.27e-3 | 3.88e-5 | 4.31e-2 · 4.87e-2 · 4.27e-2 |
| HF bf16 sdpa (noise floor) | 7.72e-3 | 4.48e-5 | 4.48e-2 · 5.19e-2 ·
4.46e-2 |

Fused vs unfused state dicts are bitwise identical after loading, and
each packed parameter equals the concatenation of the parameters it
replaces.

**Fake-data training matrix** (`mini-glm-moe`, 2 GPUs, EP=2, Muon,
compile + AC on, `ckpt.interval=5`, 10 steps), all runs complete without
errors:

| run | result |
|---|---|
| fused / unfused, optimizer offload on / off | ✅ losses agree to ≤ 5e-4
relative on every step |
| `shard_fused_on_dim1 = true`: load, resume (both offload paths), fused
↔ unfused resume, 10-step loss vs unfused | ✅ (verified with this code
before the flag existed; see #3486 for the measurements) |
| fused ckpt → fused resume, fused ckpt → unfused resume | ✅ post-resume
losses agree to ≤ 1e-3 relative |
| unfused ckpt → fused resume vs unfused ckpt → unfused resume | ✅ |
| the same three resumes with optimizer-state CPU offload | ✅ |
| DeepGEMM FP8 (`quantization.type=fp8`,
`moe.compute.type=deepgemm_fp8`), fused and unfused | ✅ |

(Resumed runs deliberately diverge from the un-interrupted run:
`FakeDataLoader` reseeds from a batch counter that restarts at 0, so a
resume replays the first batches. Fused and unfused resumes see
identical data and are compared against each other.)

**RL end to end** (`configs/ci/integration/reverse-text-moe/start.toml`,
custom impl, EP=2, 2 trainer GPUs + 1 vLLM GPU, 20 steps, filesystem
weight broadcast): fused `mismatch_kl/all/mean` 1.8e-4–2.2e-4 on every
step vs 1.9e-4–2.1e-4 unfused.

**Fix included in this branch.** Before `fix(trainer): load packed
parameters and their optimizer state explicitly`, the same runs showed
the `qkv` fusion training from zero attention weights: the HF weight
load wrote into the replicated q/k/v copies, every q/k/v tensor in a
fused checkpoint was exactly 0, the fused/unfused step-1 loss differed
by 20% reproducibly under both bf16 and FP8, and the RL run aborted with
no trainable rollouts. A fused resume also lost the Muon momentum of
every packed parameter (verified with lr=0: momentum after resume was
1.00× instead of 1.95× the saved value; both fusions with optimizer CPU
offload, `qkv` without). With the fix, loaded weights are bitwise
identical to the source and momentum is restored on both resume paths.
Full optimizer offload (`model.full_offload`) with fusions was not
exercised. MXFP8 expert compute needs Blackwell and could not be tested
on H200.

## Cluster verification with merged Dion (2026-09-05)

Pinned `samsja/dion@99e5f7e` (merged samsja/dion#3) and refreshed
`uv.lock`; its tree is identical to the prior fork pin. Synced with `uv
sync --all-extras --inexact`, then ran GPU verification through Slurm on
H200s:

- 10 prime-rl fusion/activation-checkpointing tests, 13 Dion single-GPU
tests, and 4 Dion distributed tests passed.
- All **16 distributed checkpoint combinations** passed: fused/unfused
save and load, default/dimension-1 sharding, and optimizer-state offload
on/off. Canonical weights, optimizer state, and the next Muon update
with identical supplied gradients were **bitwise exact**.
- **13 compiled EP=2 training/resume variants** completed on
`samsja/mini-glm-moe` (512-token fake batches): both fusion modes, all
four resume combinations, state offload, dimension-1 sharding, and
DeepGEMM FP8. Fused/unfused BF16 losses differed by at most **0.031%**
across the three initial steps.
- All **406 pretrained model tensors** were bitwise exact in the zero-LR
checkpoint and after its offloaded resume. All 13 variants saved
canonical model/optimizer projection names, with no packed `qkv_proj` or
`gate_up_proj` entries.
- The real **2-step RL run with vLLM weight reloads** completed with
mismatch KL **0.00019046 / 0.00019005**. Fake-data runs use random
inference logprobs, so their mismatch KL is not a trainer/inference
agreement metric.
- H200 module checks: gate/up outputs and matrix-weight gradients, plus
Q/K/V outputs with/without bias, were exact. BF16 MoE input-gradient
relative differences were ~0.29%. Bias reductions in an all-BF16 module
varied ~1.5%, also reproduced by repeating the unfused calculation
itself.

Slurm evidence: 147/148 (test suites), 149 (RL), 150/158 (checkpoint
equivalence), 153 (training matrix), 157 (saved checkpoint inspection).
Job 148's test suites passed before an overly strict ad-hoc BF16 bias
assertion stopped that script; the numerical diagnostic was resolved
separately. Full optimizer offload and Blackwell-only MXFP8 were not
exercised.

## CI collection fix (2026-09-05)

The `reverse_text` integration job failed before running any tests
because importing `prime_rl.utils.weights` first triggered a circular
import through the model registry and `fusions`. Import
`PreTrainedModelPrimeRL` inside `convert_state_dict_to_hf`, its only
use, so loading weight utilities no longer eagerly imports the model
registry.

Reproduced the failing import locally before the fix. After the fix,
standalone collection of `test_reverse_text.py` succeeds (6 tests), the
complete integration suite collects (38 tests), and all 6 fusion unit
tests pass. Ruff lint/format checks and `git diff --check` pass.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core training paths (FSDP sharding, weight load, DCP optimizer
state, Muon) and defaults fusions on; incorrect packing/load logic would
corrupt weights or momentum on resume, though extensive
checkpoint/resume testing is described in the PR.
> 
> **Overview**
> Adds **runtime parameter fusions** (on by default via
`[trainer.model.fusions]`) that pack related weights into single tensors
so MoE **gate/up** and attention **q/k/v** run as one GEMM each, while
**checkpoints and exports still use canonical names** (`gate_proj`,
`q_proj`, etc.).
> 
> A new **`fusions` module** implements packing (`PackedParameterSpec`),
state-dict hooks, HF/DCP load **write-back** for packed weights, and
explicit **optimizer-state split/join** around distributed checkpoint
save/load (including CPU-offload resume). Optional
**`shard_fused_on_dim1`** wires FSDP2 **`shard_placement_fn`** for
experimental zero-copy fused weight/optimizer I/O.
> 
> **Attention and MoE layers** advertise fusions through
`supported_fusions`; forwards use **`project_qkv`** / a single grouped
**`gate_up`** GEMM when fused. Fusions are **skipped with LoRA**.
**Muon** gets **`matrix_partitions`** from packed params via an updated
**dion** pin. Docs and unit tests cover config and canonical state-dict
behavior.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
52e736c685485fdbca109c86721017ab8065f65d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 19:47:47 +02:00
samsjaandGitHub 04a61d3b75 fix: warm Muon all-to-all connections during optimizer initialization (#3490)
## Summary

Automatically establish the NCCL peer connections used by Dion's Muon
optimizer immediately after constructing Muon and before returning it to
the trainer.

The warm-up runs only for Muon. It covers the exact main optimizer
process group and, when expert parameters use expert parallelism, the
separate expert-shard process group. Single-rank and non-NCCL groups
remain no-ops; AdamW, SGD, and other optimizers are unchanged.

This is a required correctness workaround for a reproducible multi-node
GLM-4.5-Air first-step deadlock. The source now documents that optimizer
refactors must preserve the warm-up, its process groups, and its
placement between Muon construction and the first optimizer step.

## Failure signature

Pretrained GLM-4.5-Air training with Muon reproducibly stalled while
submitting the first optimizer all-to-all on two nodes. All 16 ranks
reached the collective, but only rank 0 enqueued it successfully; ranks
1–15 remained inside submission until the NCCL watchdog fired.

The clearest controlled failure was job 1182:

- Nodes `qpn01gpu009` and `qpn01gpu011`, 16 GPUs total.
- Pretrained eight-layer GLM-Air reproduction with CP4, EP8/automatic
expert mesh, BF16 compute, and optimizer-state offload.
- First Muon all-to-all was NCCL sequence 67 with 50,331,648 BF16
elements per rank.
- The watchdog fired after 182 seconds.
- Setting `NCCL_CUMEM_ENABLE=0` did not resolve it.

This was not a generic inability of the nodes to communicate: Adam
training and standalone all-reduce/all-to-all controls completed on the
same cluster. Fake-weight and reduced-model tests further isolated the
trigger to Muon's pretrained-model initialization state and first bulk
all-to-all.

## Implementation

`_warmup_muon_mesh` takes the `DeviceMesh`, resolves its single process
group, and performs a bulk BF16 list all-to-all matching Dion's
communication path, waits for completion, and synchronizes CUDA before
releasing its temporary buffers. A scalar collective is intentionally
not used because it may not initialize the same bulk-transfer peer
channels. Meshes with more than one dimension (the replicate-only world
mesh) have no single group and are skipped; Dion's Muon only accepts 1-D
meshes there anyway.

The ordering is part of the fix:

1. Construct the Dion Muon optimizer.
2. Warm Muon's main distributed NCCL group.
3. If expert parameters and EP are active, warm the independent
expert-shard NCCL group.
4. Return the optimizer only after both required warm-ups complete.

The temporary allocation is approximately 12 MiB per peer for send plus
receive buffers. No config flag is introduced because making this
optional would allow the known deadlock to recur.

Patch scope remains one optimizer source file. There are no
trainer-loop, dependency, precision, optimizer-offload, allocator, Dion,
or experiment-config changes.

## Validation

- Ruff lint/format and whitespace checks passed.
- Existing configuration tests passed: 70 passed, 67 deselected.
- Job 1183, reduced pretrained model with early connection warm-up: one
full step passed on all 16 ranks; 42.6 seconds, loss 15.4930, gradient
norm 49.0578, clean exit.
- Job 1184, full 46-layer pretrained GLM-4.5-Air with the earlier
pre-model-load placement: three fake-data steps passed with finite
losses and nonzero gradient norms.
- Job 1185, full 46-layer model with the final optimizer-construction
placement in this PR: three steps passed on all 16 ranks. Losses were
13.2325, 13.1564, and 13.3399; gradient norms were 27.9833, 27.8885, and
31.8815; clean exit.
- The research-prod Air ablations pin the backport of this
implementation. IPO-KL, IPO, DPPO, and IcePop have each subsequently
advanced beyond 400 Muon steps without recurrence of the initialization
deadlock.
- Review follow-up (`dfa07cd7e`): the warm-up now resolves the process
group from the mesh and no-ops on non-1-D meshes. Verified on 2 GPUs
with NCCL: the `dp_shard` path still completes the warm-up collectives,
and the 2-D replicate-only world mesh returns cleanly where the previous
no-arg `get_group()` call raised `RuntimeError`.

Both full-model validations used `qpn01gpu009/011`, 16 GPUs, CP4 + EP8,
optimizer-state offload, BF16 compute, and expandable CUDA allocator
segments. They used fake data with no evaluation or checkpoint overhead.

Job 1185 artifacts are retained at:

```text
/home/outputs/int4-debug/sft-air-full-muon-init-warmup-2n-009-011
```

## Confidence and limitations

Confidence is high that this initialization prevents the observed
first-all-to-all deadlock: the failure was reproducible without it, the
matching warm-up removed it in progressively more production-like tests,
and the final implementation has continued to work in four long-running
RL jobs.

The exact NCCL-native deadlock mechanism remains unproven. The warm-up
changes connection state, allocation history, and startup timing, so
this should be described as a targeted correctness workaround rather
than proof of a particular NCCL defect. Removing or moving it requires
reproducing the original multi-node pretrained GLM-Air Muon case, not
merely passing a standalone collective test.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes distributed initialization for Muon only, but incorrect group
selection or removal could reintroduce multi-node deadlocks or add
startup memory/time on every Muon run.
> 
> **Overview**
> Adds a **correctness workaround** for multi-node Muon training: NCCL
peer channels for bulk all-to-all are established **right after** Dion
`Muon` is built and **before** the first optimizer step, so
GLM-Air-style jobs avoid deadlocking on the initial Muon collective.
> 
> New helper `_warmup_muon_process_group` no-ops for single-rank or
non-NCCL groups; otherwise it runs an async **list** `all_to_all` on ~3
MiB BF16 buffers per rank (matching Dion’s bulk path), waits, and
synchronizes CUDA. Warm-up runs on the main **`dp_shard_cp`** (or world)
process group and, when expert MLP params use EP, separately on
**`dp_shard_mod_ep`**. AdamW, SGD, and other optimizers are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d0b707438f77780e4b5e0ed69237c08435ba3a41. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-07 11:20:40 -07:00
26b3131d27 fix(transports): make NCCL respect keep_in_fp32_for_weight_transfer (#3480)
The NCCL weight-broadcast transport hardcoded every tensor to
`bfloat16`, ignoring `keep_in_fp32_for_weight_transfer`. This PR makes
NCCL transport respect the fp32 overrides. This makes NCCL honor the
same declaration the other two transports already respect. Note: NIXL
does its own thing and does not use this shared helper, yet.

- Extracted `resolve_wire_dtype()` so the filesystem and NCCL paths
share one implementation.
- Lifted `NCCLBroadcaster._resolve_dtensors` to a module-level
`resolve_dtensors()`, since a method reachable only through a live
`PyNcclCommunicator` can't be unit tested.
- Added `tests/unit/utils/test_weights.py`, the flag's first test
coverage, parametrized over all six models that declare it.

Ran various experiments with small models to see if this affected KL mismatch in any way, but results were inconclusive. See commit https://github.com/PrimeIntellect-ai/prime-rl/pull/3480/changes/4b152bf3fa551ff5a1fc1752036262d14520c343 for example experiment configs.


---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 16:57:19 -04:00
samsjaandGitHub ef9dea1781 chore(inference): introduce admin plane abstraction (#3472)
## Summary

- consolidate the inference control path into a single `AdminPlane`
abstraction over its worker HTTP clients
- make the static plane own readiness, NCCL setup, weight updates, and
lifecycle management
- expose one typed `update_weights` operation; each receiver identifies
its transport explicitly
- route filesystem, NCCL, and NIXL receivers through the admin plane
instead of passing raw HTTP client lists
- remove the separate admin-plane protocol, unused factory argument, and
pass-through weight-update wrapper

`InferenceClient` remains the data-plane client for generation and
scoring, while `AdminPlane` coordinates control operations against one
or more inference workers. Alternate backends can specialize a transport
operation without adding backend flags to weight receivers.

## Validation

- `uv run ruff check src/prime_rl/orchestrator/clients.py
src/prime_rl/orchestrator/orchestrator.py src/prime_rl/evals/evals.py
src/prime_rl/transports/weights tests/unit/orchestrator/test_clients.py`
- `uv run python -m compileall -q src/prime_rl/orchestrator/clients.py
src/prime_rl/orchestrator/orchestrator.py src/prime_rl/evals/evals.py
src/prime_rl/transports/weights`
- `uv run pytest -q tests/unit/orchestrator/test_clients.py` (10 passed)

The transport test module could not be collected on this host because
its optional CUDA import chain requires `flash_attn`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Refactors the weight-broadcast control path (pause/resume,
NCCL/NIXL/filesystem updates) used during training; behavior should be
equivalent but mistakes here can strand engines paused or desync policy
versions.
> 
> **Overview**
> Renames **`AdminClients`** to **`AdminPlane`** and makes it the single
control-plane entry point for inference workers (readiness, NCCL init,
weight updates, LoRA load, teardown).
> 
> **NCCL setup** and **weight updates** move from module-level helpers
into **`AdminPlane.initialize_nccl`** and
**`AdminPlane.update_weights`**, with callers passing an explicit
**`transport`** (`filesystem` | `nccl` | `nixl`). Orchestrator, evals,
and all **`WeightReceiver`** implementations now take an
**`AdminPlane`** instead of raw **`httpx`** client lists;
**`load_lora_adapter`** and **`init_nixl_broadcast`** follow the same
pattern.
> 
> Unit tests are updated and **`test_admin_plane_initializes_nccl`** is
added.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
65043370b7a9c857e6e3302f665b0b8c389043f1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-03 16:36:16 -07:00
Konstantin DunasandGitHub 6c7b1ef375 feat: visualize compaction attempts and exclude rejected branches (#3478) 2026-09-03 22:09:41 +02:00
samsjaandGitHub 608c75c0af feat(dashboard): add timed terminal trace replay (#3456)
## Summary


https://github.com/user-attachments/assets/cd2caaa1-d700-40e5-8465-911812313f15

- add a terminal-style Replay view for rollout traces using recorded
model-call and tool timing
- add play/pause, seek, restart, 0.5x-32x speed controls, and an
inference-skipping tool-timing mode
- expose recorded model thinking with a toggle and T shortcut
- support Top/Live transcript navigation with Home/End shortcuts
- document replay timing semantics and extend dashboard smoke coverage

## Rebase notes

Rebased onto main (past #3444 overlays, #3465 chunked trace streams,
#3470 task/judge evidence, and #3455 semantic traces). Resolutions:

- `app.js` view state: trace viewer now has four modes — transcript,
timeline, replay, semantic; `setTraceView` keeps main's `persist` option
(replay is never persisted as a preference) and stops replay playback on
view switches; control visibility unions both sides (token-signal /
view-mode / collapse / expand hidden in graph, evidence, and replay
modes)
- `app.js` keyboard handler: replay T/Home/End shortcuts run first, then
main's step-bar arrow-key walking
- `app.js` click handler: replay control handlers first, then the
copy-button selector (including main's task/judge copy buttons)
- `index.html`: Replay button sits alongside main's Semantic button and
its episode-nav row
- `docs/training.md` / `skills/dashboard/SKILL.md`: describe all four
trace views together

## Validation

- `node --check src/prime_rl/dashboard/static/app.js` (rebased)
- `uv run --frozen ruff check tests/integration/dashboard_smoke.py`
(rebased)
- focused Playwright checks were run on the original branch (timed
playback, inference skipping, thinking toggles, keyboard shortcuts,
Top/Live navigation)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Read-only dashboard frontend and documentation; no changes to
training, inference, or data persistence.
> 
> **Overview**
> Adds a **Replay** tab to the rollout trace viewer that plays the
selected branch as a terminal session, using recorded model-call and
message timestamps for wall-clock pacing.
> 
> Playback includes play/pause, seek, restart, **0.5×–32×** speed
(default **8×**), **Skip inference** (instant model replies while
keeping tool delays), optional **Thinking** display (**T**), and **Top**
/ **Live** scroll follow (**Home** / **End**). Response text is revealed
evenly across each model-call span and labeled as inferred when
per-token timestamps are absent; prompt nodes committed at response time
are aligned to call start to avoid false idle gaps. Transcript-only
controls are hidden in Replay mode, and integration smoke tests cover
the new UI.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fddf8349c2f99ec4ac658b6bbfacb2e8f24532c9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-02 16:50:33 -07:00
Konstantin DunasandGitHub b28714289a feat(dashboard): visualize semantic agent traces (#3455) 2026-09-03 01:33:18 +02:00
Konstantin DunasandGitHub 903baaaa01 fix(dashboard): hide repeated timeline rewards (#3473) 2026-09-03 00:51:31 +02:00
Konstantin DunasandGitHub ae170acda1 feat(dashboard): surface task and judge evidence (#3470) 2026-09-03 00:45:13 +02:00
samsjaandGitHub c84068cf9e fix(evals): show error rate on partially evaluated epochs (#3462)
## Summary

- the partially-evaluated (cancelled-epoch) warning line in the `uv run
evals` entrypoint log now shows the `Error` rate next to `Reward` —
previously it reported reward with no signal of how many completed
episodes errored

```
Partially evaluated swebench-pro (Step 240) |  1m 32s | Reward 0.4167 | Error 5.0% | Completed 92/100 | Cancelled 8/100
```

The completed-epoch success line already shows `Error` and is unchanged:

```
Evaluated swebench-pro (Step 240) |  1m 32s | Reward 0.4167 | Turns 3.2 | Branches 1.0 | Error 5.0% | Truncation 2.0%
```

## Verification

- `uv run ruff check src/prime_rl/evals/evals.py` — passed
- `uv run ruff format --check src/prime_rl/evals/evals.py` — passed

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Logging-only change in eval finalization; no behavior, scheduling, or
metric emission changes.
> 
> **Overview**
> When an eval epoch is **cancelled** (e.g. superseded by a newer
checkpoint), the warning log line now includes the **Error** rate from
completed episodes, using the same `full.has_error` formatting as the
full **Evaluated** success line.
> 
> Previously that partial-eval message only showed reward and
completion/cancel counts, so operators could not see how many finished
rollouts failed without digging into metrics.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
010a7eceb61c71fa105ffadf7b4dc4e6708fc188. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-02 13:26:03 -07:00
262 changed files with 19021 additions and 9060 deletions
+3
View File
@@ -87,6 +87,9 @@ jobs:
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py"
- test: gsm8k_eval
runner: vm
pytest_args: "tests/integration/test_gsm8k_eval.py"
steps:
- name: Install Git
run: |
+3 -2
View File
@@ -5,6 +5,7 @@
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
- **Don't touch `optimization_dtype` / `reduce_dtype`**: never change these model config fields (or their defaults in `trainer.py`) unless the user explicitly asks. They're load-bearing numerical knobs — flipping bfloat16/float32 silently changes training dynamics.
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
- **Context parallelism**: a module that needs CP state holds a `CPContext` (`models/base.py`) as `self.cp_context`, defaulting to `CPContext()`, which is the non-CP case; `PreTrainedModelPrimeRL` supplies that default. `setup_context_parallel` in `utils/cp.py` builds one `CPContext` and assigns it to every module that has the field, so each module holds the same frozen object.
- **Zen of Python**: remember the Zen of Python when writing code.
```
Beautiful is better than ugly.
@@ -42,9 +43,9 @@ Namespaces are one honking great idea -- let's do more of those!
## Skills
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs). When you make changes to the codebase, check if any skills need to be updated to stay accurate.
Skills live in `skills/` and are symlinked to `.claude/skills/` (Claude Code) and `.agents/skills/` (Codex). They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs).
You are responsible for maintaining the skills folder. When a workflow fails and you fix it – whether with help from the user or through trial and error – you must update the skills to make implicit knowledge explicit. You are also responsible for keeping the skills up to date whenever you or anyone else modifies the code.
If a repository skill could benefit from an update, suggest the specific change, explain why it would help, and ask the user for approval before making it. Wait for approval before creating, modifying, renaming, or deleting skills, including their supporting files and symlinks. If the user has already explicitly requested or approved the skill change, proceed without asking again. Requests to change code, fix workflows, update documentation, or open a PR do not implicitly authorize skill changes. You may read and follow skills without changing them.
## Testing
-1
View File
@@ -1 +0,0 @@
@AGENTS.md
+19 -2
View File
@@ -94,9 +94,10 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# Third-party deps only — source edits don't bust this layer. First-party
# editables install in the source-layer sync below. No build-context bind
# mount here: .git would bust the cache every commit.
# `--extra dashboard` (fastapi/uvicorn) is baked in so the fft chart's dashboard pod needs no runtime uv sync (see PR body).
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
@@ -132,10 +133,26 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
# Needed for private environments hub auth.
#
# FIXME(prime#940): workaround, remove once the prime CLI drops verifiers as
# a dependency (https://github.com/PrimeIntellect-ai/prime/pull/940). The CLI
# pins verifiers==0.2.0, which replaced the editable verifiers synced above
# with the PyPI wheel and left prime-rl's own entrypoints unable to import;
# the --overrides file ignores that one requirement. When removing it, drop
# the overrides file and the --overrides flag, keep the import assertion, and
# make the same change in scripts/docker-entrypoint.sh, which replays this
# step for the runtime source overlay.
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
printf 'verifiers\n' > /tmp/prime-cli-overrides.txt \
&& VIRTUAL_ENV=/app/.venv uv pip install --overrides /tmp/prime-cli-overrides.txt 'prime>=0.7' \
&& rm /tmp/prime-cli-overrides.txt \
&& /app/.venv/bin/python -c 'import pathlib, verifiers; assert pathlib.Path(verifiers.__file__).is_relative_to("/app/deps/verifiers"), verifiers.__file__'
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
# (#2883); rebuilding against our UCX is the documented fix. Only needed for
+7 -24
View File
@@ -38,7 +38,7 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
7. Hackable, modular, and extensible by design.
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.2/).
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.3/).
## Models support
@@ -59,7 +59,7 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
| GLM-4 · GLM-4.5 MoE · INTELLECT-3 (`glm4_moe`) | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5-Air`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | yes | ✅ | ✅ |
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ✅ | ✅ |
| GPT-OSS (`gpt_oss`) | `unsloth/gpt-oss-20b-BF16`, … | yes | ✅ | ✅ |
| Other HF causal LMs | Qwen3 dense, Mistral, … (`impl = "hf"`) | varies | ❌ | ✅ |
@@ -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>`.
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.
> *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
uv pip install "flash-attn-3 @ git+https://github.com/Dao-AILab/flash-attention.git@main#subdirectory=hopper" --no-build-isolation
```
</details>
<details>
@@ -148,19 +139,13 @@ uv run python -c "import flash_attn"
uv run sft @ configs/debug/fake/sft.toml
```
4. Check that you can run the RL trainer (*this requires 1 GPU*)
```bash
uv run trainer @ configs/debug/fake/rl.toml
```
5. Check that you can run the inference server (*this requires 1 GPU*)
4. Check that you can run the inference server (*this requires 1 GPU*)
```bash
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*)
5. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
```bash
uv run rl @ configs/basic/reverse-text/rl.toml
@@ -204,10 +189,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
3. [**Nemotron-3-Super**](examples/advanced/nemotron-3-super/): Train the `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
4. [**MiniMax-M2.5 SWE**](examples/advanced/minimax-m2.5/): Train `MiniMax-M2.5` on agentic SWE tasks.
5. [**INTELLECT-3.1**](examples/advanced/intellect-3.1/): Reproduce our `INTELLECT-3.1` training run.
6. [**High-throughput GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation, the `llm-d` router, and FP8.
3. [**GLM-5**](examples/advanced/glm-5.3/): Large-scale `GLM-5`/`GLM-5.3` training with P/D disaggregation, the `llm-d` router, and FP8.
## Docs
@@ -215,7 +197,8 @@ Check out the [docs](docs) directory for in-depth guides on how to use prime-rl.
- [**Overview**](docs/overview.md) - Architecture, install, and a copy-pasteable end-to-end RL run
- [**Configuration**](docs/configuration.md) - TOML composition, CLI overrides, env vars, validation
- [**Training**](docs/training.md) - RL, SFT, evals, checkpointing, observability, rules of thumb
- [**Training**](docs/training.md) - RL, SFT, checkpointing, observability, rules of thumb
- [**Eval**](docs/eval.md) - Standalone evals against any inference server, online evals, resume, platform upload
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA
+12 -5
View File
@@ -6,13 +6,20 @@ Configurations for running prime-rl.
environments, sized to run on a single dev machine. Each mirrors the matching
[`examples/basic/`](../examples/basic) tutorial and is smoke-tested for one step.
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
- **[`advanced/`](advanced)** — frontier-model training configs without launch walkthroughs:
`minimax-m2.5` (swe), `nemotron-3-super` (swe), `deepseek-v4-flash` (sft + a standalone
vLLM serving pre-flight). For the tutorialized equivalents, see
[`examples/advanced/`](../examples/advanced).
- **`ci/`** — integration and nightly configs used by CI.
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
(two reverse-text train sources + one eval source, one env server per source). Not
guaranteed functional or up to date.
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), `multi-env/`
(two reverse-text train sources + one eval source, one env server per source), and
`eval/` (`uv run eval` smokes against Prime Inference, one per shape: `single-turn`
(gsm8k), `multi-turn` (terminal-bench-2 fix-git in sandboxes against a local vLLM deployment with the adaptive band), `resume`, `multi-env`).
Not guaranteed functional or up to date.
```bash
uv run rl @ configs/basic/<env>/rl.toml
uv run sft @ configs/basic/<env>/sft.toml # where present
uv run rl @ configs/basic/<env>/rl.toml
uv run sft @ configs/basic/<env>/sft.toml # where present
uv run eval @ configs/debug/eval/<shape>.toml
```
@@ -22,8 +22,6 @@ num_infer_replicas = 4
project = "nemotron-3-super"
name = "nemotron-3-super-swe"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
+12
View File
@@ -0,0 +1,12 @@
# CI eval smoke: gsm8k with the null harness in a local subprocess runtime against
# Prime Inference — the eval path end to end without a GPU or sandbox.
num_examples = 4
dashboard = false
[sampling]
max_completion_tokens = 8192
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+1 -1
View File
@@ -135,5 +135,5 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
quantization = "fp8"
quantization = "fp8_per_block"
enable_return_routed_experts = true
+16
View File
@@ -0,0 +1,16 @@
# AIME 2026 at avg@16: every problem 16 times with the null harness (one chat
# completion per rollout) against Prime Inference. The math tasksets forbid the
# agent any network, and only the sandboxed runtimes enforce that policy, so the
# rollouts run in prime sandboxes (PRIME_API_KEY) rather than as subprocesses.
# Competition math needs room to reason, so the completion budget is generous.
#
# uv run eval @ configs/debug/eval/aime2026.toml
group_size = 16
[sampling]
max_completion_tokens = 32768
[[source]]
env.taskset.id = "aime26"
env.agent.harness.id = "null"
+20
View File
@@ -0,0 +1,20 @@
# Multi env: 16 terminal-bench-2 tasks under two harnesses, bash and rlm, in prime
# sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout each with
# a ten-minute budget, against Prime Inference on the default model. One env server
# per source; the sources share the taskset, so each carries its own name.
#
# uv run eval @ configs/debug/eval/multi-env.toml
num_examples = 16
[[source]]
name = "tb2-bash"
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 600
[[source]]
name = "tb2-rlm"
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "rlm"
env.agent.timeout.rollout = 600
+12
View File
@@ -0,0 +1,12 @@
# Single env, multi turn: 16 terminal-bench-2 tasks with the bash harness in
# prime sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout
# each, against Prime Inference on the default model.
#
# uv run eval @ configs/debug/eval/multi-turn.toml
num_examples = 16
[[source]]
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
+23
View File
@@ -0,0 +1,23 @@
# Single env, resume: gsm8k with a low pinned concurrency so the run can be
# interrupted partway. Relaunch with the same --run.name and --resume: the landed
# episodes are restored from the trace stream and only the owed rollouts run.
# Resuming a finished run restores everything and exits.
#
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug
# <Ctrl-C partway>
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug --resume
num_examples = 8
group_size = 2
[concurrency]
min_inflight = 2
max_inflight = 2
[sampling]
max_completion_tokens = 8192
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+15
View File
@@ -0,0 +1,15 @@
# Single env, single turn: gsm8k with the null harness (one chat completion per
# task, no sandbox) against Prime Inference.
#
# uv run eval @ configs/debug/eval/single-turn.toml
num_examples = 8
group_size = 2
[sampling]
max_completion_tokens = 8192
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+13
View File
@@ -0,0 +1,13 @@
# Terminal-Bench 2 at avg@4: every task 4 times with the bash harness in prime
# sandboxes (PRIME_API_KEY authenticates sandbox creation) against Prime Inference.
#
# uv run eval @ configs/debug/eval/tb2.toml
group_size = 4
[[source]]
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
env.agent.retries.max_retries = 2
env.agent.retries.include = ["ProviderError", "SandboxError"]
+1 -1
View File
@@ -1,6 +1,6 @@
# Minimal multi-env debug run: two reverse-text train sources + one eval source.
# The launcher spawns one env server per source at its derived address
# (tcp://127.0.0.1:5000-5002); the orchestrator connects to each.
# (each on an OS-assigned loopback port it publishes); the orchestrator connects to each.
max_steps = 10
seq_len = 2048
+1 -1
+1 -1
+45 -2
View File
@@ -6,6 +6,7 @@ This page covers the specialized features layered on top of the core training st
- [Custom Modeling](#custom-modeling)
- [Expert Parallelism Backends](#expert-parallelism-backends)
- [Runtime Fusions](#runtime-fusions)
- [Multimodal Training](#multimodal-training)
- [Supported Families](#supported-families)
- [Enabling VLM Mode](#enabling-vlm-mode)
@@ -33,10 +34,14 @@ impl = "custom" # or "hf" to force the HF path
| Nemotron H | `nvidia/Nemotron-3-Nano-30B-A3B`, … | ✅ | ❌ |
| Trinity (AFMoE) | `arcee-ai/Trinity-Mini`, … | ✅ | ✅ |
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
| GPT-OSS | `unsloth/gpt-oss-20b-BF16`, … | ✅ | ✅ |
| DeepSeek V4 | `deepseek-ai/DeepSeek-V4-Flash-0731` | ✅ | ✅ |
Selective activation checkpointing works with either implementation. The custom path additionally enables EP, CP, low-precision training, and grouped MoE kernels. Forcing `impl = "hf"` is mostly useful when debugging and disables those model-specific runtime features.
GPT-OSS uses FlashAttention 4 with learned attention sinks. Training requires SM90 or SM100/SM110 GPUs
and a BF16 checkpoint such as `unsloth/gpt-oss-20b-BF16`; the original MXFP4 checkpoints are not supported.
### Low-precision training
Dense linear precision and routed-expert precision are configured independently. `[trainer.model.quantization]` applies only to dense `Linear` modules:
@@ -64,6 +69,26 @@ type = "torch"
transport = "mxfp8"
```
All MoE compute backends accept `apply_to`:
- `"all"` (default) applies the backend to all expert groups.
- `"85%"` applies it to the first 85% of model layers, rounded down. For a 48-layer model, this selects layers 0–39.
- `[0, 1, 2, 3]` selects explicit zero-based model layer indices; `[]` selects none.
Percentages must be between 0% and 100%; explicit indices must be within the model's layer count. Non-MoE blocks in hybrid models count toward layer indices and percentages. Each selected layer uses the backend for all its routed experts. Other expert groups use BF16 compute and BF16 token transport while retaining the configured dispatch backend and expert parallelism. Dense linear quantization is configured separately.
For example, this selects routed experts in Qwen3's first four model layers:
```toml
[trainer.model.moe.compute]
type = "mxfp8"
apply_to = [0, 1, 2, 3]
```
Backend shape checks and token alignment apply only to the selected compute path.
In RL runs, configure the same precision selection for rollouts. Inference module names can differ from the trainer's names, and inference precision is configured explicitly, not inferred from `apply_to`. Check the selected modules on both sides before comparing trainer and rollout logprobs.
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
### Expert Parallelism Backends
@@ -82,6 +107,24 @@ token_chunk_size = 4096
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
### Runtime Fusions
`model.fusions` packs parameters that are always computed together into one tensor, turning several GEMMs into one. Both fusions are on by default:
- `gate_up` — each gated MoE expert's `gate_proj` and `up_proj` become one `[num_experts, 2 * intermediate_size, hidden_size]` weight, halving the routed-expert grouped GEMMs.
- `qkv` — an attention layer's `q_proj`, `k_proj` and `v_proj` (and their biases) become one linear layer.
```toml
[trainer.model.fusions]
enabled = ["gate_up", "qkv"] # [] disables
```
Fusions are runtime-only. Checkpoints keep the canonical parameter names and shapes, so a run can turn a fusion on or off at any point and still load its own checkpoints, and exported weights are unaffected. Only modules that support a fusion are packed; a requested fusion that no module supports logs a warning, or fails at startup with `raise_on_fail = true`. Fusions are skipped when LoRA is enabled.
Muon receives the packed layout as matrix partitions and orthogonalizes each logical matrix on its own, so a packed parameter trains exactly as the parameters it replaces would — including per-projection learning-rate scaling for grouped-query attention — while keeping a single momentum tensor.
The experimental `shard_fused_on_dim1 = true` shards fused 2-D weights along dim 1 under FSDP, which makes weight loading and checkpointing zero-copy: fused weights and their optimizer state are read and written in place rather than assembled into a full copy on each rank first. It requires `hidden_size` to be divisible by the FSDP shard mesh size.
## Multimodal Training
### Supported Families
@@ -145,7 +188,7 @@ For large MoE serving, splitting prefill and decode onto separate vLLM groups ca
| Agentic (SWE, Lean) | 3:1 | Long growing contexts → prefill-heavy |
| Non-agentic (math, chat) | 1:2 | Short prompts, long generations → decode-heavy |
Example config: [`examples/advanced/glm-5.2/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.2/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.2/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2/infer).
Example config: [`examples/advanced/glm-5.3/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.3/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.3/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3/infer).
Monitor live queue depths to detect imbalance:
+34 -4
View File
@@ -112,7 +112,7 @@ patterns = ["WARNING"]
def drop_warnings(rollout, *, patterns: list[str]) -> list[list[bool]]: ...
```
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and aborts after repeated zero-trainable batches), not at config time.
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and skips it), not at config time.
### Per-Env Algorithms
@@ -184,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]`): IPO 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).
- `rl` — the configured RL loss (`[trainer.loss]`): IPO by default, or optionally [IcePop](#icepop-loss) 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`).
@@ -209,12 +209,42 @@ The knobs under `[trainer.loss]` are:
| Knob | Default | What it does |
|---|---|---|
| `eps` | 0.1 | Maximum absolute probability change before a token is masked. |
| `eps` | 0.3 | Maximum absolute probability change before a token is masked. |
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
| `kl_tau` | 0.0 | Temperature on the KL regularizer. Set to 0 to disable. |
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
### IcePop Loss
IcePop is an opt-in RL loss that drops tokens whose trainer-to-inference
importance ratio falls outside a fixed acceptance band, introduced to stabilize
MoE RL in [Every Step Evolves: Scaling Reinforcement Learning for Trillion-Scale
Mixture-of-Experts Reasoning Models](https://arxiv.org/abs/2510.18855). Accepted
tokens retain the importance-weighted policy-gradient term, and there is no
separate KL penalty:
$$
\mathcal{L}(\theta) = -\frac{1}{N}\sum_t
\mathbb{1}\!\left(\alpha \le \frac{\pi(y_t)}{\mu(y_t)} \le \beta\right)
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}.
$$
Enable it explicitly:
```toml
[trainer.loss]
type = "icepop"
ratio_low = 0.2
ratio_high = 5.0
```
| Knob | Default | What it does |
|---|---|---|
| `ratio_low` | 0.2 | Lower accepted trainer-to-inference probability ratio. |
| `ratio_high` | 5.0 | Upper accepted trainer-to-inference probability ratio. |
| `adv_tau` | 1.0 | Temperature on the advantage term. |
### Custom Loss
`[trainer.loss] type = "custom"` replaces the `rl` component. The loss is computed **per sequence**: you write a function that takes one sequence's tensors and returns a scalar loss. The trainer iterates and aggregates. `inputs.loss_mask` selects exactly the rl member tokens (for a plain GRPO run, all trainable tokens).
+14 -5
View File
@@ -171,7 +171,16 @@ 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.
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — takes an `env` block that each of its sources inherits. A source's own `env` values win. The block holds only the knobs that every env and taskset has: `retries`, `timeout`, `max_concurrent_agents`, `interception`, and `taskset.task` and `taskset.system_prompt`. Ids and agents stay on each source:
```toml
[orchestrator.eval.env]
retries.max_retries = 3
retries.include = ["ProviderError", "SandboxError"]
timeout.episode = 7200
```
`ratio` is a training-source field: it defaults to `1` (equal weight per env), and values are relative weights normalized to probabilities across envs. Eval sources of a training run carry `interval` instead, the step interval at which they fire (inherited from the group-level `interval` when unset); a standalone eval has neither.
Everything environment lives under the `env` block (verifiers' `[env]` shape): `env.taskset` configures the v1 taskset, and each agent is a field on the env — `env.agent.harness` selects how the single-agent env's tasks are run, and per-run caps are per-agent (`env.agent.max_turns`, `env.agent.timeout`, `env.agent.max_output_tokens`). A multi-agent env declares its own seats (`env.<role>.*`).
@@ -225,11 +234,11 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
**Advanced** (32–2048 GPUs, SLURM):
- [**Qwen3-30B-A3B**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-30b-a3b) — `Qwen3-30B-A3B` on math, SWE, and tool use.
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal.
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal; includes a variant that trains the 100B+ MoE on only two nodes.
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation and FP8.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale `GLM-5`/`GLM-5.3` inference with P/D disaggregation and FP8.
### Worked Example: Compose, Override, Dry-Run
+3 -3
View File
@@ -141,12 +141,12 @@ In the PR that adds the new model, you also need to provide a table covering the
## Adding a Custom VLM Implementation
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body — the Qwen3.5 dense (`models/qwen3_5/`) and MoE (`models/qwen3_5_moe/`) implementations are the reference. The pieces, in dependency order:
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body. The unified dense/MoE Qwen3.5 implementation in `models/qwen3_5/` is the reference. The pieces, in dependency order:
1. **Custom text model first.** The VLM body wraps a custom `*ForCausalLM` (see [Adding a New Model](#adding-a-new-model)), so the text side — including its state-dict conversion and KL-mismatch table — comes first.
2. **Composite VLM body.** A `*VLMModel` that holds the HF vision encoder and the custom text model, with a `prepare_inputs_embeds_and_position_ids` step: embed tokens, run the vision encoder, scatter image embeddings over placeholder tokens, and build MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
2. **Composite VLM body.** A `*VLMModel` that holds the vision encoder and custom text model, embeds tokens, runs vision, scatters image embeddings over placeholder tokens, and builds MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
6. **Context parallelism (optional).** CP-capable VLMs implement `set_context_parallel_attributes` and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
6. **Context parallelism (optional).** CP-capable VLMs hold a `CPContext` on all modules which need to be CP-aware and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
7. **Validation.** Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the `color-codeword` environment is the reference task).
+122
View File
@@ -0,0 +1,122 @@
# Eval
This page covers `uv run eval` — evaluating a model in one or more environments. For the online evals of a training run, see [Training](training.md#online-evals).
> **AI agents working in this repo:** the equivalent runbook is at [`skills/eval/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/eval/SKILL.md).
## Table of Contents
- [Launch](#launch)
- [Configuration](#configuration)
- [Resume](#resume)
- [Monitors](#monitors)
- [File](#file)
- [Prime](#prime)
- [Metrics](#metrics)
`uv run eval` runs one epoch of every configured source and exits. It reuses the orchestrator's eval pipeline: env servers are spawned per source, episodes are admitted under the concurrency controller, and every episode streams into the run's trace stream and metrics.
## Launch
By default the model is served by Prime Inference; authenticate with `PRIME_API_KEY` or `prime login`:
```bash
uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Inference
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
```
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
```bash
uv run inference --vllm.model Qwen/Qwen3-4B
uv run eval gsm8k -n 32 -r 4 -m Qwen/Qwen3-4B --client.base_url http://localhost:8000/v1
```
Single-source shorthands: `<taskset-id>` names the run's only source, `--env.<field> <value>` sets a field of that source's env block (`--env.agent.harness.id bash`, `--env.taskset.tasks '["fix-git"]'`), `-n`/`-r` set `num_examples`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). `<taskset-id>` cannot be combined with a TOML that defines `[[source]]` blocks; next to one, `--env.<field>` sets the shared [env block](#configuration) instead. `uv run eval -h` lists them.
Against a local vLLM deployment, set `min_inflight < max_inflight` in `[concurrency]` to dynamically adjust the number of concurrent episodes for maximum throughput. An external API exposes no vLLM `/metrics` to adapt to, so pin the concurrency there (`-c N`, i.e. `min_inflight = max_inflight`).
## Configuration
Multi-source runs use a TOML (`EvalConfig` in `packages/prime-rl-configs/src/prime_rl/configs/eval.py`). The eval block is flattened to the top level — `[[source]]`, `[client]`, `[concurrency]`, `[sampling]`, `num_examples`, `group_size` — and each source takes the same `env` block as `[[orchestrator.eval.source]]`:
```toml
model = "Qwen/Qwen3-4B"
num_examples = 32
group_size = 4
[client]
base_url = "http://localhost:8000/v1"
[concurrency] # adaptive against a local vLLM deployment
min_inflight = 8
max_inflight = 256
[sampling]
max_completion_tokens = 2048
[env] # every source inherits these
timeout.episode = 7200
retries.max_retries = 3
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "bash"
[[source]]
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
Per-source `num_examples`, `group_size` and `sampling` override the top-level defaults. The top-level `[env]` block holds the env knobs that every source inherits (see [Environments](configuration.md#environments)); a source's own `env` values win.
Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
## Resume
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: the episodes that landed rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch) and only the rollouts still owed run. Errored episodes and the ones the interruption cut off run again.
```bash
uv run eval @ eval.toml --run.name my-eval
# <interrupted>
uv run eval @ eval.toml --run.name my-eval --resume
```
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
A landed episode counts toward the task with its `task.key`, so `num_examples` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The model, the sampling and each source's env must match the config the landed episodes were measured with (kept beside them in `monitors/file/eval.json`); a resume that changes them stops with the differing config paths. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
## Monitors
Monitors receive the run's metrics and episodes through one abstraction. The file monitor is on by default; `--monitors.wandb` logs the run to Weights & Biases; `--monitors.prime` streams it to the Prime platform.
### File
The file monitor writes the run's metrics and trace stream under `output_dir / run.name / monitors/file/` and feeds the local [dashboard](training.md#dashboard). Env servers stream every rollout to the eval process as it happens: the trace's header when it is minted, then one delta per committed turn (the new messages and the model call behind them), per phase change (boot, setup, agent, finalize, scoring), and a preview of each model request's uncommitted messages, so a tool result shows the moment the model is asked about it rather than with the reply. The file monitor appends those deltas to `monitors/file/traces/live/<trace_id>.jsonl` and deletes the file when the episode lands in the finished trace stream, so that directory is exactly the live set and finished traces stay where they always were. The dashboard's traces tab shows live rollouts in the episode table itself: a pulsing dot in the `#` cell marks the row, a phase badge says where the rollout is (boot, setup, running, finalize, scoring), the `dispatched → arrived` column shows the dispatch time with the elapsed time in brackets, and the turn, token and branch counts grow as deltas land. The status filter toggles live and completed rows, and a live row opens in the trace viewer, which follows the rollout turn by turn (the transcript stays pinned to the newest turn until you scroll up; folded entries stay folded; the pending messages of the request in flight render dimmed with an `awaiting model` chip). The table and an open live trace poll once a second and transfer nothing while the rollout is unchanged. The progress line in `eval.log` counts the live rollouts by phase (`2 inflight episodes ... - boot 1 · running 1`). Read a live trace from a shell with `uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`. The same stream exists for RL runs, covering train and online-eval rollouts alike.
The dashboard's overview tab reads the trace stream directly. It shows one env at a time; the filter menu picks the env and whether errored episodes join the distributions. A block bar has one cell per expected episode: landed episodes (errored ones in red; click one to open it), live rollouts as pulsing outlines (click one to follow it), and the rest empty, with the percentage beside it. The expected count is what the eval runner wrote to `monitors/file/plan.json` when it counted the epoch's tasks. Below the bar, a summary row gives the headline numbers: avg@k and pass@k, the error and truncation rates (yellow past 10%, red past 50%), mean turns and branches in one tile, mean episode time and tokens, and the total cost when the run has costs; hover a tile for its distribution. The env's own rewards and metrics follow, a beeswarm pane each, resizable like the training charts. The usage section is one pane splitting each episode's tokens into input and output, and the timing section is the same pane over the phases of a rollout (boot, setup, model, harness, finalize, scoring, and `other` for wall time no phase accounts for): an icicle bar shows the mean split, one strip per episode below shows the split per rollout, and a legend sits above. Hovering a phase highlights it across the pane; the strips show 40 episodes by default and all of them on `show all`. A metric every episode shares appears as a chip instead of a pane, and a metric with only a few distinct values, such as a binary reward, as a counted dot plot with the count and share of each value. Every dot is an episode (or a task): hover it for its value and click it to open the trace; hover the pane's background for the summary (min, p10, median, p90, max), with a faint boxplot behind the dots. Errored episodes stay out of the distributions until the filter includes them, where they read red. The metrics tab charts every key of the run's `metrics.jsonl`: the epoch's `eval/<env>/…` summaries and the time-keyed `inference/` and `concurrency/` rows the runner samples while the epoch is in flight.
### Prime
`--monitors.prime` streams each source's epoch as an evaluation on the Prime platform:
```bash
uv run eval gsm8k -n 32 -r 4 -c 8 --monitors.prime
```
The monitor opens one platform evaluation per env when its epoch starts, streams every episode to it as it lands, and closes it with the epoch's aggregates. The run leaves its platform identity in `monitors/prime/run.json` (the training run's id and URL, or one entry per eval epoch), and the dashboard's top bar shows a `view on platform` link from the moment the evaluation opens: a direct link for a training run or a single evaluation, a menu when a run has several.
## Metrics
Eval metrics mirror the training rollout hierarchy under the `eval/<env>` scope:
| Metric | Reading |
|---|---|
| `eval/<env>/all/<agent>/reward/mean` | mean reward over the epoch |
| `eval/<env>/all/<agent>/is_truncated/mean` | share of rollouts cut by the length limit |
| `eval/<env>/all/<agent>/is_timeout/mean` | share of rollouts stopped by a stage deadline (`<stage>_timeout`) |
| `eval/<env>/all/<agent>/has_error/mean` | share of rollouts that raised |
| `eval/<env>/all/seq_len/mean` | mean episode length in tokens |
Task-specific env metrics (e.g. `correct_answer`, `format`) appear under the same prefix. The console summary line per source (`Evaluated <env> ... Reward 0.8125`) reports the epoch mean.
+5 -3
View File
@@ -190,8 +190,10 @@ Both backends support the 2 most important things:
- P/D disaggregation - handling the prefill and decode stages separately
### Routing policies
The 2 policies you might want to configure are:
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - it hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica.
The policies you might want to configure are:
- `sticky_least_loaded` - the default policy. A new `X-Session-ID` is assigned to the least-loaded replica, then every later turn in that rollout remains on the same replica for KV cache reuse. The orchestrator releases sessions when rollouts complete, fail, or are cancelled, including traces discarded during retries. Failed release requests are logged without disabling future cleanup.
- `consistent_hash` - hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica, preserving KV cache reuse without considering current load.
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
@@ -285,7 +287,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.28 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.29 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
```toml
[trainer]
+1
View File
@@ -7,6 +7,7 @@
"overview",
"configuration",
"training",
"eval",
"inference",
"scaling",
"algorithms",
+8 -7
View File
@@ -110,14 +110,14 @@ For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_
### Context Parallelism
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Prefer `ulysses`: it gets the most throughput and is the only style that works for hybrid linear-attention/Mamba models (Qwen3.5, NemotronH) and for VLMs. Each model class declares its supported styles in `cp_support`; an unsupported `cp_style`, or a model with no CP support at all (DeepSeek V4, GPT-OSS), is rejected at setup.
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Prefer `ulysses`: it gets the most throughput and is the only style that works for hybrid linear-attention/Mamba models (Qwen3.5, NemotronH) and for VLMs. Each model class declares its supported styles in `cp_support`; an unsupported `cp_style`, or a model with no CP support at all, is rejected at setup.
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Hybrid Mamba layers head-shard independently (`cp_mamba`), which requires the CP degree to divide `mamba_num_heads` and `n_groups`.
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Nemotron-H redistributes its Mamba activations between sequence- and head-parallel layouts in the model-owned Mamba path; the CP degree must divide `mamba_num_heads` and `n_groups`.
```toml
[trainer.model]
impl = "custom"
attn = "auto" # auto = FA3 on Hopper, FA4 on Blackwell; or flash_attention_2/3/4
attn = "auto" # auto = FA3 on Hopper, FA4 on datacenter Blackwell, FA2 otherwise; or flash_attention_2/3/4
cp = 2 # CP degree
cp_style = "ulysses" # "ring"
```
@@ -232,8 +232,9 @@ gpus_per_node = 8
Full multi-node configs ship under [`examples/advanced/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced):
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/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.
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/configs/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`glm-5.3/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale and P/D-disaggregated inference across the GLM-5 family.
- [`glm-4.5-air/swe-2-node.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-4.5-air/swe-2-node.toml) — train a 100B+ MoE on only two nodes: a single-node sign-SGD trainer (full optimizer offload) paired with one inference replica at batch size 64. An overlay on the shared `swe-budget.toml` base — launch with `uv run rl @ swe-budget.toml @ swe-2-node.toml`.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
@@ -273,8 +274,8 @@ To benchmark a parallelism config before committing a multi-day run, run a short
# SFT trainer alone
uv run sft @ sft.toml --data.type fake --max-steps 4
# RL trainer alone (no inference involved)
uv run trainer @ train.toml --data.fake --max-steps 4
# RL trainer alone (no inference involved) -- launch it under torchrun, like the `rl` launcher does
uv run torchrun --nproc-per-node=8 src/prime_rl/trainer/rl/train.py @ train.toml --data.fake --max-steps 4
```
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `monitors/file/metrics.jsonl` under 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.
+17 -14
View File
@@ -1,6 +1,6 @@
# Training
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md).
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md). For standalone evals, see [Eval](eval.md).
> **AI agents working in this repo:** the equivalent runbooks are at [`skills/training/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/skills/training) — top-level routing in [`skills/training/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/SKILL.md), launch details in [`skills/training/start-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/start-run/SKILL.md), and check-in / restart procedures in [`skills/training/monitor-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/monitor-run/SKILL.md).
@@ -35,9 +35,9 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run rl` | Wraps the trainer, orchestrator, and inference server in one launch from a merged TOML. | The default for any RL run. Runs locally for single-node experiments; submits to SLURM for single- or multi-node when `[slurm]` is set (see [Scaling § SLURM](scaling.md#slurm)). |
| `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, and one `env-server` per source. |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at a derived loopback address); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-server` per source. |
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
## RL Trainer
@@ -118,6 +118,7 @@ Pulled from the console logs and mirrored to W&B.
- `reward/{all,env}/mean` — main signal. Should trend upward over hundreds of steps.
- `seq_len/{all,env}/mean` and `is_truncated/{all,env}/mean` — rollout length and truncation rate.
- `is_timeout/{all,env}/mean` — share of rollouts stopped by a stage deadline (`setup`/`agent`/`finalize`/`scoring` `_timeout`). Training counts a timed-out rollout as an error, so it stays out of the batch; eval scores it.
- `num_turns/{all,env}/mean` — for multi-turn envs.
- `empty_rollouts/{all,env}`, `errored_rollouts/{all,env}` — non-zero is fine in small numbers; sustained > 5% is a smell.
- `eval/{env}/{avg@k,pass@k}` — eval scores when `[orchestrator.eval]` is set.
@@ -161,6 +162,8 @@ name = "qwen3"
enable_thinking = false
```
A `reasoning_effort` column in the dataset sets the renderer's `reasoning_effort` field per row, on top of the `[renderer]` config. The column requires a typed renderer that has that field (for example `gpt-oss`, `qwen3.8`, `deepseek-v4`); rows with a null value use the configured renderer unchanged. This lets one run mix reasoning efforts, with the `[renderer]` value as the default for rows that do not set one.
If a model needs another template control, add it to that model's renderer config in `renderers` (for example a new field on the relevant `*RendererConfig`) and consume it in the renderer implementation.
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5.
@@ -201,17 +204,17 @@ num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
The launcher starts the inference server, one env server per eval source, and an online-eval process next to the trainer (it logs to `logs/attempt_<n>/eval.log`). NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the online-eval process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
#### Multi-Node Trainer and Inference Pool
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and evals process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and online-eval process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2 # trainer nodes
num_infer_nodes = 1 # inference pool + evals
num_infer_nodes = 1 # inference pool + online evals
[inference.vllm]
tensor_parallel_size = 8
@@ -220,7 +223,7 @@ tensor_parallel_size = 8
job_name = "my-run"
```
The shared script passes the trainer rank-0 hostname directly to the evals process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, evals never sees a final broadcast, so the job remains active until walltime. Trainer and evals log to one shared W&B run. The trainer creates it, and evals finalizes it.
The shared script passes the trainer rank-0 hostname directly to the online-eval process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, online-eval never sees a final broadcast, so the job remains active until walltime. Trainer and online-eval log to one shared W&B run. The trainer creates it, and online-eval finalizes it.
### SFT-Specific Knobs
@@ -249,7 +252,7 @@ Pulled from the console log and mirrored to W&B.
- `optim/grad_norm` — spikes precede divergence.
- `optim/lr` — LR schedule.
- For MoE: `max_vio/mean` (load-balancing violation), `routing_confidence/mean` — both are logged when non-zero.
- For MoE: `max_vio/mean`, `max_vio/max` — mean and max over the step's microsteps of the largest load-balancing violation across layers and EP groups, computed from expert token counts summed across each EP group. `routing_confidence/mean` — mean routing confidence.
**Performance:**
@@ -331,7 +334,7 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
├── orchestrator.log # single instance, single file
├── evals.log # SFT online-eval process
├── eval.log # `uv run eval` process, or the SFT online-eval process
├── inference.log # symlink → inference/node_0.log on multi-node
├── trainer/
│ ├── node_*.log # per-node trainer stdout (multi-node only)
@@ -347,14 +350,14 @@ Env logs are the first place to look for env-side errors (most user code lives t
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
```bash
tail -F <run_dir>/logs/latest/{trainer,orchestrator,evals,inference}.log
tail -F <run_dir>/logs/latest/{trainer,orchestrator,eval,inference}.log
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
```
### Dashboard
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with six views per run: an overview (the W&B overview sections, read from the file monitor's `metrics.jsonl`), metrics (every key in that file, one pane each, with a regex filter), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
@@ -387,9 +390,9 @@ Or set it in TOML:
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.
The monitor is a thin layer over the [`prime-runs`](https://github.com/PrimeIntellect-ai/prime/tree/main/packages/prime-runs) SDK (installed as `prime-runs[train]`): it registers the run, streams per-step metrics, uploads every 10th step's episodes (full conversations with rewards and advantages) to the run's sample viewer, and closes the run out. A process that exits without finishing is reported as crashed. Uploaded episodes are keyed to the platform run by the SDK; the orchestrator's own run id (the launcher's `PRL_RUN_ID`) stays on W&B and in the local records.
Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted team. Currently internal-only.
Requires `PRIME_API_KEY` (`prime login` or the env var) and a team (`PRIME_TEAM_ID`, or the team selected with `prime login`) enabled for external runs. A configured monitor must work: a missing key or a team outside the allowlist fails the launch. `PRIME_RUNS_MODE=disabled` keeps the monitor configured but opens no platform run; `RUN_ID=<id>` attaches to an external run a launcher already created instead of registering a new one. Currently internal-only.
## Rules of Thumb
+33 -12
View File
@@ -2,16 +2,37 @@
End-to-end usage examples for prime-rl, referenced from the top-level [README](../README.md).
- **[`basic/`](basic)** — walk-throughs for the core environments on 1–8 GPUs (baseline eval →
optional SFT warmup → RL → eval), each with its own README:
- `reverse-text` — smallest end-to-end loop (single-turn, 0.6B)
- `alphabet-sort` — multi-turn, user simulator, LoRA
- `wiki-search` — multi-turn tool calling, LoRA
- `wordle` — multi-turn (~6-turn games)
- `hendrycks-sanity` — single-turn math, long-running
- **[`advanced/`](advanced)** — larger, mostly multi-node runs on frontier models, one folder
per model: `qwen3-30b-a3b` (math/swe/tool), `glm-4.5-air` (search/swe/terminal), `glm-5.2`
(large-scale + PD-disaggregated inference), `minimax-m2.5` (swe), `nemotron-3-super` (swe),
`intellect-3.1` (swe), `deepseek-v4-flash` (sft + a standalone vLLM serving pre-flight).
New here? Follow [`basic/reverse-text/`](basic/reverse-text/README.md) first — it trains a small model end-to-end on 2 GPUs and introduces the launch → dashboard → checkpoint flow the advanced examples reuse.
Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
## advanced/ — frontier models, multi-node
Larger runs on frontier models, one folder per model, each with a launch README covering requirements, credentials, launch, monitoring, and resume:
- [`qwen3-30b-a3b/`](advanced/qwen3-30b-a3b/README.md) — `Qwen3-30B-A3B` RL on math (`i3_math`), SWE (`r2e-gym`), and agentic tool use (general-agent on Modal). 2 train + 2 infer nodes; the SWE config runs at 131k context with `ep = 8` + `cp = 2`.
- [`glm-4.5-air/`](advanced/glm-4.5-air/README.md) — `GLM-4.5-Air` (100B MoE) RL across search, SWE, and terminal domains at 131k context, with agents in sandboxes. 2 train + 4 infer nodes (SWE: 1 + 3).
- [`glm-5.3/`](advanced/glm-5.3/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
- `intellect-3.1/` — reproduce the `INTELLECT-3.1` run: 4 train + 12 infer nodes on SWE.
All advanced configs submit through SLURM (the `rl` entrypoint writes the sbatch job when the config has a `[slurm]` table) and are monitored with `uv run dashboard`. See the per-model README for the full walkthrough.
## basic/ — 1 to 8 GPUs
Walk-throughs for the core environments (baseline eval → optional SFT warmup → RL → eval), each with its own README:
- [`reverse-text/`](basic/reverse-text/README.md) — smallest end-to-end loop (single-turn, 0.6B): `eval.toml` → `sft.toml` → `rl.toml`
- [`alphabet-sort/`](basic/alphabet-sort/README.md) — multi-turn, user simulator, LoRA
- [`wiki-search/`](basic/wiki-search/README.md) — multi-turn tool calling, LoRA
- [`wordle/`](basic/wordle/README.md) — multi-turn (~6-turn games)
- [`hendrycks-sanity/`](basic/hendrycks-sanity/README.md) — single-turn math, long-running
## extra/ — beyond the core loop
Examples that don't follow the basic eval → SFT → RL walk-through pattern:
- [`dynamo/`](extra/dynamo/README.md) — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
- [`vlm/`](extra/vlm/README.md) — multimodal (VLM) SFT, dense + MoE LoRA configs
## Related config folders
- Frontier-model configs without launch walkthroughs (`minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`) live in [`configs/advanced/`](../configs/advanced).
- Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
+103
View File
@@ -0,0 +1,103 @@
# GLM-4.5-Air
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0). The SWE configs also ship budget variants: `swe-4-node.toml` (1 train + 3 infer) and `swe-2-node.toml` — train a 100B+ MoE on only two nodes. Both are thin overlays on a shared `swe-budget.toml` base: the base holds the recipe, the overlay the topology, batch size, and per-run identity.
| Config | Trains on | Evals on | Topology |
|---|---|---|---|
| [`search.toml`](search.toml) | `openseeker` + `redsearcher` (search QA, `rlm` harness + `search` skill) | `browsecomp` (500 examples) | 2 train + 4 infer nodes |
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 2 train + 4 infer nodes |
| [`swe-budget.toml`](swe-budget.toml) + [`swe-4-node.toml`](swe-4-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
| [`swe-budget.toml`](swe-budget.toml) + [`swe-2-node.toml`](swe-2-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 1 infer node |
| [`terminal.toml`](terminal.toml) | `tmax` (per-task Docker image, `rlm` ipython harness) | `swebench-verified` + `terminal-bench-2` (avg@4) | 2 train + 4 infer nodes |
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8` (plus expert parallelism on `swe.toml`). `search.toml`, `swe.toml`, and `terminal.toml` train with Muon on 2 trainer nodes. The budget variants instead fit the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer; `swe-2-node.toml` cuts the batch size to 64 (4 groups of 16) to match the throughput of its single inference replica. They don't parse standalone: compose them left-to-right over `swe-budget.toml` (`uv run rl @ swe-budget.toml @ swe-2-node.toml`). Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
## Requirements
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. Install the `prime` CLI separately and log in. Each config's `slurm.pre_run_command` then cleans up the run's orphaned sandboxes by label before launch:
```bash
uv tool install prime
prime login # or: prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend) and drop the `slurm.pre_run_command` cleanup line.
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
- `HF_TOKEN` — `zai-org/GLM-4.5-Air` is a gated model.
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
- `SERPER_API_KEY` — search envs only; forwarded into the agent sandbox for the `search` skill (`harness.forward_env`).
## Setup
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
uv sync --all-extras --all-packages
```
## Tweak before launching
- `[slurm] partition` is set to `all` — override with `--slurm.partition <your-partition>`, or edit the config.
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
## Start the run
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
```bash
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
--output-dir /shared/outputs/glm45air \
--run.name glm45air-swe
```
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. For SWE on a smaller budget, compose a budget variant over its base: `uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml` trains the 100B+ MoE on only two nodes. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
## Monitor with the dashboard
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
```bash
uv run dashboard /shared/outputs/glm45air # serves http://localhost:7788
```
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
```bash
ssh -L 7788:localhost:7788 <head-node>
```
Pick the run (`<run_name>` from the launch) and you get five views:
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
## Checkpoint, resume, export
Checkpoints land in `<run_dir>/checkpoints/step_<N>` every 50 steps (`keep_last = 1`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
```bash
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
--output-dir /shared/outputs/glm45air \
--run.name glm45air-swe \
--resume --max-steps 1000
```
Trainer checkpoints are DCP-sharded; export HF-format weights with:
```bash
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/glm45air/glm45air-swe/checkpoints/step_100
```
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
@@ -25,8 +25,6 @@ num_infer_replicas = 4
project = "search-ablations"
name = "glm45air-search"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -0,0 +1,41 @@
# Budget variant of swe.toml: train a 100B+ MoE on only two nodes (1 train + 1 infer replica) with
# the single-node sign-SGD trainer. Overlay for swe-budget.toml — this file only carries the
# deltas, so compose the two (left-to-right merge, see docs/configuration.md "TOML Composition"):
#
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml
#
# The batch size is 64 (4 groups of 16), matching the rollout throughput of the single inference
# replica. The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the
# budget variants can run side by side.
[slurm]
job_name = "glm45air-swe-2-node"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe-2-node" -y || true'
[deployment]
num_infer_replicas = 1
[monitors.wandb]
name = "glm45air-scaleswe-2-node"
[orchestrator]
batch_size = 64
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-2-node"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-2-node"]
env.agent.timeout.rollout = 3600
@@ -0,0 +1,42 @@
# Budget variant of swe.toml: the same recipe on four nodes (1 train + 3 infer replicas, the
# topology swe.toml used before the Muon switch) with the single-node sign-SGD trainer. Overlay for
# swe-budget.toml — this file only carries the deltas, so compose the two (left-to-right merge, see
# docs/configuration.md "TOML Composition"):
#
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-4-node.toml
#
# Batch size 256 (16 groups of 16) matches the rollout throughput of the three inference replicas.
# The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the budget
# variants can run side by side.
[slurm]
job_name = "glm45air-swe-4-node"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe-4-node" -y || true'
[deployment]
num_infer_replicas = 3
[monitors.wandb]
name = "glm45air-scaleswe-4-node"
[orchestrator]
batch_size = 256
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-4-node"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-4-node"]
env.agent.timeout.rollout = 3600
@@ -0,0 +1,114 @@
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Shared base of the budget variants of swe.toml
# (`swe-4-node.toml`, `swe-2-node.toml`): the pre-Muon recipe with the single-node sign-SGD
# trainer, composed as `uv run rl @ swe-budget.toml @ <variant>.toml`. Router replay is enabled
# (trainer.enable_router_replay replays the routed-expert decisions returned by inference via
# enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe model, which supports routed_experts.
#
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
#
# Inference serves the bf16 checkpoint as-is (no quantization). The trainer fits on one node via
# cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus the
# memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
# skip-gather / skip-optimizer checkpointing. Concurrency is fully default: the controller derives
# its start from the measured KV budget and adapts from there.
#
# The variant overlays on top of this base set the inference replica count and batch size, the
# per-variant SLURM job name / sandbox cleanup label / W&B run name, and the train/eval sources
# with their matching runtime labels.
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
partition = "all"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[monitors.wandb]
project = "swe-ablations"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
[resume]
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
optim_cpu_offload = false
full_offload = true
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "sign_sgd"
# --- Orchestrator ---
[orchestrator]
group_size = 16
max_off_policy_steps = 32
[orchestrator.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
# --- Inference ---
[inference]
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
enable_return_routed_experts = true
+17 -22
View File
@@ -1,17 +1,18 @@
# 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.
# runtime; eval on SWE-Bench Verified. Follows the research-prod air ablation base config
# (research-prod PR #198): 2 trainer nodes with the Muon optimizer (instead of the single-node
# sign-SGD setup), 4 one-node inference replicas serving the bf16 checkpoint with TP=8 + expert
# parallelism, batch size 256 / group size 16, and the linear length penalty with the input-token
# and turns coefficients set to 0.1. Router replay stays 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. Optimizer state is checkpointed so runs can resume.
#
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
# GRPO uses the linear length penalty. Each term is pass_rate-scaled and normalized by the
# group's own max before the GRPO baseline subtraction.
#
# 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), and
# skip-gather / skip-optimizer checkpointing.
# Two trainer nodes fit GLM-4.5-Air with Muon plus the memory improvements from the GLM-5.1 prod
# run (research-prod rlm5/prod.toml): activation checkpointing (freq=1) + activation offloading
# (max_inflight=1). LM-head token chunking (8192) and optimizer CPU offload run at their defaults.
# Concurrency is fully default: the controller derives its start from the measured KV budget and
# adapts from there.
@@ -31,16 +32,14 @@ pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y ||
[deployment]
type = "multi_node"
num_train_nodes = 1
num_train_nodes = 2
num_infer_nodes = 1
num_infer_replicas = 3
num_infer_replicas = 4
[monitors.wandb]
project = "swe-ablations"
name = "glm45air-scaleswe"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -65,9 +64,6 @@ 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]
@@ -76,11 +72,8 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "sign_sgd"
type = "muon"
# --- Orchestrator ---
@@ -130,6 +123,8 @@ VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
gpu_memory_utilization = 0.85
max_model_len = 131072
tensor_parallel_size = 8
enable_expert_parallel = true
enable_return_routed_experts = true
@@ -26,8 +26,6 @@ num_infer_replicas = 4
project = "terminal-ablations"
name = "glm45air-terminal"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
-87
View File
@@ -1,87 +0,0 @@
seq_len = 131072
[log]
level = "debug"
[monitors.wandb]
project = "glm5-pd-disag"
[weight_broadcast]
type = "nccl"
port = 29502
timeout = 12000
quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
num_train_nodes = 16
gpus_per_node = 8
num_infer_replicas = 2
[inference.deployment]
type = "disaggregated"
prefill_nodes_per_replica = 4
decode_nodes_per_replica = 4
[inference.vllm]
model = "zai-org/GLM-5-FP8"
tool_call_parser = "glm47"
gpu_memory_utilization = 0.80
enable_expert_parallel = true
enable_eplb = false
[slurm]
job_name = "glm5-pd-disag"
[ckpt]
interval = 100
[trainer]
dist_timeout_seconds = 7200
[trainer.model]
name = "zai-org/GLM-5"
impl = "custom"
attn = "flash_attention_2" # dsa is skipping flash attn anyway
fused_lm_head_token_chunk_size = 2048
ep = 8
[trainer.model.ac]
freq = 1
[trainer.model.compile]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "adamw"
lr = 1e-6
weight_decay = 0.1
[orchestrator]
batch_size = 4096
group_size = 16
max_off_policy_steps = 16
[orchestrator.concurrency]
initial_inflight = 4096
max_inflight = 8192
[orchestrator.model]
name = "zai-org/GLM-5-FP8"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm5-pd-disag", "swe-bench-verified"]
[inference]
# we need <0.85 bc glm5 layers are too large for 0.85
use_deep_gemm = true
+117
View File
@@ -0,0 +1,117 @@
# GLM-5 family at scale
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5.3-BF16` for training and serving alike, quantized to per-block FP8 online on the vLLM side — at 131k context: 16 trainer nodes on the custom MoE implementation (expert + context parallelism) and P/D-disaggregated FP8 inference. The [`swe-llmd.toml`](swe-llmd.toml) append fronts the same inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. It also offloads KV to a Mooncake distributed CPU pool (1TB per node by default).
| Config | What it runs | Topology |
|---|---|---|
| [`swe.toml`](swe.toml) | Base GLM-5.3 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), serves `GLM-5.3-BF16` with online per-block FP8 quantization behind the default `vllm-router`. | 16 train + 16 infer nodes |
| [`swe-llmd.toml`](swe-llmd.toml) | Append for `swe.toml`: swaps in the llm-d router (EPP scorer tuning) + Mooncake KV offload — launch as `rl @ swe.toml @ swe-llmd.toml`. | same |
| [`infer/pd.toml`](infer/pd.toml) | Inference-only pre-flight: P/D-disaggregated `GLM-5-FP8`. | 6 infer nodes |
| [`infer/pd-llmd.toml`](infer/pd-llmd.toml) | Inference-only pre-flight: `GLM-5.2-FP8` with llm-d + Mooncake. | 16 infer nodes |
## Requirements
- A Slurm cluster with 8-GPU nodes, a shared filesystem, and at least **32 nodes** (16 trainer + 16 inference) for the RL configs. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path. If you have fewer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` accordingly.
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d append).
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, install the `prime` CLI separately and log in:
```bash
uv tool install prime
prime login # or: prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend).
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
- `HF_TOKEN` — the GLM-5 family checkpoints are gated models.
- `WANDB_API_KEY` — both RL variants log to W&B (`[monitors.wandb]`).
### Install llm-d (llm-d append only)
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
```bash
bash scripts/install_llmd.sh
```
## Setup
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
uv sync --all-extras --all-packages
```
## Tweak before launching
- `swe.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`.
- `swe-llmd.toml` `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
- `swe-llmd.toml` `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
## Start the run
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
```bash
# GLM-5.3 RL behind the default vllm-router
uv run rl @ examples/advanced/glm-5.3/swe.toml
# with the llm-d router + Mooncake KV offload appended
uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
```
The inference configs are standalone pre-flights: they serve the FP8 checkpoint through the same entrypoint the trainer uses (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster` included — never call `vllm serve` directly), and are a fast way to check that this cluster can serve the model at all before committing it to a run:
```bash
uv run inference @ examples/advanced/glm-5.3/infer/pd.toml
uv run inference @ examples/advanced/glm-5.3/infer/pd-llmd.toml
```
## Monitor with the dashboard
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
```bash
uv run dashboard /shared/outputs # serves http://localhost:7788
```
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
```bash
ssh -L 7788:localhost:7788 <head-node>
```
Pick the run and you get five views:
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
## Checkpoint and resume
Both RL configs ship without `[ckpt]` — add a `[ckpt]` overlay (e.g. `interval = 100`) for periodic checkpoints. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
See [Scaling](../../../docs/scaling.md) for SLURM details and [Inference](../../../docs/inference.md) for the disaggregated-inference and router reference.
## SFT
The SFT configs live under [`sft/h200/`](sft/h200) — they are tuned for 8-GPU H200 nodes. Compose the base config with a data overlay:
```bash
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml
```
This will start a SFT run with the following configuration:
- The model is `zai-org/GLM-5.3-BF16`
- The data is `PrimeIntellect/INTELLECT-3-SFT-10K` (math split)
For a fake-data dry run, append [`fake.toml`](sft/h200/fake.toml) instead. You can use the same dashboard to monitor the SFT run.
@@ -2,7 +2,7 @@
# Step 3 / goal target. Topology mirrors the proven original glm5.1_llmd_inference
# (job 348 succeeded): 8 prefill nodes (4 replicas x 2) + 8 decode nodes (1 replica).
#
# Launch: uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
# Launch: uv run inference @ examples/advanced/glm-5.3/infer/pd-llmd.toml
output_dir = "/shared/outputs/glm5.2-16node-llmd"
@@ -60,5 +60,4 @@ reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
@@ -0,0 +1,40 @@
clean = true
[env_vars]
HF_HOME = "/home/huggingface"
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "zai-org/GLM-5.3-BF16"
impl = "custom"
attn = "flash_attention_2"
cp = 8
ep = 8
optim_cpu_offload = true
[model.ac]
freq = 1
[model.ac_offloading]
max_inflight_activations = 5
[optim]
type = "sign_sgd"
lr = 5e-5
weight_decay = 0.01
[scheduler]
type = "linear"
warmup_steps = 50
decay_steps = 0
[renderer]
name = "glm-5.3"
[deployment]
type = "multi_node"
num_train_nodes = 8
[slurm]
job_name = "glm53-sft"
partition = "all"
@@ -0,0 +1,8 @@
[model.debug]
force_balanced_routing = true
[data]
type = "fake"
batch_size = 8
micro_batch_size = 1
seq_len = 131072
@@ -0,0 +1,7 @@
[data]
type = "sft"
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
splits = ["math"]
batch_size = 8
micro_batch_size = 1
seq_len = 131072
+47
View File
@@ -0,0 +1,47 @@
# llm-d append for swe.toml: fronts the P/D-disaggregated inference plane with
# the llm-d router (Endpoint Picker + Envoy) and offloads KV to a Mooncake
# distributed CPU pool. Everything else is inherited from the base config:
#
# uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
[run]
name = "glm5-llmd"
[monitors.wandb]
project = "glm5-llmd"
[slurm]
job_name = "glm5-llmd"
# Overlays replace arrays of tables wholesale, so the train source is spelled
# out again just to swap the sandbox runtime label.
[[orchestrator.train.source]]
name = "r2e"
env.taskset.id = "r2e-gym"
env.agent.harness.id = "rlm"
env.agent.runtime.labels = ["glm5-llmd"]
[inference.router]
type = "llm-d"
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
@@ -1,23 +1,29 @@
# Base GLM-5.3 RL config: P/D-disaggregated FP8 inference behind the default
# vllm-router. Serves the same GLM-5.3-BF16 checkpoint the trainer broadcasts,
# quantized to per-block FP8 online on the vLLM side. Append swe-llmd.toml to
# front the same plane with the llm-d router + Mooncake KV offload:
#
# uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
max_steps = 10000000
seq_len = 131072
output_dir = "/shared/outputs" # FILL IN: point at your shared filesystem
clean = true
[run]
name = "glm5-llmd"
name = "glm5"
[log]
level = "debug"
[monitors.wandb]
project = "glm5-llmd"
project = "glm5"
name = "base"
[weight_broadcast]
type = "nccl"
port = 29502
timeout = 12000
quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
@@ -52,41 +58,30 @@ num_decode_replicas = 1
"max_num_seqs" = 96
[inference.router]
type = "llm-d"
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
type = "vllm-router"
[inference.vllm]
model = "zai-org/GLM-5.1-FP8"
# Serve the same GLM-5.3-BF16 checkpoint the trainer broadcasts; vLLM quantizes
# it to per-block FP8 online.
model = "zai-org/GLM-5.3-BF16"
dtype = "bfloat16"
quantization = "fp8_per_block"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[slurm]
job_name = "glm5-llmd"
job_name = "glm5"
partition = "all" # FILL IN: set to your cluster's partition
[trainer]
dist_timeout_seconds = 1800
[trainer.model]
name = "zai-org/GLM-5.1"
name = "zai-org/GLM-5.3-BF16"
impl = "custom"
attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
@@ -122,10 +117,10 @@ initial_inflight = 256
max_inflight = 512
[orchestrator.model]
name = "zai-org/GLM-5.1-FP8"
name = "zai-org/GLM-5.3-BF16"
[orchestrator.renderer]
name = "glm-5.1"
name = "glm-5.3"
clear_thinking = false
[orchestrator.train.sampling]
@@ -138,17 +133,9 @@ clear_thinking = false
name = "r2e"
env.taskset.id = "r2e-gym"
env.agent.harness.id = "rlm"
env.agent.runtime.labels = ["glm5-llmd"]
env.agent.runtime.labels = ["glm5"]
[inference]
# <0.80 because glm5 layers are too large for 0.85
use_deep_gemm = true
enable_fp32_lm_head = true
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
+1
View File
@@ -45,6 +45,7 @@ weight_decay = 0.01
[orchestrator]
batch_size = 2048
group_size = 8
[orchestrator.concurrency]
initial_inflight = 4096
+107
View File
@@ -0,0 +1,107 @@
# Qwen3-30B-A3B
RL on the 30B-A3B MoE across three domains: math, SWE, and agentic tool use. The Thinking checkpoint trains math and SWE; the tool config trains the Instruct checkpoint with colocated tools on [Modal](https://modal.com). All configs use the custom MoE trainer implementation with expert parallelism (`ep = 8`), the AdamW optimizer, NCCL weight broadcast, and W&B logging. `swe.toml` adds `cp = 2` context parallelism for its 131k context; the other two run at 32k.
| Config | Trains on | Evals on | Runtime | Topology |
|---|---|---|---|---|
| [`math.toml`](math.toml) | `i3_math` | `aime2025` (every 25 steps) | `subprocess` — runs locally, no sandbox | 2 train + 2 infer nodes |
| [`swe.toml`](swe.toml) | `r2e-gym` (`bash` harness) | `swebench-verified` (every 25 steps) | sandbox (Prime Intellect by default) | 2 train + 2 infer nodes |
| [`tool.toml`](tool.toml) | `general-agent` (colocated tools) | — | `modal` | 1 train + 1 infer node |
`tool.toml` is the odd one out: 400 steps, `group_size = 16`, checkpoints every 50 steps with `keep_last = 1`, and inference at `dp = 2` / `tp = 4`. `math.toml` and `swe.toml` run 512-task batches with checkpoints every 100 steps.
## Requirements
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
- **Sandboxes** (`swe.toml` only) — the SWE agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, install the `prime` CLI separately and log in:
```bash
uv tool install prime
prime login # or: prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on the source for a runtime your environments support (e.g. a local Docker backend).
- **Modal** (`tool.toml` only) — the tool agents run on Modal (`env.agent.runtime.type = "modal"`). Authenticate once:
```bash
uv run modal setup # or export MODAL_TOKEN_ID / MODAL_TOKEN_SECRET
```
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
- `HF_TOKEN` — optional; the Qwen checkpoints are public, but a token avoids rate limits.
`math.toml` needs none of the above beyond W&B: its agents run as local subprocesses on the env server.
## Setup
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
uv sync --all-extras --all-packages
```
## Tweak before launching
- None of the configs set a `[slurm] partition` — sbatch picks your cluster default. Override with `--slurm.partition <your-partition>`.
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
## Start the run
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
```bash
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
--output-dir /shared/outputs/qwen30b \
--run.name qwen30b-math
```
Swap `math.toml` for `swe.toml` or `tool.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
## Monitor with the dashboard
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
```bash
uv run dashboard /shared/outputs/qwen30b # serves http://localhost:7788
```
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
```bash
ssh -L 7788:localhost:7788 <head-node>
```
Pick the run and you get five views:
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
## Checkpoint, resume, export
Checkpoints land in `<run_dir>/checkpoints/step_<N>` — every 100 steps for `math.toml`/`swe.toml`, every 50 steps (`keep_last = 1`) for `tool.toml`. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
```bash
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
--output-dir /shared/outputs/qwen30b \
--run.name qwen30b-math \
--resume --max-steps 1000
```
Trainer checkpoints are DCP-sharded; export HF-format weights with:
```bash
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/qwen30b/qwen30b-math/checkpoints/step_100
```
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
@@ -42,6 +42,7 @@ lr = 1e-6
[orchestrator]
batch_size = 512
group_size = 8
max_off_policy_steps = 8
[orchestrator.concurrency]
+1
View File
@@ -43,6 +43,7 @@ lr = 1e-6
[orchestrator]
batch_size = 512
group_size = 8
max_off_policy_steps = 16
[orchestrator.concurrency]
+2 -16
View File
@@ -39,14 +39,7 @@ uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507
Evaluate the base model:
```bash
# Run this in the other terminal
uv run eval alphabet-sort --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
-n 20 \
-r 3 \
--sampling.max-tokens 768 \
--args '{"min_turns": 3, "max_turns": 3, "min_names_per_turn": 1, "max_names_per_turn": 4, "task": {"similarity_power": 8, "power_per_turn": false}}' \
--no-push
uv run eval @ examples/basic/alphabet-sort/eval.toml
```
We got an **average reward of ~0.26** across 20×3 rollouts. The model achieves **0% perfect attempts** (no rollouts score 1.0) and **0% perfect examples** (no examples have all 3 rollouts at 1.0). The model shows high variance and struggles on most examples, with the high similarity power (8) heavily penalizing even small errors, and the scores aren't different for most attempts.
@@ -113,14 +106,7 @@ uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruc
```bash
# Run this in the other terminal
uv run eval alphabet-sort --harness.id null \
-m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL \
--client.base-url http://localhost:8000/v1 \
-n 20 \
-r 3 \
--sampling.max-tokens 768 \
--args '{"min_turns": 3, "max_turns": 3, "min_names_per_turn": 1, "max_names_per_turn": 4, "task": {"similarity_power": 8, "power_per_turn": false}}' \
--no-push
uv run eval @ examples/basic/alphabet-sort/eval.toml -m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
```
Way better! Our model now gets an **average reward of ~0.81** with **73% perfect attempts** (44/60 rollouts score 1.0) and **65% perfect examples** (13/20 examples have all 3 rollouts at 1.0).
+24
View File
@@ -0,0 +1,24 @@
# Evaluate a model on alphabet-sort against a local inference server
# (`uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507`).
# Override the model with `-m` to evaluate a trained checkpoint.
#
# uv run eval @ examples/basic/alphabet-sort/eval.toml
model = "Qwen/Qwen3-4B-Instruct-2507"
num_examples = 20
group_size = 3
[client]
base_url = "http://localhost:8000/v1"
[sampling]
max_completion_tokens = 768
[[source]]
name = "alphabet-sort"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+4 -5
View File
@@ -27,7 +27,7 @@ uv run inference --vllm.model Qwen/Qwen3-0.6B
```bash
# Run this in the other terminal
uv run eval reverse-text --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval @ examples/basic/reverse-text/eval.toml
```
This is of course just a quick vibe check and no full-fledged evaluation, but we can see that the model struggles with this task. In this specific instance, we got an **average reward of ~0.05** across the 20x3 rollouts. Let's do some training!
@@ -94,7 +94,7 @@ uv run inference --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
```bash
# Run this in the other terminal
uv run eval reverse-text --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval @ examples/basic/reverse-text/eval.toml -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
```
Way better! Now we get an **average reward of ~0.8**.
@@ -197,10 +197,9 @@ kubectl exec -it my-exp-inference-0 -- bash
uv run inference --vllm.model /data/outputs/weights_hf/step_20
# Back in trainer pod, run evaluation
uv run eval reverse-text --harness.id null \
uv run eval @ examples/basic/reverse-text/eval.toml \
-m /data/outputs/weights_hf/step_20 \
--client.base-url $INFERENCE_URL \
-n 20 -r 3 --sampling.max-tokens 1024 --no-push
--client.base-url $INFERENCE_URL
```
### Clean Up
+21
View File
@@ -0,0 +1,21 @@
# Evaluate a model on reverse-text against a local inference server
# (`uv run inference --vllm.model Qwen/Qwen3-0.6B`). Override the model
# with `-m` to evaluate a trained checkpoint.
#
# uv run eval @ examples/basic/reverse-text/eval.toml
model = "Qwen/Qwen3-0.6B"
num_examples = 20
group_size = 3
[client]
base_url = "http://localhost:8000/v1"
[sampling]
max_completion_tokens = 1024
[[source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+2 -14
View File
@@ -77,13 +77,7 @@ Evaluate the base model:
```bash
# Run this in the other terminal
uv run eval wiki-search --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
-n 20 \
-r 3 \
--sampling.max-tokens 512 \
--no-push
uv run eval @ examples/basic/wiki-search/eval.toml
```
## RL Training
@@ -116,13 +110,7 @@ uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSe
```bash
# Run this in the other terminal
uv run eval wiki-search --harness.id null \
-m <user>/Qwen3-4B-Instruct-WikiSearch-RL \
--client.base-url http://localhost:8000/v1 \
-n 20 \
-r 3 \
--sampling.max-tokens 512 \
--no-push
uv run eval @ examples/basic/wiki-search/eval.toml -m <user>/Qwen3-4B-Instruct-WikiSearch-RL
```
## Taskset Configuration
+21
View File
@@ -0,0 +1,21 @@
# Evaluate a model on wiki-search against a local inference server
# (`uv run inference --vllm.model Qwen/Qwen3-4B-Instruct-2507 --vllm.tool-call-parser hermes`).
# Override the model with `-m` to evaluate a trained checkpoint.
#
# uv run eval @ examples/basic/wiki-search/eval.toml
model = "Qwen/Qwen3-4B-Instruct-2507"
num_examples = 20
group_size = 3
[client]
base_url = "http://localhost:8000/v1"
[sampling]
max_completion_tokens = 512
[[source]]
name = "wiki-search"
env.taskset.id = "wiki-search"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+2 -2
View File
@@ -29,7 +29,7 @@ Then, use the `eval` entrypoint to evaluate the model in the `wordle` environmen
```bash
# Run this in the other terminal
uv run eval wordle --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval @ examples/basic/wordle/eval.toml
```
We got an **average reward of ~0.2** across the 20x3 rollouts. From the summary, we can see that the most of the reward is coming from format and partial rewards. In fact, the model does not guess the correct word within any game, leading to a win rate of **0%**. Looking at some samples, it is evident repeatedly submitting guesses in the wrong format and is not able to revise its strategy from the environment feedback. Let's do some SFT warmup to get the model to learn the format of the environment.
@@ -97,7 +97,7 @@ uv run inference --vllm.model PrimeIntellect/Qwen3-1.7B-Wordle-RL
```bash
# Run this in the other terminal
uv run eval wordle --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval @ examples/basic/wordle/eval.toml -m PrimeIntellect/Qwen3-1.7B-Wordle-RL
```
Way better! Our model now wins **~60%** and gets an average reward of **~1.5**.
+21
View File
@@ -0,0 +1,21 @@
# Evaluate a model on wordle against a local inference server
# (`uv run inference --vllm.model Qwen/Qwen3-1.7B`). Override the model
# with `-m` to evaluate a trained checkpoint.
#
# uv run eval @ examples/basic/wordle/eval.toml
model = "Qwen/Qwen3-1.7B"
num_examples = 20
group_size = 3
[client]
base_url = "http://localhost:8000/v1"
[sampling]
max_completion_tokens = 1024
[[source]]
name = "wordle"
env.taskset.id = "wordle"
env.player.harness.id = "null"
env.player.runtime.type = "subprocess"
-32
View File
@@ -1,32 +0,0 @@
# Standalone SWE evals: SWE-bench Verified + Terminal-Bench 2, one epoch each,
# against DeepSeek V4 Flash on Prime Inference.
#
# export PRIME_API_KEY=<your Prime Inference key>
# uv run evals @ 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
+73
View File
@@ -0,0 +1,73 @@
# Dynamo RL
This example runs five steps of GRPO training on the Hendrycks math environment with `Qwen/Qwen3-0.6B`, one trainer GPU, one external Dynamo inference worker, and NCCL weight transfer.
Prime-RL does not launch Dynamo from this configuration. Run the frontend, worker, and trainer as separate processes. This example requires two GPUs: GPU 0 for Prime-RL training and GPU 1 for Dynamo inference.
## Start Dynamo
Install Dynamo with its vLLM backend and activate its environment. Then start the RL-enabled frontend in the first terminal:
```bash
DYN_HTTP_HOST=127.0.0.1 DYN_ENABLE_RL=true DYN_RL_PORT=8001 python -m dynamo.frontend
```
Start the RL-enabled vLLM worker on GPU 1 in a second terminal:
```bash
CUDA_VISIBLE_DEVICES=1 DYN_SYSTEM_HOST=127.0.0.1 DYN_SYSTEM_PORT=8081 python -m dynamo.vllm \
--model Qwen/Qwen3-0.6B \
--enable-rl
```
The `--enable-rl` flag enables worker discovery and the administration routes used for NCCL weight updates. Keep GPU 0 out of `CUDA_VISIBLE_DEVICES` for this process so it remains available to the Prime-RL trainer.
These commands bind the HTTP, discovery, and worker administration endpoints to loopback. If Prime-RL and Dynamo run on different hosts, expose these endpoints only on a trusted control network; configured client headers are also sent to the discovery endpoint.
## Endpoint contract
The default configuration expects:
- The Dynamo OpenAI-compatible frontend at `http://127.0.0.1:8000/v1`.
- The Dynamo RL discovery endpoint at `http://127.0.0.1:8001/v1/rl/workers`.
- Exactly one discovered worker for `Qwen/Qwen3-0.6B` with an admin URL and `world_size = 1`.
- A vLLM worker with the Prime-RL NCCL weight-update extension enabled.
Verify both endpoints before starting training:
```bash
curl --fail http://127.0.0.1:8000/v1/models
curl --fail http://127.0.0.1:8001/v1/rl/workers
```
## Discovery URL
The example enables Dynamo with:
```toml
[orchestrator.model.client]
base_url = "http://127.0.0.1:8000/v1"
[orchestrator.model.client.dynamo]
enabled = true
```
When `discovery_url` is omitted, Prime-RL removes the path from `base_url` and increments its explicit non-default port by one. Here, `http://127.0.0.1:8000/v1` becomes `http://127.0.0.1:8001`.
If your Dynamo frontend and discovery service do not use adjacent ports, configure the discovery endpoint explicitly:
```toml
[orchestrator.model.client.dynamo]
enabled = true
discovery_url = "http://dynamo.example:9000"
```
## Run training
After both endpoint checks pass, run Prime-RL from the repository in a third terminal. With no managed `[inference]` section, Prime-RL assigns GPU 0 to its single trainer process and leaves the external Dynamo worker on GPU 1:
```bash
uv run rl @ examples/extra/dynamo/rl.toml
```
The example stops after five optimizer steps. Outputs are written under `outputs/` unless `output_dir` is overridden.
+40
View File
@@ -0,0 +1,40 @@
max_steps = 5
seq_len = 2048
[model]
name = "Qwen/Qwen3-0.6B"
[weight_broadcast]
type = "nccl"
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[orchestrator]
batch_size = 32
group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 1024
[[orchestrator.train.source]]
name = "hendrycks-math"
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.optim]
lr = 3e-6
[orchestrator.model.client]
base_url = "http://127.0.0.1:8000/v1"
[orchestrator.model.client.dynamo]
enabled = true
[orchestrator.renderer]
name = "qwen3"
enable_thinking = false
+22
View File
@@ -0,0 +1,22 @@
# VLM SFT
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training requires a custom PrimeRL implementation (`impl = "custom"`, `[model.vlm]` set — see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
| Config | Model | Hardware |
|---|---|---|
| [`sft.toml`](sft.toml) | `Qwen/Qwen3.5-0.8B` (dense, LoRA rank 16) | tiny — sanity-scale (20 steps) |
| [`sft-moe.toml`](sft-moe.toml) | `Qwen/Qwen3.6-35B-A3B` (MoE, LoRA rank 32, `ep = 8`) | one 8-GPU node (`num_train_gpus = 8`) |
## Run it
Point `data.name` at your multimodal chat dataset (HF dataset with a `messages` column — see [Training § Dataset Format](../../../docs/training.md#dataset-format)), then:
```bash
uv run sft @ examples/extra/vlm/sft.toml
```
Notes:
- The MoE config declares `[deployment]` with `num_train_gpus = 8`; keep its `ep` in sync with the GPU count.
- `micro_batch_size = 1` is required for VLM SFT — do not raise it.
- Checkpoints land in `<run_dir>/checkpoints/step_<N>`; export HF-format weights with `tools/convert_dcp_to_bf16.py` (see [Training](../../../docs/training.md)).
@@ -34,10 +34,7 @@ micro_batch_size = 1 # required for VLM SFT
seq_len = 16384
[data.loss_mask]
system = false
user = false
assistant = true
tool = false
assistant = true # only assistant turns contribute to the loss; system/user/tool default to false
[optim]
lr = 1e-5
@@ -29,5 +29,8 @@ batch_size = 1
micro_batch_size = 1
seq_len = 16384
[data.loss_mask]
assistant = true # only assistant turns contribute to the loss; system/user/tool default to false
[optim]
lr = 1e-5
+1 -1
View File
@@ -10,7 +10,7 @@ dependencies = [
"renderers>=0.1.11",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.3.0",
"verifiers>=0.3.2.dev143",
]
[build-system]
@@ -1,7 +1,8 @@
"""Algorithm abstraction: sampling and the per-token training signal.
An algorithm is a named, self-contained config — a discriminated union keyed
on ``type`` (``grpo``, ``max_rl``, ``opd``, ``opsd``, ``sft``, ``echo``).
on ``type`` (``grpo``, ``max_rl``, ``rae``, ``hierarchical_grpo``, ``opd``,
``opsd``, ``sft``, ``echo``, ``debug``).
The bundle *is* the algorithm: each variant carries
its sampling component and its credit-assignment / loss-routing parameters,
and its class defaults are the vetted setting — ``type = "opd"`` with a
@@ -364,6 +365,32 @@ class SFTAlgoConfig(BaseAlgoConfig):
return self
class DebugAlgoConfig(BaseAlgoConfig):
type: Literal["debug"] = "debug"
"""Debugging algorithm for infra work: every sampled token of every clean
trainable trace gets the same constant ``advantage`` (default 1.0),
ignoring rewards entirely. Every admitted rollout is trainable and every
action token carries gradient signal, so the full RL path (advantage
transport, importance ratios, trust region, optimizer, weight update)
can be exercised regardless of the reward function. Not a real training
signal — a policy pushed by it drifts monotonically."""
action_loss_type: ClassVar[ActionLossType] = "rl"
advantage: float = Field(1.0, allow_inf_nan=False)
"""The constant per-token advantage. Must be nonzero: a zero advantage
makes nothing trainable, the exact failure this debug tool exists to
rule out."""
@model_validator(mode="after")
def require_nonzero_advantage(self):
if self.advantage == 0.0:
raise ValueError(
"the 'debug' algorithm needs a nonzero advantage — a zero advantage leaves nothing trainable."
)
return self
AlgoConfig: TypeAlias = Annotated[
GRPOAlgoConfig
| EchoAlgoConfig
@@ -372,7 +399,8 @@ AlgoConfig: TypeAlias = Annotated[
| HierarchicalGRPOAlgoConfig
| OPDAlgoConfig
| OPSDAlgoConfig
| SFTAlgoConfig,
| SFTAlgoConfig
| DebugAlgoConfig,
Field(discriminator="type"),
]
"""The training algorithm: sampling plus the per-token training signal (credit
@@ -387,6 +415,8 @@ its class defaults are the vetted setting.
- ``opsd`` — SDFT: policy samples, demo-conditioned reverse KL against the live policy (the teacher is the policy itself).
- ``sft`` — a frozen model samples, the policy trains with CE on its tokens. Needs a frozen ``sampling.source``.
- ``echo`` — GRPO on action tokens + weighted CE on tool-response observation tokens.
- ``debug`` — the same constant advantage on every sampled token, ignoring
rewards. Debugging only: for infra work that needs every token trainable.
A new credit-assignment scheme is a new named algorithm in code (subclass
``Algorithm``, register it), not a config that points at an import path.
@@ -9,8 +9,8 @@ from prime_rl.utils.config import BaseConfig, default_output_dir
class EnvServerConfig(BaseConfig):
"""``uv run env-server``: what to serve (``[env]``) and how it's hosted (``[serve]``).
The ``rl`` launcher writes one of these per train/eval source, with ``serve.address``
set to the source's derived address."""
The launchers write one of these per train/eval source they manage, with
``address_file`` set: the server binds an OS-assigned port and publishes it there."""
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
"""The environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
@@ -18,6 +18,11 @@ class EnvServerConfig(BaseConfig):
serve: vf.ServeConfig = vf.ServeConfig()
"""How it's served: the worker pool, the bind address, each worker's episode bound."""
address_file: Path | None = None
"""Publish the bound address to this file once serving. Set by the launchers for the
servers they spawn, so the address never has to be agreed on up front (``serve.address``
unset binds an OS-assigned port)."""
log: LogConfig = LogConfig()
output_dir: Path = Field(default_factory=default_output_dir)
@@ -0,0 +1,167 @@
import uuid
from pathlib import Path
from pydantic import AliasChoices, Field, model_validator
from prime_rl.configs.monitors import EvalMonitorsConfig, MonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.utils.config import default_output_dir
class ServedEvalConfig(EvalSourcesConfig):
"""Eval sources run against a live inference server: the server's client and the
adaptive concurrency band."""
client: ClientConfig = ClientConfig()
"""Client of the inference server evals run against."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight episode concurrency, sized by the same controller as
``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on episode dispatch, in tasks per minute. Use it for
sandbox-backed environments to pace provisioning during autoscaling. None disables
rate limiting."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat for the run: one ping per landed episode — the first
landed episode is the first beat, so the run's boot never shows up as a
stale-prone silence. When episodes stop landing, the pings stop and the heartbeat
goes stale on Better Stack after its grace period. Size that period + grace above
the longest legitimate gap between episodes."""
@property
def env_addresses(self) -> dict[tuple[str, str], str | None]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: an explicit ``serve.address``
is an externally managed server; None means the launcher spawns the server and the
eval learns its address from the file it publishes."""
return {("eval", source.resolved_name): source.serve.address for source in self.source}
PRIME_INFERENCE_URL = "https://api.pinference.ai/api/v1"
class EvalConfig(ServedEvalConfig):
"""``uv run eval``: evaluate the configured sources once against a live inference
server, then exit. Every source's env server is spawned by the eval process unless
the source sets ``serve.address``. Defaults to Prime Inference (``PRIME_API_KEY`` or
``prime login``) with the concurrency pinned at 128."""
model: str = Field("deepseek/deepseek-v4.1-flash", validation_alias=AliasChoices("model", "m"))
"""Model id — the ``model`` field of every eval request and the startup model check."""
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
"""Client of the inference server. Defaults to Prime Inference."""
concurrency: ConcurrencyConfig = ConcurrencyConfig(min_inflight=128, max_inflight=128)
"""In-flight episodes, pinned at 128 (``-c N`` repins). External APIs expose no vLLM
``/metrics`` to adapt to; against a vLLM server set ``min_inflight < max_inflight`` to
let the band adapt to KV usage like the orchestrator's."""
num_examples: int = Field(-1, validation_alias=AliasChoices("num_examples", "n"))
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "r"))
"""Default rollouts per example. Can be overridden per env."""
run: RunConfig = Field(default_factory=RunConfig)
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory that groups related runs. Each run writes its artifacts (traces, logs,
checkpoints) to ``output_dir / run.name``. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
clean: bool = False
"""Delete the run directory (``output_dir / run.name``) before starting. Required to
overwrite a run directory that contains artifacts from a previous run when not resuming."""
dry_run: bool = False
"""Resolve and write the config, then exit without evaluating."""
dashboard: bool = True
"""Start (or reuse) the local dashboard daemon and print its URL."""
resume: bool = False
"""Continue the interrupted run named by ``run.name`` from its trace stream: the
landed episodes rejoin the epoch and only the rollouts still owed run. The model,
sampling and env config must match the interrupted run; ``num_examples`` and
``group_size`` may change."""
log: LogConfig = LogConfig()
monitors: EvalMonitorsConfig = EvalMonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
@property
def run_dir(self) -> Path:
assert self.run.dir is not None # resolved at construction
return self.output_dir / self.run.dir
@model_validator(mode="after")
def auto_setup_run_identity(self):
"""Auto-generate the run name (``<envs>--<model>--<short-id>``) when unset and
default the run directory, W&B run name and platform evaluation name to it."""
if self.run.name is None:
envs = "+".join(dict.fromkeys(source.resolved_name for source in self.source))
model = self.model.split("/")[-1]
self.run.name = f"{envs}--{model}--{uuid.uuid4().hex[:8]}".lower()
if self.run.dir is None:
self.run.dir = self.run.name
if self.monitors.wandb is not None and self.monitors.wandb.name is None:
self.monitors.wandb.name = self.run.name
if self.monitors.prime is not None and self.monitors.prime.name is None:
self.monitors.prime.name = self.run.name
return self
class SFTOnlineEvalConfig(ScheduledEvalConfig, ServedEvalConfig):
"""The ``[eval]`` block of the ``sft`` entrypoint, and the config of the online-eval
process the launcher spawns from it: interval-driven eval sources against the inference
server that receives the trainer's weight broadcasts. The process watches the
broadcasts directory, moves the inference server onto each broadcast, and runs the
due sources against the updated weights. The launcher fills the run-level fields
(``model``, ``weight_broadcast``, ``broadcasts_dir``, ``max_steps``, ``resume_step``,
``output_dir``, ``log``, ``monitors``) from the resolved SFT config."""
cancel_on_new_checkpoint: bool = True
"""Cancel unfinished episodes when a newer trainer checkpoint is ready. Disable to
finish every triggered eval epoch before loading later weights. The trainer can idle
while it waits for slow evals."""
model: str | None = None
"""Name the inference server serves the model under. The name stays fixed across
weight updates (weights are swapped in place), so per-step results are told apart by
``eval/{env}/policy_version``."""
weight_broadcast: WeightBroadcastConfig | None = None
"""Weight transport. None reloads weights from the filesystem broadcasts."""
broadcasts_dir: Path | None = None
"""Directory to watch for ``step_{n}`` weight broadcasts. Defaults to
``<output_dir>/broadcasts``."""
max_steps: int | None = None
"""Trainer step at which the run ends. The final checkpoint always fires every eval
env, and the process exits after processing it. If None, runs until terminated."""
resume_step: int | None = None
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
skipped; set ``retrigger_on_resume`` to re-fire interval-aligned evals at this step."""
output_dir: Path = Field(default_factory=default_output_dir)
"""The run directory, shared with the trainer. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
@model_validator(mode="after")
def auto_setup_broadcasts_dir(self):
if self.broadcasts_dir is None:
self.broadcasts_dir = self.output_dir / "broadcasts"
return self
@@ -1,141 +0,0 @@
from pathlib import Path
from pydantic import Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig, ResumeConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.utils.config import BaseConfig, default_output_dir
class EvalsEvalConfig(EvalConfig):
"""Evals against a live inference server. Extends the orchestrator ``EvalConfig``
(sources, sampling, intervals) with the client of the inference deployment and
evals-side knobs."""
client: ClientConfig = ClientConfig()
"""Client of the inference server evals run against. Auto-wired from the
``[inference]`` block when the launcher manages the server."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the eval source at position ``i`` is
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
keep it instead, without shifting the other sources' ports."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
cancel_on_new_checkpoint: bool = True
"""For online evals, cancel unfinished episodes when a newer trainer checkpoint is ready.
Disable to finish every triggered eval epoch before loading later weights. The trainer can
idle while it waits for slow evals."""
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: sources with an explicit
``serve.address`` are externally managed; the evals process spawns an env server at
the derived address for every other source."""
return {
("eval", source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, source in enumerate(self.source)
}
class OnlineConfig(BaseConfig):
"""Broadcast-driven online evals: watch a broadcasts directory for new weight
broadcasts and evaluate each eligible one. Without this block the evals process runs
every eval source once against the weights the inference server currently serves,
then exits."""
broadcasts_dir: Path | None = None
"""Directory to watch for ``step_{n}`` weight broadcasts. Defaults to
``<output_dir>/broadcasts``."""
max_steps: int | None = None
"""Trainer step at which the run ends. The final checkpoint always fires every
eval env, and the evals process exits after processing it. If None, the evals process
runs until terminated."""
resume_step: int | None = None
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
this step."""
class CheckpointConfig(BaseConfig):
"""Checkpoint progress for an interruptible standalone eval run."""
interval: int = Field(1, ge=1)
"""Save after the task cursor advances by N completed groups."""
class EvalsConfig(BaseConfig):
"""``uv run evals``: run the configured evals against a live inference server.
Standalone (no ``[online]``), one epoch of every eval source runs against the
served weights and the evals process exits. With ``[online]``, the evals process watches a
broadcasts directory for new weight broadcasts, updates the inference server through
the configured transport, and runs the configured evals against the updated weights.
The ``sft`` launcher writes this config; filesystem mode also works standalone against
any trainer that writes ``broadcasts/step_{n}`` directories with ``STABLE`` markers."""
model: str = "Qwen/Qwen3-0.6B"
"""Name the inference server serves the model under — the ``model`` field of every
eval request and the startup model check. Auto-filled from ``model.name`` by the
``sft`` launcher; the name stays fixed across weight updates (weights are
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
eval: EvalsEvalConfig
"""Eval sources, sampling, intervals, concurrency, and the inference client."""
online: OnlineConfig | None = None
"""Checkpoint watching (``[online]``). None runs the evals once and exits."""
weight_broadcast: WeightBroadcastConfig | None = None
"""Weight transport for online evals. The ``sft`` launcher fills this from its
resolved trainer transport. None uses filesystem reloads."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer for online evals. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
ckpt: CheckpointConfig | None = None
"""Checkpoint standalone eval progress. Checkpoint steps are task cursor positions."""
resume: ResumeConfig | None = None
"""Resume a standalone eval run from a cursor checkpoint. A bare block loads the latest checkpoint."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
@model_validator(mode="after")
def auto_setup_broadcasts_dir(self):
if self.online is not None and self.online.broadcasts_dir is None:
self.online.broadcasts_dir = self.output_dir / "broadcasts"
return self
@model_validator(mode="after")
def validate_skip_first_step_is_online_only(self):
"""``skip_first_step`` gates the base-model eval between checkpoints; a
standalone run has only that one epoch, so skipping it would exit
successfully without evaluating anything."""
if self.online is None and self.eval.skip_first_step:
raise ValueError(
"eval.skip_first_step only applies to online evals - a standalone run "
"would skip its only eval epoch. Remove it or add an [online] block."
)
return self
@model_validator(mode="after")
def validate_checkpointing_is_standalone_only(self):
if self.online is not None and (self.ckpt is not None or self.resume is not None):
raise ValueError(
"evals ckpt/resume only supports standalone evals - online evals are coordinated "
"with the trainer's live weight-broadcast lifecycle"
)
return self
@@ -38,6 +38,8 @@ All2AllBackend = Literal[
"flashinfer_nvlink_two_sided",
]
QuantizationType = Literal["fp8_per_block"]
class VllmConfig(BaseConfig):
"""Arguments forwarded to the vLLM server, under vLLM's own argument names
@@ -105,7 +107,7 @@ class VllmConfig(BaseConfig):
enable_prefix_caching: bool | None = None
"""Enable prefix caching."""
quantization: str | None = None
quantization: QuantizationType | None = None
"""Online inference quantization method. If None, vLLM infers it from the checkpoint."""
enable_lora: bool = False
@@ -130,6 +132,12 @@ class VllmConfig(BaseConfig):
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB)."""
enable_ep_weight_filter: bool = True
"""Skip non-local expert weights at load time under expert parallelism, so each
rank reads only its own expert shard from disk. No-op for non-MoE models, when
expert parallelism is disabled, or under EPLB (redundant expert slots need all
logical expert weights)."""
enable_dbo: bool = False
"""Enable dual batch overlap (DBO)."""
@@ -220,7 +228,7 @@ class CPUOffloadTier(BaseConfig):
class DiskOffloadTier(BaseConfig):
path: Path
"""Filesystem root for the disk tier. For ``native`` this is the ``fs_python`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
"""Filesystem root for the disk tier. For ``native`` this is the ``fs`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
class BaseKVCacheOffloadConfig(BaseConfig):
@@ -242,14 +250,14 @@ class BaseKVCacheOffloadConfig(BaseConfig):
class NativeKVCacheOffloadConfig(BaseKVCacheOffloadConfig):
type: Literal["native"] = "native"
"""vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs_python`` disk secondary). Fully self-contained — no external processes."""
"""vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs`` disk secondary). Fully self-contained — no external processes."""
def to_connector_dict(self) -> dict[str, Any]:
assert self.cpu is not None
extra: dict[str, Any] = {"cpu_bytes_to_use": int(self.cpu.num_bytes)}
if self.disk is not None:
extra["spec_name"] = "TieringOffloadingSpec"
extra["secondary_tiers"] = [{"type": "fs_python", "root_dir": str(self.disk.path)}]
extra["secondary_tiers"] = [{"type": "fs", "root_dir": str(self.disk.path)}]
return {
"kv_connector": "OffloadingConnector",
"kv_role": "kv_both",
@@ -303,8 +311,11 @@ class VllmRouterConfig(BaseConfig):
type: Literal["vllm-router"] = "vllm-router"
policy: str = "consistent_hash"
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
request_timeout_secs: int = Field(14400, ge=1)
"""Maximum lifetime of a routed request, including streamed completions."""
policy: str = "sticky_least_loaded"
"""Routing policy. Defaults to session-affine least-loaded routing; alternatives include ``consistent_hash`` and ``round_robin``."""
class LlmdRouterConfig(BaseConfig):
@@ -462,7 +473,7 @@ class InferenceConfig(BaseConfig):
"""Return per-token sampling masks (``sampling_mask``) on ``/inference/v1/generate`` responses via vLLM's native ``--return-sampling-mask`` (>= 0.28). The ``rl`` entrypoint enables this field for truncated policy sampling. Standalone inference must set it explicitly because no orchestrator sampling config is available. The field persists into per-node configs and selects the V2 model runner before vLLM starts. Capture is engine-wide: vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0`` while it is on."""
enable_fp32_lm_head: bool = True
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented natively by vLLM's LogitsProcessor, which reads ``head_dtype`` off the HF config, so this flag injects ``hf_overrides = {"head_dtype": "float32"}``."""
enable_fp32_router_logits: bool = True
"""Emit fp32 MoE router logits: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented natively by vLLM, which reads ``moe_router_dtype`` off the HF config — this flag injects ``hf_overrides = {"moe_router_dtype": "float32"}`` (GLM-5.x gets fp32 routing regardless)."""
@@ -636,6 +647,13 @@ class InferenceConfig(BaseConfig):
hf_overrides.setdefault("moe_router_dtype", "float32")
namespace.hf_overrides = hf_overrides
# vLLM's LogitsProcessor reads `head_dtype` off the HF config to pick the
# lm_head projection dtype (fp32 runs as a native bf16xbf16 -> fp32 GEMM).
if self.enable_fp32_lm_head:
hf_overrides = getattr(namespace, "hf_overrides", None) or {}
hf_overrides.setdefault("head_dtype", "float32")
namespace.hf_overrides = hf_overrides
if self.enable_return_sampling_mask:
namespace.return_sampling_mask = True
@@ -643,12 +661,4 @@ class InferenceConfig(BaseConfig):
if kv_transfer_config is not None:
namespace.kv_transfer_config = kv_transfer_config
# Pass prime-rl-specific flags through vLLM's additional_config dict;
# workers read these via get_current_vllm_config().additional_config.
additional_config = getattr(namespace, "additional_config", None) or {}
if self.enable_fp32_lm_head:
additional_config["fp32_lm_head"] = True
if additional_config:
namespace.additional_config = additional_config
return namespace
@@ -43,11 +43,16 @@ class FileMonitorConfig(BaseConfig):
not the records, so this only trades record size against overlay precision."""
class PrimeMonitorConfig(BaseConfig):
class PrimeTrainMonitorConfig(BaseConfig):
name: str | None = None
"""Run name shown on the platform. Inherits ``run.name`` when unset."""
class PrimeEvalMonitorConfig(BaseConfig):
name: str | None = None
"""Evaluation name shown on the platform. Inherits ``run.name`` when unset."""
class MonitorsConfig(BaseConfig):
wandb: WandbMonitorConfig | None = None
"""Log metrics to Weights & Biases. Off by default; enable with ``--monitors.wandb``."""
@@ -56,6 +61,11 @@ class MonitorsConfig(BaseConfig):
"""Log metrics and episode traces to the run's output directory. On by default; disable with ``--no-monitors.file``."""
class OrchestratorMonitorsConfig(MonitorsConfig):
prime: PrimeMonitorConfig | None = None
class TrainMonitorsConfig(MonitorsConfig):
prime: PrimeTrainMonitorConfig | None = None
"""Log metrics and episodes to the Prime Intellect platform. If None, disabled."""
class EvalMonitorsConfig(MonitorsConfig):
prime: PrimeEvalMonitorConfig | None = None
"""Upload every eval source's finished epoch as an evaluation on the Prime Intellect platform. If None, disabled."""
@@ -3,14 +3,14 @@ from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
import verifiers.v1 as vf
from pydantic import Field, SerializeAsAny, model_validator
from pydantic import Field, SerializeAsAny, ValidationError, model_validator
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.algorithm import (
AlgoConfig,
GRPOAlgoConfig,
)
from prime_rl.configs.monitors import OrchestratorMonitorsConfig
from prime_rl.configs.monitors import TrainMonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
BaseWeightBroadcastConfig,
@@ -161,13 +161,13 @@ class EnvConfig(BaseConfig):
"""The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
serve: vf.ServeConfig = vf.ServeConfig()
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config with an unset ``address`` filled in as the derived ``tcp://127.0.0.1:<env_server_base_port + index>``. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config; an unset ``address`` means the spawned server binds an OS-assigned port and publishes it for the orchestrator. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
name: str | None = None
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
ratio: float = Field(1.0, gt=0)
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
shuffle: bool = False
"""Shuffle the source's finite taskset once with a fixed seed. The shuffled order is fixed for the whole run; infinite tasksets cannot be shuffled."""
@model_validator(mode="before")
@classmethod
@@ -194,6 +194,22 @@ class EnvConfig(BaseConfig):
return self
def merge_group_env(data: Any) -> Any:
"""Shared ``mode="before"`` body for source groups: layer the group's ``env`` block
under the ``env`` block of each raw source."""
if not isinstance(data, dict) or data.get("env") is None:
return data
try:
shared = vf.SharedEnvConfig.model_validate(data["env"])
except ValidationError:
return data # the ``env`` field reports the errors once, not once per source
data["source"] = [
{**source, "env": vf.merge_env_defaults(shared, source.get("env"))} if isinstance(source, dict) else source
for source in data.get("source") or []
]
return data
class StandardSamplerConfig(BaseConfig):
type: Literal["standard"] = "standard"
@@ -269,6 +285,9 @@ class TrainSourceConfig(EnvConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
ratio: float = Field(1.0, gt=0)
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
group_size: int = Field(1, ge=1)
"""Rollouts generated per example for GRPO group-relative advantages.
Inherits from ``orchestrator.group_size`` when unset."""
@@ -293,6 +312,10 @@ class EvalSourceConfig(EnvConfig):
group_size: int = Field(1, ge=1)
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8)."""
class OnlineEvalSourceConfig(EvalSourceConfig):
"""An eval source of a training run: evaluated on a step interval."""
interval: int = Field(100, ge=1)
"""Per-env eval interval. If unset, inherits from the group-level eval interval."""
@@ -301,9 +324,18 @@ class TrainConfig(BaseConfig):
source: list[TrainSourceConfig] = Field(default_factory=list)
"""Training sources."""
env: vf.SharedEnvConfig = vf.SharedEnvConfig()
"""Env knobs that every training source inherits: the fields every env and taskset
has, such as ``retries`` and ``timeout``. A source's own ``env`` values win."""
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
@model_validator(mode="before")
@classmethod
def resolve_group_env(cls, data):
return merge_group_env(data)
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
@@ -328,10 +360,16 @@ class TrainConfig(BaseConfig):
return self
class EvalConfig(BaseConfig):
class EvalSourcesConfig(BaseConfig):
"""Eval sources and the group-level defaults they inherit."""
source: list[EvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources."""
env: vf.SharedEnvConfig = vf.SharedEnvConfig()
"""Env knobs that every eval source inherits: the fields every env and taskset
has, such as ``retries`` and ``timeout``. A source's own ``env`` values win."""
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
"""Shared eval sampling configuration; can differ from training sampling."""
@@ -341,6 +379,54 @@ class EvalConfig(BaseConfig):
group_size: int = Field(1, ge=1)
"""Default rollouts per example. Can be overridden per env."""
@model_validator(mode="before")
@classmethod
def resolve_group_env(cls, data):
return merge_group_env(data)
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_examples and
group_size (the worker ``pool`` is configured per env, default elastic)."""
group_sampling = self.sampling.model_dump()
for source in self.source:
if "sampling" not in source.model_fields_set:
source.sampling = EvalSamplingConfig(**group_sampling)
else:
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
source.sampling = EvalSamplingConfig(**merged)
if "num_examples" not in source.model_fields_set:
source.num_examples = self.num_examples
if "group_size" not in source.model_fields_set:
source.group_size = self.group_size
return self
@model_validator(mode="after")
def validate_non_empty_sources(self):
if not self.source:
raise ValueError(
"At least one eval source is required. Add a source block "
"(e.g. [[source]] or [[orchestrator.eval.source]]) or drop the eval block entirely to disable eval."
)
return self
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [source.resolved_name for source in self.source]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(
f"Duplicate evaluation environment names: {set(duplicates)}. Each env must have a unique name."
)
return self
class ScheduledEvalConfig(EvalSourcesConfig):
"""Eval sources evaluated on a step interval next to training."""
source: list[OnlineEvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources, each with its own step interval."""
interval: int = Field(100, ge=1)
"""Step interval at which to evaluate the model."""
@@ -354,43 +440,22 @@ class EvalConfig(BaseConfig):
exit where all evals already completed."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
group_sampling = self.sampling.model_dump()
def resolve_env_intervals(self):
"""Per-env intervals inherit the group-level interval."""
for source in self.source:
if "sampling" not in source.model_fields_set:
source.sampling = EvalSamplingConfig(**group_sampling)
else:
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
source.sampling = EvalSamplingConfig(**merged)
if "num_examples" not in source.model_fields_set:
source.num_examples = self.num_examples
if "group_size" not in source.model_fields_set:
source.group_size = self.group_size
if "interval" not in source.model_fields_set:
source.interval = self.interval
return self
@model_validator(mode="after")
def validate_non_empty_sources(self):
if not self.source:
raise ValueError(
"EvalConfig must define at least one source. Either drop the "
"[orchestrator.eval] block entirely (to disable eval) or "
"add a [[orchestrator.eval.source]] block."
)
return self
@property
def intervals(self) -> dict[str, int]:
"""Step interval per eval env, by resolved name."""
return {source.resolved_name: source.interval for source in self.source}
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [source.resolved_name for source in self.source]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(
f"Duplicate evaluation environment names: {set(duplicates)}. Each env must have a unique name."
)
return self
class RLOnlineEvalConfig(ScheduledEvalConfig):
"""The ``[orchestrator.eval]`` block: online evals against the orchestrator's
inference pool, on the policy the train rollouts see."""
class CheckpointConfig(BaseConfig):
@@ -431,9 +496,6 @@ class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
@@ -510,7 +572,7 @@ class OrchestratorConfig(BaseConfig):
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. RL/OPD roll out through the renderer
client; SFT uses it to backfill tokens for its chat-completions teacher."""
eval: EvalConfig | None = None
eval: RLOnlineEvalConfig | None = None
"""Evaluation configuration."""
log: LogConfig = LogConfig()
@@ -518,7 +580,7 @@ class OrchestratorConfig(BaseConfig):
env_vars: EnvVars = {}
"""Extra environment variables for the orchestrator process(es). Merged on top of the launcher defaults."""
monitors: OrchestratorMonitorsConfig = OrchestratorMonitorsConfig()
monitors: TrainMonitorsConfig = TrainMonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
collect_inference_metrics: bool = True
@@ -545,9 +607,6 @@ class OrchestratorConfig(BaseConfig):
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the source at position ``i`` (train, then eval) is served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address`` keep it instead, without shifting the other sources' ports (indices stay positional). Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
batch_size: int | None = Field(None, ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
@@ -770,15 +829,9 @@ class OrchestratorConfig(BaseConfig):
return sources
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each source's env server lives, keyed by ``(split, resolved_name)``:
the source's own ``serve.address`` when set (an externally managed server), else
``tcp://127.0.0.1:<port>`` with ports from ``env_server_base_port`` in
``env_sources`` order. The launcher binds env servers at exactly these addresses
and the orchestrator connects to them, so both sides agree from the config
alone."""
return {
(split, source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, (split, source) in enumerate(self.env_sources)
}
def env_addresses(self) -> dict[tuple[str, str], str | None]:
"""Where each source's env server lives, keyed by ``(split, resolved_name)``: the
source's own ``serve.address`` when set (an externally managed server), else None —
the launcher spawns the server, which binds an OS-assigned port and publishes it
to the source's address file for the orchestrator to pick up."""
return {(split, source.resolved_name): source.serve.address for split, source in self.env_sources}
@@ -7,7 +7,7 @@ from pydantic import Field, model_validator
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig
from prime_rl.configs.monitors import FileMonitorConfig, PrimeTrainMonitorConfig
from prime_rl.configs.orchestrator import (
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
)
@@ -102,7 +102,7 @@ class SharedMonitorsConfig(BaseConfig):
file: FileMonitorConfig | None = None
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/monitors/file/metrics.jsonl`` on both trainer and orchestrator."""
prime: PrimeMonitorConfig | None = None
prime: PrimeTrainMonitorConfig | None = None
"""Prime platform monitor. Propagated to the orchestrator only — the trainer has no platform integration."""
@@ -145,9 +145,6 @@ class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
port: int = 29501
"""Port for NCCL weight broadcast."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
@@ -368,22 +365,6 @@ class RLConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_quantize_in_weight_transfer(self):
if not isinstance(self.weight_broadcast, SharedNCCLWeightBroadcastConfig):
return self
if not self.weight_broadcast.quantize_in_weight_transfer:
return self
if self.inference is None:
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires an inference config.")
if self.trainer.model.impl != "custom":
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires trainer.model.impl = 'custom'.")
return self
### Auto-setup shared configs (before sub-config construction)
@model_validator(mode="before")
@@ -487,9 +468,7 @@ class RLConfig(BaseConfig):
inference_world_size=inference_world_size,
)
if self.weight_broadcast.type == "nccl":
transport_config = dict(
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
transport_config = {}
trainer_config_type = TrainerNCCLWeightBroadcastConfig
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
else:
@@ -538,18 +517,9 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_eplb_requires_quantized_weight_transfer(self):
if self.inference is None or not self.inference.vllm.enable_eplb:
return self
# TODO(matej): check if weight reloading works itself before supporting EPLB without quantized transfer.
trainer_weight_broadcast = self.trainer.weight_broadcast
if trainer_weight_broadcast.type != "nccl" or not trainer_weight_broadcast.quantize_in_weight_transfer:
raise ValueError(
"inference.vllm.enable_eplb requires weight_broadcast.type = 'nccl' and "
"weight_broadcast.quantize_in_weight_transfer = true."
)
def validate_eplb(self):
if self.inference is not None and self.inference.vllm.enable_eplb:
raise ValueError("inference.vllm.enable_eplb is not supported with RL weight updates.")
return self
@model_validator(mode="after")
@@ -8,7 +8,7 @@ from pydantic import AliasChoices, Field, model_validator
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
from renderers.base import MODEL_RENDERER_MAP
from prime_rl.configs.evals import EvalsEvalConfig
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
@@ -91,6 +91,9 @@ class SFTDataConfig(BaseDataConfig):
name: str = "PrimeIntellect/Reverse-Text-SFT"
"""HF dataset name or path."""
revision: str | None = None
"""HF dataset revision to load. Ignored for a local path."""
subsets: list[str] | None = None
"""Subsets to load from the HF dataset."""
@@ -203,7 +206,7 @@ class SFTConfig(BaseConfig):
val: SFTValConfig | None = None
"""Validation configuration. If None, no validation runs."""
eval: EvalsEvalConfig | None = None
eval: SFTOnlineEvalConfig | None = None
"""Online evaluation configuration: rollout-based evals against a live inference
server that receives the trainer's weight broadcasts. If None, no online evals run."""
@@ -437,7 +440,7 @@ class SFTConfig(BaseConfig):
"Online evals are configured without an [inference] block - the launcher will not "
f"start an inference server. Make sure one is running at eval.client.base_url "
f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', "
"otherwise the evals process will hang waiting for it. If a router fronts the "
"otherwise the online-eval process will hang waiting for it. If a router fronts the "
"deployment, set eval.client.admin_base_url to the engine URLs - admin ops "
"(pause/update_weights/resume) must bypass the router.",
stacklevel=2,
@@ -162,8 +162,16 @@ class BaseModelConfig(BaseConfig):
"""VLM configuration. Setting this enables vision-language model support."""
class DynamoConfig(BaseConfig):
enabled: bool = True
"""Enable Dynamo worker discovery for the inference admin plane."""
discovery_url: str | None = Field(default=None, min_length=1, max_length=2048)
"""Dynamo frontend URL used to discover inference workers for RL control."""
class ClientConfig(BaseConfig):
wait_for_ready_timeout: int = 1800
wait_for_ready_timeout: int = 3600
"""Seconds to wait at startup for the inference pool to become ready."""
base_url: str = "http://localhost:8000/v1"
@@ -184,6 +192,9 @@ class ClientConfig(BaseConfig):
admin_base_url: list[str] | None = None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in multi-replica or disaggregated P/D deployments where the router must not handle admin traffic."""
dynamo: DynamoConfig | None = None
"""Dynamo RL worker-discovery configuration."""
class LogConfig(BaseConfig):
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
@@ -1,8 +1,9 @@
import re
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import BeforeValidator, Field, model_validator
from pydantic import BeforeValidator, Field, field_validator, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
@@ -84,6 +85,20 @@ class CompileConfig(BaseConfig):
fullgraph: bool = False
"""Compile transformer blocks with ``fullgraph=True``."""
mode: Literal["reduce-overhead", "max-autotune", "max-autotune-no-cudagraphs", "lite"] | None = None
"""``torch.compile`` mode. ``reduce-overhead`` records CUDA graphs to cut kernel launch overhead; ``max-autotune`` modes trade longer compile times for tuned kernels (``max-autotune`` also records CUDA graphs, ``max-autotune-no-cudagraphs`` does not). CUDA-graphed layers re-record on new input shapes. ``None`` uses PyTorch's default mode."""
class FusionsConfig(BaseConfig):
enabled: list[Literal["gate_up", "qkv"]] = ["gate_up", "qkv"]
"""Runtime parameter fusions. ``gate_up`` runs each MoE expert's gate and up projections as one grouped GEMM; ``qkv`` runs attention's q, k and v projections as one GEMM. Only modules that support a fusion are packed, checkpoints keep the canonical parameter names and shapes, and fusions are skipped when LoRA is enabled. Set to ``[]`` to disable."""
raise_on_fail: bool = False
"""Fail at startup when no module supports a requested fusion, instead of logging a warning and continuing without it."""
shard_fused_on_dim1: bool = False
"""Experimental. Shard fused 2-D weights along dim 1 under FSDP so that weight loading and checkpointing are zero-copy: the checkpoint reads and writes the fused weights and their optimizer state in place, instead of assembling a full copy of every fused weight on each rank first. Requires the hidden size to be divisible by the FSDP shard mesh size."""
class IndexCacheConfig(BaseConfig):
topk_freq: int = Field(1, ge=1)
@@ -169,19 +184,46 @@ class MXFP8Config(BaseConfig):
QuantizationConfig: TypeAlias = Annotated[FP8Config | MXFP8Config, Field(discriminator="type")]
class BF16MoEComputeConfig(BaseConfig):
class MoEComputeConfigBase(BaseConfig):
apply_to: str | list[Annotated[int, Field(ge=0, strict=True)]] = "all"
"""Model layers to use this backend for: ``"all"``, a percentage such as ``"85%"``,
or zero-based layer indices such as ``[0, 1, 2]``. Percentages select the first fraction
of model layers, rounded down. Other expert groups use BF16 compute and transport.
"""
@field_validator("apply_to")
@classmethod
def validate_apply_to(cls, value: str | list[int]) -> str | list[int]:
if isinstance(value, str) and value != "all":
if re.fullmatch(r"\d+(?:\.\d+)?%", value) is None or float(value[:-1]) > 100:
raise ValueError('apply_to must be "all", a percentage from "0%" to "100%", or a list of layer indices')
return value
def resolve_layers(self, num_layers: int) -> set[int]:
if isinstance(self.apply_to, list):
invalid = [index for index in self.apply_to if index >= num_layers]
if invalid:
raise ValueError(
f"apply_to layer indices {invalid} are out of range for a model with {num_layers} layers"
)
return set(self.apply_to)
count = num_layers if self.apply_to == "all" else int(num_layers * float(self.apply_to[:-1]) / 100)
return set(range(count))
class BF16MoEComputeConfig(MoEComputeConfigBase):
"""Run routed-expert grouped GEMMs in bfloat16."""
type: Literal["bf16"] = "bf16"
class DeepGemmFP8MoEComputeConfig(BaseConfig):
class DeepGemmFP8MoEComputeConfig(MoEComputeConfigBase):
"""Run routed-expert grouped GEMMs with DeepGEMM FP8 kernels."""
type: Literal["deepgemm_fp8"] = "deepgemm_fp8"
class MXFP8MoEComputeConfig(BaseConfig):
class MXFP8MoEComputeConfig(MoEComputeConfigBase):
"""Run routed-expert grouped GEMMs with Prime's vendored MXFP8 implementation."""
type: Literal["mxfp8"] = "mxfp8"
@@ -240,6 +282,9 @@ class ModelConfig(BaseModelConfig):
compile: CompileConfig | None = CompileConfig()
"""Compile the model with ``torch.compile``."""
fusions: FusionsConfig = FusionsConfig()
"""Runtime parameter fusions, on by default."""
ac: ActivationCheckpointConfig | None = ActivationCheckpointConfig()
"""Activation checkpointing configuration. If None, activation checkpointing is disabled."""
@@ -526,16 +571,35 @@ class CheckpointConfig(BaseConfig):
class IPOLossConfig(BaseConfig):
type: Literal["ipo"] = "ipo"
eps: float = Field(0.1, ge=0)
eps: float = Field(0.3, ge=0)
"""Maximum absolute probability change before a token is masked."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
kl_tau: float = Field(1e-3, ge=0)
kl_tau: float = Field(0.0, ge=0)
"""Temperature for the KL term."""
class IcePopLossConfig(BaseConfig):
type: Literal["icepop"] = "icepop"
ratio_low: float = Field(0.2, gt=0)
"""Lower accepted trainer-to-inference probability ratio."""
ratio_high: float = Field(5.0, gt=0)
"""Upper accepted trainer-to-inference probability ratio."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
@model_validator(mode="after")
def validate_ratio_bounds(self):
if self.ratio_low > self.ratio_high:
raise ValueError("ratio_low must not exceed ratio_high")
return self
class CustomLossConfig(BaseConfig):
type: Literal["custom"] = "custom"
@@ -546,7 +610,7 @@ class CustomLossConfig(BaseConfig):
"""Kwargs forwarded to the loss function."""
LossConfig: TypeAlias = Annotated[IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
LossConfig: TypeAlias = Annotated[IPOLossConfig | IcePopLossConfig | CustomLossConfig, Field(discriminator="type")]
class FakeDataLoaderConfig(BaseConfig):
@@ -584,9 +648,6 @@ class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
@@ -699,16 +760,6 @@ class TrainerConfig(BaseConfig):
self.optim.max_norm = None
return self
@model_validator(mode="after")
def vlms_require_bfloat16(self):
if self.model.vlm is not None and (
self.model.optimization_dtype != "bfloat16" or self.model.reduce_dtype != "bfloat16"
):
raise ValueError(
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
)
return self
@model_validator(mode="after")
def vlm_freeze_incompatible_with_lora(self):
if self.model.vlm is not None and not self.model.vlm.freeze_vision_encoder and self.model.lora is not None:
+42 -18
View File
@@ -16,18 +16,20 @@ dependencies = [
"transformers==5.6.2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
"prime>=0.6.19",
"prime-sandboxes>=0.3.0",
"prime-runs[train]>=0.1.3",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
"openai>=1.106.1",
"orjson>=3.11.0",
"psutil>=7.0.0",
"prometheus-client>=0.20.0",
"pyzstd>=0.16.2",
"rich>=14.0.0",
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"verifiers[harbor]>=0.3.1",
"verifiers[harbor]>=0.3.2.dev143",
"renderers[multimodal]>=0.1.12.dev2",
"pybase64>=1.4.2",
"orjson>=3.10",
@@ -41,7 +43,7 @@ sft = "prime_rl.entrypoints.sft:main"
inference = "prime_rl.entrypoints.inference:main"
trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
evals = "prime_rl.entrypoints.evals:main"
eval = "prime_rl.entrypoints.eval:main"
env-server = "prime_rl.entrypoints.env_server:main"
dashboard = "prime_rl.entrypoints.dashboard:main"
@@ -54,13 +56,14 @@ gpu = [
"torchvision ; sys_platform == 'linux'",
"torchaudio ; sys_platform == 'linux'",
"torchdata>=0.11.0 ; sys_platform == 'linux'",
"vllm>=0.28.0 ; sys_platform == 'linux'",
"vllm>=0.29.0 ; sys_platform == 'linux'",
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
"torchtitan ; sys_platform == 'linux'",
"dion ; sys_platform == 'linux'",
"tilelang>=0.1.8 ; sys_platform == 'linux'",
"flash-linear-attention ; sys_platform == 'linux'",
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
"torchao>=0.18.0 ; sys_platform == 'linux'",
"modelexpress==0.3.0 ; sys_platform == 'linux'",
@@ -70,6 +73,7 @@ dashboard = [
"fastapi>=0.115",
"uvicorn>=0.30",
]
dynamo = ["ai-dynamo==1.4.2 ; sys_platform == 'linux'"]
# Both wheels are the same flash-attn 2.8.3 / cu130 / torch 2.13 / cp312 build and carry
# sm_80 / sm_90 / sm_100 / sm_120 cubins. `attn="auto"` picks FA4 on sm_100 and FA3 on
# sm_90, so FA2 is the resolved backend on sm_120 (see `_resolve_attn_impl` in
@@ -90,9 +94,6 @@ disagg = [
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
"vllm-router ; sys_platform == 'linux'",
]
gpt-oss = [
"kernels ; sys_platform == 'linux'",
]
quack = [
"quack-kernels>=0.4.1 ; sys_platform == 'linux'",
]
@@ -140,10 +141,12 @@ environments = [
# Override torch's pinned cuDNN to fix the Conv3d performance regression.
# See: https://github.com/pytorch/pytorch/issues/166122
override-dependencies = [
# Keep vLLM's TileLang version; Nemotron uses Mamba-2's Triton kernels.
"tilelang==0.1.12",
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
"apache-tvm-ffi==0.1.11",
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
# vLLM 0.28.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
# vLLM 0.29.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
"nvidia-cutlass-dsl==4.6.2",
"transformers==5.6.2",
@@ -168,11 +171,14 @@ members = [
"deps/verifiers/environments/wiki_search",
"deps/verifiers/environments/wordle",
]
# tau2-synth and tau3-bench pin `tau2` forks/revs that conflict with the
# canonical tau2-bench; a workspace shares one lock, so these can't coexist.
# Tau tasksets require litellm<1.82.7, while Harbor requires litellm>=1.92.0.
# Apex pins a verifiers git revision instead of the editable workspace member.
# A workspace shares one lock, so these packages need separate environments.
exclude = [
"deps/prime-envs/environments/tool_use/tau2_bench",
"deps/prime-envs/environments/tool_use/tau2_synth",
"deps/prime-envs/environments/tool_use/tau3_bench",
"deps/prime-envs/environments/tool_use/apex_agents",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -191,6 +197,15 @@ requires-dist = [
"torch>=2.6.0",
]
# Mirror the upstream Pydantic compatibility correction until the next release.
[[tool.uv.dependency-metadata]]
name = "ai-dynamo-runtime"
version = "1.4.2"
requires-dist = [
"pydantic>=2.10.6,<=2.13.5",
"uvloop>=0.21.0",
]
# NIXL publishes its CUDA 12 package as a base dependency even when the
# caller requests its CUDA 13 extra. Use the requested CUDA 13 package only.
[[tool.uv.dependency-metadata]]
@@ -212,8 +227,6 @@ requires-dist = [
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
harbor = "2026-08-11T00:00:00Z"
# we want latest vllm, remove next patch
vllm = false
tokenspeed-mla = false
fastokens = false
flash_attn_3 = false
@@ -222,6 +235,8 @@ flash_attn_3 = false
# appear in `uv tree` need to be listed; the resolver ignores entries for
# packages it never sees.
prime = false
prime-runs = false
prime-traces = false
prime-sandboxes = false
prime-tunnel = false
prime-evals = false
@@ -252,15 +267,15 @@ torchao = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
dion = { git = "https://github.com/samsja/dion.git", rev = "6f9242d" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
@@ -275,12 +290,13 @@ prime-kernels = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
mamba-ssm = { git = "https://github.com/state-spaces/mamba", rev = "f577286" }
flash_attn_3 = { index = "pytorch-cu130-test" }
[tool.uv.extra-build-dependencies]
flash-attn = [{ requirement = "torch", match-runtime = true }]
flash-attn-3 = [{ requirement = "torch", match-runtime = true }]
mamba-ssm = [{ requirement = "torch", match-runtime = true }]
mamba-ssm = ["torch>=2.13.0"]
[tool.uv.extra-build-variables]
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
@@ -295,6 +311,14 @@ name = "pytorch-cu130-test"
url = "https://download.pytorch.org/whl/test/cu130"
explicit = true
# Environments Hub wheels carry no upload time, so the exclude-newer cooldown
# would reject every one of them. The Hub is first-party: skip the cutoff there.
[[tool.uv.index]]
name = "prime-hub"
url = "https://hub.primeintellect.ai/primeintellect/simple/"
explicit = true
exclude-newer = false
[tool.ruff.lint]
select = ["F", "I"]
+3 -3
View File
@@ -63,9 +63,9 @@ env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text` or `--orchestrator.eval.source.0.env.taskset.id reverse-text`.
Source lists are set in TOML. The CLI has no list-index paths (`--orchestrator.eval.source.0.env.taskset.id` does not parse); a whole list can be passed as JSON (`--orchestrator.eval.source '[{"env": {"taskset": {"id": "reverse-text"}}}]'`), which replaces the list wholesale.
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server), e.g. `--eval.source.0.env.taskset.id reverse-text`.
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server). The `eval` entrypoint flattens it further: `[[source]]`, `[client]`, `[concurrency]`, `num_examples`, `group_size` at the top level, plus the single-source shorthands `uv run eval <taskset-id> --env.<field> <value> -n N -r N -c N -m MODEL` (see the `eval` skill).
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
@@ -73,7 +73,7 @@ The `sft` entrypoint takes the same eval shape at the top level for online evals
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1`, `adv_tau = 1.0`, and `kl_tau = 1e-3`. Omit the section to use these defaults. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1`, `adv_tau = 1.0`, and `kl_tau = 1e-3`. Omit the section to use these defaults. Set `type = "icepop"` for ratio masking with `ratio_low = 0.2`, `ratio_high = 5.0`, and `adv_tau = 1.0`; IcePop has no separate KL term. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
+21 -100
View File
@@ -5,128 +5,49 @@ description: Find, start, use, and stop the local run dashboard for metrics, con
# Run dashboard
`uv sync --extra dashboard && uv run dashboard [output_dir ...]` (default
`outputs/`, or `$PRL_OUTPUT_DIR` if set) serves a web UI at `http://localhost:7788`. It only reads run
dirs — safe against live runs — and installs anywhere (cluster head node,
laptop against a mounted outputs dir): GPU dependencies live behind the
`gpu` extra.
`uv sync --extra dashboard && uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR`) serves a web UI at `http://localhost:7788`. It only reads run dirs, so it is safe against live runs and installs anywhere: GPU dependencies live behind the `gpu` extra.
The Config and Logs views default to `latest (attempt <n>)`. Select an attempt
to inspect the immutable config or log files from an earlier launch. The Config
view shows a copyable launch command above the launch TOML or resolved JSON.
What is not obvious from the UI:
Every dashboard instance serves the dirs it was started with **plus** every dir
in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`, re-read
live). Launchers (`rl`, `sft`) register their output dir on every
start and, in interactive sessions, auto-start a dashboard only when none is
live — an already-running one absorbs the new dir automatically, whatever port
it is on. `--no-dashboard` opts a run out; non-interactive launches (CI, nohup)
register their dir but never spawn.
- Overview and Metrics read the same `monitors/file/metrics.jsonl`. **Overview** is the curated view (the sections of the W&B overview: train, eval, stability, inference, performance). **Metrics** is every key in the file, one pane per key, sectioned by parent path (`Flat`) or as a tree of sections along the key path (`Nested`), with a regex filter; time-keyed rows (`inference/`, `concurrency/`, `dispatcher/`) chart against wall time.
- Config and Logs default to `latest (attempt <n>)`; select an attempt to inspect an earlier launch. The Config view shows a copyable launch command.
- Trace viewer views: **Transcript**, **Timeline** (wall-clock Gantt of prefix branches), **Replay** (the branch as a terminal session; response text is paced evenly across the recorded model-call span and labelled inferred; default 8×; **Skip inference** collapses model calls but keeps tool delays; **T** toggles thinking, never advertise Ctrl+T) and **Semantic** (`semantic_parents` as a causal graph of model calls; width reflects peak agent concurrency; unplaceable fragments show as unlinked). Traces without semantic parents disable Semantic.
- Live rollouts appear in the traces table with a pulsing dot and a phase badge, and open in the viewer, which follows them (pinned to the newest turn until you scroll up; the request in flight's uncommitted messages render dimmed as `awaiting model`). They come from `monitors/file/traces/live/*.jsonl`, polled once a second.
- For an eval run the overview tab shows one env at a time (filter → env, `include errors`): a block progress bar (one cell per expected episode, from `monitors/file/plan.json`), summary tiles (avg@k, pass@k, error and truncation rate coloured >10% yellow / >50% red, turns / branches, episode time, tokens, cost), env metrics as dot plots or beeswarms (hover a dot for its episode, click to open it; hover the background for the quantiles), and usage / timing composition panes (icicle of the mean split over per-episode strips; `other` is wall time no phase accounts for; hover a part to dim the rest; 40 strips by default, `show all` for every one).
- `view on platform` in the top bar links to the run on the Prime platform when `--monitors.prime` was on (`monitors/prime/run.json`); an eval's evaluation opens at epoch start, so the link is live from the first episode.
- An eval reads `completed` once its stream is sealed by a clean exit; a crashed or interrupted one reads `stopped` after its files go quiet.
## Isolated mode
Every dashboard instance serves the dirs it was started with plus every dir in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`). Launchers register their output dir on every start and, in interactive sessions, auto-start a dashboard only when none is live; `--no-dashboard` opts a run out, non-interactive launches never spawn one. `--isolated` serves only the given dirs and ignores the registry.
`--isolated` serves only the given dirs: no registry read or write, no
discovery claim, and launchers ignore the instance. Use it for focused views
(demos, debugging one run dir) or to keep a scratch dir out of the registry.
## Finding, stopping, restarting
## Finding the live dashboard
The live port can differ from 7788 (a taken port bumps to the next free one),
so read the discovery file:
The port can differ from 7788 (a taken port bumps to the next free one), so read the discovery file and hand the researcher its `url`; launcher logs also end with a `Dashboard · <url>` banner.
```bash
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
curl -sf $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/runs > /dev/null && echo live
ps aux | grep PRL::Dashboard # process title
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<port>"}
kill $(jq -r .pid ~/.cache/prime-rl/dashboard/daemon.json) # stop; the next launch (or `uv run dashboard`) restarts it
```
Hand the researcher the `url` from `daemon.json`. Launcher logs also print it:
startup ends with a `Dashboard · <url>` banner. The auto-started instance logs
to `~/.cache/prime-rl/dashboard/daemon.log`.
## Stopping / restarting
```bash
kill $(jq -r .pid ~/.cache/prime-rl/dashboard/daemon.json) # the discovered instance
pkill -f PRL::Dashboard # every dashboard on the host
```
A clean exit releases `daemon.json`; a stale file from a dead process is taken
over by the next start. Killing a dashboard never affects runs (it only reads),
and killing a run never takes the dashboard down (it runs in its own session).
Restart by launching any run, or directly: `uv run dashboard`.
Killing a dashboard never affects runs and killing a run never takes the dashboard down. The daemon serves the code of the checkout that started it (`readlink /proc/<pid>/cwd`): after switching branches or worktrees, kill it so the next launch restarts it on the current code. Its log is `~/.cache/prime-rl/dashboard/daemon.log`.
## Point the open dashboard
Use `POST /api/view` to show relevant run data in every connected dashboard
tab:
`POST /api/view` shows run data in every connected tab. `run` is required; the other fields leave unspecified state alone. For trace evidence pass `step`, `kind` and `subset` together and address the episode by its stable `id` (`subset: "effective"` narrows the traces tab to the cohort shipped at that step); `highlight` entries are `{node, quote, reason, field?}`. On `409`, tell the user to open the returned `url`.
```bash
curl -sS -X POST $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/view \
-H 'content-type: application/json' -d '{
"run": "demo-rl", "tab": "traces",
"step": 0, "kind": "train", "subset": "effective",
"episode": "ep-s00-reverse-text-0",
"highlight": [{"node": 3, "quote": "hint: reverse the words", "reason": "tool result the policy conditioned on"}]
}'
-H 'content-type: application/json' -d '{"run": "demo-rl", "tab": "traces", "step": 0, "kind": "train", "subset": "effective",
"episode": "ep-s00-reverse-text-0", "highlight": [{"node": 3, "quote": "hint: reverse the words", "reason": "the tool result the policy conditioned on"}]}'
```
`run` is required; other fields are optional and leave unspecified UI state
unchanged. For trace evidence, supply `step`, `kind`, and `subset` together and
address the episode by stable `id`. The traces tab opens on the whole stream;
`subset: "effective"` switches it to the cohort that shipped at one step. Use
optional `trace` and `branch` indices
for multi-agent traces and `highlight` entries shaped as `{node, quote,
reason, field?}`. On `409`, tell the user to open the returned `url`; the stored
command applies when the tab connects.
## Reports, only when asked
## Write a report only when asked
Create a report only when the user explicitly asks for one. Otherwise answer
normally; use `/api/view` when showing trace evidence would help.
Write requested reports to `<run>/reports/<slug>.md`, then POST `{"run": ...,
"tab": "report", "report": "<slug>"}`. Use Markdown with a frontmatter
`title` and one-line JSON citation definitions:
Write a requested report to `<run>/reports/<slug>.md`, then POST `{"run": ..., "tab": "report", "report": "<slug>"}`. Markdown with a frontmatter `title` (rendered as the H1, do not repeat it) and one-line JSON citations:
```markdown
---
title: Why does reward dip at step 4?
---
The dip is provider errors, not policy regression [^err].
[^err]: {"step": 4, "kind": "train", "subset": "all", "episode": "ep-...", "node": 0, "quote": "engine overloaded", "note": "The failed call that emptied this step's batch."}
```
The frontmatter `title` is rendered as the report H1; do not repeat it with a
Markdown `#` heading. The inline renderer supports only HTTP(S) and anchor
links. Relative Markdown links render as literal text, so identify local source
files with inline code paths or link to a supported HTTP endpoint.
Each citation requires `step`, `kind`, `subset`, `episode`, `quote`, and `note`.
Use the top-level rollout record `id` returned by the dashboard episode-list
API—not a nested `traces[*].id`, and never `line`. Copy a short, distinctive
quote exactly; matching is case-sensitive and whitespace-insensitive. Keep
`note` to 1–2 sentences explaining why the quote supports the claim.
Cite major empirical, comparative, and diagnostic conclusions, but not routine
explanation. Use exact trace citations for trajectory-level claims. For
aggregate statistics, identify the run and source file; do not imply that one
example trajectory proves the aggregate.
Use adjacent markers (`[^a] [^b]`) only when one claim genuinely depends on
distinct passages, such as a comparison or corroboration. Use one citation
when one passage is sufficient.
Optional fields are `run`, `trace`, `branch`, `node`, `field`, `prefix`, and
`suffix`. Use `field: "content"` or `"reasoning"` only to disambiguate message
parts. Use verbatim adjacent `prefix`/`suffix` only when a quote repeats.
Ambiguous or mismatched citations remain broken and do not navigate.
Use Markdown; raw HTML is escaped.
Before handoff, reload the report and verify through the dashboard API that
every referenced citation resolves uniquely to its episode, node, and quote.
Confirm zero broken citations, one rendered title, and no unsupported relative
links.
A citation needs `step`, `kind`, `subset`, `episode` (the top-level record `id`, never `line` or a `traces[*].id`), an exact short `quote` (case-sensitive, whitespace-insensitive) and a one-sentence `note`; optional `trace`, `branch`, `node`, `field`, `prefix`, `suffix` disambiguate. Cite empirical and diagnostic claims, not routine explanation; one citation per passage. Only HTTP(S) and anchor links render. Before handing over, verify through the API that every citation resolves.
+75
View File
@@ -0,0 +1,75 @@
---
name: eval
description: Launch and monitor prime-rl evals — the `uv run eval` entrypoint, its config and CLI shorthands, run directory, resume, logs and metrics. Use when asked to evaluate a model or checkpoint on an environment, smoke-test an environment, or check on an eval run.
---
# Eval
`uv run eval` evaluates a model in one or more environments and exits after one epoch per source. It reuses the orchestrator's eval pipeline: one env server per source, a concurrency band, every episode through the monitors, and a trace stream that `--resume` continues from. Online evals of training runs are the `training` skill.
## Start an eval
The user launches runs; hand over the command unless told otherwise. Always cap smokes (`-n`, `-r`).
```bash
uv run eval gsm8k -n 32 -r 4 # Prime Inference
uv run eval gsm8k -n 32 -r 4 -c 8 --env.agent.harness.id bash # pin concurrency; set a field of the env block
uv run eval gsm8k -n 32 -r 4 -m Qwen/Qwen3-4B --client.base_url http://localhost:8000/v1 # a local `uv run inference` server
uv run eval @ eval.toml --run.name my-eval # multi-source TOML
uv run eval @ eval.toml --run.name my-eval --resume # continue an interrupted run
uv run eval @ eval.toml --dry-run # resolve and write the config, exit
uv run eval @ eval.toml --monitors.prime # stream each source's epoch to the platform
```
- Config: `EvalConfig` (`packages/prime-rl-configs/src/prime_rl/configs/eval.py`); `uv run eval -h` lists the fields.
- Entrypoint: `src/prime_rl/entrypoints/eval.py`; implementation `src/prime_rl/eval/eval.py`, shared engine `src/prime_rl/eval/runner.py`.
- Shorthands (single-source runs): `<taskset-id>`, `--env.<field> <value>`, `-n` `num_examples`, `-r` `group_size`, `-m` `model`, `-c N` pins `concurrency.min_inflight = max_inflight = N`. They cannot be combined with a TOML that defines `[[source]]` blocks.
- Concurrency: an API exposes no vLLM `/metrics`, so run pinned there; against `uv run inference` set `min_inflight < max_inflight` in `[concurrency]` to adapt to KV usage.
- Env servers: spawned per source on OS-assigned ports (published to `configs/attempt_N/resolved/envs/eval/<name>.address`) unless the source sets `serve.address`.
- Ready-made configs: `configs/debug/eval/*.toml`, one per shape (single turn, multi turn, resume, multi env, aime2026, tb2).
Minimal multi-source TOML (the eval block is flattened to the top level; per-source `num_examples`, `group_size`, `sampling` override the top level):
```toml
model = "Qwen/Qwen3-4B"
num_examples = 32
group_size = 4
[client]
base_url = "http://localhost:8000/v1"
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "bash"
[[source]]
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
## Monitor an eval
Run dir: `output_dir / run.name` (auto `<envs>--<model>--<short-id>`; `ls -t outputs | head -1` finds the latest). The console stays quiet while the eval runs; everything is in the files and the dashboard (`dashboard` skill).
```
{run_dir}/
├── configs/latest/ # command.txt, the launch TOML, resolved/eval.json
├── logs/latest/
│ ├── eval.log # the eval process
│ └── envs/eval/{name}.log # one log per env server
└── monitors/file/ # metrics.jsonl, the trace stream, traces/live/ (one file per live trace), plan.json
```
```bash
tail -F {run_dir}/logs/latest/eval.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/eval.log {run_dir}/logs/latest/envs/eval/*.log
grep SUCCESS {run_dir}/logs/latest/eval.log # one "Evaluated <env> ... Reward 0.xxxx" line per source
uv run python -m prime_rl.monitors.file.traces {run_dir} [<trace_id>] # live rollouts by phase, or one assembled live trace
```
The progress line in `eval.log` counts live rollouts by phase (`- boot 1 · running 3`). A rollout stuck in `boot` for minutes is waiting on its sandbox; one in `running` with a frozen turn count is waiting on a model call or tool.
Metrics live under `eval/<env>/all/<agent>/…` (`reward/mean`, `is_truncated/mean` — raise `sampling.max_completion_tokens` when high, `has_error/mean`, the taskset's own metrics). Validate a result by reading a few traces in the dashboard rather than trusting the mean alone.
Stop a run with SIGINT/SIGTERM to the eval PID (`ps aux | grep PRL::Eval`); `--resume` restores the landed episodes from the trace stream and runs only the rollouts still owed (`num_examples`/`group_size` may change, the model, sampling and env config may not). Env servers are children of the eval process and exit with it.
+2 -2
View File
@@ -59,10 +59,10 @@ See the `kernels` skill.
### NemotronH (Mamba SSD kernels)
```bash
CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
uv sync --extra gpu
```
Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch SSD path, which computes softplus in bf16 and yields ~0.4 KL divergence vs vLLM. Do **not** install `causal-conv1d` unless your GPU arch matches the prebuilt kernels — the code falls back to `nn.Conv1d` when it's absent.
Native NemotronH uses Mamba2 Triton SSD kernels and FLA's packed causal convolution. The pinned `mamba-ssm` source installs without `nvcc`; no separate `causal-conv1d` installation is needed. `uv sync --all-extras` includes these dependencies.
### Trainer DeepEP backend
+1 -1
View File
@@ -10,4 +10,4 @@ Two phases — start the run, then watch it.
- **Start a run** — see `start-run/SKILL.md` for the `rl`, `sft`, and `inference` entrypoints and how to launch them (single-node, SLURM, dry-run).
- **Monitor a run** — see `monitor-run/SKILL.md` for the runbook: how to find the output dir, what to tail, which metrics to watch, and how to restart safely.
Both subskills assume the `configs` skill for config-loading mechanics.
Both subskills assume the `configs` skill for config-loading mechanics. Standalone evals (`uv run eval`) are the `eval` skill; online evals of a training run are configured in `start-run` and read in `monitor-run`.
+6 -2
View File
@@ -82,7 +82,7 @@ Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`
{run_dir}/logs/latest/
├── trainer.log # rank 0 stdout
├── orchestrator.log # orchestrator stdout
├── evals.log # SFT online-eval evals stdout
├── eval.log # SFT online-eval process (also the `uv run eval` process — see the `eval` skill)
├── inference.log # vLLM stdout
├── trainer/
│ ├── node_*.log # per-node (multi-node only)
@@ -100,10 +100,14 @@ Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough
Scan for problems:
```bash
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evals,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,eval,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
```
### Live rollouts
`{run_dir}/monitors/file/traces/live/<trace_id>.jsonl` holds the env server's streamed deltas of one live rollout (train or eval) and disappears when its episode lands in the stream, so the directory is the live set. `uv run python -m prime_rl.monitors.file.traces {run_dir}` prints one row per live trace with `stage` (pending/boot/setup/running/finalize/scoring/done/error), turns, tokens, elapsed and the latest message; with a trace id it prints the assembled trace. The dashboard's traces tab shows them in the episode table (tinted, phase badge, growing counts; filter status → in flight) and opens them in the viewer.
### Metrics
All metrics print to the console log (and W&B when configured).
+6 -40
View File
@@ -1,6 +1,6 @@
---
name: start-run
description: How to launch prime-rl training runs — the `rl`, `sft`, `inference`, and `evals` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
description: How to launch prime-rl training runs — the `rl`, `sft`, and `inference` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint. Standalone evals are the `eval` skill.
---
# Start a run
@@ -74,7 +74,9 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
## `inference` — vLLM server
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly.
Router session cleanup runs on successful, failed, and cancelled episodes, including discarded retry traces. Cleanup failures are logged per session and do not disable subsequent releases.
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly. The default `sticky_least_loaded` policy keeps each rollout on one replica while assigning new sessions to the least-loaded replica; RL and SFT online eval automatically release completed sessions.
```bash
uv run inference --vllm.model Qwen/Qwen3-0.6B
@@ -95,43 +97,6 @@ curl http://localhost:8000/v1/chat/completions \
- Entrypoint: `src/prime_rl/entrypoints/inference.py`
- SLURM: single-node, multi-node, and disaggregated deployments
## `evals` — multi-env evals
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. Add `[ckpt]` (`interval` counts completed task groups in the eval-source order) to make the run interruptible, then use `--resume`, `--resume.step N`, or `--resume.dir path/to/checkpoints/step_N`; for standalone evals, checkpoint step N means resume from task cursor N. Checkpoints store only the cursor, not generated episode records; partially completed groups and groups beyond the durable cursor are retried. Resume loads without `[ckpt]` but does not save new checkpoints. Checkpoint/resume is rejected with `[online]` because that process is coupled to the trainer's live broadcast handshake. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. By default a newer checkpoint cancels unfinished episodes from the prior eval. Set `eval.cancel_on_new_checkpoint = false` to drain every epoch. The trainer can idle while it waits for slow evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
```bash
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
uv run evals @ eval.toml
```
Minimal standalone `eval.toml`:
```toml
model = "Qwen/Qwen3-4B"
[eval.client]
base_url = "http://localhost:8000/v1"
[eval.concurrency] # adaptive; same controller as [orchestrator.concurrency]
min_inflight = 8
max_inflight = 128
[[eval.source]]
num_examples = 32 # always cap eval size for smokes
group_size = 4
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # optional: make a standalone eval resumable
interval = 10 # completed task groups between cursor saves
```
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/latest/envs/eval/{name}.log`.
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
## Exporting checkpoints
Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`). Convert to HF safetensors with `uv run python tools/convert_dcp_to_bf16.py <run_dir>/checkpoints/step_{n}` (writes `<ckpt_dir>/weights`, serveable via `uv run inference --vllm.model <dir>`; model config auto-read from the run’s `configs/latest/resolved/trainer.json`/`sft.json`; multi-rank via `torchrun --nproc-per-node N`; full fine-tunes only, LoRA rejected). Quantize a bf16 HF dir to blockwise FP8 with `tools/convert_bf16_to_fp8.py <dir>` (vLLM-native format), or straight from a checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (rank-parallel, writes only `<ckpt_dir>/weights-FP8`, no bf16 on disk); dequantize fp8-only releases with `tools/convert_fp8_to_bf16.py <dir>`. Caveat: on SM120 GPUs (RTX PRO 6000) vLLM 0.26 picks `CutlassFp8BlockScaledMMKernel` for blockwise-fp8 checkpoints and it silently degrades outputs — serve with `VLLM_DISABLED_KERNELS=CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel` to fall back to the Triton kernel.
@@ -143,7 +108,8 @@ Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`).
| `rl` | Full RL pipeline | Production RL training |
| `sft` | Supervised fine-tuning | SFT and hard-distill |
| `inference` | vLLM server | Standalone serving / debugging |
| `evals` | Multi-env evals | Standalone evals / SFT online evals |
Standalone evals (`uv run eval`) are covered by the `eval` skill.
## Key paths
+1 -2
View File
@@ -47,8 +47,7 @@ if _hub_kernels is not None:
try:
return _original_lazy_load_kernel(kernel_name, mapping)
except OfflineModeIsEnabled:
# Return None so NemotronH skips hub kernels; prime-rl's
# _patch_mamba2_use_triton_ssd() uses mamba_ssm directly.
# Return None so callers can use their non-hub implementation.
mapping[kernel_name] = None
return None
+22 -5
View File
@@ -1,11 +1,11 @@
# Dashboard
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
directories (metrics, resolved configs, rollout traces, cited reports,
component logs) at
http://localhost:7788. The trace viewer includes transcript and synchronized
agent timeline views; timeline activities open the corresponding transcript
call. Needs the `dashboard` extra. Every instance also serves
directories (a curated overview, every logged metric, resolved configs,
rollout traces, cited reports, component logs) at
http://localhost:7788. The trace viewer includes transcript, synchronized
agent timeline, and terminal replay views; timeline activities open the
corresponding transcript call. Needs the `dashboard` extra. Every instance also serves
the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
(one dashboard per host per user); `--isolated` serves only the given dirs and
skips the registry. See `skills/dashboard/SKILL.md` for discovery,
@@ -30,6 +30,23 @@ truth, and the viewer reports when IDs, the renderer model, or its tokenizer
are unavailable. Text, advantage, logprob, mask, and content signals apply to
both views; Rendered with Text uses the exact full-sequence decode.
**Replay** plays the selected trace branch as a terminal session. Model
responses, tool commands, and tool results follow their recorded wall-clock
spans, with play/pause, seeking, restart, and speed controls. Providers persist
the full model-call span rather than timestamps for individual tokens, so text
is revealed evenly across that measured span and the UI labels the token cadence
as inferred. Replay defaults to 8× for long coding-agent waits while preserving
their relative timing; 1× restores exact wall time, and speeds up to 32× are
available. In-flight calls show measured progress and recorded output usage even
when the response contains only a tool call. Events from older traces without
timing stay in order and are marked untimed. Prompt context committed at response
time appears at the linked model call's start rather than creating a false blank
delay. **Skip inference** makes every model response immediate while retaining
the recorded delays between tool commands and their outputs. Recorded model
thinking is visible by default and can be toggled from the controls or with
**T** while Replay is open. **Top** (or **Home**) stops following the newest
line and scrolls to the beginning; **Live** (or **End**) resumes following output.
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
The integration suite covers it end to end (`tests/integration/dashboard_smoke.py`
runs after every integration test).
+428 -21
View File
@@ -28,24 +28,27 @@ from prime_rl.entrypoints.dashboard import DAEMON_FILE, DIRS_FILE, STATE_DIR, re
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
from prime_rl.monitors.file.traces.chunks import open_chunk
from prime_rl.monitors.file.traces.index import summarize_episode
from prime_rl.monitors.file.traces.live import LiveFolds, live_etag, live_path, live_rows, stage
from prime_rl.monitors.file.traces.update import branch_node_paths, fold_trace_updates
from prime_rl.utils.config import default_output_dir
from prime_rl.utils.pathing import get_file_monitor_dir
from prime_rl.utils.pathing import get_eval_plan_path, get_file_monitor_dir, get_platform_run_path
from prime_rl.utils.process import set_proc_title
try:
import uvicorn
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
except ModuleNotFoundError as error: # the dashboard ships as an extra
raise SystemExit("the dashboard needs the 'dashboard' extra - install with `uv sync --extra dashboard`") from error
STATIC_DIR = Path(__file__).parent / "static"
MASTER_LOGS = {"trainer.log", "orchestrator.log", "inference.log", "evals.log"}
MASTER_LOGS = {"trainer.log", "orchestrator.log", "inference.log", "eval.log"}
MAX_LOG_CHUNK = 2_000_000
app = FastAPI()
app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=1)
output_dirs: list[Path] = [default_output_dir()]
# run id -> run dir, rebuilt on every /api/runs poll; ids are the run name,
@@ -75,6 +78,8 @@ def _lru_put(cache: OrderedDict, key, value) -> None:
# Append-only file caches keyed by absolute path: line-start offsets and per-episode summaries.
_offsets_cache: OrderedDict[Path, tuple[int, bytes, list[int]]] = OrderedDict()
_summaries_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
_series_keys: dict[tuple[Path, str | None], tuple[int, set[str]]] = {}
"""Per stream and kind filter: how many summaries were scanned for series keys, and the keys."""
_annotations_cache: OrderedDict[Path, tuple[tuple, dict[str, dict], dict[Path, int]]] = OrderedDict()
_index_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
_rows_cache: OrderedDict[Path, tuple] = OrderedDict() # key, rows, entered, by_trace, consumed, last row
@@ -239,7 +244,7 @@ def main_config(run_dir: Path) -> tuple[str, dict]:
return "sft", read_json(configs / "sft.json")
if (configs / "orchestrator.json").exists() or (configs / "trainer.json").exists():
return "rl", read_json(configs / "orchestrator.json") or read_json(configs / "trainer.json")
if (configs / "eval.json").exists(): # verifiers `uv run eval` run dir
if (configs / "eval.json").exists():
return "eval", read_json(configs / "eval.json")
return "other", {}
@@ -258,6 +263,40 @@ def step_numbers(run_dir: Path) -> list[int]:
return sorted({step for _, step in effective_steps(run_dir)})
def eval_env(config: dict) -> str | None:
"""The taskset(s) of an eval run: the ``[[source]]`` list, else a single ``[env]``."""
sources = config.get("source") or []
if sources:
return "+".join(((s.get("env") or {}).get("taskset") or {}).get("id") or "?" for s in sources)
return ((config.get("env") or {}).get("taskset") or {}).get("id")
def source_total_episodes(source: dict) -> int | None:
"""What one ``[[source]]`` will produce, from its config alone: ``num_examples = -1``
means the whole taskset, unknown up front unless the source names its tasks."""
tasks = ((source.get("env") or {}).get("taskset") or {}).get("tasks")
count = source.get("num_examples") or -1
if count < 0 and not tasks:
return None
return (count if count >= 0 else len(tasks)) * (source.get("group_size") or 1)
def eval_totals(config: dict) -> dict[str, int | None]:
"""Expected episodes per eval env (a source's name, else its taskset id)."""
return {
s.get("name") or ((s.get("env") or {}).get("taskset") or {}).get("id") or "?": source_total_episodes(s)
for s in config.get("source") or []
}
def eval_total_episodes(config: dict) -> int | None:
sources = config.get("source") or []
if sources:
totals = [source_total_episodes(s) for s in sources]
return None if any(t is None for t in totals) else sum(totals) or None
return (config.get("num_tasks") or 0) * (config.get("num_rollouts") or 0) or None
def run_meta(run_dir: Path) -> dict:
configs = run_dir / "configs"
run_type, config = main_config(run_dir)
@@ -278,18 +317,43 @@ def run_meta(run_dir: Path) -> dict:
started = orjson.loads(f.readline()).get("time")
except orjson.JSONDecodeError:
started = None
# Liveness reads every artifact the processes touch: an eval ships its metrics at
# epoch end and its first episode can take minutes, but its log ticks every few
# seconds. The launch itself is the start until a metrics row says otherwise.
stream = traces_file(run_dir)
if updated is None and stream is not None: # eval runs have no metrics
updated = stream.stat().st_mtime
started = configs.stat().st_mtime if configs.is_dir() else None
touched = []
for path in (run_dir / "logs" / "latest").glob("*.log"):
try:
touched.append(path.stat().st_mtime)
except FileNotFoundError:
continue # rotated away between the listing and the stat
if stream is not None:
touched.append(stream.stat().st_mtime)
if touched:
updated = max(touched + ([updated] if updated is not None else []))
# An eval writes its only metrics row at the end of the epoch, so its start is the
# launch, not that row; a training run's first row follows its launch closely.
if (started is None or run_type == "eval") and resolved.is_dir():
started = resolved.stat().st_mtime
# An eval has no step horizon; it is complete when its file monitor finalized, which
# only a clean exit does: the stream's live chunk is sealed and nothing plain is left.
finished = run_type == "eval" and stream is not None and stream.is_dir() and not any(stream.glob("*.jsonl"))
plan_path = get_eval_plan_path(run_dir)
eval_plan = orjson.loads(plan_path.read_bytes()) if plan_path.is_file() else {}
platform_path = get_platform_run_path(run_dir)
platform = orjson.loads(platform_path.read_bytes()) if platform_path.is_file() else None
return {
"name": run_dir.name,
"type": run_type,
"finished": finished,
"eval_plan": eval_plan,
"platform": platform,
"model": model_name(config),
"dataset": (config.get("data") or {}).get("name"),
"has_validation": run_type == "sft" and config.get("val") is not None,
"env": ((config.get("env") or {}).get("taskset") or {}).get("id"),
"total_episodes": (config.get("num_tasks") or 0) * (config.get("num_rollouts") or 0) or None,
"env": eval_env(config),
"total_episodes": eval_total_episodes(config),
"eval_totals": eval_totals(config),
"max_steps": config.get("max_steps"),
"train_envs": envs("train"),
"eval_envs": envs("eval"),
@@ -329,8 +393,7 @@ def log_component(rel: Path) -> tuple[str, str]:
"trainer.log": ("trainer", "trainer"),
"orchestrator.log": ("orch", "orchestrator"),
"inference.log": ("infer", "inference"),
"evals.log": ("evals", "evals"),
"eval.log": ("evals", "eval"),
"eval.log": ("eval", "eval"),
}.get(parts[0], ("other", parts[0]))
if parts[0] == "trainer":
if parts[1] == "torchrun": # trainer/torchrun/<rdzv>/attempt_0/<rank>/std{out,err}.log
@@ -377,7 +440,7 @@ def list_logfiles(run: str, attempt: str = "latest") -> dict:
add(path, component, label)
# Include unscoped env logs from runs created before attempt-scoped eval logging.
for path in sorted((run_dir / "logs" / "envs").rglob("*.log")):
add(path, f"env:{path.stem}", f"{path.stem} (evals)")
add(path, f"env:{path.stem}", f"{path.stem} (eval)")
return {"attempt": attempt_num, "attempts": attempts, "files": files}
@@ -408,7 +471,7 @@ def read_log(run: str, file: str, start: int | None = None, end: int | None = No
# ------------------------------------------------------------------------- configs
CONFIG_ORDER = ["rl", "sft", "eval", "evals", "orchestrator", "trainer", "inference"]
CONFIG_ORDER = ["rl", "sft", "eval", "orchestrator", "trainer", "inference"]
def config_rank(name: str) -> tuple[int, str]:
@@ -489,7 +552,7 @@ def read_report(run: str, file: str) -> dict:
# ------------------------------------------------------------------------- metrics
MAX_METRICS_CHUNK = 4 * 1024 * 1024
MAX_METRICS_CHUNK = 16 * 1024 * 1024
"""Per-response cap on /metrics: huge runs stream in chunks the client loops over,
so the first charts paint long before a 100MB metrics.jsonl finishes loading."""
@@ -505,7 +568,9 @@ def read_metrics(run: str, offset: int = 0) -> dict:
rows = []
with path.open("rb") as f:
f.seek(offset)
data = f.read(MAX_METRICS_CHUNK)
# Keep the first response small for quick initial chart rendering.
chunk_size = 4 * 1024 * 1024 if offset == 0 else MAX_METRICS_CHUNK
data = f.read(chunk_size)
if data and b"\n" not in data: # a single line larger than the chunk
data += f.readline()
consumed = data.rfind(b"\n") + 1 # leave a partially-written last line for the next poll
@@ -529,8 +594,7 @@ def _file_size(path: Path) -> int:
def traces_file(run_dir: Path) -> Path | None:
"""The run's episode stream: the chunk directory the file monitor writes, browsed
through its index, or the single ``traces.jsonl`` a verifiers ``uv run eval`` run
writes at the run root."""
through its index, or a bare ``traces.jsonl`` at the run root."""
stream = get_trace_stream(run_dir)
if _file_size(get_index_path(stream)) > 0:
return stream
@@ -759,6 +823,8 @@ def message_text(message: dict) -> str:
def timeline_status(trace: dict) -> str:
if not trace.get("is_completed"):
return "running"
if trace.get("is_timeout"):
return "timeout"
if not trace.get("ok") and (trace.get("errors") or trace.get("stop_condition") == "error"):
return "failed"
return "completed"
@@ -884,6 +950,7 @@ def activity_spans(
if reasoning_tokens is None:
reasoning_tokens = (usage.get("completion_tokens_details") or {}).get("reasoning_tokens")
text = " ".join(message_text(node.get("message") or {}).split())
mask = node.get("mask")
spans.append(
{
"kind": "model_call",
@@ -901,6 +968,7 @@ def activity_spans(
"output_tokens": output_tokens,
"reasoning_tokens": reasoning_tokens,
"cost": usage.get("cost"),
"trainable": any(mask) if isinstance(mask, list) and mask else None,
}
)
return sorted(spans, key=lambda span: span["started_at"] if span["started_at"] is not None else float("inf"))
@@ -991,6 +1059,7 @@ def timeline_lane(
"total_input_tokens": total_input_tokens,
"output_tokens": output_tokens,
"reasoning_tokens": reasoning_tokens,
"latest_context_tokens": context_lengths[-1] if context_lengths else None,
"max_context_tokens": max(context_lengths, default=None),
"total_tokens": total_tokens,
"cost": total("cost"),
@@ -999,8 +1068,254 @@ def timeline_lane(
}
def trace_semantic_edges(trace: dict, trace_index: int) -> list[dict]:
"""Resolve persisted ``MessageNode.semantic_parents`` into timeline edges."""
nodes = trace.get("nodes") or []
call_order = {
node_index: call_index
for call_index, call in enumerate(trace.get("calls") or [])
if isinstance((node_index := call.get("node")), int) and 0 <= node_index < len(nodes)
}
call_nodes = set(call_order)
edges = []
for target_node, node in enumerate(nodes):
if target_node not in call_nodes:
continue
for link in node.get("semantic_parents") or []:
source_node = link.get("node")
edge_type = link.get("type")
if source_node not in call_nodes or not isinstance(edge_type, str):
continue
edges.append(
{
"trace_index": trace_index,
"source_node": source_node,
"target_node": target_node,
"type": edge_type,
}
)
if not edges:
return []
incoming = {edge["target_node"] for edge in edges}
for target_node in sorted(call_nodes - incoming, key=call_order.get):
source_node = physical_continuation_source(nodes, call_nodes, target_node)
if source_node is None or call_order[source_node] >= call_order[target_node]:
continue
edges.append(
{
"trace_index": trace_index,
"source_node": source_node,
"target_node": target_node,
"type": "continuation",
"inferred": True,
}
)
return edges
def physical_continuation_source(nodes: list[dict], call_nodes: set[int], target_node: int) -> int | None:
"""Recover a missing continuation only from a completed tool round-trip."""
between = []
visited = {target_node}
cursor = nodes[target_node].get("parent")
while isinstance(cursor, int) and 0 <= cursor < len(nodes) and cursor not in visited:
if cursor in call_nodes:
source_node = cursor
break
visited.add(cursor)
between.append(cursor)
cursor = nodes[cursor].get("parent")
else:
return None
source_message = nodes[source_node].get("message") or {}
tool_call_ids = {
tool_call.get("id")
for tool_call in source_message.get("tool_calls") or []
if isinstance(tool_call, dict) and isinstance(tool_call.get("id"), str)
}
if not tool_call_ids or not between:
return None
for node_index in between:
message = nodes[node_index].get("message") or {}
if message.get("role") != "tool" or message.get("tool_call_id") not in tool_call_ids:
return None
return source_node
def semantic_context_lanes(
trace: dict,
trace_index: int,
role: str,
edges: list[dict],
) -> list[dict]:
"""Project continuation components as execution-context timeline lanes.
``continuation`` keeps calls in one context. ``subagent_call`` creates a child
agent, ``compaction_attempt`` creates a summary leaf beside its source context,
and ``compaction`` starts a new context for the same agent. Other edge labels
remain visible but do not invent session semantics.
"""
nodes = trace.get("nodes") or []
call_nodes = {
node_index
for call in trace.get("calls") or []
if isinstance((node_index := call.get("node")), int) and 0 <= node_index < len(nodes)
}
if not call_nodes or not edges:
return []
representatives = {node_index: node_index for node_index in call_nodes}
def find(node_index: int) -> int:
while representatives[node_index] != node_index:
representatives[node_index] = representatives[representatives[node_index]]
node_index = representatives[node_index]
return node_index
def union(left: int, right: int) -> None:
left_root = find(left)
right_root = find(right)
if left_root != right_root:
representatives[right_root] = left_root
for edge in edges:
if edge["type"] == "continuation":
union(edge["source_node"], edge["target_node"])
components: dict[int, set[int]] = {}
for node_index in call_nodes:
components.setdefault(find(node_index), set()).add(node_index)
component_for = {
node_index: component for component, node_indexes in components.items() for node_index in node_indexes
}
component_activities = {
component: activity_spans(trace, node_indexes) for component, node_indexes in components.items()
}
def component_start(component: int) -> float:
activities = component_activities[component]
starts = [span["started_at"] for span in activities if span["started_at"] is not None]
timestamps = [
nodes[node_index].get("timestamp")
for node_index in components[component]
if nodes[node_index].get("timestamp") is not None
]
return min(starts or timestamps, default=float("inf"))
ordered_components = sorted(components, key=lambda component: (component_start(component), component))
cross_edges = [edge for edge in edges if component_for[edge["source_node"]] != component_for[edge["target_node"]]]
created_components = {
component_for[edge["target_node"]]
for edge in cross_edges
if edge["type"] in {"subagent_call", "compaction_attempt", "compaction"}
}
root_components = [component for component in ordered_components if component not in created_components]
# component -> (agent label, depth, context index)
identities: dict[int, tuple[str, int, int]] = {}
unlinked_components = set()
if root_components:
identities[root_components[0]] = (role, 0, 0)
for index, component in enumerate(root_components[1:], start=1):
identities[component] = (f"unlinked {index}", 0, 0)
unlinked_components.add(component)
subagent_number = 0
changed = True
while changed:
changed = False
for edge in cross_edges:
source = component_for[edge["source_node"]]
target = component_for[edge["target_node"]]
if source not in identities or target in identities:
continue
agent_label, depth, context_index = identities[source]
if edge["type"] == "subagent_call":
subagent_number += 1
identities[target] = (f"subagent {subagent_number}", depth + 1, 0)
elif edge["type"] == "compaction_attempt":
identities[target] = (agent_label, depth, context_index)
elif edge["type"] == "compaction":
identities[target] = (agent_label, depth, context_index + 1)
else:
continue
changed = True
unlinked_index = len(unlinked_components)
for component in ordered_components:
if component not in identities:
unlinked_index += 1
identities[component] = (f"unlinked {unlinked_index}", 0, 0)
unlinked_components.add(component)
lanes = []
accepted_attempt_nodes = {edge["source_node"] for edge in cross_edges if edge["type"] == "compaction"}
attempt_by_component = {
component_for[edge["target_node"]]: {
"source_node": edge["source_node"],
"target_node": edge["target_node"],
"accepted": edge["target_node"] in accepted_attempt_nodes,
}
for edge in cross_edges
if edge["type"] == "compaction_attempt"
}
for component in ordered_components:
agent_label, depth, context_index = identities[component]
activities = component_activities[component]
start = component_start(component)
end = max(
[span["ended_at"] for span in activities if span.get("ended_at") is not None]
+ [
nodes[node_index].get("timestamp")
for node_index in components[component]
if nodes[node_index].get("timestamp") is not None
],
default=None,
)
completed = bool(trace.get("is_completed"))
label = f"{agent_label} · context {context_index}"
lifecycle = (
[
{
"kind": "agent",
"label": label,
"track": "lifecycle",
"started_at": start,
"ended_at": end if completed else None,
"status": "completed" if completed else "running",
}
]
if start != float("inf")
else []
)
lane = timeline_lane(
trace,
trace_index,
label=label,
depth=depth + 1,
branch=True,
lifecycle=lifecycle,
activities=activities,
)
lane["context"] = {
"agent": agent_label,
"index": context_index,
}
if component in unlinked_components:
lane["context"]["unlinked"] = True
if component in attempt_by_component:
lane["compaction_attempt"] = attempt_by_component[component]
lanes.append(lane)
return lanes
def project_episode_timeline(episode: dict) -> dict:
lane_groups = []
semantic_lane_groups = []
semantic_edges = []
for trace_index, trace in enumerate(episode.get("traces") or []):
nodes = trace.get("nodes") or []
branch_paths = branch_node_paths(nodes)
@@ -1085,9 +1400,22 @@ def project_episode_timeline(episode: dict) -> dict:
)
branches.sort(key=lambda item: (item[0] if item[0] is not None else float("inf"), item[1]))
lane_groups.append((parent, [lane for _, _, lane in branches]))
trace_edges = trace_semantic_edges(trace, trace_index)
semantic_lanes = semantic_context_lanes(trace, trace_index, role, trace_edges)
if semantic_lanes:
semantic_lane_groups.append((parent, semantic_lanes))
semantic_edges.extend(trace_edges)
lane_groups.sort(key=lambda group: group[0]["started_at"] if group[0]["started_at"] is not None else float("inf"))
lanes = [lane for parent, children in lane_groups for lane in (parent, *children)]
return {"lanes": lanes}
semantic_lane_groups.sort(
key=lambda group: group[0]["started_at"] if group[0]["started_at"] is not None else float("inf")
)
semantic_lanes = [lane for parent, children in semantic_lane_groups for lane in (parent, *children)]
return {
"lanes": lanes,
"semantic_lanes": semantic_lanes,
"semantic_edges": semantic_edges,
}
NICE_BINS = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400]
@@ -1210,7 +1538,7 @@ def row_filter(
return False
if episode is not None and row.get("id") != episode:
return False
if errors_only and not (row.get("num_errors") or not row.get("ok")):
if errors_only and row.get("ok"):
return False
arrival = row.get("arrival") or 0
return not ((start is not None and arrival < start) or (end is not None and arrival >= end))
@@ -1425,6 +1753,51 @@ def rendered_token_text(trace: dict, model: str | None) -> dict:
}
_live_folds = LiveFolds()
"""The dashboard's incremental folds of every run's live files."""
@app.get("/api/runs/{run}/live")
def live_traces(run: str, etag: str | None = None) -> dict:
"""The run's in-flight traces, folded from the env servers' streamed deltas
(``monitors/file/traces/live/<trace_id>.jsonl``): one row per live trace with its
phase, turns, tokens, cost, elapsed time and last message. A trace whose file is
gone has finished and sits in the stream. ``etag`` is the fingerprint the client
last saw: an unchanged live set answers a poll with ``{unchanged}``."""
run_dir = get_run_dir(run)
current = live_etag(run_dir)
if etag is not None and etag == current:
return {"unchanged": True}
return {"time": time.time(), "etag": current, "rows": live_rows(run_dir, _live_folds)}
@app.get("/api/runs/{run}/live/{trace_id}")
def live_trace(run: str, trace_id: str, etag: str | None = None) -> dict:
"""One in-flight trace assembled from its deltas, shaped like a stream record (an
episode with this one trace) so the trace viewer renders it as it grows. ``etag``
is the file size the client last folded: nothing appended means ``{unchanged}``."""
path = live_path(get_run_dir(run), trace_id)
try:
size = path.stat().st_size # before the read: a delta landing in between shows up next poll
except FileNotFoundError:
raise HTTPException(404, "live trace not found - its episode finished or never streamed")
if etag is not None and etag == str(size):
return {"unchanged": True}
folded = _live_folds.read(path)
if folded is None:
raise HTTPException(404, "live trace not found - its episode finished or never streamed")
dispatch, trace = folded
return {
"id": None,
"etag": str(size),
"kind": dispatch.get("kind"),
"env": {"name": dispatch.get("env")},
"group": {"id": dispatch.get("group")},
"live": {**dispatch, "stage": stage(trace)},
"traces": [trace],
}
@app.get("/api/runs/{run}/episodes/series")
def episode_series(run: str, kind: str | None = None, etag: str | None = None, after: int = 0) -> dict:
"""Per-episode series over the stream (x = arrival order): reward, shape, and the
@@ -1436,15 +1809,38 @@ def episode_series(run: str, kind: str | None = None, etag: str | None = None, a
if etag is not None and etag == current_etag:
return {"unchanged": True, "etag": current_etag}
summaries = [s for s in episode_summaries(path) if not kind or s.get("kind") == kind]
keys: set[str] = set()
for s in summaries:
# the key set only grows: rescan the summaries past the ones already scanned
with _lock:
scanned, keys = _series_keys.get((path, kind)) or (0, set())
if scanned > len(summaries):
scanned, keys = 0, set()
for s in summaries[scanned:]:
keys.update(
k
for k in ("reward", "advantage", "cost", "turns", "branches", "input_tokens", "output_tokens")
for k in (
"env",
"group",
"line",
"ok",
"num_errors",
"truncated",
"timeout",
"stop_condition",
"duration",
"reward",
"advantage",
"cost",
"turns",
"branches",
"input_tokens",
"output_tokens",
)
if s.get(k) is not None
)
for group in ("rewards", "metrics", "timing"):
keys.update(f"{group}/{name}" for name in s.get(group) or {})
with _lock:
_series_keys[(path, kind)] = (len(summaries), keys)
def value(s: dict, key: str):
group, _, name = key.partition("/")
@@ -1720,6 +2116,17 @@ def get_episode_timeline(run: str, line: int) -> dict:
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
@app.middleware("http")
async def revalidate_static(request, call_next):
"""The page and its assets change with the checkout the daemon runs; a reload must
revalidate them (an ETag answers 304 when unchanged) instead of trusting a heuristic
freshness from ``Last-Modified``."""
response = await call_next(request)
if request.url.path == "/" or request.url.path.startswith("/static/"):
response.headers["Cache-Control"] = "no-cache"
return response
@app.get("/")
def index() -> FileResponse:
return FileResponse(STATIC_DIR / "index.html")
File diff suppressed because it is too large Load Diff
+71 -10
View File
@@ -21,29 +21,57 @@
</div>
<nav id="tabs">
<button data-tab="config">Config</button>
<button data-tab="metrics" class="active">Metrics</button>
<button data-tab="overview" class="active">Overview</button>
<button data-tab="metrics">Metrics</button>
<button data-tab="traces">Traces</button>
<button data-tab="report">Report</button>
<button data-tab="logs">Logs</button>
</nav>
<label class="toggle" title="apply agent view commands as they arrive"><input type="checkbox" id="follow-toggle" checked><span class="dot"></span>follow</label>
<label class="toggle" title="poll for updates"><input type="checkbox" id="live-toggle" checked><span class="dot"></span>live</label>
<div id="platform-wrap" class="dd-wrap" hidden>
<a id="platform-link" class="btn platform" target="_blank" rel="noopener">view on platform<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 17L17 7M9 7h8v8"></path></svg></a>
<button id="platform-btn" class="btn dd-btn platform" hidden>view on platform</button>
<div class="dd-menu" id="platform-menu" hidden></div>
</div>
</header>
<div id="run-overview"></div>
<main>
<section id="tab-metrics">
<section id="tab-overview">
<div class="controls">
<div class="seg" id="metrics-mode">
<button data-mode="overview" class="active">Overview</button>
<button data-mode="all">All</button>
<div id="overview-filter-wrap" class="dd-wrap" hidden>
<button id="overview-filter-btn" class="btn dd-btn" title="filter">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
</button>
<div class="dd-menu dd-filters" id="overview-filter-menu" hidden>
<div class="dd-sec">filter</div>
<label class="dd-row" id="overview-env-row"><span class="t-label">env</span>
<select id="overview-env"></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="overview-errors"><span class="dot"></span>include errors</label>
</div>
</div>
<input id="overview-search" class="search" type="search" placeholder="regex filter, e.g. reward or ^inference/">
<label class="ctl">smooth <input id="overview-smooth" type="range" min="1" max="50" value="1"><span id="overview-smooth-val">off</span></label>
<span id="overview-status" class="muted"></span>
<div class="spacer"></div>
<button id="overview-collapse" class="btn">collapse</button>
<button id="overview-expand" class="btn">expand</button>
</div>
<div id="overview-body"></div>
<div id="swarm-tip" hidden></div>
</section>
<section id="tab-metrics" hidden>
<div class="controls">
<input id="metrics-search" class="search" type="search" placeholder="regex filter, e.g. ^entropy/ or reward">
<label class="ctl">smooth <input id="smooth-range" type="range" min="1" max="50" value="1"><span id="smooth-val">off</span></label>
<label class="ctl">smooth <input id="metrics-smooth" type="range" min="1" max="50" value="1"><span id="metrics-smooth-val">off</span></label>
<span id="metrics-status" class="muted"></span>
<div class="spacer"></div>
<div class="seg" id="all-layout" hidden>
<div class="seg" id="metrics-layout">
<button data-layout="flat">Flat</button>
<button data-layout="nested">Nested</button>
</div>
@@ -91,6 +119,12 @@
</button>
<div class="dd-menu dd-filters" id="trace-filter-menu" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row"><span class="t-label">status</span>
<div class="seg toggle-seg" id="trace-status-filter">
<button data-status="live" class="on" title="live rollouts, streamed by their env servers">live</button>
<button data-status="done" class="on" title="episodes in the finished stream">completed</button>
</div>
</div>
<div class="dd-row"><span class="t-label">kind</span>
<div class="seg toggle-seg" id="trace-kinds">
<button data-kind="train" class="on">train</button>
@@ -130,9 +164,13 @@
</div>
<div id="episode-table-wrap">
<table id="episode-table">
<colgroup>
<col class="c-line"><col class="c-phase"><col class="c-span"><col class="c-kind"><col class="c-env"><col class="c-group">
<col class="c-tok"><col class="c-turns"><col class="c-branches"><col class="c-stop"><col class="c-reward">
</colgroup>
<thead><tr>
<th>#</th><th>arrived</th><th>took</th><th>kind</th><th>env</th><th>group</th><th>reward</th>
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>status</th>
<th>#</th><th>phase</th><th title="when the rollout was dispatched, when its episode arrived, and how long that took (or has taken so far)">dispatched → arrived</th><th>kind</th><th>env</th><th>group</th>
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>reward</th>
</tr></thead>
<tbody></tbody>
</table>
@@ -179,7 +217,7 @@
<aside id="tm-left">
<div class="tm-head tm-stephead" id="tm-stephead">
<button id="tm-step-prev" class="btn tm-nav" title="previous step">‹</button>
<span id="tm-step-label"></span>
<span id="tm-step-label"></span><span id="tm-live-label" class="muted"></span>
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
</div>
<div class="tm-head tm-ctlrow">
@@ -190,6 +228,12 @@
</button>
<div class="dd-menu dd-filters" id="tm-filter-menu" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row"><span class="t-label">status</span>
<div class="seg toggle-seg" id="tm-status-filter">
<button data-status="live" class="on" title="live rollouts, streamed by their env servers">live</button>
<button data-status="done" class="on" title="episodes in the finished stream">completed</button>
</div>
</div>
<div class="dd-row"><span class="t-label">kind</span>
<div class="seg toggle-seg" id="tm-kinds">
<button data-kind="train" class="on">train</button>
@@ -232,6 +276,13 @@
<div class="seg" id="tm-view">
<button data-view="transcript" class="active">Transcript</button>
<button data-view="timeline">Timeline</button>
<button data-view="replay">Replay</button>
<button data-view="semantic">Semantic</button>
</div>
<div id="tm-semantic-nav" class="tm-semantic-nav" hidden>
<button id="tm-episode-prev" class="btn tm-nav" title="previous episode">‹</button>
<span id="tm-episode-label"></span>
<button id="tm-episode-next" class="btn tm-nav" title="next episode">›</button>
</div>
<div class="spacer"></div>
<div class="seg" id="trace-view-mode">
@@ -251,12 +302,22 @@
<button id="tm-expand" class="btn">expand</button>
<button id="drawer-close" class="btn">✕</button>
</div>
<div id="tm-episode-errors" hidden></div>
<div class="tm-head tm-tabs-row" id="tm-tabs-row" hidden>
<div id="tm-trace-tabs" class="seg" hidden></div>
<div id="tm-branch-tabs" class="seg" hidden></div>
<div id="tm-evidence-tabs" class="seg" hidden></div>
</div>
<div id="tm-messages"></div>
<div id="tm-timeline" hidden></div>
<aside id="sg-inspector" hidden>
<div class="sg-inspector-head">
<span id="sg-inspector-title">Model call</span>
<button id="sg-inspector-close" class="btn" title="close inspector">✕</button>
</div>
<div id="sg-inspector-body"></div>
<button id="sg-open-transcript" class="btn">open in transcript</button>
</aside>
</section>
<aside id="tm-right">
<div class="tm-head"><span class="tm-title">Overview</span></div>
+582 -13
View File
@@ -15,6 +15,7 @@
--accent: #b6ff3c;
--negative: #ff4539;
--timeout: #ffd166;
--positive: #b6ff3c;
--infra: #4a9eff;
--risk: #ff6b4a;
@@ -90,6 +91,15 @@ body {
#tabs button:hover { color: var(--grey-6); }
#tabs button.active { color: var(--accent); border-bottom-color: var(--accent); }
#topbar .toggle { margin-left: auto; }
#topbar .toggle + .toggle { margin-left: 0; }
#platform-wrap { margin-left: 14px; }
/* looks like the run and compare pickers; the arrow says it leaves the page */
#platform-wrap .platform { display: inline-flex; align-items: center; gap: 8px; text-decoration: none; cursor: pointer; }
#platform-wrap .platform:hover { color: var(--accent); border-color: var(--accent); }
#platform-wrap .platform.disabled { color: var(--grey-4); border-color: var(--grey-3); cursor: default; }
#platform-menu { left: auto; right: 0; min-width: 180px; }
#platform-menu .dd-opt { display: block; color: var(--grey-5); text-decoration: none; }
#platform-menu .dd-opt:hover { color: var(--grey-6); }
select, .search, .btn {
background: transparent;
@@ -297,12 +307,14 @@ main > section { flex: 1; min-height: 0; display: flex; flex-direction: column;
/* --------------------------------------------------------------- metrics */
/* stable gutter: no layout shift when collapsing sections hides the scrollbar */
#metrics-body { flex: 1; overflow-y: auto; scrollbar-gutter: stable; min-height: 0; padding-right: 10px; }
#overview-body, #metrics-body { flex: 1; overflow-y: auto; scrollbar-gutter: stable; min-height: 0; padding-right: 10px; }
.chart-card.dragging { opacity: 0.45; }
/* one 12px rhythm everywhere: section-to-section, header-to-panes, pane-to-pane */
details.section { margin-bottom: 12px; }
/* nested sections (all-mode key tree) indent one step */
details.section details.section { margin-left: 14px; }
/* a section's own panes keep the rhythm before the sections nested under them */
details.section > .chart-grid:not(:last-child) { margin-bottom: 12px; }
details.section:not([open]) > summary { margin-bottom: 0; }
/* section headers are full-width bars so the clickable region is obvious */
details.section > summary {
@@ -336,9 +348,89 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
text-overflow: ellipsis;
}
.stat-value { font-size: 20px; color: var(--grey-6); margin: 6px 0 0; }
.eval-progress { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
.ep-bar { flex: 1; height: 6px; background: var(--grey-2); border: 1px solid var(--hairline); }
.ep-fill { height: 100%; background: var(--accent); }
/* eval progress: one cell per expected episode */
.eval-progress { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; }
.ep-head { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
.ep-row { display: flex; align-items: center; gap: 12px; }
.ep-row .ep-blocks { flex: 1; }
.ep-pct { font-size: 13px; color: var(--grey-6); min-width: 4ch; text-align: right; }
.ep-head .name { font-size: 14px; color: var(--grey-6); }
.ep-blocks { display: flex; gap: 2px; height: 28px; }
.ep-cell { flex: 1; min-width: 0; background: var(--grey-2); border: 1px solid var(--hairline); }
.ep-cell.done { background: var(--accent); border-color: var(--accent); cursor: pointer; }
.ep-cell.done.err { background: var(--negative); border-color: var(--negative); }
.ep-cell.done.timeout { background: var(--timeout); border-color: var(--timeout); }
.ep-cell.done:hover { filter: brightness(1.2); }
.ep-cell.live { border-color: var(--accent); background: rgba(182, 255, 60, 0.18); animation: live-pulse 1.6s ease-in-out infinite; cursor: pointer; }
/* distributions: a beeswarm per metric, a faint boxplot behind it, stats on hover */
#tab-overview { position: relative; }
.swarm-card .chart-head { cursor: default; }
.swarm-host { height: var(--pane-h, 150px); margin-top: 6px; }
.swarm { display: block; }
.swarm .sw-bg { fill: transparent; }
.swarm circle { fill: var(--accent); fill-opacity: 0.7; cursor: pointer; }
.swarm circle.err { fill: var(--negative); }
.swarm circle.timeout { fill: var(--timeout); }
.swarm circle:hover { fill-opacity: 1; stroke: var(--grey-6); stroke-width: 1; }
.sw-axis { stroke: var(--grey-3); stroke-width: 1; }
.sw-grid { stroke: var(--hairline-faint); stroke-width: 1; }
.sw-box rect { fill: var(--hairline-faint); stroke: var(--grey-3); stroke-width: 1; }
.sw-box line { stroke: var(--grey-3); stroke-width: 1; }
.sw-box .median { stroke: var(--grey-4); stroke-width: 1.5; }
/* timing pane: breadcrumb, icicle of the zoomed node, per-episode strips, tree legend */
/* eval metrics sections: flat, a muted heading each */
.eval-sec { margin-bottom: 18px; }
.eval-sec-title { text-transform: uppercase; font-size: 10px; letter-spacing: 0.08em; color: var(--grey-4); border-bottom: 1px solid var(--hairline); padding-bottom: 4px; margin-bottom: 10px; }
.phase-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; margin-right: 6px; vertical-align: middle; }
.timing-pane .chart-head { cursor: default; }
.tm-crumbs { font-size: 12px; color: var(--grey-5); }
.tm-crumb.current { color: var(--grey-6); }
.tm-legend { display: flex; flex-wrap: wrap; gap: 4px 18px; margin: 4px 0 14px; font-size: 11px; color: var(--grey-5); }
.tm-icicle svg { display: block; margin-bottom: 14px; }
.tm-seg text { fill: #111; font-size: 10px; pointer-events: none; }
.tm-strip-seg { cursor: pointer; }
.tm-row-hit { fill: transparent; cursor: pointer; }
.tm-line.dim { opacity: 0.3; }
.tm-strip-seg.dim { opacity: 0.2; }
.tm-strip-seg:hover { filter: brightness(1.25); }
.tm-line.err { fill: var(--negative); }
.tm-line.timeout { fill: var(--timeout); }
.comp-pane [data-part].dim { opacity: 0.2; }
.comp-pane .tm-node.dim { opacity: 0.35; }
/* the summary is one row whatever the count: the tiles share the width equally */
.sum-grid { margin-bottom: 4px; display: grid; grid-template-columns: none; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); gap: 12px; }
.sum-tile { cursor: default; padding: 14px 16px; min-height: 96px; display: flex; flex-direction: column; justify-content: center; }
.sum-tile .stat-label, .sum-tile .stat-value { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.sum-tile .stat-value { font-size: clamp(16px, 1.7vw, 24px); margin-top: 8px; }
.sum-tile.rate-warn .stat-value { color: #ffd166; }
.sum-tile.rate-bad .stat-value { color: var(--negative); }
.sum-tile.rate-timeout .stat-value { color: var(--timeout); }
.tm-note { font-size: 10px; margin-top: 4px; }
.tm-more { color: var(--grey-5); cursor: pointer; text-decoration: underline dotted; text-underline-offset: 3px; }
.tm-more:hover { color: var(--grey-6); }
.tm-strips.scroll { max-height: 560px; overflow-y: auto; }
.tm-node { white-space: nowrap; cursor: default; }
.tm-node:hover { color: var(--grey-6); }
/* constants as chips; counted dot plots for few-valued metrics */
.const-row { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; }
.const-chip { font-size: 12px; color: var(--grey-6); background: var(--grey-2); border: 1px solid var(--hairline); padding: 4px 10px; }
.const-chip .k { color: var(--grey-4); font-size: 10px; text-transform: uppercase; letter-spacing: 0.05em; margin-right: 8px; }
.dp-count { fill: var(--grey-5); font-size: 10px; }
#swarm-tip {
position: absolute;
z-index: 50;
pointer-events: none;
background: var(--grey-1);
border: 1px solid var(--grey-3);
padding: 6px 8px;
min-width: 160px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
font-size: 11px;
}
#swarm-tip .tip-head { color: var(--accent); margin-bottom: 4px; }
#swarm-tip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
#swarm-tip .tip-row span:first-child { color: var(--grey-4); }
.ep-label {
font-size: 10px;
letter-spacing: var(--track-caps);
@@ -443,7 +535,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
/* metrics regex filter (overview + all) */
#metrics-search, #config-search, #log-search { flex: 1; max-width: 460px; }
#overview-search, #metrics-search, #config-search, #log-search { flex: 1; max-width: 460px; }
/* wandb-style resize handles on every chart card: right edge = width, bottom
edge = height, corner = both. Resizing one pane resizes all of them. */
@@ -633,7 +725,7 @@ mark.hit {
.sb-cell.eval:hover::after { background: var(--grey-6); }
#trace-filter-menu {
right: 0;
min-width: 240px;
min-width: 320px;
display: flex;
flex-direction: column;
gap: 8px;
@@ -643,7 +735,21 @@ mark.hit {
#episode-table-wrap { flex: 1; overflow: auto; border: 1px solid var(--hairline); background: var(--grey-1); min-height: 0; }
#episode-table .vpad td { padding: 0; border: 0; }
#episode-table { width: 100%; border-collapse: collapse; font-size: 11.5px; }
/* fixed columns: a poll that swaps rows in or out never reflows the table. The sized
columns hold mono text whose width follows the font, not the window, so they are
measured in characters; env and stop take what is left, and below the minimum the
wrap scrolls sideways instead of crushing them. */
#episode-table { width: 100%; min-width: 190ch; border-collapse: collapse; font-size: 11.5px; table-layout: fixed; }
#episode-table col.c-line { width: 7.5ch; }
#episode-table col.c-phase { width: 11.5ch; }
#episode-table col.c-span { width: 50ch; }
#episode-table col.c-kind { width: 8.5ch; }
#episode-table col.c-group { width: 13.5ch; }
#episode-table col.c-tok { width: 25ch; }
#episode-table col.c-turns { width: 9ch; }
#episode-table col.c-branches { width: 12.5ch; }
#episode-table col.c-reward { width: 10.5ch; }
#episode-table td, #episode-table th { overflow: hidden; text-overflow: ellipsis; }
#episode-table th {
text-align: left;
font: 400 10px var(--font-mono);
@@ -680,6 +786,10 @@ mark.hit {
display: grid;
grid-template-columns: 280px minmax(0, 1fr) 320px;
}
#trace-modal.semantic-view { grid-template-columns: minmax(0, 1fr); }
#trace-modal.semantic-view #tm-left,
#trace-modal.semantic-view #tm-right { display: none; }
#trace-modal.semantic-view #tm-main { grid-column: 1; position: relative; }
.tm-head {
display: flex;
align-items: center;
@@ -694,7 +804,19 @@ mark.hit {
overflow-y: hidden;
scrollbar-width: thin;
}
#tm-evidence-tabs [data-evidence="task"].active { color: var(--chart-3); }
#tm-evidence-tabs [data-evidence="judge"].active { color: #7adfff; }
#tm-evidence-tabs { margin-left: auto; }
.tm-title { font-size: 12px; font-weight: 500; color: var(--grey-6); white-space: nowrap; }
.tm-semantic-nav { display: flex; align-items: center; gap: 7px; min-width: 0; }
#tm-episode-label {
max-width: 260px;
overflow: hidden;
color: var(--grey-5);
font-size: 10.5px;
text-overflow: ellipsis;
white-space: nowrap;
}
#tm-left { border-right: 1px solid var(--hairline); display: flex; flex-direction: column; min-height: 0; }
#tm-left .search { margin: 10px 14px 6px; }
#tm-list { flex: 1; overflow-y: auto; padding: 4px 8px 10px; }
@@ -717,6 +839,9 @@ mark.hit {
.tm-item.active { background: var(--grey-2); border-color: var(--grey-3); color: var(--grey-6); }
.tm-item.err { background: rgba(255, 69, 57, 0.08); border-color: var(--negative); }
.tm-item.err:hover, .tm-item.err.active { background: rgba(255, 69, 57, 0.16); }
.tm-item.timeout { background: rgba(255, 209, 102, 0.08); border-color: var(--timeout); }
.tm-item.timeout:hover, .tm-item.timeout.active { background: rgba(255, 209, 102, 0.16); }
.tm-item.retried { border-left: 2px dotted var(--grey-4); }
.tm-item .tm-reward { margin-left: auto; }
.tm-nav { padding: 0 8px; height: 24px; }
.tm-stephead { justify-content: space-between; background: var(--grey-2); min-height: 40px; }
@@ -738,11 +863,39 @@ mark.hit {
#tm-messages { display: flex; flex: 1; flex-direction: column; overflow-y: auto; padding: 14px 16px; }
#tm-messages > * { flex-shrink: 0; }
#tm-timeline { flex: 1; min-height: 0; overflow: auto; padding: 14px 16px 24px; }
#tm-timeline.semantic-canvas { padding: 0; background: var(--grey-1); }
#tm-right { border-left: 1px solid var(--hairline); overflow-y: auto; min-height: 0; }
#tm-meta { padding: 12px 14px; }
/* episode timeline: lifecycle spans above exact model-call activity */
.tl-shell { min-width: 780px; border: 1px solid var(--hairline); }
.tl-shell { position: relative; min-width: 780px; border: 1px solid var(--hairline); }
.tl-edge-legend {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 14px;
min-height: 34px;
padding: 7px 10px;
border-bottom: 1px solid var(--hairline);
color: var(--grey-4);
font-size: 9px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.tl-edge-legend-title { color: var(--grey-5); }
.tl-edge-key { color: var(--grey-5); white-space: nowrap; }
.tl-edge-key i {
display: inline-block;
width: 18px;
margin-right: 6px;
vertical-align: 3px;
border-top: 2px solid var(--grey-4);
}
.tl-edge-key i.subagent-call { border-color: var(--infra); }
.tl-edge-key i.subagent-return { border-color: var(--risk); }
.tl-edge-key i.compaction-attempt { border-color: var(--chart-2); border-top-style: dotted; }
.tl-edge-key i.compaction { border-color: var(--chart-2); border-top-style: dashed; }
.tl-edge-key i.custom { border-color: var(--accent); border-top-style: dotted; }
.tl-head, .tl-lane {
display: grid;
grid-template-columns: minmax(160px, 220px) minmax(390px, 1fr) 105px 150px;
@@ -773,7 +926,7 @@ mark.hit {
.tl-label-meta { color: var(--grey-4); font-size: 9.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tl-track { position: relative; height: 42px; margin: 11px 0; border: 1px solid var(--hairline); overflow: hidden; }
.tl-gridline { position: absolute; top: 0; bottom: 0; border-left: 1px solid var(--hairline-faint); pointer-events: none; }
.tl-span { position: absolute; min-width: 3px; cursor: pointer; border: 0; padding: 0; }
.tl-span { position: absolute; z-index: 2; min-width: 3px; cursor: pointer; border: 0; padding: 0; }
.tl-span.lifecycle { top: 7px; height: 13px; opacity: 0.78; }
.tl-span.activity { top: 28px; height: 6px; background: var(--grey-4); }
.tl-span.activity.shared { opacity: 0.28; }
@@ -787,11 +940,11 @@ mark.hit {
.tl-time { color: var(--grey-5); font-size: 11px; }
.tl-time .muted { display: block; font-size: 9.5px; }
.tl-outcome { display: flex; flex-direction: column; align-items: flex-start; gap: 5px; font-size: 9.5px; }
.tl-state, .tl-reward { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
.tl-state { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
.tl-state.completed { color: var(--positive); }
.tl-state.failed { color: var(--negative); }
.tl-state.timeout { color: var(--timeout); }
.tl-state.running { color: var(--infra); }
.tl-reward { color: var(--chart-3); }
.tl-tooltip {
position: fixed;
z-index: 60;
@@ -809,8 +962,223 @@ mark.hit {
.tl-tooltip dd { color: var(--grey-6); margin: 0; }
.tl-tooltip-hint { color: var(--grey-4); border-top: 1px solid var(--hairline); margin-top: 9px; padding-top: 7px; font-size: 9.5px; }
/* Semantic view: ordinal causal flow down the page. Agent identities occupy
reusable concurrency slots, so width reflects peak fan-out rather than the
total number of children created over a rollout. */
.semantic-canvas > .tl-edge-legend {
position: sticky;
top: 0;
left: 0;
z-index: 9;
width: max-content;
min-width: 100%;
box-sizing: border-box;
background: var(--grey-1);
font-size: 11px;
}
.sg-shell {
position: relative;
min-width: 100%;
overflow: clip;
background: var(--grey-1);
}
.sg-lane-band {
position: absolute;
inset-block: 0;
z-index: 0;
border-inline: 1px solid rgba(255, 255, 255, 0.035);
background: rgba(255, 255, 255, 0.009);
pointer-events: none;
}
.sg-lane-band.root {
border-inline-color: rgba(182, 255, 60, 0.07);
background: rgba(182, 255, 60, 0.012);
}
.sg-edge-layer { position: absolute; inset: 0; z-index: 1; pointer-events: none; overflow: visible; }
.sg-lifeline {
fill: none;
stroke: var(--lane-color);
stroke-width: 1.5;
vector-effect: non-scaling-stroke;
opacity: 0.38;
}
.sg-edge {
fill: none;
stroke: var(--grey-4);
stroke-width: 1.4;
stroke-linecap: round;
stroke-linejoin: round;
vector-effect: non-scaling-stroke;
opacity: 0.68;
}
.sg-edge.continuation { opacity: 0.34; }
.sg-edge.subagent-call { stroke: var(--infra); stroke-width: 2.2; opacity: 0.9; }
.sg-edge.subagent-return { stroke: var(--risk); stroke-width: 2.2; opacity: 0.9; }
.sg-edge.compaction-attempt { stroke: var(--chart-2); stroke-dasharray: 2 4; opacity: 0.66; }
.sg-edge.compaction { stroke: var(--chart-2); stroke-dasharray: 5 4; opacity: 0.9; }
.sg-edge.custom { stroke: var(--accent); stroke-dasharray: 2 4; opacity: 0.9; }
#sg-arrow-continuation path { fill: var(--grey-4); }
#sg-arrow-subagent-call path { fill: var(--infra); }
#sg-arrow-subagent-return path { fill: var(--risk); }
#sg-arrow-compaction-attempt path { fill: var(--chart-2); }
#sg-arrow-compaction path { fill: var(--chart-2); }
#sg-arrow-custom path { fill: var(--accent); }
.sg-agent-label {
position: absolute;
z-index: 6;
display: flex;
flex-direction: column;
align-items: center;
gap: 1px;
padding: 2px 6px;
background: var(--grey-1);
pointer-events: none;
white-space: nowrap;
}
.sg-agent-label.unlinked {
outline: 1px dashed var(--grey-3);
}
.sg-agent-label.unlinked .sg-agent-name,
.sg-agent-label.unlinked .sg-context-name {
color: var(--grey-5);
}
.sg-agent-name,
.sg-context-name {
padding: 0;
border: 0;
background: transparent;
cursor: pointer;
font: inherit;
white-space: nowrap;
pointer-events: auto;
}
.sg-agent-name {
display: flex;
align-items: center;
gap: 6px;
color: var(--grey-6);
font-size: 15px;
font-weight: 600;
}
.sg-agent-name i { width: 8px; height: 8px; flex: none; }
.sg-context-name { color: var(--grey-5); font-size: 10.5px; letter-spacing: var(--track-caps); text-transform: uppercase; }
.sg-agent-label.compacted .sg-context-name { color: var(--chart-2); }
.sg-agent-name:hover,
.sg-agent-name:focus-visible,
.sg-context-name:hover,
.sg-context-name:focus-visible { color: var(--accent); outline: none; }
.sg-agent-name:focus-visible,
.sg-context-name:focus-visible { text-decoration: underline; text-underline-offset: 3px; }
.sg-agent-label.side-left { align-items: flex-end; text-align: right; }
.sg-agent-label.side-right { align-items: flex-start; text-align: left; }
.sg-turn {
position: absolute;
z-index: 3;
padding: 0;
border: 0;
background: transparent;
color: var(--grey-4);
cursor: pointer;
font: inherit;
outline: none;
}
.sg-turn-mark {
position: absolute;
left: 50%;
top: 50%;
width: var(--turn-mark-width, 44px);
height: var(--turn-mark-height, 12px);
background: var(--turn-color);
transform: translate(-50%, -50%);
transition: width 100ms ease, height 100ms ease, background 100ms ease;
}
.sg-turn-index {
position: absolute;
top: 50%;
left: calc(50% + var(--turn-label-offset, 31px));
color: var(--grey-5);
font-size: 12.5px;
transform: translateY(-50%);
white-space: nowrap;
}
.sg-turn:hover,
.sg-turn:focus-visible { z-index: 4; }
.sg-turn:hover .sg-turn-mark,
.sg-turn:focus-visible .sg-turn-mark {
width: calc(var(--turn-mark-width, 44px) + 6px);
height: calc(var(--turn-mark-height, 12px) + 2px);
background: var(--accent);
}
.sg-turn:focus-visible .sg-turn-mark { outline: 1px solid var(--grey-6); outline-offset: 2px; }
.sg-turn.compaction-attempt.accepted .sg-turn-mark {
outline: 1px solid var(--chart-2);
outline-offset: 2px;
}
.sg-turn.compaction-attempt.rejected .sg-turn-mark {
border: 1px dashed var(--chart-2);
background: var(--grey-1);
opacity: 0.72;
}
.sg-turn.compaction-attempt.rejected .sg-turn-index { color: var(--grey-4); }
.sg-turn.compaction-attempt.rejected:hover .sg-turn-mark,
.sg-turn.compaction-attempt.rejected:focus-visible .sg-turn-mark {
border-color: var(--grey-6);
background: var(--grey-2);
opacity: 1;
}
.sg-turn-run {
position: absolute;
z-index: 5;
padding: 0 7px;
border: 0;
border-block: 1px solid color-mix(in srgb, var(--turn-color) 56%, var(--grey-3));
background: var(--grey-1);
color: var(--grey-5);
cursor: pointer;
font: 10.5px/1 var(--font-mono);
letter-spacing: 0.04em;
white-space: nowrap;
}
.sg-turn-run.collapsed {
box-shadow: 0 0 0 4px var(--grey-1);
}
.sg-turn-run.expanded {
border: 1px dashed color-mix(in srgb, var(--turn-color) 45%, var(--grey-3));
color: var(--grey-4);
}
.sg-turn-run:hover,
.sg-turn-run:focus-visible {
color: var(--grey-6);
outline: none;
}
.sg-turn-run.collapsed:hover,
.sg-turn-run.collapsed:focus-visible { border-block-color: var(--turn-color); }
.sg-turn-run:focus-visible { box-shadow: 0 0 0 2px var(--grey-1), 0 0 0 3px var(--turn-color); }
#sg-inspector {
position: absolute;
top: 62px;
right: 14px;
bottom: 14px;
z-index: 20;
display: flex;
flex-direction: column;
width: min(330px, calc(100% - 28px));
border: 1px solid var(--grey-4);
background: rgba(25, 25, 25, 0.98);
}
.sg-inspector-head { display: flex; align-items: center; gap: 8px; min-height: 46px; padding: 0 12px; border-bottom: 1px solid var(--hairline); color: var(--grey-6); font-size: 11px; }
.sg-inspector-head button { margin-left: auto; }
#sg-inspector-body { flex: 1; min-height: 0; overflow-y: auto; padding: 4px 13px 14px; }
.sg-inspector-section { margin: 13px 0 6px; color: var(--accent); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
.sg-inspector-row { display: flex; gap: 12px; padding: 3px 0; font-size: 10.5px; }
.sg-inspector-row span { color: var(--grey-4); }
.sg-inspector-row strong { margin-left: auto; color: var(--grey-6); font-weight: 400; }
.sg-inspector-snippet { color: var(--grey-5); font-size: 10.5px; line-height: 1.5; white-space: pre-wrap; word-break: break-word; }
#sg-open-transcript { margin: 0 12px 12px; min-height: 30px; }
/* the banners lead the transcript, so they stand off the first entry */
.trace-errors { margin-top: auto; padding-top: 12px; margin-bottom: 14px; }
.trace-errors { margin-top: auto; margin-bottom: 14px; }
.trace-error-banner {
border: 1px solid var(--negative);
background: rgba(255, 69, 57, 0.08);
@@ -819,6 +1187,40 @@ mark.hit {
.trace-error-banner + .trace-error-banner { margin-top: 8px; }
.trace-error-message { padding: 10px 12px; font-size: 12px; white-space: pre-wrap; word-break: break-word; }
.trace-error-type { font-weight: 500; color: var(--negative); }
.trace-error-scope {
display: inline-block;
margin-right: 8px;
padding: 1px 6px;
border: 1px solid currentColor;
font-size: 9px;
line-height: 11px;
letter-spacing: var(--track-mono);
text-transform: uppercase;
color: var(--grey-4);
vertical-align: middle;
}
.trace-error-banner .trace-error-scope { color: var(--negative); }
#tm-episode-errors { padding: 12px 16px 0; border-bottom: 1px solid var(--hairline); }
#tm-episode-errors .trace-errors { margin-top: 0; margin-bottom: 12px; }
#tm-episode-errors .trace-recovered { margin-bottom: 12px; }
.trace-recovered { margin-bottom: 14px; border: 1px solid var(--grey-3); color: var(--grey-6); }
.trace-recovered > summary {
display: flex;
align-items: center;
gap: 10px;
padding: 6px 12px;
font-size: 11px;
color: var(--grey-4);
cursor: pointer;
list-style: none;
}
.trace-recovered > summary::-webkit-details-marker { display: none; }
.trace-recovered[open] > summary .entry-chev { transform: rotate(90deg); }
.trace-recovered-item { border-top: 1px solid var(--grey-3); }
.trace-recovered-item .trace-error-type { color: var(--grey-4); }
.trace-recovered-item .trace-error-tb > summary { border-top-color: var(--grey-3); }
.seg button.err, .seg button.err.active { color: var(--negative); }
.seg button.timeout, .seg button.timeout.active { color: var(--timeout); }
.trace-error-tb > summary {
display: flex;
align-items: center;
@@ -844,6 +1246,14 @@ mark.hit {
/* numbered collapsible message entries */
details.entry { border: 1px solid var(--hairline); margin-bottom: 8px; }
details.entry.pending { opacity: 0.55; border-style: dashed; }
details.entry.semantic-origin {
border-color: var(--accent);
outline: 1px solid rgba(182, 255, 60, 0.55);
outline-offset: 2px;
scroll-margin-block: 80px;
}
details.entry.semantic-origin > summary { background: rgba(182, 255, 60, 0.08); }
details.entry > summary {
display: flex;
align-items: center;
@@ -915,6 +1325,80 @@ details.tool-definitions, .rendered-transcript {
margin-bottom: 12px;
background: rgba(183, 166, 250, 0.025);
}
.task-evidence {
border: 1px solid color-mix(in srgb, var(--chart-3) 42%, var(--grey-3));
margin-bottom: 12px;
background: color-mix(in srgb, var(--chart-3) 3%, transparent);
}
.task-evidence.standalone,
.judging-view .judging-divider { margin-top: 0; }
.task-evidence > summary {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
padding: 7px 12px;
background: var(--grey-2);
}
.task-evidence .context-label { color: var(--chart-3); }
.task-evidence[open] > summary { border-bottom: 1px solid var(--hairline); }
.task-evidence[open] > summary .entry-chev { transform: rotate(90deg); }
.evidence-fields { display: grid; gap: 8px; padding: 10px 12px 12px; }
.evidence-field { min-width: 0; border: 1px solid var(--hairline); background: rgba(0, 0, 0, 0.08); }
.evidence-field > header {
display: flex;
align-items: center;
padding: 5px 9px;
border-bottom: 1px solid var(--hairline);
color: var(--chart-3);
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.evidence-field > header .icon-btn { margin-left: auto; }
.evidence-field > pre,
.judge-result > pre {
max-height: 360px;
margin: 0;
overflow: auto;
padding: 9px 11px;
color: var(--grey-5);
font: 400 11px/1.55 var(--font-mono);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.judging-divider {
display: flex;
align-items: center;
gap: 10px;
margin: 20px 0 8px;
color: #7adfff;
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.judging-divider::after { content: ""; flex: 1; height: 1px; background: var(--hairline); }
.judging-divider > :last-child { order: 2; color: var(--grey-4); }
.judge-entry { border-color: color-mix(in srgb, #7adfff 38%, var(--grey-3)); }
.judge-entry .entry-role { color: #7adfff; }
.judge-call-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; padding: 10px 12px 12px; }
.judge-request,
.judge-result { min-width: 0; border: 1px solid var(--hairline); }
.judge-request > header,
.judge-result > header {
padding: 6px 10px;
border-bottom: 1px solid var(--hairline);
color: #7adfff;
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.judge-result.parsed > header { color: var(--chart-2); }
.judge-message { display: grid; grid-template-columns: 72px minmax(0, 1fr); border-bottom: 1px solid var(--hairline-faint); }
.judge-message:last-child { border-bottom: 0; }
.judge-message > header { display: flex; gap: 8px; padding: 9px 10px; color: var(--grey-4); font-size: 10px; }
.judge-message > header strong { color: var(--grey-5); font-weight: 500; text-transform: uppercase; }
.judge-message > div { min-width: 0; padding: 9px 11px; border-left: 1px solid var(--hairline); color: var(--grey-5); font-size: 11.5px; white-space: pre-wrap; overflow-wrap: anywhere; }
details.tool-definitions > summary, details.rendered-transcript > summary,
details.tool-definition > summary {
display: flex;
@@ -978,6 +1462,78 @@ details.meta-fold > pre { margin: 0; border: none; border-top: 1px solid var(--h
word-break: break-word;
}
/* terminal replay follows the trace's wall clock; message text is revealed
across its recorded model-call span because providers do not persist per-token timestamps */
.replay-shell {
display: flex;
flex: 1 1 auto !important;
min-height: 420px;
flex-direction: column;
overflow: hidden;
border: 1px solid var(--grey-3);
background: #080b07;
}
.replay-bar, .replay-controls {
display: flex;
align-items: center;
gap: 10px;
min-height: 40px;
padding: 7px 12px;
border-bottom: 1px solid rgba(182, 255, 60, 0.12);
background: #0d110c;
}
.replay-lights { color: var(--grey-3); letter-spacing: 3px; font-size: 8px; }
.replay-title { color: var(--grey-6); font-size: 11px; }
.replay-bar .chip { margin-left: auto; }
.replay-controls .btn { min-width: 48px; }
#replay-top, #replay-live { min-width: 52px; }
#replay-top.active, #replay-live.active { color: var(--accent); border-color: rgba(182, 255, 60, 0.35); }
#replay-restart { min-width: 30px; }
#replay-progress { flex: 1; min-width: 80px; accent-color: var(--accent); }
#replay-time { color: var(--grey-4); font: 400 10.5px var(--font-mono); white-space: nowrap; }
.replay-skip { display: flex; align-items: center; gap: 5px; color: var(--grey-5); font-size: 10.5px; white-space: nowrap; }
.replay-skip input { accent-color: var(--accent); }
.replay-skip kbd { color: var(--grey-4); font: 400 8.5px var(--font-mono); border: 1px solid var(--grey-3); padding: 1px 3px; }
.replay-control-label { color: var(--grey-4); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
#replay-speed {
border: 1px solid var(--grey-3);
background: var(--grey-1);
color: var(--grey-5);
font: 400 10.5px var(--font-mono);
padding: 4px 6px;
}
.replay-output-pane {
flex: 1;
overflow: auto;
padding: 16px 18px 40px;
color: #c8d1c5;
font: 400 12px/1.6 var(--font-mono);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.replay-event { display: grid; grid-template-columns: 64px minmax(0, 1fr); gap: 12px; margin-bottom: 14px; }
.replay-event > div > span { display: block; }
.replay-stamp { color: #52604e; font-size: 9.5px; padding-top: 2px; }
.replay-system { color: #7c8978; }
.replay-user { color: #f1f5ef; }
.replay-assistant { color: #c8d1c5; }
.replay-command { margin-top: 7px; color: var(--accent); }
.replay-output { padding-left: 10px; border-left: 1px solid #33432d; color: #9dac98; }
.replay-wait, .replay-running { color: #70806c; }
.replay-model-wait {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 4px 16px;
margin-bottom: 8px;
color: #70806c;
font-size: 10.5px;
}
.replay-model-wait > i { grid-column: 1 / -1; height: 2px; overflow: hidden; background: #1c2719; }
.replay-model-wait > i > b { display: block; height: 100%; background: var(--accent); }
.replay-running { display: flex; align-items: center; gap: 8px; margin: 0 0 14px 76px; }
.replay-spinner { width: 7px; height: 7px; border: 1px solid #52604e; border-top-color: var(--accent); border-radius: 50%; animation: replay-spin 0.8s linear infinite; }
@keyframes replay-spin { to { transform: rotate(360deg); } }
.tok { padding: 0 1px; }
.tok:hover { outline: 1px solid var(--grey-6); }
.tok-tip {
@@ -1112,7 +1668,7 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
/* filter & sort popover */
.dd-filters { min-width: 210px; display: flex; flex-direction: column; gap: 6px; }
.dd-filters { min-width: 320px; display: flex; flex-direction: column; gap: 6px; }
.dd-sec {
text-transform: uppercase;
font-size: 10px;
@@ -1123,6 +1679,7 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
margin-top: 2px;
}
.dd-filters .dd-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin: 0; }
.dd-filters .seg button { padding: 0 9px; }
/* controls sit right, sized to their content, so the label reads as the row's subject */
.dd-filters .dd-row select, .dd-filters .dd-row .dd-select, .dd-filters .dd-row .seg { margin-left: auto; }
.dd-filters .dd-row .dd-btn { justify-content: space-between; gap: 8px; }
@@ -1178,3 +1735,15 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
background: var(--grey-2);
border-bottom: 1px solid var(--hairline);
}
/* in-flight rollouts share the episode table; the phase badge and a pulsing dot in
place of their number set them apart */
.live-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); animation: live-pulse 2s ease-out infinite; }
#episode-table tr.err td:first-child { border-left: 2px solid var(--negative); }
#episode-table tr.timeout td:first-child { border-left: 2px solid var(--timeout); }
#episode-table tr.retried td:first-child { border-left: 2px dotted var(--grey-4); }
#episode-table tr.live.landing .live-dot { animation: none; opacity: 0.45; }
.badge.stage { font-size: 9px; padding: 2px 5px; line-height: 12px; border-radius: 3px; background: var(--hairline); border-color: transparent; color: var(--accent); }
#tm-live-label { margin-left: 8px; }
#log-comp-menu .file-item.sub { padding-left: 22px; }
#episode-table .day { margin-right: 8px; }
+24 -1
View File
@@ -1,5 +1,9 @@
import os
import queue
import threading
import uuid
from functools import partial
from pathlib import Path
from verifiers.v1 import pool_serve_kwargs
from verifiers.v1.runtimes import set_base_sandbox_labels
@@ -17,15 +21,30 @@ def setup_worker(log_level: str | None, json_logging: bool, sandbox_labels: list
set_base_sandbox_labels(sandbox_labels)
def publish_address(addresses: queue.SimpleQueue, path: Path) -> None:
"""Write the bound address once serve_env reports it (it blocks in the server loop
afterwards). Atomic, so a waiting client never reads a partial line."""
address = addresses.get()
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".address.tmp")
tmp.write_text(address)
tmp.replace(path)
@clean_exit
def run_server(config: EnvServerConfig):
run_name = os.environ.get("PRL_RUN_NAME")
sandbox_labels = [run_name] if run_name else []
addresses: queue.SimpleQueue | None = None
if config.address_file is not None:
addresses = queue.SimpleQueue()
threading.Thread(target=publish_address, args=(addresses, config.address_file), daemon=True).start()
# ``serve.pool`` (static or elastic) sizes the server. serve_env applies the worker
# setup in this process and in every spawned worker.
serve_env(
**pool_serve_kwargs(config.serve.pool),
address=config.serve.address,
address=config.serve.address or "tcp://127.0.0.1:0",
address_queue=addresses,
log_setup=partial(setup_worker, config.log.level, config.log.json_logging, sandbox_labels),
config_data=env_config_data(config.env),
max_concurrent=config.serve.max_concurrent,
@@ -35,6 +54,10 @@ def run_server(config: EnvServerConfig):
def main():
"""Main entry-point for the env server. Run using `uv run env-server`"""
set_proc_title("EnvServer")
# verifiers keys run-scoped state (creation limiters) by $VF_RUN_ID. Every launcher,
# the Python entrypoints and the SLURM templates alike, hands env servers $PRL_RUN_ID;
# a standalone server is a run of its own.
os.environ.setdefault("VF_RUN_ID", os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex)
run_server(cli(EnvServerConfig))
+210
View File
@@ -0,0 +1,210 @@
"""Launcher for ``uv run eval``: one epoch of every configured eval source.
Defers heavy ML imports until after the config is parsed, so ``eval --help``
short-circuits. The implementation lives in ``prime_rl.eval.eval``.
"""
import asyncio
import json
import os
import re
import signal
import sys
import tomllib
import uuid
from pathlib import Path
from subprocess import Popen
from typing import Any
from prime_rl.configs.eval import EvalConfig
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes, set_proc_title
USAGE = """\
usage: uv run eval [<taskset-id>] [--env.<field> <value> ...] [-n N] [-r N] [-c N] [-m MODEL] [options]
uv run eval @ eval.toml [options] multi-source runs ([[source]] blocks)
uv run eval @ eval.toml --run.name <name> --resume resume an interrupted run
Shorthands:
<taskset-id> the taskset of the run's only source
--env.<field> <value> a field of that source's env block (e.g. --env.agent.harness.id bash); next to a
TOML with [[source]] blocks, a field of the shared env block (e.g. --env.retries.max-retries 3)
-c N pin the concurrency band (concurrency.min_inflight = max_inflight = N)
"""
NUMBER = re.compile(r"-?\d+(\.\d+)?")
def set_nested(target: dict[str, Any], keys: list[str], value: Any) -> None:
for key in keys[:-1]:
target = target.setdefault(key, {})
target[keys[-1]] = value
def parse_value(raw: str) -> Any:
"""A JSON list/object stays structured; every other value is left to pydantic."""
return json.loads(raw) if raw.startswith(("[", "{")) else raw
def expand_shorthands(argv: list[str]) -> list[str]:
"""Rewrite the shorthands into flags ``EvalConfig`` parses.
``<taskset-id>`` and ``--env.<path> <value>`` describe the run's only source and fold
into one JSON ``--source`` flag (pydantic-config has no list-index paths, so
``--source.0.env...`` cannot address it). Next to a config file that defines
``[[source]]`` blocks, ``--env.*`` flags pass through to the shared ``env`` block.
``-c N`` pins the concurrency band. Everything else passes through untouched.
"""
out: list[str] = []
source: dict[str, Any] = {}
rest = list(argv)
positional = bool(rest) and not rest[0].startswith(("-", "@"))
sources_in_toml = any(toml_defines_source(path) for path in root_config_files(argv))
shared_env = sources_in_toml and not positional
if positional:
set_nested(source, ["env", "taskset", "id"], rest.pop(0))
i = 0
while i < len(rest):
arg = rest[i]
flag, has_value, value = arg.partition("=")
if not has_value and (flag.startswith("--env.") or flag == "-c"):
if i + 1 >= len(rest) or (rest[i + 1].startswith("-") and not NUMBER.fullmatch(rest[i + 1])):
raise SystemExit(f"{flag} needs a value")
i += 1
value = rest[i]
if flag.startswith("--env.") and shared_env:
out += [flag, value]
elif flag.startswith("--env."):
set_nested(source, [key.replace("-", "_") for key in flag[2:].split(".")], parse_value(value))
elif flag == "-c":
out += ["--concurrency.min_inflight", value, "--concurrency.max_inflight", value]
else:
out.append(arg)
i += 1
if source:
if sources_in_toml:
raise SystemExit(
"The <taskset-id> shorthand describes a single source and cannot be combined "
"with a config file that defines [[source]] blocks - use one or the other"
)
out += ["--source", json.dumps([source])]
return out
def root_config_files(argv: list[str]) -> list[Path]:
"""Root ``@ file`` references (a ``--flag @ file`` is a nested reference)."""
return [
Path(argv[i + 1])
for i, arg in enumerate(argv[:-1])
if arg == "@" and (i == 0 or not argv[i - 1].startswith("--"))
]
def toml_defines_source(path: Path) -> bool:
if path.suffix != ".toml" or not path.is_file():
return False
with path.open("rb") as f:
return "source" in tomllib.load(f)
def main():
set_proc_title("Eval")
argv = sys.argv[1:]
if not argv or any(arg in ("-h", "--help") for arg in argv):
print(USAGE)
sys.argv = [sys.argv[0], "--help"]
cli(EvalConfig)
return
# The typed parse sees the expanded flags; the launch artifacts keep the command as typed.
sys.argv = [sys.argv[0], *expand_shorthands(argv)]
config = cli(EvalConfig)
sys.argv = [sys.argv[0], *argv]
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import (
format_config_message,
format_log_message,
prepare_attempt_dirs,
validate_run_dir,
write_env_server_config,
write_launch_artifacts,
)
# The run identity is runtime-only: $PRL_RUN_ID / $PRL_RUN_NAME are stamped on
# every episode and inherited by the env servers.
os.environ.setdefault("PRL_RUN_ID", uuid.uuid4().hex)
assert config.run.name is not None # resolved at construction
os.environ["PRL_RUN_NAME"] = config.run.name
clean = config.clean and not os.environ.get("NEVER_CLEAN")
validate_run_dir(config.run_dir, output_dir=config.output_dir, resuming=config.resume, clean=clean)
config.run_dir.mkdir(parents=True, exist_ok=True)
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
log_file = log_dir / "eval.log"
logger = setup_logger(config.log.level, json_logging=config.log.json_logging, log_file=log_file)
logger.info("Starting eval")
write_launch_artifacts(config_dir, "eval")
(config_dir / "eval.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
components: list[tuple[str, Path | str]] = [("Eval", config_dir / "eval.json")]
# One env server per source without an explicit `serve.address`, like the rl launcher's:
# `env-server @ <path>` binds an OS-assigned port and publishes it to the source's
# address file, where the eval picks it up.
env_servers = [source for source in config.source if source.serve.address is None]
env_names = [source.resolved_name for source in env_servers]
if env_servers:
components.append(("Envs", f"{config_dir}/envs/eval/*.json"))
for source in env_servers:
components.append(
(f" {source.resolved_name}", write_env_server_config(config_dir, "eval", source, config.log))
)
if config.dry_run:
logger.info(f"Configs:\n{format_config_message(config_dir, 'eval', components)}")
logger.success("Dry run complete. To start the eval, remove --dry-run from your command.")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
from prime_rl.eval.eval import run_eval
processes: list[Popen] = []
for source in env_servers:
name = source.resolved_name
logger.info(f"Starting {name} server")
env_server_log = log_dir / "envs" / "eval" / f"{name}.log"
env_server_log.parent.mkdir(parents=True, exist_ok=True)
with open(env_server_log, "w") as log_file_handle:
processes.append(
Popen(
["env-server", "@", (config_dir / "envs" / "eval" / f"{name}.json").as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS},
stdout=log_file_handle,
stderr=log_file_handle,
)
)
logger.info(f"Configs:\n{format_config_message(config_dir, 'eval', components)}")
logger.info(format_log_message(log_dir, eval=True, env_names={"eval": env_names}))
def sigterm_handler(signum, frame):
logger.warning("Received SIGTERM, terminating all processes...")
cleanup_processes(processes)
sys.exit(1)
signal.signal(signal.SIGTERM, sigterm_handler)
log_dashboard_url(logger, dashboard_url)
# Like the rl/sft launchers, the console stays quiet while the eval runs: results
# live in the dashboard and the log file, only errors surface here.
setup_logger(config.log.level, json_logging=config.log.json_logging, log_file=log_file, console_level="ERROR")
try:
asyncio.run(run_eval(config))
finally:
cleanup_processes(processes)
setup_logger(config.log.level, json_logging=config.log.json_logging, log_file=log_file).success("Eval finished!")
if __name__ == "__main__":
main()
-34
View File
@@ -1,34 +0,0 @@
"""Lightweight launcher for the online evals.
Defers heavy ML imports until after ``cli()`` parses CLI args, so
``evals --help`` short-circuits in ``cli()``. The actual implementation
lives in ``prime_rl.evals.evals``.
"""
import asyncio
import json
import os
from prime_rl.configs.evals import EvalsConfig
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Evals")
config = cli(EvalsConfig)
from prime_rl.utils.pathing import prepare_attempt_dirs, write_launch_artifacts
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
os.environ["PRL_LOG_DIR"] = str(log_dir)
write_launch_artifacts(config_dir, "evals")
(config_dir / "evals.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
from prime_rl.evals.evals import run_evals
asyncio.run(run_evals(config))
if __name__ == "__main__":
main()
+2
View File
@@ -181,6 +181,8 @@ def start_router(config: InferenceConfig) -> subprocess.Popen:
str(config.vllm.data_parallel_size_local or config.vllm.data_parallel_size),
"--request-id-headers",
"x-session-id",
"--request-timeout-secs",
str(config.router.request_timeout_secs),
"--worker-startup-timeout-secs",
"4200",
"--prometheus-port",
+46 -39
View File
@@ -20,6 +20,7 @@ from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import (
clean_future_steps,
format_config_message,
format_log_message,
get_ckpt_dir,
get_launcher_dir,
@@ -27,6 +28,7 @@ from prime_rl.utils.pathing import (
prepare_attempt_dirs,
resolve_latest_ckpt_step,
validate_run_dir,
write_env_server_config,
write_launch_artifacts,
)
from prime_rl.utils.process import (
@@ -50,23 +52,18 @@ INFERENCE_CONFIG = "inference.json"
ENVS_DIR = "envs"
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig, str]]:
"""``(split, source, address)`` for every launcher-managed train/eval source. The
launcher runs one env server per source at its deterministic address; the
orchestrator connects there. A source with ``serve.address`` set is externally
managed — its server runs elsewhere and only the orchestrator connects to it — so
the launcher neither writes its TOML nor spawns a server for it."""
addresses = config.orchestrator.env_addresses
return [
(split, source, addresses[(split, source.resolved_name)])
for split, source in config.orchestrator.env_sources
if source.serve.address is None
]
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig]]:
"""``(split, source)`` for every launcher-managed train/eval source. The launcher
runs one env server per source; each binds an OS-assigned port and publishes it to
its address file, where the orchestrator picks it up. A source with ``serve.address``
set is externally managed — its server runs elsewhere and only the orchestrator
connects to it — so the launcher neither writes its TOML nor spawns a server for it."""
return [(split, source) for split, source in config.orchestrator.env_sources if source.serve.address is None]
def env_server_names(config: RLConfig, split: str) -> list[str]:
"""Names of the launcher-managed env servers for one split."""
return [source.resolved_name for source_split, source, _ in env_servers(config) if source_split == split]
return [source.resolved_name for source_split, source in env_servers(config) if source_split == split]
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
@@ -76,6 +73,19 @@ def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None =
json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2)
def rl_config_components(config: RLConfig, config_dir: Path) -> list[tuple[str, Path | str]]:
"""The resolved per-component configs ``write_subconfigs`` leaves in ``config_dir``."""
components: list[tuple[str, Path | str]] = [
("Orchestrator", config_dir / ORCHESTRATOR_CONFIG),
("Trainer", config_dir / TRAINER_CONFIG),
]
if config.inference is not None:
components.append(("Inference", config_dir / INFERENCE_CONFIG))
if env_servers(config):
components.append(("Envs", f"{config_dir}/{ENVS_DIR}/*/*.json"))
return components
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
"""Write resolved subconfigs to disk as TOML files."""
output_dir.mkdir(parents=True, exist_ok=True)
@@ -96,21 +106,11 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
with open(output_dir / INFERENCE_CONFIG, "w") as f:
json.dump(inference_dict, f, indent=2)
# One EnvServerConfig TOML per launcher-managed source: `env-server @ <path>` binds
# at the source's deterministic address, where the orchestrator connects. The source's
# env/serve blocks carry over; its other knobs (sampling, algo, name, ...) are
# orchestrator-side.
for split, source, address in env_servers(config):
env_dir = output_dir / ENVS_DIR / split
env_dir.mkdir(parents=True, exist_ok=True)
source_dict = dump_resolved_config(source)
env_server_dict = {
"env": source_dict["env"],
"serve": {**source_dict.get("serve", {}), "address": address},
"log": {"level": config.orchestrator.log.vf_level, "json_logging": config.orchestrator.log.json_logging},
}
with open(env_dir / f"{source.resolved_name}.json", "w") as f:
json.dump(env_server_dict, f, indent=2)
# One EnvServerConfig per launcher-managed source: `env-server @ <path>` binds an
# OS-assigned port and publishes it to the source's address file, where the
# orchestrator picks it up.
for split, source in env_servers(config):
write_env_server_config(output_dir, split, source, config.orchestrator.log)
def rl_local(config: RLConfig):
@@ -124,12 +124,21 @@ def rl_local(config: RLConfig):
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_artifacts(config_dir, "rl")
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', rl_config_components(config, config_dir))}")
if config.dry_run:
logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.")
return
logger.info(
format_log_message(
log_dir=log_dir,
trainer=True,
orchestrator=True,
inference=config.inference is not None,
env_names={split: env_server_names(config, split) for split in ("train", "eval")},
)
)
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs from deployment config
@@ -153,7 +162,6 @@ def rl_local(config: RLConfig):
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
start_command = sys.argv
logger.info("Starting RL run")
logger.debug(f"RL start command: {' '.join(start_command)}")
# Build shared W&B env vars for subprocesses. Shared mode is always on for
@@ -248,10 +256,10 @@ def rl_local(config: RLConfig):
"otherwise rollouts will hang."
)
# Start one env server per source. The orchestrator connects to each source's
# deterministic address, polling until the server is up, so the servers and the
# Start one env server per source. The orchestrator waits for each server's
# published address and polls until it answers, so the servers and the
# orchestrator start in parallel.
for split, source, address in env_servers(config):
for split, source in env_servers(config):
name = source.resolved_name
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
logger.info(f"Starting {name} server")
@@ -586,7 +594,7 @@ def rl_slurm(config: RLConfig):
if config.deployment.type == "single_node":
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean"})
logger.info(f"Wrote config to {config_dir / RL_CONFIG}")
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', [('RL', config_dir / RL_CONFIG)])}")
train_env_names = env_server_names(config, "train")
eval_env_names = env_server_names(config, "eval")
@@ -596,12 +604,11 @@ def rl_slurm(config: RLConfig):
trainer=True,
orchestrator=True,
inference=True,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
env_names={"train": train_env_names, "eval": eval_env_names},
)
else:
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', rl_config_components(config, config_dir))}")
train_env_names = env_server_names(config, "train")
eval_env_names = env_server_names(config, "eval")
@@ -612,8 +619,7 @@ def rl_slurm(config: RLConfig):
trainer=True,
orchestrator=has_infer,
inference=has_infer,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
env_names={"train": train_env_names, "eval": eval_env_names},
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
)
@@ -661,6 +667,7 @@ def rl(config: RLConfig):
# step is stale. When training from scratch, every existing step directory is
# stale — without this, a fresh run in a dirty run dir would pick up rollouts
# from a previous run and the orchestrator would see a negative async level.
get_logger().info("Starting RL run")
resume_step: int | None = None
if resuming:
if config.resume.dir is not None:
+84 -76
View File
@@ -8,8 +8,8 @@ from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from prime_rl.configs.evals import EvalsConfig, OnlineConfig
from prime_rl.configs.orchestrator import EvalSourceConfig
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.orchestrator import OnlineEvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.shared import LogConfig
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
@@ -17,6 +17,7 @@ from prime_rl.utils.config import cli, dump_resolved_config, find_package_resour
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import (
clean_future_steps,
format_config_message,
format_log_message,
get_broadcast_dir,
get_ckpt_dir,
@@ -25,6 +26,7 @@ from prime_rl.utils.pathing import (
prepare_attempt_dirs,
resolve_latest_ckpt_step,
validate_run_dir,
write_env_server_config,
write_launch_artifacts,
)
from prime_rl.utils.process import (
@@ -42,23 +44,17 @@ SFT_CONFIG = "sft.json"
SFT_SBATCH = "sft.sbatch"
INFERENCE_CONFIG = "inference.json"
EVALS_CONFIG = "evals.json"
ONLINE_EVAL_CONFIG = "eval.json"
ENVS_DIR = "envs"
def eval_env_servers(config: SFTConfig) -> list[tuple[EvalSourceConfig, str]]:
"""``(source, address)`` for every launcher-managed eval source. A source with
``serve.address`` set is externally managed — the launcher neither writes its
config nor spawns a server for it."""
def eval_env_servers(config: SFTConfig) -> list[OnlineEvalSourceConfig]:
"""Every launcher-managed eval source. A source with ``serve.address`` set is
externally managed — the launcher neither writes its config nor spawns a server for it."""
if config.eval is None:
return []
addresses = config.eval.env_addresses
return [
(source, addresses[("eval", source.resolved_name)])
for source in config.eval.source
if source.serve.address is None
]
return [source for source in config.eval.source if source.serve.address is None]
def get_ckpt_base(config: SFTConfig) -> Path:
@@ -76,28 +72,37 @@ def resolve_resume_step(config: SFTConfig) -> int | None:
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
def build_evals_config(config: SFTConfig) -> EvalsConfig:
"""Derive the evals subconfig from the resolved SFT config. The launcher
spawns the env servers itself, so each source's derived address is stamped in,
marking it externally managed for the evals process."""
def build_online_eval_config(config: SFTConfig) -> SFTOnlineEvalConfig:
"""The online-eval process's config: the resolved ``[eval]`` block with the run-level
fields filled from the SFT config. The launcher spawns the env servers itself; the
online-eval process finds each one through the address it publishes in the shared
config attempt."""
assert config.eval is not None
eval_config = config.eval.model_copy(deep=True)
addresses = config.eval.env_addresses
for source in eval_config.source:
source.serve.address = addresses[("eval", source.resolved_name)]
return EvalsConfig(
run_fields = dict(
model=config.model.name,
eval=eval_config,
weight_broadcast=config.weight_broadcast,
online=OnlineConfig(
broadcasts_dir=get_broadcast_dir(config.run_dir),
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
),
broadcasts_dir=get_broadcast_dir(config.run_dir),
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
output_dir=config.run_dir,
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
monitors=config.monitors,
)
return SFTOnlineEvalConfig(**{**eval_config.model_dump(exclude=set(run_fields)), **run_fields})
def sft_config_components(config: SFTConfig, config_dir: Path) -> list[tuple[str, Path | str]]:
"""The resolved configs a launch leaves in ``config_dir``: the SFT config and, with
online evals, the inference, online-eval and env-server configs."""
components: list[tuple[str, Path | str]] = [("SFT", config_dir / SFT_CONFIG)]
if config.eval is not None:
if config.inference is not None:
components.append(("Inference", config_dir / INFERENCE_CONFIG))
components.append(("Eval", config_dir / ONLINE_EVAL_CONFIG))
if eval_env_servers(config):
components.append(("Envs", f"{config_dir}/{ENVS_DIR}/eval/*.json"))
return components
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
@@ -108,7 +113,7 @@ def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None
def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: bool = False) -> None:
"""Write the inference, evals, and env-server configs for online evals."""
"""Write the inference, online-eval, and env-server configs for online evals."""
config_dir.mkdir(parents=True, exist_ok=True)
if config.inference is not None:
@@ -121,26 +126,18 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
with open(config_dir / INFERENCE_CONFIG, "w") as f:
json.dump(inference_dict, f, indent=2)
with open(config_dir / EVALS_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_evals_config(config)), f, indent=2)
with open(config_dir / ONLINE_EVAL_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_online_eval_config(config)), f, indent=2)
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>`
# binds at the source's deterministic address, where the evals process connects.
for source, address in eval_env_servers(config):
env_dir = config_dir / ENVS_DIR / "eval"
env_dir.mkdir(parents=True, exist_ok=True)
source_dict = dump_resolved_config(source)
env_server_dict = {
"env": source_dict["env"],
"serve": {**(source_dict.get("serve") or {}), "address": address},
"log": {"level": config.log.vf_level, "json_logging": config.log.json_logging},
}
with open(env_dir / f"{source.resolved_name}.json", "w") as f:
json.dump(env_server_dict, f, indent=2)
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>` binds an
# OS-assigned port and publishes it to the source's address file, where the
# online-eval process picks it up.
for source in eval_env_servers(config):
write_env_server_config(config_dir, "eval", source, config.log)
def write_slurm_script(
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str | None = None
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str, wandb_shared: bool
) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
@@ -191,12 +188,12 @@ def write_slurm_script(
"dp_per_node": config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
"enable_expert_parallel": config.inference.vllm.enable_expert_parallel,
"inference_env_vars": inference_env_vars,
"evals_env_vars": {
"online_eval_env_vars": {
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
},
"eval_env_names": [source.resolved_name for source, _ in eval_env_servers(config)],
"eval_env_names": [source.resolved_name for source in eval_env_servers(config)],
}
script = template.render(
**config.slurm.template_vars,
@@ -213,6 +210,7 @@ def write_slurm_script(
gpus_per_node=config.deployment.gpus_per_node,
ranks_filter=",".join(map(str, config.log.ranks_filter)),
prl_run_id=prl_run_id,
wandb_shared=wandb_shared,
run_name=config.run.name,
online_eval=online_eval,
use_nccl_broadcast=(
@@ -236,6 +234,7 @@ def sft_slurm(config: SFTConfig):
online_eval = config.deployment.type == "multi_node" and config.eval is not None
logger.info("Starting SFT run")
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_artifacts(config_dir, "sft")
config_path = config_dir / SFT_CONFIG
@@ -249,19 +248,16 @@ def sft_slurm(config: SFTConfig):
# inference pool runs on its dedicated nodes in the same allocation.
exclude = exclude | {"inference"}
write_config(config, config_path, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
# Trainer and evals processes log to a single shared W&B run.
prl_run_id: str | None = None
if online_eval and config.monitors.wandb is not None:
prl_run_id = os.environ["PRL_RUN_ID"]
# Trainer and online-eval processes log to a single shared W&B run.
wandb_shared = online_eval and config.monitors.wandb is not None
launcher_dir = get_launcher_dir(config.run_dir)
if online_eval:
write_eval_subconfigs(config, config_dir, strip_router=True)
logger.info(f"Wrote eval subconfigs to {config_dir}")
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
script_path = launcher_dir / SFT_SBATCH
write_slurm_script(config, config_path, log_dir, script_path, prl_run_id)
write_slurm_script(config, config_path, log_dir, script_path, os.environ["PRL_RUN_ID"], wandb_shared)
logger.info(f"Wrote SLURM script to {script_path}")
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
@@ -269,9 +265,9 @@ def sft_slurm(config: SFTConfig):
log_dir=log_dir,
trainer=True,
num_train_nodes=num_nodes,
evals=online_eval,
eval=online_eval,
inference=online_eval,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)] if online_eval else None,
env_names={"eval": [source.resolved_name for source in eval_env_servers(config)]} if online_eval else None,
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
)
@@ -297,20 +293,28 @@ def sft_local(config: SFTConfig):
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
logger.info("Starting SFT run")
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_artifacts(config_dir, "sft")
config_path = config_dir / SFT_CONFIG
write_config(config, config_path)
logger.info(f"Wrote config to {config_path}")
if config.eval is not None:
write_eval_subconfigs(config, config_dir)
logger.info(f"Wrote eval subconfigs to {config_dir}")
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
if config.dry_run:
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
return
logger.info(
format_log_message(
log_dir=log_dir,
trainer=True,
eval=config.eval is not None,
inference=config.inference is not None,
env_names={"eval": [source.resolved_name for source in eval_env_servers(config)]},
)
)
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
@@ -329,17 +333,17 @@ def sft_local(config: SFTConfig):
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
# Trainer and evals log to a single shared W&B run whose id ($WANDB_RUN_ID)
# Trainer and online-eval log to a single shared W&B run whose id ($WANDB_RUN_ID)
# equals $PRL_RUN_ID, one label per process.
wandb_shared_env: dict[str, str] = {}
if config.eval is not None:
# The trainer creates the run; the evals process (which drains its final evals
# after the trainer exits) finalizes it.
# The trainer creates the run; the online-eval process (which drains its final
# evals after the trainer exits) finalizes it.
wandb_shared_env = {
"WANDB_SHARED_MODE": "1",
"WANDB_RUN_ID": os.environ["PRL_RUN_ID"],
"WANDB_SHARED_PRIMARY": "trainer",
"WANDB_SHARED_FINISHER": "evals",
"WANDB_SHARED_FINISHER": "online-eval",
"WANDB_PROGRAM": "uv run sft",
"WANDB_ARGS": json.dumps(sys.argv),
}
@@ -388,9 +392,9 @@ def sft_local(config: SFTConfig):
log_path=log_dir / "inference.log",
)
# Start one env server per eval source. The evals process connects to each source's
# deterministic address, polling until the server is up.
for source, address in eval_env_servers(config):
# Start one env server per eval source. The online-eval process waits for each
# server's published address and polls until it answers.
for source in eval_env_servers(config):
name = source.resolved_name
logger.info(f"Starting {name} server")
start_process(
@@ -401,10 +405,10 @@ def sft_local(config: SFTConfig):
)
if config.eval is not None:
logger.info("Starting evals")
logger.info("Starting online evals")
start_process(
"evals",
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
"online-eval",
[sys.executable, "-m", "prime_rl.eval.online", "@", (config_dir / ONLINE_EVAL_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
@@ -414,9 +418,9 @@ def sft_local(config: SFTConfig):
"PRL_ATTEMPT_LOG_DIR": str(log_dir),
"PRL_LOG_DIR": str(log_dir),
**wandb_shared_env,
"WANDB_SHARED_LABEL": "evals",
"WANDB_SHARED_LABEL": "online-eval",
},
log_path=log_dir / "evals.log",
log_path=log_dir / "eval.log",
)
from prime_rl.utils.utils import get_free_port
@@ -455,11 +459,11 @@ def sft_local(config: SFTConfig):
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Wait for the trainer (and the evals process, which drains its final evals after
# the trainer's last checkpoint) while surfacing any process failure.
# Wait for the trainer (and the online-eval process, which drains its final evals
# after the trainer's last checkpoint) while surfacing any process failure.
terminal_events = [stop_events["trainer"]]
if "evals" in stop_events:
terminal_events.append(stop_events["evals"])
if "online-eval" in stop_events:
terminal_events.append(stop_events["online-eval"])
while True:
pending = [event for event in terminal_events if not event.is_set()]
if error_queue:
@@ -497,12 +501,12 @@ def sft_local(config: SFTConfig):
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
"""Remove eval artifacts a previous run left behind: weight broadcasts and rollout
trace dirs — everything on a fresh start, steps past the resume step on resume.
Without this the evals process would replay stale broadcasts (and then skip the
Without this the online-eval process would replay stale broadcasts (and then skip the
re-trained ones at the same steps), and the append-only trace files would mix two
policies' rollouts under one step."""
logger = setup_logger(config.log.level or "info")
if os.environ.get("NEVER_CLEAN"):
logger.warning("NEVER_CLEAN is set - keeping stale weight broadcasts; the evals process may replay them")
logger.warning("NEVER_CLEAN is set - keeping stale weight broadcasts; the online-eval process may replay them")
return
resume_step = resolve_resume_step(config)
clean_future_steps(config.run_dir, resume_step if resume_step is not None else -1)
@@ -539,8 +543,12 @@ def sft(config: SFTConfig):
if not config.dry_run:
from prime_rl.trainer.model import pre_download_model
from prime_rl.trainer.sft.data import pre_download_data
pre_download_model(config.model.name, skip_weights=config.model.debug.random_init)
pre_download_data(config.data, config.env_vars)
if config.val is not None:
pre_download_data(config.val.data, config.env_vars)
if config.slurm is not None:
sft_slurm(config)
+67
View File
@@ -0,0 +1,67 @@
"""Evals: one epoch of every configured eval source against the weights the inference
server currently serves.
Every episode streams through the monitors as it arrives; a finished epoch also goes to
the platform when ``monitors.prime`` is set. An interrupted run resumes with
``--resume`` from its trace stream: the landed episodes rejoin the epoch and only the
rollouts still owed run (``prime_rl.eval.resume``)."""
from __future__ import annotations
from prime_rl import monitors
from prime_rl.configs.eval import EvalConfig
from prime_rl.eval import resume
from prime_rl.eval.runner import EvalRunner
from prime_rl.utils.config import dump_resolved_config
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import clean_exit
class Eval:
def __init__(self, config: EvalConfig) -> None:
self.config = config
self.runner = EvalRunner(config, run_dir=config.run_dir)
async def run(self) -> None:
config = self.config
landed: list[dict] = []
if config.resume:
# read and set aside before the monitors start: the resumed attempt writes a fresh stream
landed = resume.take_landed(config.run_dir)
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
producer="eval",
wandb=config.monitors.wandb,
prime=config.monitors.prime,
file=config.monitors.file,
output_dir=config.run_dir,
run_config=config,
eval_env_names=[source.resolved_name for source in config.source],
overview_flavor="eval",
)
resume.stamp_config(config.run_dir, dump_resolved_config(config))
await self.runner.setup()
restored: list = []
if config.resume:
restored, owed, groups = resume.plan(landed, self.runner.eval_envs)
self.runner.eval_source.restore(owed, groups)
get_logger().info(
f"Resuming from the trace stream: {len(restored)} episodes restored, "
f"{sum(sum(counts.values()) for counts in owed.values())} rollouts owed"
)
await self.runner.start()
fired = self.runner.eval_source.trigger(0)
await self.runner.run_epoch(fired, 0, restored=restored)
await self.runner.drain()
@clean_exit
async def run_eval(config: EvalConfig) -> None:
evaluation = Eval(config)
try:
await evaluation.run()
# Finalize only on a clean exit — a crashed run must not mark itself completed.
await monitors.finalize()
finally:
await evaluation.runner.stop()

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