## 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 -->
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 -->
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>
## 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.
<!-- 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>
<!-- 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 -->
## 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`
## 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 -->
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 -->
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>
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 -->
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>
## 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).
## 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>
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 -->
## 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 -->
## 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 -->
## 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 -->
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>
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>
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 -->
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>
## 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 -->
## 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>
## 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.
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>
#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>
## 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 -->
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>
## 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>
## 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 -->
## 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>
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 -->
## 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 -->
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>
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>
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 -->
## 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 -->
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>
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>
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>
## 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 -->
## 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>
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>
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>
## 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>
## 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 -->
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>
## 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 -->
## 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 -->
## 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 -->
## Summary
- Each trace stream (`traces/stream`, `traces/annotations/<producer>`)
is now a directory of numbered chunks. `ChunkedJsonl`
(`monitors/file/traces/chunks.py`) rolls at `monitors.file.chunk_bytes`
(default 5 GiB; a line never spans chunks) and, with
`monitors.file.compress` (default on), seals each full chunk with zstd
in a background thread. The live chunk stays plain text; a finished run
seals its live chunk too. A relaunch resumes the live chunk it finds and
seals anything a crash left mid-seal.
- Sealed chunks use zstd's seekable format (`pyzstd`, 4 MiB frames), so
a seek costs one frame, not the chunk. `zstd -dcf stream/* | jq` reads a
whole stream, sealed and live alike.
- Index rows carry `chunk` beside `offset`; the dashboard resolves both
through `open_chunk` (plain or sealed) for episodes and annotation
records, keys its caches and etags on the index size, and parses chunked
streams for the series view through the index, one chunk open at a time.
Annotation readers rely on the producer's index (the file monitor always
writes one).
- `monitors.file.float_decimals` (default 4, `None` for every digit)
sets the precision of per-token float streams in both the episode
records (`to_record(float_decimals=...)`) and the trainer's annotation
streams. Trainer streams also hold `null` outside the loss mask - the
fold keeps sampled tokens only, so nothing a reader sees changes, and
runs of nulls seal to nothing. The trainer finalizes its monitors on
exit so its live chunk seals.
- Submodule bump to verifiers main `cfc7c474`
(PrimeIntellect-ai/verifiers#2495, merged): JSON records round per-token
floats to `to_record(float_decimals=...)`, 4 by default. The msgpack
wire keeps full precision, so the importance ratio is unaffected.
## Measurements
Replayed the 100-step, 33,342-episode scaleswe baseline
(`ipo-baseline-rollouts-steps1-100`, 15.17 GB as one `stream.jsonl`)
through the new writer with 5 GiB chunks:
| | raw | 4 dp | on disk (sealed) | total |
|---|---|---|---|---|
| 10 steps (5,696 episodes) | 1.06 GB | 0.89 GB | **0.10 GB** | 11.0x |
| 100 steps (33,342 episodes) | 15.17 GB | 12.66 GB | **1.38 GB** |
11.0x |
| 1000 steps (extrapolated from steps 11-100: 307 episodes, 157 MB raw
per step) | 156 GB | 130 GB | **14.2 GB** | 11.0x |
Rounding contributes 1.20x on the plain bytes and lifts zstd from 6.9x
to 9.2x, since mantissa digits were the incompressible part. Writing 33K
episodes took 81.8 s with sealing vs 80.4 s plain: sealing runs beside
the writer, not in front of it. The final 2.7 GB live chunk sealed in 4
s.
Dashboard against the sealed run (same box, 5 GiB chunks): open one
episode 5.8 ms cold / 4.0 ms warm vs 3.9 / 3.4 ms plain; table page 17
ms cold (index only, unchanged); series view full parse of all 33K
records 35.7 s sealed vs 39.7 s plain (orjson-bound, cached and
persisted after the first pass). Browser check: traces table renders,
episode viewer opens from a sealed chunk, no console errors. Unit suite:
571 passed.
## Breaking
- On-disk trace layout: `traces/stream.jsonl` →
`traces/stream/<NNNNN>.jsonl[.zst]`,
`traces/annotations/<producer>.jsonl` →
`traces/annotations/<producer>/<NNNNN>.jsonl[.zst]`; index rows gain
`chunk` and their `offset` is chunk-relative. Read a stream with `zstd
-dcf <stream dir>/* | jq`. The dashboard reads only the new layout.
- Per-token floats in records (`logprobs`, `reference_logprobs`,
`advantages`, trainer `trainer_logprobs`/`entropies`) are written with 4
decimals by default; set `monitors.file.float_decimals = None`
(orchestrator and trainer) to keep full precision.
- New dependency `pyzstd`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking on-disk trace layout and default float precision affect
observability and external readers; dashboard and monitor paths are
heavily touched but training wire precision is unchanged per PR notes.
>
> **Overview**
> **Trace on-disk layout is now chunked directories** instead of single
`stream.jsonl` / `annotations/<producer>.jsonl` files. The file monitor
writes through `ChunkedJsonl`: rolls at `monitors.file.chunk_bytes`
(default 5 GiB), optionally seals full chunks with seekable zstd in
background threads (`monitors.file.compress`, default on), and seals the
live chunk on `finalize()` (trainer now calls
`asyncio.run(monitors.finalize())` at shutdown). Index rows add
**`chunk`** beside chunk-relative **`offset`**.
>
> **`monitors.file.float_decimals`** (default 4) rounds per-token floats
in episode `to_record(...)` and trainer annotation streams; trainer
streams also emit **`null`** outside the loss mask for better
compression without changing what readers fold onto traces.
>
> The **dashboard** detects chunked streams via the index, reads
episodes and annotations with `open_chunk` (plain or `.zst`), versions
caches/etags on index size, and builds series summaries by walking the
index one chunk at a time. **Breaking:** tools and scripts must use
`zstd -dcf <stream-dir>/*` and per-producer chunk dirs under
`annotations/`. New dependency **`pyzstd`**.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
62a6893f75cbc770cbad06fd65d640aec13f058b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Initial commit for adding deepseek v4 flash.
This architecture brings in multiple new ingredients and will require
multiple commits for a fully mature implementation to be ready. The
present PR should be regarded as the very rough first draft, focused on
unblocking basic SFT runs.
Other notes:
* I am attempting to isolate most changes to live under
`trainer/models/deepseek_v4/` to keep the PR clean and easier to iterate
on later without entangling this code with other `prime-rl` changes.
E.g. the `deepseek_v4/attention.py` impls may eventually get hoisted to
`attn.py`
* Does not yet implement methods needed for RL weight broadcasting
(blocking evals as well)
* We will incrementally pull in kernels to replace the current
pure-eager torch impl
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Use the standard zero-indexing convention for `position_ids` in patched
LM head forward, (`_patch_model_forward`), rather than one-indexing.
A uniform shift is mathematically invisible to RoPE, which sees only
query-key angle differences, but it is wrong for attention that keys off
absolute token indices (as is important for deepseek v4 where
compression boundaries are tied to absolute positions).
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
## Summary
Every rollout episode is written to disk exactly once, as an
arrival-ordered stream, and everything learned about it afterwards is an
append-only annotation folded back on read. The trainer's recomputed
per-token streams ride that mechanism, and the trace viewer renders them
as overlays (entropy, the trainer↔sampling mismatch, the IPO stable
mask) next to the loss mask.
**Layout** (replaces
`rollouts/step_N/{train,eval}/{all,effective}/traces.jsonl`):
```
<run_dir>/monitors/file/metrics.jsonl # every metric row, tagged by producer
<run_dir>/monitors/file/traces/stream.jsonl # every episode, appended as it arrives
<run_dir>/monitors/file/traces/stream.index.jsonl # one compact row per episode, with its byte offset
<run_dir>/monitors/file/traces/annotations/<producer>.jsonl # trace updates: orch ship-time facts, trainer per-token streams
<run_dir>/monitors/file/traces/annotations/<producer>.index.jsonl # each update's scalars and where its record sits
```
Everything the file monitor dumps lives under its own directory, and
nothing is written there when the monitor is off. The traces and
everything written about them sit under `traces/`, and every index is
named for the stream it indexes and sits beside it. Each file is
append-only with exactly one writer, so there are no locks and live
tailing keeps working.
**Steps are events, not locations.** A trace is dispatched at one step,
arrives at another and is trained at a third, so a step directory could
only ever be honest about one of them — and picking arrival forced the
arrival step onto the batch wire just so the trainer could find the
right directory. Instead each step is stamped as its own event on the
record. `orchestrator/annotations.py` owns both events: `stamp_arrival`
puts `info.kind` plus `info.dispatch` / `info.arrival` (`{step, time}`)
on a trace as its episode lands, and `stamp_ship` produces the update
carrying `info.effective` and `info.ship` — the orchestrator step whose
batch shipped the cohort, or for eval the policy version the epoch
measured. Staleness is `ship.step - dispatch.step`; the trace viewer
shows all three for a train trace, and an eval trace shows the step it
measured instead (it never ships in a batch and never goes stale).
- **Annotations**: one record format and one fold, in
`prime_rl.monitors.trace_updates`, used by the file monitor, the trainer
writer and the dashboard. An update names a trace and carries an `info`
dict merged into the trace's own plus per-branch token streams,
full-length over the branch's token prefix (nulls mark unknown
positions) so folding never depends on the producer's loss mask.
- **Indexes**: the file monitor summarises each episode into
`stream.index.jsonl` as it writes it, and each update's scalars into the
producer's `.index.jsonl`, both with byte offsets. A reader browses the
indexes and seeks for the one episode it opens, so the cost of listing a
run stops scaling with the token streams — which outweigh the episodes
themselves.
- **Branch identity on the batch wire**: `TrainingSample` gains
`trace_id` / `branch_index`; `MicroBatch` carries them per sequence,
parallel to `sequence_lengths`, preserved through packing/padding and
nulled on dummy micro batches.
- **Trainer**: accumulates one update per trained sequence per forward
(packing-boundary first value and non-finite values are null), gathers
them to rank 0 at the end of each step, and logs them through its own
file monitor — the same monitor it already logs metrics through — rather
than writing to disk behind it. Always on; the token-export path is
gone.
- **Dashboard**: same HTTP API shape. The traces tab opens on the whole
stream — newest first, paged as you scroll, with a histogram of episodes
finished per interval you can click to narrow to a moment — and switches
to step mode for the cohort that shipped at one step (arrow keys walk
the step bar). Episode reads fold every annotation onto the record, so
the overlays work in both views. Token signals are Advantage, Entropy,
Mismatch (`r − log r − 1`, computed client-side from the trainer and
sampling logprobs), Stable mask (`|Δp|` vs the run's IPO `eps`), Loss
Mask and Content Mask; an overlay the open episode cannot colour is
disabled in the selector and names the input it is missing, rather than
silently painting nothing. In a token overlay the reasoning renders
inside the token spans that already cover it instead of in its own box.
- Verifiers gained only the two per-token node fields the records land
on (`MessageNode.trainer_logprobs` / `entropies`, with matching `Branch`
spread properties) —
[verifiers#2481](https://github.com/PrimeIntellect-ai/verifiers/pull/2481),
merged; `deps/verifiers` tracks verifiers main.
## Verification
Reverse-text, 4 steps: 645 episodes on one stream, 496 annotated by both
producers, 55,694 masked tokens folded with every node's compact arrays
equal to its masked-token count. Mean KL mismatch 0.0014, mean entropy
0.61. Staleness came out as 336 traces shipped at their dispatch step
and 160 a step later — the lag the old layout could not express. Re-run
end to end on a 20-step reverse-text run after the layout change.
SFT-online-eval and verifiers `uv run eval` run shapes checked through
the real API with a FastAPI test client; the dashboard's browser smoke
suite covers the stream/step views, the histogram, the step bar and
every token signal.
## Breaking
- The `rollouts/` trace tree is gone. Episodes now live in one
`monitors/file/traces/stream.jsonl` stream, written once at arrival,
with the effective cohort expressed as
`monitors/file/traces/annotations/<producer>.jsonl` records instead of
duplicate episode copies (per-token advantages and the scalar advantage
now arrive via annotations). The dashboard reads only the new layout;
runs recorded before this change need the old dashboard.
- `metrics.jsonl` moves from the run root to
`monitors/file/metrics.jsonl`.
- `trainer.enable_token_export` is removed and `token_exports/` is no
longer written; the trainer's per-token streams are always logged as
annotations.
- The filesystem batch transport writes packed micro batches to
`batches/step_<n>/rank_<r>.bin` (previously `rollouts/step_<n>/`).
## 20-step GLM-Air ScaleSWE comparison
- The baseline ran `main`; the comparison ran this PR. The code change
was the only behavioral difference. Run names, output directories, and
conversion cache paths were isolated.
- Trainer step 1: before 874.0 s; after 822.0 s (-5.9%).
- Trainer steps 1–20: before 3,179.2 s; after 2,995.2 s (-5.8%).
- Steady trainer steps 2–20: before 121.3 s mean / 120.0 s median; after
114.4 s mean / 99.0 s median. The after run was 5.7% faster by mean step
time.
- Trace data at each run's trainer step-20 cutoff: before 3.516 GB
across duplicated `all` and `effective` traces; after 3.476 GB across
the arrival stream plus orchestrator and trainer annotations. The after
layout was 1.1% smaller despite 864 MB of per-token trainer logprob and
entropy annotations.
- Dashboard on the after run at step 20: a 128-episode page took 15.7
ms, a 2.22 MB annotated episode took 42.7 ms, and its timeline took 9.7
ms.
The after job was cancelled after step 24 at the researcher's request.
The baseline completed trainer step 20.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Large observability and on-disk contract change (breaking paths and
removed `trainer.enable_token_export`); training/orchestration logic is
mostly additive but any tool still expecting `rollouts/` or root
`metrics.jsonl` will break.
>
> **Overview**
> Replaces the per-step `rollouts/.../traces.jsonl` tree with a **file
monitor layout** under `monitors/file/`: metrics at `metrics.jsonl`,
episodes in one append-only `traces/stream.jsonl` plus sidecar indexes,
and **append-only trace annotations** per producer (orchestrator
ship-time facts, trainer per-token streams).
>
> **Orchestrator/evals** stamp arrival metadata on episodes at log time
and log **effective cohort** membership, advantages, and ship step via
`log_annotations` instead of duplicating episode files. **Trainer**
drops `enable_token_export` / `token_exports/`; per-token logprobs and
entropies always go through the same annotation path. **Dashboard**
reads the new layout: stream vs step cohort views, paged
`/api/runs/.../episodes`, arrival histogram, and token overlays
(entropy, mismatch KL, IPO stable mask, masks) folded from annotations.
>
> Docs, skills, configs, and `run_single_benchmark.py` are updated for
the new paths and for skipping non-step metric rows. Filesystem batch
transport writes to `batches/step_*` instead of under `rollouts/`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
16bf663b7805ecfe7d993ff6b6d34c8b7bc47308. 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>
## Summary
- Add typed top-p and top-k settings for policy rollouts.
- Capture vLLM 0.28 sampling masks and replay the truncated distribution
in the trainer.
- Bound sampling masks with a default `top_k = 512` when truncation is
enabled.
- Use Model Runner V2 for router replay on standard deployments.
- Support router replay and sampling replay together on Model Runner V2.
- Keep NIXL P/D router replay on V1 and reject the unsupported combined
P/D mode.
- Use `SamplingMask` and `sampling_mask` across Renderers, Verifiers,
and prime-rl.
- Pin merged Renderers and require its published `0.1.12.dev2` build.
- Pin Verifiers to the latest `main` after its sampling-mask merge.
- Document standalone capture, the NIXL replay matrix, and sampling-mask
layout examples.
- Shard sampling masks with labels for multimodal context-parallel
training.
- Reject mixed enabled and disabled top-k settings across live-policy
train sources.
This builds on vLLM 0.28.0 from #3430. It supersedes #3235. The capture
side uses vLLM's native sampling-mask support from
[vllm#49577](https://github.com/vllm-project/vllm/pull/49577).
## Usage
```toml
[orchestrator.train.sampling]
top_p = 0.95
top_k = 20
```
There are no replay flags for sampling replay. Truncated policy sampling
enables mask capture and trainer replay automatically.
Set `trainer.enable_router_replay = true` to combine router replay with
sampling replay. Standard deployments use Model Runner V2 for both
captures. Disaggregated NIXL deployments keep router replay on V1 and
cannot combine both replay modes.
## Behavior
- Policy sampling with `top_p < 1` or `top_k` gets a bounded sampling
mask.
- Truncation without an explicit `top_k` defaults to 512.
- Different truncating sources can use different top-p values; each gets
a positive top-k.
- Mixed top-k capture modes across live-policy sources are rejected.
- Values above 512 are rejected to bound trainer memory.
- The trainer renormalizes each sampled token over the same mask as
inference.
- Frozen-source environments do not require masks.
- `opd` and `opsd` reject truncated policy sampling because their
reference scores use the full vocabulary.
- vLLM rejects sampling-mask requests with `temperature <= 0` or without
an effective `top_k > 0`.
## Runs
GLM-4.5-Air on `scaleswe` on 4 nodes
| Run | Runner | Router replay | Top-p | Effective top-k | Nodes |
| --- | --- | --- | --- | --- | --- |
| `glm-air-v1-baseline` | V1 | Off | 1.0 | Off | 6 |
| `glm-air-v2-baseline` | V2 | Off | 1.0 | Off | 6 |
| `glm-air-v2-router-replay` | V2 | On | 1.0 | Off | 6 |
| `glm-air-v2-top-p-0.95` | V2 | Off | 0.95 | 512 | 6 |
| `glm-air-v2-router-replay-top-p-0.95` | V2 | On | 0.95 | 512 | 6 |
<img width="279" height="238" alt="Screenshot 2026-09-01 at 3 45 20 PM"
src="https://github.com/user-attachments/assets/bbbf5334-4b06-4573-9232-80d9207a97e6"
/>
<img width="286" height="226" alt="Screenshot 2026-09-01 at 3 46 03 PM"
src="https://github.com/user-attachments/assets/8d048fb1-3e2a-4484-a437-8084d845d47e"
/>
<img width="285" height="238" alt="Screenshot 2026-09-01 at 3 45 39 PM"
src="https://github.com/user-attachments/assets/ca5c21c7-6355-497f-a553-adade238dc1a"
/>
Sampling replay leads to
- no reduction in step 0 KL mismatch
- more stable KL mismatch in conjunction with router replay
- more stable entropy (not rising)
- slower step time (follow-up perf investigation TBD)
## Verification
- `uv run pytest -q tests/unit/test_configs.py -k 'policy_sources'`: 2
passed.
- `uv run pytest -q tests/unit/test_configs.py -k 'not
test_load_configs'`: 69 passed and 67 deselected.
- Pre-commit checks passed for the changed config and test files.
- `uv run pytest tests/unit/train/rl/test_fused_lm_head.py
tests/unit/train/rl/test_loss.py -q`: 19 passed and 1 skipped after the
context-parallel fix.
- `uv run pytest
tests/unit/test_configs.py::test_combined_replay_uses_v2_runner -q`:
passed after the documentation review.
- `uv sync --all-extras`: passed with merged Renderers and Verifiers
dependencies.
- `uv run pytest tests/unit/orchestrator tests/unit/inference
tests/unit/train/rl/test_loss.py
tests/unit/train/rl/test_fused_lm_head.py
--ignore=tests/unit/orchestrator/test_qwen3_vl_e2e.py -q`: 108 passed
and 1 skipped.
- The excluded Qwen3-VL test has an existing fake-response fixture
mismatch.
- `uv run rl @ examples/basic/reverse-text/rl.toml --max-steps 5
--orchestrator.train.sampling.top-p 0.95`: completed five trainer and
orchestrator steps on the final dependency chain.
- The end-to-end run used Model Runner V2, effective `top_k = 512`, and
sampling-mask capture. Final mismatch KL was 0.0035 with no rollout
errors.
- Renderers: `uv run pytest tests/test_client.py -q`: 21 passed and 5
skipped. Ruff and format checks pass.
- Latest Verifiers main: `uv run pytest
deps/verifiers/tests/v1/test_graph.py
deps/verifiers/tests/v1/test_trace.py -q`: 21 passed. Ruff, format,
type, and pre-commit checks pass.
- Reverse-text baseline, top-p 0.95, and top-p 0.95 plus top-k 20 runs
completed with 100% sampling-mask coverage.
W&B:
`reverse-text/reverse-text-native-replay-{baseline,topp095,topp095-topk20}`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Changes core RL logprob/importance-ratio math and vLLM runner
selection; misconfiguration or missing masks can bias training or fail
at runtime, though validation and runtime checks aim to catch
incompatible modes.
>
> **Overview**
> Adds **sampling replay** so policy rollouts with `top_p < 1` or
`top_k` stay aligned with trainer importance ratios: vLLM 0.28 returns
per-token sampling masks (`enable_return_sampling_mask` /
`--return-sampling-mask`), and the trainer renormalizes logprobs over
the same mask instead of the full vocabulary.
>
> **Config & orchestration:** `TrainSamplingConfig` gains typed `top_p`
and `top_k` (truncation via `extra_body` is rejected). The `rl`
entrypoint auto-enables mask capture when policy sampling truncates;
unbounded truncation defaults `top_k = 512`, values above 512 are
rejected, `temperature = 0` and `opd`/`opsd` are blocked. Policy train
sources must agree on top-k capture mode (engine-wide). **Inference:**
new `enable_return_sampling_mask`; vLLM env setup prefers **V2** for
sampling capture and for router replay on standard deployments, while
**disaggregated NIXL P/D** keeps routed-expert capture on V1 and
**rejects** router + sampling replay together.
>
> **Data path:** `SamplingMask` on `TrainingSample` / `MicroBatch`,
encoding in trajectories, packing/padding in the trainer batch builder,
and a hard error in `TrainSink` if truncated rollouts lack masks.
**Trainer:** masks flow through CP sharding; fused `lm_head` and
vanilla-path `selective_log_softmax_with_sampling_mask` compute
mask-renormalized logprobs (Gemma softcap heads explicitly unsupported).
Docs cover sampling replay; `renderers` is bumped for mask support in
the rollout stack.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
cee517e2266a2b819765612ccf3a10ba8801a23e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- advance the `deps/verifiers` submodule from `e2103d6` to `d4a2177`
- include merged Bash and RLM context compaction from verifiers #2454
and #2459
- pick up nano-rlm compaction commit `4ef3438` through the default RLM
harness pin
- refresh `uv.lock` for verifiers' `aiohttp>=3.14.1` requirement
- migrate three RLM examples to `compaction.summarize_at_tokens`; use
the former range's `98_304` midpoint
- include the optional ACP semantic-edge and shared harness utility
changes already on verifiers `main`
Companions: [verifiers
#2454](https://github.com/PrimeIntellect-ai/verifiers/pull/2454),
[verifiers
#2459](https://github.com/PrimeIntellect-ai/verifiers/pull/2459), and
[nano-rlm #147](https://github.com/PrimeIntellect-ai/nano-rlm/pull/147).
## Breaking
- RLM harness configs must move `summarize_at_tokens` to
`compaction.summarize_at_tokens`.
- Leave `compaction` unset to disable proactive and reactive compaction.
## Verification
- `git diff --check`
- `uv lock`
- `uv lock --check`
- `uv run pytest -q tests/unit/test_configs.py` — 133 passed
- `git submodule status deps/verifiers` —
`d4a217794fc0bfd70369a8230e56653c193da8ce`
- verified that `d4a2177` descends from the previous `e2103d6` pin
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Submodule bump plus a breaking harness config shape affects all RLM
runs still using the old `summarize_at_tokens` field; example migrations
are mechanical but custom configs must be updated.
>
> **Overview**
> Advances the **`deps/verifiers`** submodule to pick up merged Bash/RLM
**context compaction** (and related harness defaults), with
**`uv.lock`** refreshed so **`aiohttp`** meets the new **`>=3.14.1`**
floor.
>
> **Breaking for RLM harness TOML:** flat
**`env.agent.harness.summarize_at_tokens`** is replaced by
**`env.agent.harness.compaction.summarize_at_tokens`**. The three
advanced examples (**`glm-4.5-air/search`**, **`glm-4.5-air/terminal`**,
**`nemotron-3-super/swe`**) are updated accordingly—train sources that
used a two-threshold list **`[65536, 131072]`** now use a single
**`98304`** threshold; eval sources keep **`98304`** but under the
nested **`compaction`** key.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7429aba97da77a30db191432d5295827c64ae621. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- add top-level `[ckpt]` and `[resume]` support to standalone `uv run
evals`
- write atomic cursor checkpoints at
`<output_dir>/checkpoints/step_N/evals/progress.pt`, where N is the
durable eval-source task cursor
- store only the cursor in eval progress checkpoints; generated episode
records are not copied into checkpoint payloads
- resume with `--resume`, `--resume.step N`, or `--resume.dir
path/to/checkpoints/step_N` by skipping the durable cursor prefix
- retry partial groups and out-of-order completions beyond the durable
cursor
- size resumed eval batches to the remaining queued task suffix
- reject checkpointing in online mode, where progress is coupled to the
trainer weight-broadcast lifecycle
- keep the training start-run skill current with the new workflow
- clarify that checkpoint writes use temp-file replacement so resume
never observes a partial pickle
## Verification
- `uv run pytest tests/unit/evals/test_ckpt.py` — 3 passed
- focused `ruff check` — passed
- focused Python `ruff format --check` — passed
- `git diff --check` — passed
Local note: `uv run evals --help` is currently blocked before CLI
loading by the locked `prime-sandboxes==0.2.39` / `connectrpc==0.11.1`
import mismatch (`connectrpc.client` is missing).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Shared orchestrator types (`Dispatcher`, `EvalSource`, `EvalSink`)
change, but checkpoint/resume logic is gated to standalone evals with
config validation; unit tests cover cursor and I/O semantics.
>
> **Overview**
> Standalone `uv run evals` can now be made **interruptible** via
optional `[ckpt]` and `[resume]` on `EvalsConfig` (rejected when
`[online]` is set).
>
> Progress is a **task cursor** over round-robin eval tasks:
`EvalSource` assigns `source_index`, advances the durable cursor only
over a fully completed prefix (`mark_completed`), and on resume skips
tasks below the loaded cursor. `CheckpointManager` writes only
`{"cursor": N}` to `<output_dir>/checkpoints/step_N/evals/progress.pt`
using atomic temp-file replace; saves run every `ckpt.interval`
completed groups in standalone mode.
>
> The evals loop loads resume state at setup, sizes epochs with
`EvalSink.set_batch_size` from remaining queued tasks, and on each
finished eval group calls `dispatcher.pop_source_index` to drive
checkpointing. Online eval rollout totals use the triggered queue
instead of full env example counts.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d4dc69fac552a55cb6c7c412a0d4e1b194a39c03. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Why
`libfabric` needs a newer `libefa.so.1` (symbol version `EFA_1.4`) than
this image's own apt-installed rdma-core provides, so NCCL fails to load
the OFI plugin: `version 'EFA_1.4' not found`.
## What
- The AWS EFA installer upgrades rdma-core system-wide via its own
apt/dpkg step, but running it in a separate build stage and copying out
only `/opt/amazon` left that system-wide upgrade behind — libfabric
ended up paired with the older, separately-apt-installed rdma-core.
- Run the installer directly in the runtime stage instead, so its
rdma-core upgrade lands in place with no copy-forwarding gap.
- Verified locally: before the installer, stock rdma-core
(50.0-2ubuntu0.2); after, upgraded to 61.0-1 system-wide,
`libfabric.so.1` resolves `libefa.so.1` cleanly, and
`libnccl-net-ofi.so` dlopens with zero missing dependencies.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes CUDA image build and RDMA/EFA library versions used for
multi-node NCCL; incorrect pairing could still break distributed
training on EFA hosts, but the change targets a known symbol-version
mismatch.
>
> **Overview**
> Fixes NCCL OFI plugin load failures (`EFA_1.4` not found) by changing
**how** the CUDA image gets the AWS EFA stack, not by adding new runtime
behavior.
>
> The dedicated `efa-installer` build stage and `COPY
--from=efa-installer /opt/amazon` are removed. The same AWS
`efa_installer.sh` run (still with `--skip-kmod` and
`--skip-limit-conf`) now executes **in the final runtime image**,
immediately after the base `apt` install of `libibverbs` / `librdmacm`
and related packages. That way the installer’s system-wide rdma-core
upgrades stay in the image libfabric actually runs in, instead of
shipping only `/opt/amazon` from an isolated stage paired with older
distro rdma-core.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6f879a4bf88704c58b5719b1c8635258121ae2de. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Why
NCCL now finds `libnccl-net-ofi.so` but fails to load it:
`libhwloc.so.15: cannot open shared object file`, falling back to
sockets.
## What
- Add `libhwloc15` to the runtime stage's apt install list.
- The EFA installer stage pulls in libhwloc as one of its own
dependencies, but only `/opt/amazon` gets copied forward into the
runtime stage — the shared lib itself never did.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Single-package addition to the Docker runtime image with no
application code or auth/data-path changes.
>
> **Overview**
> Fixes NCCL failing to load the AWS OFI network plugin
(`libnccl-net-ofi.so`) because **`libhwloc.so.15`** was missing at
runtime, which forced a fallback to sockets.
>
> The CUDA **runtime** stage now **`apt install`s `libhwloc15`**
alongside the other RDMA/EFA-related packages. The EFA installer stage
already pulled in hwloc as a dependency, but only **`/opt/amazon`** is
copied into the final image—not the distro **`libhwloc`** package—so the
shared library never landed in the runtime filesystem.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a1d18804238afc171a4e8b856e86c24818d2b95d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Why
Trainer crashes with `ModuleNotFoundError: No module named
'prime_kernels'` on startup. `collectives.py` imports it unconditionally
at the top of the file.
## What
- `prime-kernels` is declared and pinned in `pyproject.toml`/`uv.lock`
under its own `kernels` extra, but that extra was never passed to `uv
sync` in `Dockerfile.cuda` — so it resolves but never actually installs.
- Add `--extra kernels` to both `uv sync` calls.
- Add `prime-kernels` to the post-sync version-check so a missing
install fails the build loudly instead of shipping silently.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Docker build-only dependency wiring with no runtime logic changes;
slightly larger images when the kernels extra is enabled.
>
> **Overview**
> Fixes CUDA Docker images that could start the trainer without
**`prime-kernels`**, causing **`ModuleNotFoundError: No module named
'prime_kernels'`** even though the package is pinned under the
**`kernels`** optional extra.
>
> Both **`uv sync`** stages in **`Dockerfile.cuda`** now pass **`--extra
kernels`**, so the wheel is actually installed into the venv. The
post-sync **`importlib.metadata`** smoke check also includes
**`prime-kernels`**, so a missing install fails the image build instead
of surfacing only at runtime.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
180ec8e7944f5be98a55a24200959fff882b652d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Bundles libfabric + the aws-ofi-nccl NCCL plugin into the image via
AWS's official installer, so NCCL can find the OFI plugin at runtime
instead of silently falling back to sockets
- Inert by default — only takes effect where a deployment's config
points `LD_LIBRARY_PATH` at it
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Docker build-only change that adds optional EFA libraries without
altering default runtime env or application code; main risk is larger
images and relying on the pinned AWS installer URL/version.
>
> **Overview**
> The CUDA runtime image now **ships the AWS EFA userspace stack**
(libfabric and the **aws-ofi-nccl** NCCL plugin) so multi-node jobs on
EFA-capable hosts can use NCCL’s OFI path instead of silently falling
back to sockets.
>
> A new **`efa-installer` build stage** on the same Ubuntu 24.04 base as
runtime downloads AWS’s official installer (default **1.47.0**), runs it
with **`--skip-kmod`** and **`--skip-limit-conf`**, and copies
**`/opt/amazon`** into the final image. **`LD_LIBRARY_PATH` is
unchanged** in the Dockerfile—deployments that have EFA on the host are
expected to prepend those libraries when needed; elsewhere the bundle
stays inert.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
007d6d6b8af5e5f567fa94fce5e2b6f06e02d62a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Replace method- and attribute-based selective activation checkpointing
with one non-reentrant checkpoint region around each selected
transformer block.
- Keep `mode = "full"` as the default. Full mode retains only mandatory
non-replayable operations and recomputes everything else; selective mode
additionally retains configured expensive operations through the same
Prime-owned policy.
- Allow selective mode to replace its public default targets with
explicit operator names or namespaces. Correctness-required targets
remain active for every selective configuration.
- Register real runtime boundaries for Torch EP/CP collectives, DeepEP
combine, ring attention, sparse MLA, dense/grouped DeepGEMM, MXFP8
transport, and MoE routing telemetry so checkpointing, autograd, and
compile observe the same operations.
- Keep sparse MLA dispatcher, fake, and autograd registration beside the
vendored forward/backward kernel entrypoints rather than in GLM model
code.
- Collapse ring attention into one backend-neutral forward/backward
custom-op pair. Its adapters call only the pinned FA2, FA3, and FA4 APIs
explicitly, without signature probing or generated per-backend
registrations.
- Remove checkpoint-only attention helpers and the model-specific
checkpointing module. Generic attention, AFMoE, Qwen3.5, and Laguna keep
their projection/output logic directly in `forward`; GLM DSA keeps only
its substantive `mla_latents` and `mla_up_proj` helpers.
- Rebase onto the Torch 2.13, CUDA 13, and vLLM 0.28 runtime from
current `main`, and update FlashAttention 4 to `0251105` with the shared
TVM FFI version required by vLLM.
- Ignore FSDP replay-only profiler markers when selective checkpointing
validates the saved forward operation sequence.
- Prefetch the final MoE block, experts, and separately wrapped router
before backward replay so FSDP collectives occur in the same order as
the saved forward.
## Runtime contract
- Model implementations do not expose checkpoint target names or
checkpoint-only methods.
- `freq` selects whole transformer blocks; the dispatched operator and
selected target set determine whether selective AC saves or recomputes
its result.
- Both modes retain mandatory MoE routing, telemetry, non-replayable
DeepEP, and CUDA-to-CPU metadata operations so they execute once. Full
mode recomputes every other operation; selective mode additionally
retains its configured targets.
- The default selective targets retain supported attention, matrix
multiplication, grouped GEMM, and distributed communication operators.
Elementwise operations, norms, reshapes, and RoPE replay.
- Custom targets replace the selective defaults and match either an
exact operator name or an operator namespace. They cannot exclude
mandatory routing, telemetry, non-replayable communication, or
CUDA-to-CPU metadata operations.
- Unsupported or missing backend operators fail at their normal call
site; there is no checkpoint fallback layer.
- MXFP8 transport resolves `mxfp8_moe` inside its custom-op
implementation. MXFP8 grouped compute still resolves it during runtime
setup because the exported grouped GEMM is already an operator boundary.
## Configuration
```toml
[trainer.model.ac]
mode = "selective" # full | selective
freq = 1
# targets = ["aten::mm", "prime_rl_collectives"]
```
Omitting `targets` uses the public Prime defaults. Any explicit list
replaces those defaults; an empty list retains only the mandatory
operations.
## Validation
- Ruff, Ruff formatting, `uv lock --check`, and `git diff --check`
passed.
- Focused config, checkpointing, and Qwen3.5 CP tests on the rebased
dependency stack: 138 passed.
- A6000 CI regression suite passed all eight checks: four-GPU peak
memory was 6.2467 GiB against the 6.2988 GiB baseline (down from 6.6185
GiB before the fix); one-GPU peak memory was 10.6738 GiB.
- Compiled selective AC with DeepEP completed a two-GPU, two-step
`samsja/mini-glm-moe` training smoke after rebasing onto the merged MoE
runtime.
- The pinned FA2, FA3, and FA4 varlen backends all use the `[heads,
total_tokens]` LSE layout; the ring fake and backward paths enforce that
single contract.
- Two-H200 compiled ring validation matched each backend's direct
attention reference exactly for FA2, FA3, and FA4 output and `dq`, `dk`,
and `dv`.
- Full H200 unit suite: 574 passed, 9 skipped.
- Eager and compiled output/gradient/replay validation passed for local
MoE, Torch EP, DeepEP with and without chunking, CP, FA2/FA3 ring
attention, sparse MLA, dense DeepGEMM, grouped DeepGEMM, and the
production MXFP8 transport boundary with a fake numerical kernel.
- FSDP parameter/state-dict parity and selective AC plus activation
offloading passed.
- Whole-model parity passed for Llama, Nemotron-H, GPT-OSS, AFMoE,
Laguna, and Qwen3.5 full-attention layers. Sparse MLA parity also passed
after restoring its substantive helper structure.
- On the stacked Qwen3.8 Flash Next implementation, selective and full
activation checkpointing each completed 20 RL steps on 24 H200s with
compile, FSDP, expert parallelism, SignSGD, NIXL policy reload, and CPU
optimizer-state offload. Steps 2-20 averaged 8,008 tokens/s for
selective and 7,211 tokens/s for full; both peaked at 130.4 GiB and held
mismatch KL at 0.0014-0.0021 with a final value of 0.0016.
## Hardware boundary
- Numerical MXFP8 grouped GEMM and transport still require SM100
hardware. The H200 validation exercised the production
custom-op/autograd/compile boundary with a BF16 fake transport kernel.
- FA4 forward/backward numerical validation passed on H200 (SM90);
Blackwell remains untested in this PR.
- Qwen3.5 GatedDeltaNet whole-model parity did not reach execution
because the no-AC reference forward remained in FLA kernel compilation
until the diagnostic jobs were cancelled. Qwen3.5 full-attention parity
passed, and the GatedDeltaNet runtime code itself is unchanged.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Touches core training memory/throughput (activation checkpointing),
distributed MoE/DeepEP/ring attention autograd, and compile
boundaries—incorrect replay or double-counted routing would show up as
silent wrong grads or NCCL deadlocks.
>
> **Overview**
> **Replaces layer-specific selective activation checkpointing** with
whole-block non-reentrant checkpointing driven by a PyTorch selective
operator policy (`activation_checkpointing.py`). Semantic targets like
`norm` / `attn_proj` are gone; `model.ac.targets` is now optional
operator names or namespaces that replace Prime’s defaults, while
mandatory saves still cover MoE routing/top-k, DeepEP, and CUDA→CPU
copies.
>
> **Registers distributed and kernel paths as `torch.library` custom
ops** so checkpoint replay, autograd, and compile see the same
boundaries: new `prime_rl_collectives` for EP/CP all-to-all and
gather/reduce-scatter, `deepep::combine`, unified `prime_rl_ring` ring
attention (FA2/FA3/FA4), `prime_rl::sparse_mla`, FP8/grouped FP8 GEMMs,
and `record_moe_routing_statistics` so routing counters are not
double-applied on recompute. Inline `autograd.Function` wrappers in
token dispatch, Mamba CP, and ring attention are removed in favor of
these ops.
>
> **Simplifies trainer wiring and models**: `apply_ac` always wraps
whole transformer blocks; the old `layers/checkpointing.py` hook layer
is deleted and attention modules no longer expose checkpoint-only
`attn_projections` / `output_proj` splits. FSDP backward prefetch now
includes the last block’s MoE experts/router. Docs, examples, and
benchmarks drop legacy selective target lists; **flash-attn-4** is
bumped to `0251105` with a pinned **apache-tvm-ffi** override.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3a51c78f1ed46b0603ec42c1011c36e14533b710. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Resolve SFT data shard identities after worker processes start.
- Shard fake data by DP rank while replicating it across CP ranks.
- Read epoch and sample progress from the furthest worker cursor.
- Aggregate per-source sample and token counters across workers.
- Preserve worker counters across dataloader checkpoint resume.
- Extend the existing CPU dataloader suite with tiny in-memory SFT data
across worker, DP, and CP layouts.
- Clarify the dummy renderer token decode in the sharding test.
## Verification
A one-GPU SFT run used two local dataset splits, two data workers, and
four logged steps.
- Before: sample progress was `5, 5, 9, 9`, and source ratio metrics
were absent.
- After: sample progress was `9, 10, 17, 18`, and source sample and
token ratios were present at every step.
- Before the sharding fix, two workers yielded `0, 0, 1, 1, 2, 2, 3, 3`
from increasing fake data.
- The CPU regression matrix verifies unique DP shards, CP replicas,
checkpoint resume, counters, and the `0 → 1` epoch transition.
- The fake-data test verifies distinct samples across DP ranks and
identical samples across CP ranks.
- The uneven-packing regression verifies that worker progress never
moves backward.
- `uv run pytest tests/unit/train/sft/test_dataloader.py -q` passed with
16 tests.
- `uv run ruff check tests/unit/train/sft/test_dataloader.py
src/prime_rl/trainer/sft/data.py src/prime_rl/trainer/sft/train.py`
passed.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes distributed data partitioning and checkpointed iterator state,
which can silently skew training if wrong; behavior is covered by
expanded unit tests but affects core SFT loops.
>
> **Overview**
> Fixes **incorrect SFT data sharding and stale progress metrics** when
using multiple DataLoader workers and/or context-parallel (CP) ranks.
>
> **Sharding:** `data_rank` / `data_world_size` are now derived from
**DP rank only** (`rank // non_dp_size`), so CP ranks see the same
samples while DP ranks stay distinct. Rank/worker identity is resolved
in **`__iter__` via `_setup_world_info()`** instead of at dataset
construction, so worker processes get the right shard after fork.
>
> **Progress & checkpoints:** `CatDataset` state now stores and restores
per-source **`num_samples` / `num_tokens`**. New
**`get_dataset_progress()`** reads worker snapshots, uses the **furthest
worker** for `step`/`epoch`, and **sums** counters across workers. SFT
training logs **`progress/*`** from the dataloader instead of the
main-process dataset object (which stayed at zero after resume).
>
> **Tests:** Dataloader tests drop the heavy tokenizer/GPU mark, add a
shared dummy renderer, and cover multi-rank/worker sharding, resume, CP
replication, and monotonic progress under uneven packing.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
30f7de1d229f8e88e0f334be6b8baaa7d2dccf14. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Remove dispatch-failure rates from per-step success logs.
- Exclude dispatch-failure metrics from curated W&B overview panels.
- Keep raw dispatch-failure metrics unchanged.
## Verification
Before: training success lines and W&B overview panels showed
dispatch-failure rates.
After: both summaries omit dispatch failures while the raw metrics
remain available.
- `uv run ruff check src/prime_rl/orchestrator/orchestrator.py
src/prime_rl/monitors/wandb/overview.py`
- `UV_PROJECT_ENVIRONMENT=/home/ubuntu/prime-rl/.venv uv run --no-sync
pytest tests/unit/orchestrator/test_metrics.py`
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Presentation-only changes to logs and W&B overview panels; dispatch
failure metrics and pipeline handling are unchanged.
>
> **Overview**
> **Dispatch failure rates are removed from operator-facing train
summaries** while leaving underlying W&B metrics intact.
>
> The per-step **Step …** success log (aggregate and per-env `╰─` lines)
no longer computes or prints **Dispatch Failure**; multi-env breakdowns
also stop folding `batch.failures` into env name lists. Docstrings now
describe window metrics as **Error**, **Cancelled**, and **Ratio** only,
and clarify that cancellations are pipeline decisions rather than
rollout failures.
>
> The curated W&B **overview** saved view drops
`all/dispatch_failure/mean` from `COMMON_METRICS`, so the default
dashboard panels no longer highlight dispatch-failure rate alongside
turns, tokens, and error/truncation signals. `dispatch_failure_metrics`
in `finalize_train_batch` is unchanged, so raw
`train/*/all/dispatch_failure/*` series remain available outside the
overview.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
db0d538c93bbcfa9e764e9f9f295dca9c1b45ab3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
Builds on the CUDA 13, Torch 2.13, and vLLM 0.27.1 stack from #3425.
- Bump vLLM to 0.28.0. Torch stays at 2.13.0+cu130; only the wheel pins
move. vLLM 0.28 requires `nvidia-cutlass-dsl == 4.6.2` and
`quack-kernels == 0.6.4`, so the override pin and its dependency
metadata move with it.
- Drop patches obsoleted by the pinned release (reviewed the
0.27.0/0.27.1/0.28.0 release notes and diffed the patched vLLM sources
between 0.27.1 and 0.28.0):
- `monkey_patch_harmony_stop_token_propagation` — fixed upstream by
vllm#35076 (in the release since 0.27.1).
- `monkey_patch_fp32_router_logits` — vLLM reads `moe_router_dtype` off
the HF config (vllm#47410) and forces fp32 routing for GLM-5.x.
`inference.enable_fp32_router_logits` keeps its name and default but now
injects `hf_overrides = {"moe_router_dtype": "float32"}` instead of
patching `DeepseekV2MoE`.
- `PrimeRlServingTokens` — upstream `serve_tokens` now handles DP-rank
header routing, server-side `max_tokens` defaulting, and `usage`
reporting (cached tokens surface via `--enable-prompt-tokens-details`,
which the launcher now sets). The subclass shrinks to the compact
`routed_experts` export and the `kv_transfer_params` engine bridge
(vllm#42644 merged 6h after the 0.28.0 cut — drop at the next bump).
- Follow vLLM's own V1/V2 model runner resolution instead of pinning V1
globally. vLLM resolves non-MoE generate models (plus an arch allowlist)
to the V2 runner. Only routed-experts capture still requires V1 (the V2
runner silently never captures routing decisions): the launcher pins
`VLLM_USE_V2_MODEL_RUNNER=0` when `enable_return_routed_experts` is set,
and the NIXL routed-experts patch rejects a V2 resolution explicitly.
Patches verified still needed on 0.28.0 (targets byte-identical or issue
still open): kv-xfer freed-request assert (vllm#46240), qwen3_coder
param newline trim, minimax-m2 think-end passthrough, TokenizeParams
validation, DP coordinator startup timeout, LoRA expert-key acceptance
(vllm#38522 closed unmerged), Qwen3.5-MoE 2D LoRA format, online-fp8
Parameter cast, nano_v3 reasoning parser, fp32 lm_head (kept over vLLM's
`head_dtype=float32`, which upcasts the weight per forward instead of
using an fp32-out GEMM), chat routed-experts strip.
Known 0.28 caveats:
- NIXL connector handshake version bumps 5 → 7: a 0.27 and a 0.28 engine
refuse to transfer KV to each other, so rolling P/D upgrades need a full
pool restart.
- vllm#50465 (batch-sharded sampling, merged after 0.28.0) silently
drops sampling masks under TP; re-check vllm#53826 before the next bump.
Validated on GLM-4.5-Air SWE
<img width="882" height="241" alt="Screenshot 2026-08-28 at 9 08 56 PM"
src="https://github.com/user-attachments/assets/d1af34c4-a80a-410b-bcdc-afdf0ffabd81"
/>
## Verification
- `uv lock --check`
- `uv run --frozen pytest -q tests/unit/test_configs.py
tests/unit/inference` (137 passed)
- Ruff check and format checks for the changed Python files
- E2E reverse-text RL on this branch (Qwen3-0.6B-Reverse-Text-SFT, 20
steps, 1 trainer + 1 inference GPU, NCCL broadcast): reward 0.18 → 0.81,
0% rollout errors, 100% trainable, mismatch KL 0.003–0.005. The engine
ran the V2 model runner (vLLM's default for this model) with the fp32
lm_head patch active. W&B: `reverse-text/reverse-text-vllm028-smoke`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> A broad inference dependency bump plus behavioral changes to MoE
routing, model-runner selection, and P/D KV transfer bridging;
misconfiguration could affect logprob fidelity, router replay, or
disaggregated decode performance until upstream fixes land.
>
> **Overview**
> Upgrades the GPU inference stack from **vLLM 0.27.1 to 0.28.0**, with
matching lockfile and wheel pins (`nvidia-cutlass-dsl` 4.6.2,
`quack-kernels` 0.6.4).
>
> **Config / launcher:** `to_namespace()` now defaults
**`enable_prompt_tokens_details`** so `/inference/v1/generate` `usage`
includes cached prompt tokens for router billing.
**`enable_fp32_router_logits`** no longer sets `additional_config`; it
injects **`hf_overrides.moe_router_dtype = "float32"`** so vLLM’s native
MoE routing path applies. **`VLLM_USE_V2_MODEL_RUNNER=0`** is set only
when **`enable_return_routed_experts`** is on (V2 never captures routed
experts); other models follow vLLM’s V1/V2 resolution.
>
> **Removed patches** superseded by 0.28: harmony stop-token merge on
chat completions, `DeepseekV2MoE` fp32 router monkey-patch, and most of
the custom `ServingTokens` fork (DP routing, `max_tokens` defaulting,
manual `usage` assembly). **`PrimeRlServingTokens`** now delegates to
upstream `serve_tokens` except for **`kv_transfer_params` →
`sampling_params.extra_args`** (PD disagg until vllm#42644 ships) and
compact **`routed_experts`** post-processing.
>
> **Other:** NIXL routed-experts guard uses
**`config.use_v2_model_runner`** instead of the env flag. Unit tests for
deleted helpers are trimmed; post-process test asserts `usage` is
preserved from upstream responses.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
77c9264df8bb12af89eda7c238e2415e9a339857. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- upgrade Torch to 2.13 and vLLM to 0.27.1 on CUDA 13
- pin matching CUDA 13 wheels for FlashAttention, prime-kernels, DeepEP,
DeepGEMM, TorchAO, NIXL, CUTLASS DSL, cuDNN, and vLLM
- load DeepGEMM only when FP8 kernels execute so CPU imports do not
require a CUDA toolkit
- reject TorchAO MXFP8 on GPUs other than SM100
- move native wheel builds to prime-kernels and remove the duplicate
PrimeRL workflow and build scripts
- use the CUDA 13 toolkit and runtime in the PrimeRL CUDA image
Validated against GLM-4.5-Air SWE run
<img width="295" height="227" alt="Screenshot 2026-08-28 at 7 29 36 PM"
src="https://github.com/user-attachments/assets/d125177e-86e0-4a2e-bb78-3a44bb4f15ce"
/>
<img width="294" height="239" alt="Screenshot 2026-08-28 at 7 30 05 PM"
src="https://github.com/user-attachments/assets/ea277670-c42a-49b6-a2cc-b10c5d9b8713"
/>
## Breaking
- remove `scripts/install_deep_gemm.sh` and
`scripts/install_ep_kernels.sh`; use the builders under
`deps/prime-kernels/scripts/` for source builds
## Verification
- `uv lock --check`
- `git diff --check`
- `bash -n deps/prime-kernels/scripts/install_deep_gemm.sh
deps/prime-kernels/scripts/install_ep_kernels.sh`
- Ruff check and format checks for the changed Python files
- verified that importing `prime_rl.trainer.model` does not import
DeepGEMM
- verified that MXFP8 rejects the local SM120 GPU with an SM100
requirement
- ran FlashAttention 2 forward on the local SM120 GPU
- `uv run pytest tests/unit -m "not gpu"`: 476 passed and one unrelated
Qwen3-VL fake-response assertion failed
- after merging `main`, focused config and MoE tests passed: 148 passed
and 3 skipped
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Wide dependency and Docker CUDA migration affects training, inference,
MoE/FP8, and disaggregated NIXL paths; MXFP8 now fails on non-SM100 GPUs
that previously passed the SM100+ check.
>
> **Overview**
> Moves the GPU stack from **CUDA 12.8 / torch 2.9 / vLLM 0.26** to
**CUDA 13 / torch 2.13 / vLLM 0.27.1**, with matching prebuilt wheels
(FlashAttention, prime-kernels, DeepEP, DeepGEMM, torchao, NIXL, cuDNN,
CUTLASS) pinned via `[tool.uv.sources]` to **prime-kernels** release
assets instead of prime-rl releases. `uv` **dependency-metadata**
overrides steer NIXL and CUTLASS toward CUDA 13 variants so cu12
packages are not pulled alongside extras.
>
> **CI and packaging:** Deletes `.github/workflows/build_kernels.yaml`
and the release jobs that built kernel wheels before publishing; native
wheel builds are documented as owned by the **prime-kernels** repo.
Removes in-repo `install_deep_gemm.sh` / `install_ep_kernels.sh` in
favor of `deps/prime-kernels/scripts/`.
>
> **Docker:** `Dockerfile.cuda` uses **nvidia/cuda 13.0.1** end-to-end,
drops the sidecar CUDA 13 runtime copy used for deep-gemm, and installs
**nixl_cu13** when building NIXL from source.
>
> **Runtime behavior:** **DeepGEMM** is imported lazily inside FP8
autograd paths so CPU-only imports do not require the CUDA toolkit.
**MXFP8** quantization is restricted to **exactly SM100** (not
“SM100+”), and torchao’s MXFP8 linear helper import path is updated.
Benchmark baseline JSON files are refreshed for the new commit and
benchmark harness fields.
>
> **Docs/skills:** Install and kernels skills describe `uv sync --extra
disagg` and prime-kernels release workflow instead of the removed
PrimeRL kernel CI.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4f6159cbe8333759cb55720ca2abaeeb7ff8b40b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
### Model and checkpoint contract
- Replace the separate standard, GPT-OSS, and Nemotron expert/router
implementations with one canonical MoE tree.
- Store routed expert weights as separate `gate_proj`, `up_proj`, and
`down_proj` parameters. Non-gated experts omit `gate_proj`.
- Nest every custom router at `mlp.router.gate`, routed experts at
`mlp.experts`, and optional shared experts inside `mlp`.
- Store the single selection-only router bias at
`mlp.router.selection_bias`; model-specific checkpoint names are
converted only at the HF boundary.
- Keep shared expert projections canonical. Qwen3.5 alone nests its
scalar sigmoid gate at `mlp.shared_expert.output_gate`, with conversion
mapping the standalone Hugging Face key at the boundary.
- Use the same activation protocol and `FeedForward` implementation for
dense MLPs, shared experts, and grouped experts.
- Make shared-expert construction exclusively parent-owned: model layers
pass an explicit `FeedForward`/subclass or `None`, while `MoEArgs` and
`MoE` never infer or construct one.
- Keep existing HF source layouts at the conversion boundary. GPT-OSS
alone adds the structural split/join required for its interleaved source
tensor.
- Require `.prime-v1` in reusable `<conversion_dir>/prime` caches so
legacy Prime layouts fail before loading.
### MoE runtime contract
- Use one routed execution sequence for every backend: dispatch tokens,
run canonical grouped experts, combine tokens.
- Select grouped expert compute through explicit BF16, DeepGEMM FP8, or
MXFP8 implementations. `MoEArgs` remains architecture-only.
- Select local/Torch or DeepEP token dispatch once during model setup.
Dispatchers own routing metadata, communication, padding, chunking, and
synchronization.
- Keep `TokenDispatcher` as the structural interface while a shared base
owns the canonical run/synchronize sequence; local, Torch, and DeepEP
implementations own only their dispatch/combine details.
- Keep DeepEP combine events, concatenate streams, and flattened
dispatch state owned by each dispatcher; chunking uses the equal input
shape shared by EP ranks and does not synthesize empty chunks.
- Ignore dispatch configuration when expert parallelism resolves to one
rank; local dispatch remains active and DeepEP has no optimizer side
effects.
- Keep grouped expert execution directly in `GroupedExperts.forward` and
router confidence accounting directly in
`TokenChoiceTopKRouter.forward`.
- Shard every canonical expert parameter with one backend-independent
`Shard(0)` placement.
- Keep dense linear quantization, routed-expert compute, and EP
transport independent.
- Remove the TorchTitan module hooks, expert decorator, dynamically
attached process group, backend attributes, tensor-subclass
interception, and process-global MXFP8 patches from the reachable path.
- Vendor the narrow MXFP8 grouped-GEMM and Torch EP transport
implementation in [prime-kernels PR
#1](https://github.com/PrimeIntellect-ai/prime-kernels/pull/1),
preserving the pinned torchao revision and BSD license.
## Public contracts
Checkpoint tree:
- `mlp.router.gate`: `nn.Linear`
- `mlp.router.selection_bias`: optional persistent selection-only buffer
- `mlp.experts.gate_proj`: stacked `nn.Parameter` for gated experts,
absent for non-gated experts
- `mlp.experts.up_proj`: stacked `nn.Parameter`
- `mlp.experts.down_proj`: stacked `nn.Parameter`
- `mlp.shared_expert.{gate_proj,up_proj,down_proj}`: `FeedForward`
projections when present
- `mlp.shared_expert.output_gate`: Qwen3.5-only scalar `nn.Linear`
- expert matrices: `[num_experts, output_features, input_features]`
Runtime configuration:
```toml
[trainer.model.moe.compute]
type = "bf16" # bf16 | deepgemm_fp8 | mxfp8
[trainer.model.moe.dispatch]
type = "torch" # torch | deepep
transport = "bf16" # bf16 | mxfp8 for torch dispatch
```
DeepEP owns its tuning fields:
```toml
[trainer.model.moe.dispatch]
type = "deepep"
num_sms = 20
token_chunk_size = 4096
```
This is intentionally breaking. `enable_grouped_gemm`, `enable_a2a`,
`ep_comm_backend`, `deepep_num_sms`, and `deepep_token_chunk_size` are
removed without aliases.
## Validation completed
- Foundation conversion, detector, marker, state-loading, checkpoint,
NIXL graph, and wire-format tests passed.
- Focused CPU configuration and MoE contracts: 143 passed.
- Focused MoE runtime configuration parametrizations after the EP=1
no-op change: 6 passed.
- Affected custom-model CUDA suite: 24 passed, 3 skipped across AFMoE,
GLM, GPT-OSS, Nemotron, Qwen3/Qwen3.5, and state loading.
- Final H200 model suite after execution-path cleanup: 81 passed, 3
skipped (Slurm 2597).
- Torch EP on two H200 GPUs passed with BF16 and DeepGEMM FP8, top-k 2,
both score locations, shared experts, gated/non-gated/bias variants,
uneven routing, a rank receiving zero routed tokens, and
input/router/expert gradients.
- Final Torch EP BF16 and DeepGEMM FP8 matrix passed after the cleanup
(Slurm 2596).
- DeepEP on two H200 GPUs passed with BF16 and DeepGEMM FP8, chunking
on/off, both score locations, shared experts, a rank receiving zero
routed tokens, and gradients.
- Final DeepEP BF16 and DeepGEMM FP8 matrix passed after the cleanup
(Slurm 2595).
- Parent-owned shared-expert construction: 16 focused CPU tests and 64
H200 model tests passed, with 3 expected skips (Slurm 2600).
- Full-graph MoE and shared `FeedForward` compile validation passed
after the ownership cleanup (Slurm 2601).
- Local DeepGEMM FP8 passed across all supported topology, activation,
and bias combinations.
- `torch.compile(fullgraph=True)` forward/backward passed for the full
MoE and shared `FeedForward` across all supported topology/activation
combinations.
- Single-rank DCP and Torch EP + FSDP DCP model/optimizer resume passed.
- The `mxfp8_moe` wheel build includes its public module, manifest, and
license; the module imports against the pinned torchao build.
- Unsupported H200 MXFP8 selection fails before model mutation.
- Review audit: every queued DeepEP combine event is now synchronized,
including chunked execution (two-H200 Slurm 2604).
- Dispatcher review cleanup passed on two H200s: DeepEP BF16/DeepGEMM
with chunking and a zero-receive rank (Slurm 2847), plus Torch EP
topology/bias/zero-receive coverage (Slurm 2848).
- The exact `reverse_text_moe` integration passed end-to-end on two
H200s with an isolated conversion cache (Slurm 2607).
- Conversion ranks now make the create decision on master and validate
`.prime-v1` only after the final all-rank barrier.
- Canonical router selection bias: 12 CPU MoE/conversion tests passed;
CUDA checkpoint loading, Nemotron, and GLM model tests passed, with the
existing GLM BF16 gradient comparison passing on isolated rerun after
one threshold-edge miss (Slurm 2851/2852).
- Ruff, Ruff formatting, compileall, and `git diff --check` passed.
## Deliberate exclusions
- MultiLoRA is not adapted to the new runtime and may fail.
- Fused-MoE trainer integration is removed and will be reconsidered only
after the canonical runtime is finalized.
- Routed-expert selective activation checkpointing is removed; the
remaining selective targets are unchanged.
## Remaining before marking ready
- Run numerical MXFP8 grouped-GEMM and MXFP8 Torch EP transport
forward/backward on SM100 hardware. The available Slurm fleet currently
has only H200 nodes.
- Merge prime-kernels PR #1, publish wheels containing `mxfp8_moe`, and
update the `pyproject.toml`/lock wheel pins. The currently pinned v0.8.0
wheel does not contain this module.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> This changes the MoE forward/backward path, expert-parallel dispatch,
checkpoint key layout, and trainer TOML in breaking ways across all
custom MoE models.
>
> **Overview**
> **Breaking trainer config:** MoE is configured via
`[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, `mxfp8`) and
`[trainer.model.moe.dispatch]` (`torch` with `transport`, or `deepep`
with `num_sms` / `token_chunk_size`). Dense
`[trainer.model.quantization]` no longer drives expert GEMMs or EP
transport. Removed flags include `ep_comm_backend`, `deepep_*`,
`moe_use_grouped_mm`, `moe_fused_kernel`, and quantization
`enable_grouped_gemm` / `enable_a2a`.
>
> **Unified MoE execution:** All custom models share one `MoE`
path—`TokenChoiceTopKRouter`, stacked `GroupedExperts` (`gate_proj` /
`up_proj` / `down_proj`), and a pluggable `TokenDispatcher`
(`LocalTokenDispatcher`, `TorchTokenDispatcher`,
`MXFP8TorchTokenDispatcher`, `DeepEPTokenDispatcher`).
`configure_moe_runtime` wires grouped GEMM backends and dispatch at
setup; EP weight sharding is only `ExpertWeightParallel`. DeepEP
dispatch/combine, grouped-GEMM permutation, and chunk pipelining live in
the new dispatcher layer instead of ad hoc `MoE` hooks.
>
> **Checkpoint and model surface:** PrimeRL checkpoints rename routed
weights from `w1/w2/w3` to `gate/down/up_proj`, move selection bias to
`mlp.router.selection_bias`, and add GPT-OSS HF↔prime conversion.
`LatentMoE` / Nemotron-specific expert classes are folded into the
canonical tree; dense layers use `FeedForward`. Reusable `prime`
conversion caches must include a `.prime-v1` marker.
>
> **Removed / docs:** Fused `flash_moe` trainer integration and
`bench_fused_moe.py` are dropped; `routed_experts` selective activation
checkpointing is removed. Docs and examples (e.g. GLM-5) are updated for
the new tables.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ffd5be7d48d28b889f9d73c8815ab0eb618b9dc9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Change
`prep_xfer_dlist(mem_type=...)` passed `"cuda"`, which nixl marks
deprecated in
favor of `"VRAM"` (`src/api/python/_api.py`):
"VRAM": nixlBind.VRAM_SEG,
"cuda": nixlBind.VRAM_SEG, # deprecated
Both resolve to `VRAM_SEG`, so this is a no-op at runtime. `"VRAM"` is
also the
spelling nixl's own `_tensor_mem_type()` helper emits.
## Note
The accelerator-derived `UCX_TLS` defaults this PR originally carried
are dropped
per review. Since `set_ucx_env_defaults()` uses `setdefault`, a non-CUDA
accelerator supplies its own copy transport from the launcher
environment.
---------
Signed-off-by: Yaser Afshar <yaser.afshar@intel.com>
## Summary
- use ModelExpress only for startup peer discovery and the trainer
tensor table, then use exact versioned NIXL notifications for all policy
transfers, including startup
- prepare static NIXL READ requests once, repost them after completion,
and post every trainer-rank pull in a group before waiting
- attach trainer arena credits to READ completion instead of performing
a separate acknowledgement handshake
- add explicit, opt-in two-arena overlap through
`weight_broadcast.overlap_transfer_and_replay`
The path remains receiver-driven PULL. The default remains one arena
because the second arena has a model-dependent GPU-memory cost. This PR
adds no fallback protocol, runtime sizing heuristic, profiling
instrumentation, or inference-scheduler change.
## Protocol
ModelExpress is the one-time startup discovery plane. It exchanges the
trainer tensor table and NIXL agent metadata, after which the fixed
peers establish NIXL/UCX connections. The shared
`WeightSender`/`WeightReceiver` sentinel handshake offers and
acknowledges every policy version before the NIXL transport runs; this
is the same outer lifecycle used by the other transports. MX source
statuses are not used. Policy 0 and later policies use exact NIXL ready
and complete notifications for the transfer itself.
```mermaid
sequenceDiagram
participant T as Trainer ranks
participant B as Broadcast directory
participant R as NIXL weight receiver
participant MX as ModelExpress
participant I as Inference ranks
Note over T,I: One-time setup
I->>MX: Publish inference NIXL metadata
R->>MX: Publish receiver NIXL metadata
loop Each policy version
T->>B: Offer version with sender ready marker
R->>B: Acknowledge with receiver ready marker
T->>B: Mark transfer started
alt First version
T->>MX: Publish tensor table and trainer metadata
T->>MX: Fetch inference and receiver metadata
R->>MX: Fetch trainer table and metadata
Note over T,I: Establish NIXL and UCX connections once
end
T-->>R: NIXL policy ready notification
R->>I: Update weights
loop Each transfer group
T-->>I: NIXL group ready notification
I->>T: Post READs to every trainer rank
T-->>I: RDMA payload
I-->>T: READ completion returns arena credit
end
I-->>R: Update complete
R-->>T: NIXL policy complete notification
T->>B: Commit version with finished marker
end
```
Each group signal contains `(group index, generation)`, and each policy
signal contains `(step, event)`, so it is consumed exactly once. A
trainer staging slot is reused only after every inference rank completes
its READ from that slot.
`NIXLWeightReceiver` owns the ModelExpress discovery session, local NIXL
agent, and typed trainer peer in the orchestrator process. The generic
orchestrator and `WeightWatcher` only use the `WeightReceiver` API and
contain no NIXL-specific state. Transfer plans and the trainer
broadcaster store ordered `NixlPeer` lists, so positional trainer-agent
indices stay direct list lookups and raw NIXL agent names remain inside
the adapter. On the trainer, `finish_transfer_group` waits for every
inference rank to complete a group before advancing its generation and
allowing its arena slot to be reused.
Tensor addresses, shard routes, peers, and descriptor lists remain
static for the worker lifetime. Requests are therefore prepared once and
reposted after completion. For each group, inference waits for every
serving trainer rank, posts all trainer-rank READs, and then waits for
completion. Inference ranks rotate their trainer order, while #3340 pins
each process to the active InfiniBand port nearest its GPU.
With overlap enabled, trainer and inference allocate exactly two
largest-group-sized arenas. Inference replays and quantizes group N
while receiving group N+1. Allocation is explicit: there is no
free-memory probe, automatic downgrade, or hidden retry.
## Measured results
Every populated cell below is the median of the positive framework
`time/broadcast_weights` samples; terminal zero entries are excluded.
This is the only timing definition used in the description. Parentheses
contain Slurm job IDs, and blank cells mean that configuration was not
measured.
| Model | Old NIXL | New NIXL | New NIXL + overlap | NCCL |
|---|---:|---:|---:|---:|
| Qwen3-30B-A3B | 4.651 s (2260) | 1.898 s (2278) | | |
| GLM-4.5-Air | 8.676 s (2286) | 4.125 s (2288) | 3.043 s (2305) | 7.616
s (2289) |
| GLM-5.2 | | 12.513 s (2297) | 8.577 s (2317, EP32) | |
All NIXL baselines use the correct rail pinning, and router replay is
disabled. The GLM-4.5-Air old, new, and overlap measurements are 20-step
Hendrycks-math runs with 4096 maximum sampling tokens; the NCCL
comparison uses the same model and node roles over three positive
broadcasts. NCCL uses BF16 checkpoint-format transfer with
`quantize_in_weight_transfer = false`.
GLM-5.2 job 2317 completed 20 rollout steps and 18 steady trainer
broadcasts on 64 trainer and 32 inference H200s. Framework
`time/broadcast_weights` was 8.577s median and 12.987s p95. At the
inference client, end-to-end synchronization was 7.899s median and
12.577s p95: pause was 5.204s median / 9.882s p95, while the weight
update itself was 2.842s median / 2.960s p95. Each inference GPU
received 82.501 GB per policy; across all 576 rank/version samples, RDMA
was 1.864s median / 2.027s p95, replay was 1.954s median / 1.993s p95,
and their overlapped process time was 2.682s median / 2.836s p95. Median
payload was 44.26 GB/s per GPU, or approximately 354 GB/s across an
eight-GPU inference node. The [W&B
run](https://wandb.ai/primeintellect/prime-rl/runs/c3bee790465640d88958f100fb3d74f4)
contains the completed training metrics.
On this single framework metric, Qwen improves by 59.2% from old to new.
GLM-4.5-Air improves by 52.5% from old to new and 64.9% from old to the
final overlapped path; the final path is 60.1% faster than NCCL. GLM-5.2
improves by 31.5% from the measured EP16 one-arena path to the EP32
overlap run. Holding overlap constant, EP32 reduces median framework
broadcast time by 11.4% from the EP16 result (9.683s, job 2301), while
median client update time falls by 19.4% from 3.524s to 2.842s.
Framework timing includes the unchanged vLLM pause/resume interval,
whose variance dominates the EP32 tail, so it should not be interpreted
as raw fabric bandwidth.
## Memory and scope
Overlap adds one largest-group arena rather than another model copy. For
GLM-5.2, that is 0.308 GB per trainer GPU and 3.807 GB per inference
GPU. The EP32 run therefore used a 7.613 GB two-buffer arena per
inference GPU and added 141.5 GB across the tested
64-trainer/32-inference topology. The option is disabled by default;
models without that headroom retain the one-arena path.
GLM-5.2 uses 64 trainer H200s with EP=8 and full offload, plus DP/EP
inference with online blockwise FP8 and DeepGEMM. EP16 receives 127.800
GB per inference GPU and retains 5,056 host-side handles per rank; EP32
receives 82.501 GB per GPU and prepares 72,819 descriptors across 79
transfer groups per rank. These request structures add no model-sized
GPU allocation.
Every serving trainer rank connects to every inference rank so
completion returns exact source credits. Static membership is the
expected hot path; elastic scaling and fault tolerance remain out of
scope.
## Numerical validation
Jobs 2286 and 2305 completed the configured 20 GLM-4.5-Air rollout steps
and finalized metrics. Step 20 of job 2305 contained 0/8 trainable
traces, so it correctly emitted no optimizer or mismatch-KL row. Across
the 19 steps with measurements in both runs, mean mismatch KL was
0.002602538 before and 0.002608075 after (+0.2%); median was 0.002786405
before and 0.002702605 after (-3.0%). Router replay was deliberately
disabled, so individual steps include normal sampling variation.
## Validation
- Ruff 0.15.14: `uv run ruff format --check` and `uv run ruff check`
- `uv run python -m compileall` on changed Python modules
- `uv run pytest -q tests/unit/test_configs.py`
- ported onto main at `21a4a3245` through #3340 at `0d809b1e4`; the
generic orchestrator and `WeightWatcher` are unchanged
- two-node, three-step Qwen3-0.6B end-to-end NIXL smoke (Slurm job
2451): startup policy v0 and policies v1-v3 synchronized; trainer and
orchestrator completed
- Qwen3-30B-A3B and GLM-4.5-Air eight-rail transfer benchmarks
- GLM-5.2 ten-node EP16 and twelve-node EP32 runs with full trainer
offload, online blockwise FP8 inference, and DeepGEMM
- matched NCCL comparison on GLM-4.5-Air
- final 20-step GLM-4.5-Air Hendrycks-math run with 4096 sampling tokens
and router replay disabled
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes core distributed weight-sync choreography between trainer,
orchestrator, and vLLM; mis-sync would cause stale weights or hangs,
though scope is limited to the NIXL transport path.
>
> **Overview**
> **NIXL weight broadcast** is reworked so ModelExpress is only used for
one-time peer discovery (trainer tensor table and NIXL agent metadata).
Per-group and per-policy coordination now uses **versioned NIXL
notifications** instead of ModelExpress READY/INITIALIZING buffer
sessions.
>
> The NIXL adapter gains **`PreparedRead`** / **`NixlPeer`**: READ
descriptor lists are prepared once, reposted each update, and all
trainer-rank pulls in a group are posted before waiting. Arena reuse is
tied to READ completion via group `(index, generation)` signals; the
orchestrator participates with policy `ready` / `complete` notifications
over NIXL.
>
> Inference follows the trainer’s **`staging_buffer_count`** (no GPU
free-memory sizing heuristic). Optional
**`weight_broadcast.overlap_transfer_and_replay`** allocates exactly
**two** largest-group arenas on trainer and inference so the next group
can be received while the current one is replayed; default remains one
arena.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0dc85f865aa7850e5a123fbb2791a9670c631d44. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- start a job-scoped Redis and ModelExpress service when
`slurm.launch_modelexpress = true`
- inject the trainer-head service address into trainer, inference, and
orchestrator processes, or use the configured host when
`slurm.launch_modelexpress = false`
- pin every NIXL process to the active InfiniBand HCA nearest its GPU,
so an eight-GPU node uses all eight rails
- add a pinned, idempotent installer for ModelExpress v0.3.0 and Redis
7.4.2
- remove stale job-scoped ModelExpress and Redis processes before
managed-service startup
This is the launch prerequisite for the stacked transfer optimization in
#3341. It does not change the NIXL transfer protocol itself.
## Design
With `slurm.launch_modelexpress = true`, the generated job removes stale
ModelExpress and Redis processes from an interrupted managed launch,
then starts both services on the trainer head before launching the three
prime-rl components. The resolved ModelExpress address is passed to
every component, and service logs stay in the run directory. With
`slurm.launch_modelexpress = false`, the launcher performs no service
cleanup, starts no service, and uses `weight_broadcast.host` and
`weight_broadcast.port` unchanged.
Rail selection remains local to each NIXL process. Unless
`UCX_NET_DEVICES` is explicitly configured, startup resolves the process
GPU's PCI path, selects the nearest active InfiniBand port, and
constrains UCX to that port. TP8 therefore uses one distinct local rail
per GPU instead of relying on UCX's cluster-dependent default choice.
`UCX_NET_DEVICES` remains an explicit site override.
The installer pins both service versions, verifies their checksums, and
reuses valid existing installations. Generated jobs fail directly if a
required binary or UCX capability is missing.
## Scope
- ModelExpress provides startup discovery for a fixed Slurm allocation.
- Elastic discovery, autoscaling, and fault tolerance are intentionally
out of scope.
- The local service adds two small CPU processes on the trainer head and
no GPU allocation.
## Validation
- `bash -n scripts/install_modelexpress.sh`
- ran `scripts/install_modelexpress.sh` twice and verified that the
pinned binaries are reused
- rebased onto `main` at `21a4a3245`; rendered and shell-checked managed
and external ModelExpress modes for single-node and multi-node NIXL
Slurm jobs, including main’s trainer/orchestrator completion markers
- verified stale-service cleanup is present only in managed ModelExpress
renders and absent in external-service renders
- Ruff 0.15.14: `uv run ruff format --check` and `uv run ruff check`
- `uv run python -m compileall` on changed Python modules
- `uv run pytest -q tests/unit/test_configs.py` (122 passed)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes multi-node SLURM launch and NIXL UCX/IB selection for weight
sync; misconfiguration or rail selection bugs could break or degrade
policy updates, but scope is limited to NIXL SLURM paths.
>
> **Overview**
> Adds **job-scoped ModelExpress + Redis** startup for SLURM RL when
`[weight_broadcast] type = "nixl"` and **`slurm.launch_modelexpress`**
is true (default). Single- and multi-node sbatch templates verify the
**`third_party/ucx`** build, optionally start pinned
**modelexpress-server** / **redis-server** (new
**`scripts/install_modelexpress.sh`**), wait for readiness, and pass
**`--weight-broadcast.host`** into trainer, orchestrator, and the local
`rl` launcher. With **`launch_modelexpress = false`**, jobs use
configured **`weight_broadcast.host`** / **`port`** and skip
managed-service cleanup.
>
> **NIXL networking** now picks **`UCX_NET_DEVICES`** per process from
the **InfiniBand port nearest each GPU** (unless already set), and
inference workers **rotate which trainer ranks they pull from** so
concurrent pulls spread across rails.
>
> Docs and the start-run skill describe install steps and the new SLURM
flag. **Does not change the NIXL transfer protocol** (prerequisite for
stacked transfer work).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0d809b1e4d24121690faab3a22b1f7f832de4f53. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Remove the DPPO loss and make IPO the default RL loss.
- Rename the IPO trust-region setting from `ipo_threshold` to `eps`.
- Update token exports, metrics, docs, tests, and agent skills for IPO.
## Breaking
- Remove `[trainer.loss] type = "default"`, `DefaultLossConfig`, and
`default_loss_fn`. Omit `[trainer.loss]` or set `type = "ipo"`.
- Rename `ipo_threshold` to `eps`. Update all IPO loss configs to use
`eps`.
- Remove the DPPO-only `dppo_mask_low` and `dppo_mask_high` settings.
- Remove the DPPO-only `is_masked_low`, `is_masked_high`, and
`masked_advantage_*` trainer metrics. Use `is_masked` for the IPO
trust-region mask.
## Verification
- RL loss GPU tests: 10 passed.
- Nemotron-H KL pipeline GPU tests: 7 passed.
- Ruff check and format hooks passed.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Removes the default RL loss and changes default training dynamics for
every run that relied on implicit DPPO; configs using `type = "default"`
or DPPO fields will fail or need migration.
>
> **Overview**
> Makes **Importance Policy Optimization (IPO)** the only built-in RL
loss and the default when `[trainer.loss]` is omitted. The DPPO-based
`default` loss (`DefaultLossConfig`, `default_loss_fn`, `dppo_mask_low`
/ `dppo_mask_high`) is removed.
>
> IPO trust-region config is renamed from `ipo_threshold` to **`eps`**
(default `0.1`). `setup_rl_loss_fn` always routes non-custom configs to
`ipo_loss_fn`.
>
> **Breaking for configs:** use `type = "ipo"` or omit the section;
`type = "default"` and DPPO knobs no longer exist.
>
> Monitoring and exports align with symmetric IPO masking: docs/skills
point to **`is_masked/mean`** instead of DPPO `masked_advantage_*`
metrics; W&B filtering drops the old DPPO-only series; token export
computes mask flags from `|prob_delta| > eps`. Unit tests now exercise
IPO instead of the default loss.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2c4227527992519e8ff7e1d08c8866c5068febb1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Write a shell-safe `command.txt` for every config attempt.
- Keep the outer command when a pinned child launch uses the same
attempt.
- Show each attempt's command in the dashboard Config view.
- Document the command artifact in the config and training runbooks.
<img width="2656" height="1506" alt="Screenshot 2026-08-26 at 11 34
20 AM"
src="https://github.com/user-attachments/assets/d5b4da3a-f6a9-4bdc-9c16-ae41c1d192c6"
/>
## Verification
- `uv run pytest tests/unit/utils/test_pathing.py -q`
- `uv run ruff check src/prime_rl/utils/pathing.py
src/prime_rl/entrypoints/rl.py src/prime_rl/entrypoints/sft.py
src/prime_rl/entrypoints/inference.py src/prime_rl/entrypoints/evals.py
src/prime_rl/dashboard/server.py tests/unit/utils/test_pathing.py
tests/integration/dashboard_smoke.py`
- `node --check src/prime_rl/dashboard/static/app.js`
- Ran reverse-text SFT through step 10 with `--max-steps 10`.
- Resumed reverse-text SFT from step 10 through step 11.
- Ran the dashboard browser smoke test against the per-attempt commands.
- Ran a two-node SFT SLURM dry-run and checked its pinned config
attempt.
- Ran a local SFT dry-run after the review changes and checked
`command.txt`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Adds run-metadata recording and dashboard read-only UI; no changes to
training, inference, or config resolution logic.
>
> **Overview**
> Each launch now writes **`command.txt`** under `configs/attempt_<n>/`
with the full **`uv run <entrypoint>`** invocation (CLI overrides
included), using **`shlex.join`** for shell-safe quoting.
**`write_launch_artifacts`** replaces direct **`write_launch_toml`** on
**`rl`**, **`sft`**, **`inference`**, and **`evals`**; the command file
is created **only if missing** so a pinned child process reusing the
same attempt keeps the **outer** launcher command.
>
> The dashboard **Config** tab surfaces that command (per attempt) with
a **copy** button; **`/api/runs/{run}/configs`** and
**`/api/runs/{run}/config`** expose **`command.txt`**. Docs and
training/config/dashboard skills describe the artifact and point
monitors to **`configs/latest/command.txt`**.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c9ce79c772d842af7556626a790e78faba20be75. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- cancel queued and in-flight SFT eval episodes when the trainer offers
a newer checkpoint
- report scores from completed episodes and log the cancelled count and
fraction for each superseded checkpoint
- show the cancellation fraction in the local dashboard and W&B eval
sections
- allow `eval.cancel_on_new_checkpoint = false` to drain every epoch,
which can idle the trainer while slow evals finish
- document the online-eval behavior and configuration
## Verification
- `uv run ruff check
packages/prime-rl-configs/src/prime_rl/configs/evals.py
src/prime_rl/evals/evals.py src/prime_rl/monitors/wandb/overview.py
tests/unit/test_configs.py`
- `node --check src/prime_rl/dashboard/static/app.js`
- `uv run pytest tests/unit/test_configs.py -q` (122 passed)
- two-GPU SFT and online-eval run with NCCL broadcast (steps 0 and 1
reported partial scores with 6 of 8 episodes cancelled; step 2 completed
all 8 episodes; the launcher exited successfully)
- dashboard browser smoke test for the cancellation panel and run
metrics
- `PYTEST_OUTPUT_DIR=/tmp/prime-rl-eval-cancel-tests uv run pytest
tests/unit -m "not gpu" -q` (477 passed, 86 deselected; one unrelated
baseline Qwen3-VL fixture failure in
`tests/unit/orchestrator/test_qwen3_vl_e2e.py`)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes online eval scheduling and trainer–evals checkpoint handoff;
mis-cancellation could skew eval metrics or stall weight updates, but
behavior is configurable and scoped to online evals.
>
> **Overview**
> Online SFT evals now **preempt unfinished epochs** when the trainer
publishes a newer checkpoint, so slow eval rollouts no longer block
loading the next weights. This is the default
(`eval.cancel_on_new_checkpoint = true`); set it to `false` to finish
every triggered epoch (the trainer may idle waiting).
>
> The evals loop detects a superseding published step, calls
**`Dispatcher.cancel_eval_step`**, and **`EvalSink`** counts cancelled
groups toward partial epochs instead of treating `GroupCancellation` as
fatal. **`GroupCancellation`** carries the eval **`step`** and a
**`superseded`** reason. Weight reload hooks **`on_version_pending` /
`on_new_version`** run before consuming the epoch. Partial results still
log with **`eval/{env}/all/cancelled/count`** and **`cancelled/mean`**
(dashboard and W&B overview panels added).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
730dce804cc20fb3257c8c3a457bb22f95a82e94. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- store launch TOML and resolved JSON files under `configs/attempt_<n>/`
- point `configs/latest` and `logs/latest` at the same launch attempt
- pin local and SLURM child processes to concrete attempt paths
- add config attempt selection to the dashboard
- default config and log selectors to `latest (attempt <n>)`
- keep the dashboard and checkpoint converter compatible with legacy
runs
## Breaking
- New runs no longer write configs to `configs/resolved/` or launch TOML
files directly under `configs/`. Update custom tooling to read
`configs/latest/resolved/` and `configs/latest/<entrypoint>.toml`. Use
`configs/attempt_<n>/` for a specific launch.
## Verification
Before this change, a resumed launch replaced the run-scoped config
files. After this change, both SFT and RL preserved attempt 1 and wrote
the resumed settings to attempt 2. Both `configs/latest` and
`logs/latest` resolved to `attempt_2`.
- SFT completed steps 1-5, then resumed from step 5 and completed steps
6-10
- RL completed steps 1-5, then resumed from step 5 and completed steps
6-10
- browser dashboard smoke passed for both resumed runs, including
attempt switching
- local, single-node SLURM, multi-node SLURM, and inference dry runs
produced matching attempt paths
- all generated SLURM scripts passed `bash -n`
- pathing unit tests passed: 11 tests
- Ruff checks and format checks passed
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes the on-disk run layout and all launch paths (local, SLURM,
evals); legacy fallbacks limit breakage, but custom tooling must move
from `configs/resolved/` to `configs/latest/resolved/`.
>
> **Overview**
> Each launch now keeps its **launch TOML and resolved JSON** under
**`configs/attempt_<n>/`** (resolved files in **`resolved/`**), with
**`configs/latest`** aligned to the same attempt as **`logs/latest`**.
Resumes no longer overwrite prior launch configs.
>
> Launchers allocate matching config and log attempts via
**`prepare_attempt_dirs`** / **`create_attempt_dirs`**, pin children
with **`PRL_ATTEMPT_CONFIG_DIR`** and **`PRL_ATTEMPT_LOG_DIR`**, and
SLURM templates receive concrete **`config_dir`** / **`log_dir`**
instead of shell attempt loops. **`evals`** writes attempt-scoped
configs like **`rl`** / **`sft`**.
>
> The **dashboard** adds a config **attempt** selector and **`attempt`**
query params on config APIs; logs already supported attempts and now
default to **`latest (attempt <n>)`**. **`get_config_dir`** and
dashboard resolution keep **legacy** `configs/resolved/` runs working.
>
> Docs, skills, **`convert_dcp_to_bf16`**, and tests/smoke cover the new
paths.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
29cab3515b5c1b97eaa3aa53f9be3b947a11802c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Expose whether an SFT run has a validation dataset in dashboard
metadata.
- Hide `val/loss` and `val/perplexity` plots when validation is not
configured.
- Keep both validation plots when the resolved SFT config includes
`val.data`.
## Verification
Before: `dashboard-sft-no-val-1-step` showed empty `val/loss` and
`val/perplexity` plots.
After:
- `dashboard-sft-no-val-1-step` shows only training loss, perplexity,
and epoch plots.
<img width="1607" height="1045" alt="Screenshot 2026-08-26 at 12 15
49 AM"
src="https://github.com/user-attachments/assets/d4ebe5bf-48fa-4f07-a626-0cb9f369dfa1"
/>
- `dashboard-sft-with-val-1-step` shows both validation plots and
reports `val/loss = 5.811`.
<img width="1607" height="1045" alt="Screenshot 2026-08-26 at 12 15
32 AM"
src="https://github.com/user-attachments/assets/4746e568-dea3-4660-9692-545bf2dfa5dd"
/>
Both runs completed one SFT step. A browser check confirmed the expected
plot titles and rendered validation data.
- Ran `node --check src/prime_rl/dashboard/static/app.js`.
- Ran `uv run --no-sync ruff check src/prime_rl/dashboard/server.py`.
## Summary
- Render a dot when a metric series has one data point.
- Keep line-only rendering after a second data point arrives.
- Apply the same behavior to auxiliary band series.
## Verification
Before: a metric series with one sample rendered no visible data. After:
the sample renders as a dot at its chart coordinate. The dot disappears
when a second sample arrives.
<img width="546" height="285" alt="Screenshot 2026-08-26 at 12 07 40 AM"
src="https://github.com/user-attachments/assets/4af1930a-4bc0-47d3-990f-4bf723b641d6"
/>
- Confirmed that one-point series enable markers and two-point series
disable them.
- Ran `node --check src/prime_rl/dashboard/static/app.js`.
## Summary
- run multi-node SFT training and online evals in one SLURM job
- reserve `num_train_nodes + num_infer_nodes` and assign inference nodes
first
- keep every node in the shared step until trainer and eval completion
sentinels exist
- keep trainer, inference, router, evals, and env logs in one
`logs/attempt_<n>` directory
- give standalone `evals` launches an attempt directory and update
`logs/latest`
- update configuration help, training docs, and run skills for the new
topology
## Breaking
- Multi-node SFT online evals now require one combined SLURM allocation.
The scheduler must allocate all trainer and inference nodes together.
Trainer nodes remain allocated until the final eval finishes.
- The launcher no longer writes `launcher/eval.sbatch`. Custom
multi-node SFT templates must launch inference and eval roles from the
main SFT template.
- The bundled `multi_node_sft_eval.sbatch.j2` template is removed. Use
`multi_node_sft.sbatch.j2` as the template source.
## Verification
Before this change, a multi-node SFT dry run generated two batch
scripts. The eval script wrote inference, evals, and env logs directly
under `$OUTPUT_DIR/logs`.
After this change, the same dry run generates only
`launcher/sft.sbatch`. A `2 trainer + 1 inference` configuration renders
`#SBATCH --nodes=3`. The script contains one attempt allocator and no
`TRAIN_JOB_ID`, log-path marker, or NCCL-host marker. It backgrounds
trainer and evals roles. Every node waits for the job-specific trainer
and eval completion sentinels. Online-eval and trainer-only renders both
pass `bash -n` and sentinel checks.
Local two-GPU end-to-end smokes passed:
- SFT completed one training step with NCCL broadcasts and evals at
steps 0 and 1.
- RL completed one training step and evals at policy versions 0 and 1.
- Standalone inference served a standalone two-example eval run.
The filesystem audit found relative `latest -> attempt_1` links for all
three runs. Every component log was nonempty UTF-8 text. No component
log existed outside its attempt directory.
Targeted config, CLI parser, and pathing tests passed: 282 tests. Ruff
checks and formatting checks passed.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking change for multi-node SFT online evals: cluster scheduling
and custom SLURM templates must launch inference and trainer in one job;
misconfiguration could strand nodes or break NCCL broadcast wiring.
>
> **Overview**
> **Multi-node SFT with online evals** no longer submits separate
trainer and eval SLURM jobs. One allocation reserves `num_train_nodes +
num_infer_nodes`; the first `num_infer_nodes` run the inference pool,
router, env servers, and `evals`, and the rest run the trainer. NCCL
weight broadcast uses the trainer rank-0 hostname directly—no cross-job
`TRAIN_JOB_ID` or shared run-dir host marker.
>
> The launcher only writes `launcher/sft.sbatch` (
**`multi_node_sft_eval.sbatch.j2` is removed** ). The unified template
backgrounds trainer and eval roles, waits on job-specific completion
sentinels so the job can drain the final eval after a clean trainer
exit, and uses one attempt-scoped log tree under `logs/attempt_<n>/`
(including `evals.log` and env logs). Standalone/local SFT sets
`PRL_LOG_DIR` for evals; the dashboard still lists legacy `logs/envs/`
files for older runs.
>
> Docs, `SFTConfig` field descriptions, and training skills are updated
for the single-job topology and log paths.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
997c8c1457c1ba95a013eb353abdcb754bc1a648. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- add a Prime-styled synchronized timeline for agent lifecycle phases
and model-call activity
- render VF-native root-to-leaf `Branch` paths instead of inferring
harness-specific subagent identities or hierarchy
- keep each environment agent as the main lane and show one flat row per
native zero-based branch index, ordered by its first unique activity
- retain shared-prefix calls on every branch path and mute them visually
to distinguish reuse from branch-unique execution
- show the trace reward on every branch training sample
- preserve exact call identity, including repeated calls, node-less
calls, and explicitly unknown timing
- show input, cached input, total input, output, reasoning, maximum
context length, total tokens, and cost in timeline tooltips and Overview
when reported
- keep large multi-agent tab strips horizontally scrollable and
integrate with Messages and Rendered transcript modes
- reject stale timeline responses after episode selection changes and
preserve unknown completed-phase end timing
- retain report navigation, transcript highlighting, rendered-token
mode, and dashboard view-command support
## Screenshot of multiagent episode (with subagent calls)
Codex harness
<img width="2400" height="2490" alt="image"
src="https://github.com/user-attachments/assets/1fe4a274-5cf2-49de-adf8-f328086d9f4a"
/>
RLM harness
<img width="2400" height="3260" alt="image"
src="https://github.com/user-attachments/assets/1ea0d693-a72e-495d-8133-c5b82770f2a0"
/>
## Validation
- `uv run --frozen ruff check .`
- `uv run --frozen ruff format --check .`
- `node --check src/prime_rl/dashboard/static/app.js`
- real interactive Codex multi-agent episode projects 29 native branches
across four environment-agent traces, with every branch containing
exactly its root-to-leaf model calls and all 46 actual calls covered
- real interactive RLM multi-agent episode projects 40 native branches
across four environment-agent traces, with every branch containing
exactly its root-to-leaf model calls and all 125 actual calls covered
- captured full-episode Playwright screenshots of both branch timelines
## Summary
- Replace `scripts/export_sft.py` with
`tools/convert_traces_to_hf_dataset.py`.
- Convert each branch of each agent trace into one dataset row.
- Export trainable and non-trainable agents without selection or
filtering.
- Add top-level outcome fields for downstream filters, including
`reward`, `stop_condition`, `has_error`, and `is_truncated`.
- Preserve task, run, agent, error, timing, usage, call, reward, metric,
and trace metadata.
- Push to a private Hugging Face Hub dataset by default, with `--public`
as an explicit opt-out.
- Use `--local` to write Parquet files with Hugging Face dataset-card
metadata.
- Preserve existing dataset-card content when local metadata is updated.
## Verification
### Eval → dataset → SFT
1. Generated eight GSM8K episodes without uploading the eval:
```bash
uv run --project /home/ubuntu/prime-rl eval gsm8k -n 8 -r 1 -c 8 \
--no-push -o /tmp/trace-converter-e2e-20260825 \
--run.name trace-converter-gsm8k --run.dir eval
```
All eight episodes succeeded. Mean reward was 1.0 and the error rate was
0.0.
2. Converted the trace file into a local Hugging Face dataset:
```bash
uv run --project /home/ubuntu/prime-rl python \
tools/convert_traces_to_hf_dataset.py \
/tmp/trace-converter-e2e-20260825/eval/traces.jsonl \
--name /tmp/trace-converter-e2e-20260825/dataset --local
```
The converter wrote eight branch rows. The dataset loaded through
`load_dataset`.
3. Trained Qwen3-0.6B on the converted dataset:
```bash
uv run --project /home/ubuntu/prime-rl sft \
--output-dir /tmp/trace-converter-e2e-20260825 --run.name sft \
--max-steps 5 --model.name Qwen/Qwen3-0.6B \
--data.type sft --data.name /tmp/trace-converter-e2e-20260825/dataset \
--data.subsets '["default"]' --data.splits '["train"]' \
--data.seq-len 2048 --data.batch-size 4 --data.micro-batch-size 1 \
--deployment.gpus-per-node 2 --deployment.num-train-gpus 1
```
The run completed all five steps. Final loss was 0.7764, the NaN count
was zero, and peak GPU memory was 10.7 GiB. No Hub or Prime platform
uploads occurred.
### Additional checks
- Ran the Ruff check and format pre-commit hooks.
- Converted a separate saved file with 132 episodes and loaded all 132
branch rows with `load_dataset`.
- Verified that a non-trainable errored trace still emits its branch row
and top-level error fields.
- Verified that local updates preserve plain, valid-frontmatter, and
unclosed-frontmatter README content.
- Verified that default uploads pass `private=True`, while `--public`
passes `private=False`.
## Breaking
- `scripts/export_sft.py` is removed. Use `uv run python
tools/convert_traces_to_hf_dataset.py <traces.jsonl> --name
<dir-or-repo-id>`.
- The converter no longer accepts `--min-reward` or `--drop-truncated`.
Apply filters in a separate script.
- The converter pushes to the Hub by default. Use `--local` to write a
local dataset.
- New Hub datasets are private by default. Use `--public` to create a
public dataset.
- The `--push` flag is removed because Hub upload is now the default.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Changes are limited to offline export tooling and CLI workflows; no
in-repo training or runtime code is modified in this diff.
>
> **Overview**
> **Removes** `scripts/export_sft.py` and **adds**
`tools/convert_traces_to_hf_dataset.py` as the path from eval/train
`traces.jsonl` to Hugging Face datasets.
>
> The new converter reads **one episode per line** (`WireEpisode`)
instead of per-trace wire rows, emits **one row per branch** for every
agent trace (no `--min-reward`, `--drop-truncated`, or empty-branch
skipping), and keeps **`messages`** plus JSON **`tools`** for SFT while
adding top-level filter fields (`reward`, `stop_condition`, `has_error`,
`is_truncated`, etc.) and JSON metadata for task, run, agent, errors,
timing, and usage.
>
> **Output behavior changes:** Hub upload is the default via required
`--name`; use **`--local`** to write `<name>/<subset>/<split>.parquet`
and update **`README.md`** dataset-card configs for `load_dataset`.
**`--public`** controls visibility on new Hub repos; **`--push`** is
gone.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8834b7aea61f2e6e9ba467758b593cf6ffb7a29b. 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>
## Summary
- Add `tools/convert_dcp_to_bf16.py`: convert a DCP trainer checkpoint
to HF sharded safetensors offline. Recovers the converter deferred out
of #3316 and adapts it: required positional `ckpt_dir` (accepts
`<run>/checkpoints/step_{n}` or `.../step_{n}/trainer`), output defaults
to `<ckpt_dir>/weights` (or a second positional arg), model/tokenizer
configs read from the run's resolved `configs/trainer.json` / `sft.json`
(the single source of truth — the checkpoint must live in its run
directory), single-process (`uv run python`) and multi-rank (`torchrun`)
invocations. Local `trust_remote_code` models get their custom code
files copied next to the weights. Full fine-tunes only — LoRA
checkpoints are rejected up front. Export replaces training-only
attention, fused-MoE, and DeepEP settings with portable
model-construction values.
- Add `tools/convert_bf16_to_fp8.py`: quantize an HF safetensors dir to
blockwise FP8 (DeepSeek/GLM format: e4m3 weights + `weight_scale_inv`
per-128×128-block scales, `quantization_config` block vLLM loads
natively). Streams shard-by-shard; norms, embeddings, lm_head, router
gates, GatedDeltaNet low-rank projections, MTP projection, and vision
towers stay bf16. Reuses `quantize_to_fp8_blockwise` from
`prime_rl.trainer.models.fp8`. Inspired by slime/miles
`tools/convert_hf_to_fp8.py`.
- Add `tools/convert_dcp_to_fp8.py`: DCP straight to fp8 — same gather
as `dcp_to_bf16`, but each rank quantizes its slice on GPU and only fp8
shards are written to `<ckpt_dir>/weights-FP8` (no intermediate bf16
export on disk).
- Add `tools/convert_fp8_to_bf16.py`: the inverse (dequantize
blockwise-fp8 releases like GLM-5-FP8 to bf16 for training). Inspired by
slime/miles `tools/fp8_cast_bf16.py`.
- Fold converter e2e checks into the existing reverse-text CI runs (no
new CI matrix entries): both the SFT and RL integration tests convert
their final DCP checkpoint to bf16 and fp8 and assert the exports reload
in HF with a clean loading report; the RL test additionally asserts
direct `dcp_to_fp8` output is byte-identical to chained `bf16_to_fp8` on
a real trainer checkpoint. Shared helpers
`convert_checkpoint`/`check_hf_load` in `tests/utils.py`. (A standalone
per-arch byte-exactness matrix over the mini_moe archs — glm4_moe,
laguna, minimax_m2, qwen3.5-MoE VLM; bf16 exports byte-identical to
their random-init sources, both fp8 paths byte-identical — was validated
during development and dropped from CI in favor of these hooks.) Also
fixes the mini_moe VLM preset `mrope_section` for its shrunken head_dim.
- Read the run config from the `configs/resolved/` layout via
`get_config_dir` (adapted after merging main).
- Document the export flow in `docs/training.md` and
`skills/training/start-run/SKILL.md`, and note the CLI convention in
`AGENTS.md`: `tools/` scripts use plain argparse, `[project.scripts]`
entrypoints use pydantic-config.
## Verification
All run on 2× RTX PRO 6000 Blackwell (SM120), vLLM 0.26.
**dcp→hf, real RL run (qwen3 dense)** — 20-step reverse-text RL run with
`--ckpt.interval 10 --weight-broadcast.type filesystem`:
- step 10 converted single-process, step 20 with `torchrun
--nproc-per-node 2`.
- Both exports are **bit-identical** (all 310 tensors) to the trainer's
own filesystem-broadcast weights at the same step; tied `lm_head.weight`
is dropped per HF convention and verified equal to `embed_tokens`.
- `uv run inference --vllm.model .../step_10/weights` serves the export;
reverse-text eval (`uv run eval`, n=64 r=4) scores **0.754** vs 0.744
training reward at step 10. Step 20 export scores **0.801** vs ~0.80 at
end of training.
**dcp→hf, architecture matrix** — per arch: tiny random model
(`scripts/mini_moe.py`) → 3-step fake-data SFT → convert (exercises
`configs/sft.json` auto-detection) → verify:
| arch | strict HF load | prime reload + forward | notes |
|---|---|---|---|
| glm4_moe (MoE) | ✓ | ✓ | plus direct HF→DCP→HF round trip: 889/889
tensors bit-exact (expert stack/unstack) |
| laguna | ✓ (`trust_remote_code=True`) | ✓ | HF→DCP→HF round trip
433/433 tensors bit-exact modulo the conversion chain's canonical
per-expert layout (the same layout the live broadcast path emits;
poolside's HF class stores fused `experts.gate_up_proj` and re-inits
experts it doesn't recognize — see `converting_laguna.py` docstring) |
| minimax_m2 (MoE) | ✓ | ✓ | mini built via prime impl (MiniMax remote
code incompatible with transformers v5) |
| qwen3_5_moe VLM | ✓ (`Qwen3_5MoeForConditionalGeneration`) | key-set
identity vs source | vision tower + linear attention round-trip |
**bf16→fp8 + fp8→bf16** — on the real step-20 Qwen3-0.6B export and all
four minis: dequant error bounded (worst median relative error ~2.2%,
e4m3-consistent), skip-list modules bit-identical,
index/`quantization_config` consistent; fp8→bf16 round trip drops all
`*_scale_inv` keys and `quantization_config`. Structure matches the
official `Qwen/Qwen3-0.6B-FP8` release (same scale shapes/names).
Serving the fp8→bf16 round-tripped weights scores **0.798** (vs 0.801
bf16 baseline), confirming the stored values.
**fp8 serving on SM120 (vLLM kernel bug, not the script)**: serving the
fp8 checkpoint scores **0.31** with vLLM's default
`CutlassFp8BlockScaledMMKernel` on this box, but **0.790** with the same
checkpoint after forcing the Triton kernel
(`VLLM_DISABLED_KERNELS=...CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel`
→ `TritonFp8BlockScaledMMKernel`), and vLLM's *online* fp8 of the same
weights scores 0.79. vLLM's CUTLASS blockwise-fp8 GEMM silently degrades
on SM120 (RTX PRO 6000); upstream already tracks other SM120
blockwise-fp8 breakage (vllm-project/vllm#47990, #47436). Noted the
workaround in `skills/training/start-run/SKILL.md`; H100/H200/B200
(SM90/SM100) use different kernels.
## Not ported from slime/miles
Megatron converters (`convert_torch_dist_to_hf*`,
`convert_hf_to_torch_dist`) — prime-rl is FSDP/DCP; int4 converters
(Kimi-K2-specific); mxfp8/nvfp4 (no checkpoint-level use case yet);
`param_name_remap.py` (covered by prime conversion chains); profiling
tools (prime-rl has its own monitors).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Converters touch distributed gather, HF weight layout, and
quantization paths that must match live training/broadcast behavior;
mistakes could ship broken checkpoints, though integration tests and
LoRA rejection reduce exposure.
>
> **Overview**
> Adds offline **checkpoint export and FP8 conversion** tooling under
`tools/convert_*.py`, plus docs/skills updates and integration-test
coverage.
>
> **DCP → Hugging Face:** `convert_dcp_to_bf16.py` loads FSDP DCP
trainer checkpoints using the run’s resolved
`configs/resolved/trainer.json` or `sft.json`, gathers weights in
parallel (single GPU or `torchrun`), writes sharded bf16 safetensors and
tokenizer/config assets to `<ckpt_dir>/weights`, and **rejects LoRA**
checkpoints.
>
> **FP8 round-trip:** `convert_bf16_to_fp8.py` blockwise-quantizes HF
safetensors (e4m3 + `weight_scale_inv`, vLLM-native
`quantization_config`); `convert_dcp_to_fp8.py` quantizes each rank’s
gathered slice straight to `<ckpt_dir>/weights-FP8` without a bf16
export on disk; `convert_fp8_to_bf16.py` dequantizes fp8-only releases
for training.
>
> **CI:** Reverse-text RL and SFT integration tests convert the final
checkpoint, assert clean `AutoModelForCausalLM` loads, and (RL)
byte-identity between direct `dcp_to_fp8` and chained `bf16_to_fp8`.
Shared helpers `convert_checkpoint` / `check_hf_load` live in
`tests/utils.py`. `scripts/mini_moe.py` fixes `mrope_section` for the
shrunk VLM preset.
>
> **Docs:** `docs/training.md` and training skills document the export
flow; `AGENTS.md` notes `tools/` scripts use plain argparse vs
pydantic-config entrypoints. Run artifact paths use `step_{n}`
consistently.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fe1241dec3e1369cc930ffa6b736fe6baf4e5200. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- bump the prime-rl project version from 0.8.0 to 0.9.0
- update the matching prime-rl entry in uv.lock
- prepare the [draft v0.9.0 GitHub
release](https://github.com/PrimeIntellect-ai/prime-rl/releases/tag/untagged-6fdfe34d2c7a47da166a)
with notes for 105 commits since v0.8.0
- include the latest dashboard, SLURM teardown, weight synchronization,
and eval policy fixes in the release notes
## Verification
- uv lock --check
- git diff --check origin/main...HEAD
## Problem
`Envs.start()` starts every source concurrently
(`asyncio.gather(env.start() for env in self)`), and each `env.start()`
materializes its taskset via `load_dataset()` in a worker thread
(`asyncio.to_thread(lambda: list(taskset))`). HuggingFace `datasets`
reads cached arrow shards through
`tqdm.contrib.concurrent.thread_map(tqdm_class=hf_tqdm)`, whose
`ensure_lock()` is:
```python
old_lock = getattr(tqdm_class, "_lock", None)
lock = old_lock or tqdm_class.get_lock()
...
yield lock # the (slow) arrow read happens here
if old_lock is None:
del tqdm_class._lock # <-- racing line
else:
tqdm_class.set_lock(old_lock)
```
When two of these run concurrently with the class lock unset, both
observe `old_lock is None`, both reach `del tqdm_class._lock` on exit,
and the second raises:
```
AttributeError: type object 'tqdm' has no attribute '_lock'
```
That kills the orchestrator during `setup()` ("Fatal error in
run_orchestrator"), and the trainer then hangs waiting for rollouts that
never come.
**When it triggers:** ≥2 sources load datasets concurrently at startup
(e.g. multiple train sources over the same taskset). The race window is
the arrow read, so more sources / colder caches make it more likely — 3
concurrent loads hit it essentially every run, 2 intermittently, 1
never. It is **not** caught by `--dry-run`, which never calls
`load_dataset()`.
Root cause is a tqdm thread-safety gap (`ensure_lock` isn't safe for
concurrent use on a single class), exposed by `datasets`' `thread_map`
plus concurrent taskset loading here.
## Fix
Pre-seed the `datasets` tqdm class lock once, before the concurrent
gather, so `old_lock` is never `None` and every `ensure_lock` takes the
non-deleting `else` branch — the same state tqdm is in whenever a
progress bar is active:
```python
from datasets.utils import tqdm as _hf_tqdm
_hf_tqdm.set_lock(_hf_tqdm.get_lock())
```
This targets the exact class `datasets` passes to `thread_map`
(`datasets.utils.tqdm.tqdm`, the same object `arrow_reader` imports). It
only stops the lock object from being created-and-deleted per call; no
change to progress-bar display, dataset contents, or ordering.
## Reproduction
Hammering the failing primitive directly (16 threads, window widened to
mimic the slow arrow read):
- **without** the fix: consistent `AttributeError: type object 'tqdm'
has no attribute '_lock'`
- **with** the fix: clean, 0 failures
Also observed live: a 3-train-source run crashed here every time; after
the fix all three arms load cleanly.
## Alternative considered
Loading sources sequentially in `Envs.start()` also avoids the race, at
the cost of startup parallelism. The pre-seed keeps the parallel load.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Single-line lock initialization before existing parallel env startup;
no auth, data, or algorithm changes.
>
> **Overview**
> **Fixes a startup crash** when multiple train/eval sources load
HuggingFace datasets in parallel during `Envs.start()`.
>
> Concurrent `load_dataset()` paths use `datasets`' `thread_map` with
tqdm's `ensure_lock()`, which can race on `del tqdm_class._lock` and
raise `AttributeError`—fatal during orchestrator `setup()` and leaving
the trainer waiting on rollouts.
>
> Before `asyncio.gather` on `env.start()`, the change **pre-seeds** the
lock on `datasets.utils.tqdm` via `set_lock(get_lock())` so concurrent
readers never hit the delete branch. Parallel startup is preserved; no
change to dataset contents or progress display.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a1007d2d9cc0b8e15a2df959cec54cf3b366fce3. 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 4.8 <noreply@anthropic.com>
## Summary
- Route startup and later policy loads through one `WeightWatcher`
update path. Advance `policy.version` and trigger evals only after
inference applies the weights.
- Key fresh startup evals to policy v0. On resume, evaluate the loaded
checkpoint only when `retrigger_on_resume=true`.
- Pause rollout scheduling across each weight apply so rollout
provenance matches the policy served at dispatch.
- Remove the resume-step broadcast directory before the trainer rebuilds
its startup handshake.
- Always broadcast and consume the final RL policy. Remove the
conditional final-broadcast config and helper path.
- Remove the mixed-policy eval warning. Keep the minimum policy version
in metrics and success logs.
- Remove the parenthesized step from eval success logs.
## Verification
Before the fix, a 20-step reverse-text run with eval interval 1
reproduced the bug:
- Eval step 20 used policy v18.
- The final policy broadcast triggered eval step 21 with policy v20.
- The run wrote step-21 eval artifacts.
After the fix, this requested interval-10 run completed all 20 steps:
```bash
uv run rl @ examples/basic/reverse-text/rl.toml \
--orchestrator.eval.interval 10 \
--orchestrator.eval.num-examples 1 \
--orchestrator.eval.group-size 1 \
--orchestrator.eval.source '[{"name":"reverse-text-eval","env":{"taskset":{"id":"reverse-text"},"agent":{"harness":{"id":"null"},"runtime":{"type":"subprocess"}}}}]' \
--no-monitors.wandb --no-dashboard
```
- Eval step 10 used policy v10.
- Final eval step 20 used policy v20.
- No step-21 eval artifacts were written.
A two-step run without evals applied final policy v2 and exited cleanly.
This verifies unconditional final broadcast and consumption.
Fresh and resumed two-step smokes verified the startup matrix:
- A fresh interval-1 run evaluated policies v0, v1, and v2.
- Resume from v2 with `retrigger_on_resume=false` skipped v2, then
evaluated v3 and v4.
- Resume from v2 with `retrigger_on_resume=true` evaluated v2, v3, and
v4.
- Resume from v2 with interval 3 skipped v2 and evaluated v3 only.
- Every resumed startup rebuilt its v2 broadcast handshake and exited
cleanly.
After the final review fixes, a fresh interval-1 run evaluated v0, v1,
and v2. A resume from v2 with `retrigger_on_resume=false` skipped only
v2, then evaluated v3 and v4.
```bash
uv run pytest \
tests/unit/test_configs.py \
tests/unit/orchestrator/test_batch.py \
tests/unit/utils/test_pathing.py -q
# 156 passed
uv run ruff check \
src/prime_rl/orchestrator/orchestrator.py \
src/prime_rl/orchestrator/watcher.py \
src/prime_rl/orchestrator/dispatcher.py \
src/prime_rl/orchestrator/eval_source.py \
src/prime_rl/utils/pathing.py \
src/prime_rl/trainer/rl/train.py \
src/prime_rl/utils/utils.py \
packages/prime-rl-configs/src/prime_rl/configs/rl.py \
packages/prime-rl-configs/src/prime_rl/configs/shared.py \
tests/unit/utils/test_pathing.py \
tests/utils.py
# All checks passed!
```
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Changes core RL orchestration around weight updates, rollout
scheduling barriers, and eval timing—incorrect ordering could cause
wrong-policy evals or inference crashes during weight swaps.
>
> **Overview**
> Fixes evals running against stale or wrong policy versions by tying
**eval triggers and `policy.version` to inference actually applying
weights**, not merely publishing them.
>
> **Policy lifecycle:** `WeightWatcher` now advances `policy.version`
only after `receive()` completes, routes startup sync through
`sync_startup` + shared `on_update` hooks, and registers orchestrator
hooks for eval and dispatch-gate refresh. Batch shipping and shutdown
waits refer to **inference-applied** versions.
>
> **Eval scheduling:** Eval fires from `trigger_eval` after each applied
policy (including startup v0 on fresh runs). Resume skips re-eval at the
checkpoint step unless `retrigger_on_resume=true`; final eval uses
`force` at `max_steps` without a spurious step-21 epoch. The dispatcher
blocks new scheduling across weight swaps via `policy_update_pending`
and a scheduling lock.
>
> **Broadcast config:** Removes `broadcast_final` and
`final_broadcast_version`; the trainer **always** broadcasts every step
including the final policy, and resume cleanup deletes broadcast dirs
from the resume step onward so the startup handshake is rebuilt.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5fa6b01df79f028ad974509ff78e9e51188cf1f0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- show `trace.tools` as a distinct, collapsible model-context block in
the Messages view, with tool counts/names, full descriptions, formatted
parameter schemas, and per-item/schema/all copy actions
- add a separate `Rendered` view that decodes recorded post-renderer
`token_ids` for the selected trace and branch as a full sequence,
retaining special tokens and offering decoded-text and authoritative-ID
copy actions
- compose both `Messages` and `Rendered` with the `Text`, `Advantage`,
`Logprob`, `Mask`, and `Content` signal dropdown, with explicit
unavailable states for missing IDs, missing model metadata, tokenizer
load failures, and decode failures
## Details
The Messages view continues to render literal `message.content`. Tool
definitions are shown immediately after the first system message in a
purple-accented context card, so they are not presented as
system-message text; traces without a system message keep the card at
the top. The collapsed row shows the count and normalized names;
expanding it exposes each full description and scrollable JSON schema.
Direct tool objects, OpenAI-style `function` wrappers, multiple
definitions, missing fields, and malformed values degrade to readable
fallback labels.
Rendered does not rerun or infer a chat template. The server uses
`client.renderer_model_name` with the existing run-model fallback,
concatenates the recorded node spans in the selected root-to-leaf order,
and calls the tokenizer once for the full sequence with special-token
skipping disabled. The selected branch controls which decoded sequence
is shown; the all-branches option uses recorded node write order. With
`Text` selected, Rendered shows that exact full-sequence decode. With
another signal selected, it shows the same recorded sequence as token
spans with the existing color scale and token hover metadata.
Compatibility is intentionally additive: the default endpoint response
and default Messages/Text display stay unchanged, token strings are
still fetched lazily for overlays, and full rendered text is only added
when `rendered=true` is requested. The mode buttons and signal dropdown
are independent, and a one-time preference migration recovers sessions
that briefly saved `Rendered` in the signal field.
Episode navigation and token/render enrichment use separate request
lifecycles. Opening or closing an episode invalidates prior enrichment,
while changing controls during an in-flight open no longer discards the
episode response; the newly opened episode then picks up any enrichment
required by the latest controls. Decode failures remain branch-local in
the viewer: valid text for the selected branch is shown even if another
branch fails to decode.
## Verification
- `uv run --no-sync ruff format --check
src/prime_rl/dashboard/server.py`
- `uv run --no-sync ruff check src/prime_rl/dashboard/server.py`
- `uv run ruff check src/prime_rl/dashboard`
- `node --check src/prime_rl/dashboard/static/app.js`
- `git diff origin/main...HEAD --check`
- exercised a generic synthetic two-branch trace through the live
dashboard API with three tool-definition shapes; verified renderer-model
selection, retained `<|im_start|>` / `<|im_end|>` markers, separate
branch text, all-node ordering, and existing per-token pieces
## Visual description
A compact `Tool definitions · 3 tools · lookup, calculate, tool 3` row
appears directly after the system message. It expands into nested tool
cards with full prose and scrollable monospace schemas. `Messages` /
`Rendered` buttons sit beside a signal dropdown containing `Text`,
`Advantage`, `Logprob`, `Mask`, and `Content`. Either mode can use any
signal; Rendered/Text shows the exact decoded transcript, while Rendered
with an overlay shows colored token spans. A hover tooltip describes the
signal choices. A screenshot is not included because a browser runtime
was unavailable in the checkout used for verification.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Additive dashboard and optional episode API fields; no changes to
training, auth, or data persistence beyond larger lazy-loaded episode
payloads.
>
> **Overview**
> The trace viewer adds **Messages** vs **Rendered** modes and surfaces
**`trace.tools`** as model context separate from message text.
>
> In **Messages**, tool definitions appear in a collapsible context
block (after the first system message when present), with descriptions,
parameter schemas, and copy actions; message bodies still show literal
**`message.content`**. **Rendered** decodes recorded post-renderer
**`token_ids`** per branch (or all nodes) via **`renderer_model_name`**
with run-model fallback—no chat-template reconstruction—and reports
missing IDs, model, tokenizer, or decode failures.
>
> The episode API accepts optional **`tokens`** and **`rendered`** query
params; **`rendered_token_text`** on the server concatenates branch
paths and decodes full sequences with special tokens retained. The UI
lazily fetches enrichment, versions open/enrichment requests to avoid
stale responses, and shares the Text / Advantage / Logprob / Mask /
Content signal dropdown across both modes.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
596f7d3fe9746c9283d8a872b1d506c26a525e1a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Use successful trainer and orchestrator exits as the shared completion
condition in local and multi-node SLURM launchers.
- Let each SLURM component publish `.trainer.done` or
`.orchestrator.done`, then stop inference after both markers exist.
- Make trainer-only fake-data SLURM runs stop after `.trainer.done`; no
orchestrator exists in that mode.
- Store all generated SLURM scripts and coordination files under
`<run_dir>/launcher/`.
- Store SLURM stdout and stderr under `<run_dir>/launcher/logs/`.
- Apply the launcher layout to RL, SFT, decoupled SFT eval, and
standalone inference entrypoints.
- Keep local launchers unchanged on disk. They do not create `launcher/`
because they persist no launcher files.
- Preserve failure propagation through `srun --kill-on-bad-exit=1`.
At `max_steps`, the trainer can exit while the orchestrator still drains
the final eval. The template previously tore down the node after the
first background process exited. This killed the final eval. A clean
exit also did not trigger `--kill-on-bad-exit`, so inference nodes could
hold the allocation until wall time.
## Breaking
- Generated SLURM scripts move from `<run_dir>/*.sbatch` to
`<run_dir>/launcher/*.sbatch`. Update manual submission commands and
tooling to use the new paths.
- SLURM job logs move from `<run_dir>/*job_*.log` to
`<run_dir>/launcher/logs/*job_*.log`. Update log collection and
monitoring paths.
## Verification
Before this change, a 1000-step GLM-4.5-Air run lost its final eval at
450 of 500 tasks. The six-node allocation then remained active for
another 23 hours.
After this change, a 10-step reverse-text run evaluated at its final
step and exited successfully:
- The final eval completed all 64 rollouts with no rollout errors.
- The trainer finished at 01:39:08 UTC.
- The orchestrator drained its pipeline and finished at 01:39:14 UTC.
- Inference stopped after both terminal components finished.
- The launcher exited with code 0 and released both GPUs.
A two-node trainer-only fake-data dry run rendered a one-marker watcher
with no `ORCHESTRATOR_DONE` reference. The normal inference path still
rendered the two-marker watcher. Both scripts passed `bash -n`.
All RL, SFT, decoupled SFT eval, and inference SLURM variants rendered
successfully. Every rendered script passed `bash -n`. Local RL, SFT, and
inference dry runs did not create `launcher/`.
An additional two-node SLURM run used the regular reverse-text
configuration with 100 eval rollouts per evaluation:
- The trainer completed all 20 steps and wrote `launcher/.trainer.done`.
- The orchestrator continued to drain queued evaluations after trainer
completion.
- The orchestrator then wrote `launcher/.orchestrator.done`.
- Both nodes logged teardown with exit code 0, and the job released its
allocation.
Ruff passed. The pathing unit tests passed with 10 tests.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Changes multi-node SLURM lifecycle and coordination (eval completion
vs allocation hold time) and breaks paths for manual `sbatch` and log
monitoring; incorrect completion logic could still strand nodes or kill
in-flight evals.
>
> **Overview**
> Fixes premature SLURM teardown at `max_steps` when the trainer exits
while the orchestrator is still draining the **final eval**. Multi-node
RL jobs no longer stop on the first background process exit; trainer
rank 0 and the orchestrator publish **`launcher/.trainer.done`** and
**`launcher/.orchestrator.done`** on success, and every node waits for
the appropriate pair (trainer-only vs trainer+orchestrator) before
killing inference and releasing the allocation. Failures still propagate
via **`srun --kill-on-bad-exit=1`**.
>
> **Breaking layout change:** generated `*.sbatch` scripts, coordination
sentinels, and SLURM `job_*.log` output move from the run directory root
to **`<run_dir>/launcher/`** and **`launcher/logs/`** for RL, SFT,
decoupled SFT eval, and standalone inference. Entrypoints and Jinja
templates pass `launcher_dir` / `launcher_log_dir`; local launches stay
unchanged on disk (no `launcher/`). Docs and training skills note the
new paths; `format_log_message` and `LAUNCHER_ARTIFACTS` validation
follow the same layout.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
02f3807d4a4f9cd53830b9b90e4035c386d01bdc. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
- One-line fix for the deterministic `CUDA error: an illegal memory
access` that killed every SignSGD run without full optimizer offload
since #3234.
- `torch.cuda.empty_cache()` returns cached blocks to the driver; a
kernel still in flight that references a cached block faults once its
block is freed under it. The pre-broadcast `empty_cache` (added in #3234
for FP8 gather headroom) runs immediately after `optimizer.step()` —
SignSGD's per-param loop leaves thousands of tiny kernels still running
at that point, while AdamW's compact foreach step happens to finish in
time, which is why only SignSGD crashed. Draining pending work with
`torch.cuda.synchronize()` before releasing blocks closes the race for
every optimizer, at ~ms cost once per step.
## Verification
All on the same GLM-4.5-Air scaleswe config (2 trainer + 2 inference
nodes, `sign_sgd` + `optim_cpu_offload`, no full offload):
| state | outcome |
|---|---|
| main | illegal memory access right after step 1, 2/2 slurm attempts |
| main + `CUDA_LAUNCH_BLOCKING=1` | no crash — ordering, not indexing |
| **main + this one line** | [runs
clean](https://wandb.ai/primeintellect/swe-ablations?nw=nwuser&search=sgd-nooffload):
11+ steps and counting, healthy grad norms, no restarts |
Supersedes #3373 — its foreach SignSGD rewrite turned out to be
unnecessary for correctness (verified by running the untouched optimizer
with only this line).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches the per-step RL training hot path and GPU memory lifecycle
before weight broadcast; the change is narrow and matches existing
synchronize-before-empty_cache patterns elsewhere, but any extra sync
can affect step timing.
>
> **Overview**
> Fixes a **CUDA illegal memory access** that could occur right after
`optimizer.step()` when the trainer frees GPU cache before broadcasting
weights.
>
> The pre-broadcast `torch.cuda.empty_cache()` (for FP8 gather headroom)
can return cached blocks to the driver while **optimizer kernels are
still in flight**—especially with SignSGD’s many small per-parameter
updates. The change **drains pending GPU work** via
`torch.cuda.synchronize()` immediately before `empty_cache()`, with
expanded comments explaining the race.
>
> This is a one-line behavioral fix in the RL training loop’s
weight-broadcast path; it does not change broadcast semantics, only
ordering so memory is not reclaimed under active kernels.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8947aa400631ca5a2dab829642f7755fab7dafd0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Lets a user set a persistent default output location for all runs
without repeating --output-dir on every launch. Precedence stays class
default ("outputs") < PRL_OUTPUT_DIR < TOML < CLI, since the new
default_factory only fires when output_dir is untouched by TOML/CLI
merge.
Also respected by the dashboard UI.
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
## Summary
- refresh live metrics and trace rows on the same five-second cadence
- better `no data yet` for unavailable overview data
- show episode and trace errors at the bottom of the trace viewer
- add the task key as `task ID` to the identity section of the trace
overview pane
- use `n/a` for missing value uniformly; some spots showed an en dash.
- allow filter from trace viewer
## Verification
### Overview empty state
<img width="1608" height="1045" alt="Screenshot 2026-08-24 at 3 54 20
PM"
src="https://github.com/user-attachments/assets/02e06087-5286-435e-9776-52ec9502f7f5"
/>
### Errors
<img width="1608" height="1045" alt="Screenshot 2026-08-24 at 3 52 29
PM"
src="https://github.com/user-attachments/assets/b39a28cc-c50d-467c-b7f7-39c354a5e008"
/>
### Task ID
<img width="318" height="151" alt="Screenshot 2026-08-24 at 3 52 42 PM"
src="https://github.com/user-attachments/assets/f12f50b5-685d-4ca5-8b80-5c89877cab43"
/>
### Checks
- `node --check src/prime_rl/dashboard/static/app.js`
- `git diff --check`
- dashboard browser smoke against `outputs/reverse-text-rl`
- live append browser repro for metrics, trace rows, and new trace steps
- fake inference URL eval and browser layout check with a full traceback
- headless browser render of a synthetic `ProviderError` episode:
collapsed and expanded traceback, `task ID` row, consistent `n/a`
placeholders, red-marked error rows in the sidebar
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Frontend-only dashboard static assets; no API or training-path
changes. Risk is limited to UI regressions in metrics/traces polling and
the trace modal.
>
> **Overview**
> This PR tightens **live updates** and **trace UX** in the static
dashboard (`app.js`, `index.html`, `style.css`).
>
> **Polling & loading:** Poll interval moves to **5s**; metrics and
traces refresh when switching tabs with live on, on tab visibility, and
when re-enabling live. Metrics streaming stops retrying the same offset
when a partial JSONL line sits at EOF; `fetching` guards avoid
overlapping metrics/trace loads.
>
> **Traces:** Step selection **follows the latest preferred step** while
you’re on the tail (historical picks and an open modal stay put). Empty
trace/metrics states use shorter labels and the episode table keeps its
chrome with an in-table empty row to avoid layout shift. Overview panels
show **“no data yet”** for configured eval sections before data lands.
>
> **Trace viewer:** Episode/trace **errors render as banners** at the
bottom of the message column (with expandable tracebacks); **task ID**
appears in the identity pane. The modal gets the same
**filter/sort/env/errors** controls as the traces tab, synced through
shared state. Error episodes are highlighted in the sidebar list.
>
> **Polish:** Missing numeric/overview fields use **`n/a`** instead of
en dashes (empty eval env list still shows **–**). Run overview merges
the full run record from the runs list on refresh.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
239dc7797d996fb0b17badb9dd60b640474b431d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
- Launchers (`rl`, `sft`) register their output dir in
`~/.cache/prime-rl/dashboard/dirs.json` and make sure one dashboard
serves it (`ensure_dashboard` in the new `entrypoints/dashboard.py`,
kept free of `dashboard`-extra imports). Every dashboard instance serves
its CLI dirs **plus** the registry, re-read live — a run in a new output
dir appears on the one live URL without a restart: one dashboard per
host per user.
- Discovery goes through `daemon.json` (pid + **actual** url), so it
survives port spillover — nothing ever probes port 7788. A live daemon's
URL is logged (`Dashboard running at <url>`); interactive sessions spawn
a detached daemon (own session — killing a run never takes it down) when
none is live (`Dashboard started at <url>`); non-tty launches (CI,
nohup) only register. A stale claim from a dead process is taken over on
the next start.
- `--isolated` is the escape hatch: serve only the given dirs, no
registry read/write, no discovery claim (launchers ignore the instance).
`dashboard: bool = True` on RL/SFT opts a run out via `--no-dashboard`.
- The daemon carries the process title `PRL::Dashboard` via the shared
`set_proc_title`. `psutil` is promoted from transitive to a core
dependency so `prime_rl.utils.process` imports in the slim GPU-free env.
- Launcher startup now ends with a `Dashboard · <url>` banner (blank
lines around, green url) as the last log, after `Launcher complete` (was
`Startup complete. Showing ... logs`). The launcher no longer tails
orchestrator/trainer logs into its terminal - the dashboard is the
monitoring surface.
- New `skills/dashboard/SKILL.md` teaches agents discovery, liveness
checks, and kill/restart commands; `monitor-run` and `start-run` skills
point at it.
Supersedes #3368, rebuilt on the (now merged) stack #3369 (PRL prefix) →
#3370 (GPU extra; the server is a normal package member, so no
setproctitle fallback and no duplicated cache-dir logic); targets
`main`.
## Verification
E2E on this box: daemon claims `daemon.json` with pid + url and shows
`PRL::Dashboard` in `ps`; `ensure_dashboard` from a second process
registers a fresh output dir and the live dashboard absorbs it (run
count grows without restart); a second instance spills to port 7789 and
does **not** steal the claim; `--isolated` serves only its dirs and
leaves the registry untouched; a pty-spawned launcher starts a detached
daemon that survives the launcher's exit; slim `uv sync --extra
dashboard` env (no torch/vllm) imports `entrypoints.dashboard`,
`dashboard.server`, and `set_proc_title`, and `dashboard --help` works;
`tests/unit/test_configs.py` passes (122).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Changes are local dev/monitoring UX and read-only dashboard serving;
training paths are unchanged aside from optional subprocess spawn and
registry file writes.
>
> **Overview**
> **RL and SFT launchers** now register each run’s `output_dir` in a
per-user registry and ensure a single local dashboard serves it. New
`dashboard: bool = True` (disable with `--no-dashboard`) drives
`ensure_dashboard` in `entrypoints/dashboard.py`, which reuses a live
daemon via `~/.cache/prime-rl/dashboard/daemon.json` or spawns a
detached process in interactive TTY sessions only.
>
> The **dashboard server** merges CLI dirs with `dirs.json` (live
re-read), claims/releases daemon discovery, adds **`--isolated`** to opt
out of the registry, and moves sidecar cache under the shared dashboard
state dir. The **`dashboard` console script** now enters through
`entrypoints.dashboard.main`.
>
> **Launcher UX** drops `tail -F` on orchestrator/trainer logs; startup
ends with **Launcher complete** and a **Dashboard · url** banner.
**`psutil`** is a direct dependency so process titles work without the
GPU stack. Agent skills/docs describe discovery, liveness, and
kill/restart.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
035e7ec4c1a2671db778a85a42147d332a8a73ed. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
- The CUDA/linux-only stack (torch+cu128 index, vllm, torchtitan,
mooncake-transfer-engine, ring-flash-attn, dion, tilelang,
flash-linear-attention, torchao, nvidia-ml-py, modelexpress) moves from
core dependencies into a **`gpu` extra** (linux-marked), and
`darwin/arm64` joins `tool.uv.environments` — a bare `uv sync` now
resolves and installs on a MacBook (slim: configs, monitors, dashboard,
CLI tooling). `uv sync --all-extras` — already the recommended install
on GPU machines — pulls everything exactly as before (`all` aggregates
`gpu` too).
- Every other GPU extra (`flash-attn-3`, `flash-attn-cute`, `disagg`,
`gpt-oss`, `quack`, `kernels`, the `mamba-ssm` group) gets linux markers
so the darwin lock split resolves; the torch cu128 index sources are
linux-scoped.
- CI (`cpu_tests`, benchmarks) and the docker entrypoint's
`PRIME_RL_REF` override sync move to `--all-extras`; `Dockerfile.cuda`
adds `--extra gpu`; the install skill documents the split.
- The dashboard's standalone PEP 723 `--script` form is removed: `uv
sync --extra dashboard && uv run dashboard` is now the dependency-free
path everywhere, and `server.py` becomes a normal package member — it
imports the new `CACHE_DIR` from `utils/pathing` instead of duplicating
the cache-dir logic.
## Breaking
- `uv sync` without extras no longer installs the training/inference
stack; use `uv sync --all-extras` (recommended) or `--extra gpu`.
Anything invoking `uv sync --extra flash-attn` alone must add `--extra
gpu`.
- `uv run --script src/prime_rl/dashboard/server.py` no longer works
(header removed); use `uv sync --extra dashboard && uv run dashboard`.
## Verification
On linux: bare `uv sync --extra dashboard` produces an env with no
torch/vllm from which `uv run dashboard` serves real runs end to end;
`uv sync --all-extras --all-packages` restores the full env (torch
2.11+cu128, vllm import, `entrypoints.rl` import OK);
`tests/unit/test_configs.py` (122 passed) and the dashboard browser
smoke pass. `uv lock` resolves all three environments including the new
darwin split.
#3369 (PRL prefix) is merged and this now targets `main`; the
dashboard-daemon PR (#3371) lands on top.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes the default dependency contract and Docker runtime `uv sync`
behavior; anyone on bare `uv sync` or old dashboard script paths will
miss GPU deps, and PRIME_RL_REF overrides now pull all extras (including
heavy disagg/quack) at pod startup.
>
> **Overview**
> **Slim default install:** Core dependencies no longer pull the Linux
CUDA training stack (torch/cu128, vllm, torchtitan, mooncake,
ring-flash-attn, dion, tilelang, flash-linear-attention, torchao,
modelexpress, nvidia-ml-py). Those move behind a new **`gpu` optional
extra** (linux-marked). Other GPU extras (`flash-attn-3`, `disagg`,
`quack`, `kernels`, `mamba-ssm`, etc.) get linux markers;
**`darwin/arm64`** is added to `tool.uv.environments` so a bare `uv
sync` resolves on macOS. The **`all`** extra now includes
`prime-rl[gpu]`.
>
> **Install paths updated:** CI (`cpu_tests`, benchmarks) and
**`Dockerfile.cuda`** sync with **`--all-extras`** / explicit **`--extra
gpu`** so Linux GPU images still get the full stack.
**`scripts/docker-entrypoint.sh`** on `PRIME_RL_REF` overrides switches
from a hand-picked extra list to **`uv sync --inexact --all-extras`**
(plus `mamba-ssm` group)—so override checkouts may install disagg/quack
at startup, not only flash-attn/gpt-oss.
>
> **Dashboard:** The PEP 723 **`uv run --script`** standalone form is
removed from `server.py`; docs/skills point to **`uv sync --extra
dashboard && uv run dashboard`**. Dashboard sidecar cache uses shared
**`CACHE_DIR`** from `utils/pathing` (`home_dir()` fallback to temp).
>
> **Breaking:** `uv sync` alone no longer installs training/inference
deps—use **`uv sync --all-extras`** (recommended on GPU Linux) or
**`--extra gpu`** (and add flash-attn etc. as before). **`uv run
--script src/prime_rl/dashboard/server.py`** no longer works.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
64562e87834dc6ef1eba7ab372b50f102088cb5f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
- require the stable `verifiers[harbor]>=0.3.1` release instead of a
development build
- point the Verifiers submodule at the published `v0.3.1` tag
## Verification
- `uv lock --check`
- built `verifiers-0.3.1-py3-none-any.whl` and `verifiers-0.3.1.tar.gz`
from `deps/verifiers`
- verified the submodule commit has the exact `v0.3.1` tag
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Dependency constraint only—switches from a dev pre-release to the
stable 0.3.1 minimum with no application code changes in this diff.
>
> **Overview**
> Pins **`verifiers[harbor]`** to the stable **`>=0.3.1`** release
instead of the prior **`>=0.3.1.dev59`** development build in
`pyproject.toml`.
>
> This moves dependency resolution off a pre-release dev tag onto the
published 0.3.1 line while keeping the same optional **`harbor`** extra
and existing editable **`deps/verifiers`** source configuration.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f399e80c03ad6e26533aa770df28e90c69517891. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- `PRIME_RL_PROC_PREFIX` becomes `PRL`, so every component's process
title reads `PRL::Trainer`, `PRL::Orchestrator`, `PRL::Inference`,
`PRL::EnvServer`, `PRL::Launcher`, ... — shorter to type and grep. The
`monitor-run` skill's process tree is updated.
## Breaking
- Process titles change from `PRIME-RL::<Name>` to `PRL::<Name>`;
anything matching the old prefix (`pgrep -f PRIME-RL`, dashboards, ops
scripts) must switch.
First PR of a 3-stack: PRL prefix → CPU-only `uv sync` (GPU deps behind
an extra) → dashboard daemon.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
Adds a local run dashboard for SFT / RL / Eval runs. Start with
```bash
# default (all runs in outputs/, port 7788)
uv run dashboard
```
For example, populate with
```
# rl run
uv run rl @ examples/basic/reverse-text/rl.toml --run.name reverse-text-rl
# sft run
uv run sft @ examples/basic/reverse-text/sft.toml --max-steps 10 --run.name reverse-text-sft
# eval run (multi-agent, multi-branch)
uv run eval \
--env.id agentic-judge \
--env.taskset.id terminal-bench-2 \
--env.taskset.tasks '["fix-git"]' \
--env.solver.harness.id rlm \
--env.solver.harness.summarize-at-tokens 4000 \
--env.judge.harness.id bash \
--run.name tb2-agentic-judge
```
Combines the best things from W&B + PI platform. Fully isolated
agent-maintained logic in `prime_rl.dashboard`. Fully supersedes the
previously advertised tmux viewer. Should basically be always on when
working with prl locally.
## Gallery
**Configs**
<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 01 35
PM"
src="https://github.com/user-attachments/assets/a6dec2e2-26d0-49a9-a220-f1baa8c7b1ea"
/>
**Metrics**
<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 01 55
PM"
src="https://github.com/user-attachments/assets/c38cbac5-177e-4850-a3fc-d09e10da6185"
/>
**Trace Overview**
<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 02 08
PM"
src="https://github.com/user-attachments/assets/27f4d197-3969-4334-a629-161ac5df434d"
/>
**Trace Viewer**
<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 02 47
PM"
src="https://github.com/user-attachments/assets/2b9c4aed-20bb-4623-a272-93b5603a79d3"
/>
**Logs**
<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 03 08
PM"
src="https://github.com/user-attachments/assets/91aa3334-8f97-409a-9f8a-d9e19bff1892"
/>
## Breaking
- `scripts/tmux.sh` is removed — the dashboard replaces the tmux
log-pane workflow (docs, example walkthroughs, and the monitor-run skill
updated).
- Resolved per-component configs move from `{run_dir}/configs/*.json` to
`{run_dir}/configs/resolved/*.json`; `configs/` now holds the launch
TOML (`rl.toml`/`sft.toml`). Anything reading the old paths must switch
(the dashboard reads both layouts).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Changes are additive for training (new CLI and docs) plus removal of
the tmux helper; the config path split may break external tooling that
still reads `{run_dir}/configs/*.json` directly.
>
> **Overview**
> This PR adds **`uv run dashboard`** — a local web UI (default
**http://localhost:7788**) for watching SFT/RL/eval runs from output
directories only: **metrics** (W&B-style overview from `metrics.jsonl`),
**configs** (launch TOML vs merged resolved JSON), **rollout traces**
with per-token advantage/logprob views, and **merged component logs**.
It ships as a **`dashboard` optional extra** (FastAPI/uvicorn) or as
**`uv run --script src/prime_rl/dashboard/server.py`** on machines
without full GPU deps.
>
> **`scripts/tmux.sh` is removed**; docs, basic examples, and the
**monitor-run** skill now recommend two terminals plus the dashboard
instead of tmux panes. Side-by-side ablations on one node can use **`uv
run dashboard outputs`** to track multiple experiments.
>
> **Resolved configs** from dry-run and launches are documented at
**`{run_dir}/configs/resolved/*.json`**, with the launch TOML at
**`configs/*.toml`**; the dashboard server still reads the old flat
`configs/*.json` layout for older runs.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
99d9a8f34e9c53b7de1f6a74f82c4053285ba506. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
- Require renderers 0.1.10 in Prime RL and prime-rl-configs.
- Update the renderers submodule to the 0.1.10 release.
- Update the verifiers submodule to the latest main commit.
- Refresh lock metadata for both dependency constraints.
## Verification
- uv lock --check
- uv run --no-project --with pre-commit pre-commit run --files
pyproject.toml packages/prime-rl-configs/pyproject.toml uv.lock
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> <sup>[Cursor Bugbot](https://cursor.com/bugbot) is generating a
summary for commit 95ca34dcca9b2737cf2ebb431a47391ed874052a. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
`uv sync --group dev` only installs the pre-commit package; the git hook
stays inert until `uv run pre-commit install` runs, which the install
skill omitted (README's Development section already covers it).
## Summary
- yield tensor views into the contiguous NCCL receive buffer instead of
cloning every reconstructed tensor
- avoid duplicating checkpoint payloads while vLLM performs layerwise
weight loading
The change intentionally keeps the existing flat receive stream and vLLM
reload lifecycle. Trainer state-dict boundaries are transport framing,
not loader semantics: vLLM tracks layer completion from the weights
loaded for each module.
## Safety
Each yielded tensor is a disjoint view of the receive buffer. A view
retains its underlying storage, so the buffer cannot be released while
the loader still references one of its tensors. The existing consumers
either copy tensors directly into model parameters or synchronously
process the ordered checkpoint stream.
## H200 reproduction
The reported Laguna-S-2.1 failure was reproduced with one EP8 trainer
node, one TP8 inference node, BF16 checkpoint transfer, and
`gpu_memory_utilization = 0.94`. The receiver code at the tested
baseline (`f53e4d9c`) is unchanged on current `main`.
| Receiver | Startup v0 | Post-training v1 |
|---|---:|---:|
| `main` | OOM on a 20 MiB clone in state dict 3/49; HTTP 500; retry
decoded `54639` state dicts | — |
| this change | 49/49 on all 8 ranks; HTTP 200 | 49/49 on all 8 ranks;
HTTP 200 |
Both successful transfers took approximately 12 seconds by broadcast
markers; the trainer reported `time/broadcast_weights = 13.2418s` for
v1. The inference server subsequently completed two rollout batches, and
the trainer completed its first optimization step.
At `gpu_memory_utilization = 0.97`, the baseline failed earlier while
allocating the 4.64 GiB receive buffer itself, so `0.94` was used to
isolate the additional clone allocation.
## Validation
- `uv run --no-sync pytest -q tests/unit/inference
tests/unit/transports/test_nccl_broadcast.py` — 14 passed, 1 existing
skip
- `uv run --no-sync ruff check
src/prime_rl/inference/vllm/worker/nccl.py`
- `uv run --no-sync python -m py_compile
src/prime_rl/inference/vllm/worker/nccl.py`
- `git diff --check`
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches distributed weight-transfer memory semantics on the inference
path; incorrect view lifetime could corrupt loads, but consumers copy
into model parameters synchronously.
>
> **Overview**
> Fixes GPU OOM during NCCL weight broadcast by **not cloning** each
tensor when splitting the per-dtype receive buffer in
`receive_state_dict`.
>
> Reconstructed weights are now **views** into the contiguous
`concatenated` buffer (`view(shape)` only), so checkpoint payloads are
not duplicated while vLLM runs layerwise loading via
`load_weights_checkpoint_layerwise` / `load_weights_kernel`. The flat
NCCL stream and per-state-dict receive lifecycle stay the same; disjoint
views keep the buffer alive until consumers finish using yielded
tensors.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d7bd908099d5cffb6792b9b40bdbd322851bc19a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- `AdminClients.wait_for_ready` still health-checks every engine and the
router, but when admin URLs bypass a router, the per-engine waiting
lines log at debug. Startup then logs one info waiting line instead of
one per engine plus the router:
```
03:18:09 INFO Waiting for inference server at http://localhost:8000 to start up (30s elapsed)
03:18:09 INFO Waiting for inference server at http://localhost:8100 to start up (30s elapsed)
```
- `check_health` grows a `quiet` flag that demotes its periodic waiting
lines to debug.
- Deployments without a router (no `client.admin_base_url`) keep logging
at info, as before.
Waiting only on the router is not enough: the llm-d router (Envoy) only
routes `/v1/` and `/inference/v1/`, so `/health` 404s and `check_health`
treats that as "no health route" and skips. The engines therefore stay
part of the readiness wait for correctness; the router just owns the
info-level log. Caveat: on llm-d deployments the info-level waiting line
disappears once Envoy binds its port (the engine waits continue at
debug).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Readiness polling and log-level only; no change to auth, weights, or
request serving. Timeout behavior is the same, just split across two
concurrent health waits.
>
> **Overview**
> Fixes readiness for llm-d/Envoy routers: `/health` on the router 404s
and was treated as “no health route,” so waiting on the router alone was
not a real ready signal.
>
> `AdminClients.wait_for_ready` now health-checks engines and router in
parallel. Engine waits use a new `quiet` flag so periodic “waiting”
lines log at debug when a router is present; the router still logs at
info. Deployments without `admin_base_url` are unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5167b63bac1ed60edf3f79a99ed470d25a6a026e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
The weight-broadcast core: one protocol for every transport instead of
three private ones.
- **One handshake per version, on every transport**:
`WeightSender.broadcast` is a template method - the trainer resets the
step dir and offers (`.sender_ready`), blocks until the consumer
acknowledges (`.receiver_ready`), transfers (`.started`), commits
(`.finished`), and cleans old dirs. Filesystem does the full handshake:
no consumer run-ahead while the trainer writes, no version skipping ("fs
== nccl behavior").
- **`WeightReceiver`**: consumer-side counterpart, colocated with its
sender per transport file
(`transports/weights/{base,filesystem,nccl,nixl}`). The weight watcher,
the orchestrator startup rendezvous, and the evals process drive the
same object; discovery is uniform on `.sender_ready`. Every offered
version must be received - a failed receive fails the run. This deletes
the NIXL version-cap/cycle-counting hack (markers are versioned on every
transport). The engine-side byte receiver stays in
`inference/vllm/worker`.
- **Consumption-driven sequencing**: broadcast `v{N}` iff something
consumes it. `broadcast_final` lives once on the shared
`BaseWeightBroadcastConfig`, launcher-stamped, never user-set (RL:
`orchestrator.eval is not None`; SFT: `True`). With evals, the final
eval measures `v{max_steps}` on every transport.
- **Bounded handshake**: the trainer's wait for the receiver raises
`TimeoutError` after `weight_broadcast.timeout` (now on the shared
config base, so filesystem has it too), with progress warnings every
60s.
- **Unified cleaning**: keep exactly `{step, step-1}` - broadcasts are
purely transitive, `checkpoints/` owns persistence. Fixes NCCL/NIXL dirs
leaking forever.
- **Fail-fast startup**: RL and SFT both broadcast the incoming policy
before the first step; resume hygiene (`prune_broadcasts_beyond`) lives
at the trainer call sites and prunes stale future dirs.
## Breaking
- On-disk sentinels replaced: `STARTED`/`STABLE`/`NCCL_READY` →
`.sender_ready`/`.receiver_ready`/`.started`/`.finished`, one uniform
handshake per version. Trainer and orchestrator must ship together. A
resume over old broadcast dirs re-broadcasts the startup version.
- Filesystem runs in lockstep with its consumer: the trainer blocks
until each version is acknowledged (bounded by
`weight_broadcast.timeout`), no longer writes versions nobody consumes,
and the consumer no longer skips to the newest version.
- RL with evals broadcasts `v{max_steps}` and the final eval measures it
(metric shift). Without evals, `v{max_steps}` is skipped on every
transport.
- Broadcast-dir retention: exactly the last 2 dirs on every transport
(NCCL/NIXL dirs were previously leaked; SFT kept newest-only).
## Verification
Stack 6/6 of the #3335 breakup; the composed stack is tree-identical to
the e2e-verified #3335 branch (FFT NCCL 10→20 with resume, FFT
filesystem 10→20 with resume, LoRA filesystem 15→20 with resume,
LoRA+NCCL config rejection - all green; per-leg details in #3335).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Rewrites the trainer–inference weight-sync protocol (handshake,
version sequencing, eval/startup rendezvous) across all transports. A
mismatch or timeout now blocks or fails the run rather than skipping a
version.
>
> **Overview**
> Unifies filesystem, NCCL, and NIXL weight updates onto one lockstep
handshake so every offered policy version is acknowledged before
transfer.
>
> Trainer `WeightSender.broadcast` now always offers `.sender_ready`,
waits for `.receiver_ready` (bounded by `weight_broadcast.timeout`),
then marks `.started` / `.finished`. Orchestrator, evals, and the weight
watcher all drive a shared `WeightReceiver` instead of per-transport
polling (`STABLE` / `NCCL_READY` / ModelExpress cycle counting). Failed
receives fail the run; filesystem no longer lets the consumer skip ahead
while the trainer writes.
>
> Broadcasts are consumption-driven: `v{max_steps}` is sent only when a
final eval will measure it (`broadcast_final`, launcher-stamped). Both
RL and SFT fail-fast with a startup broadcast, prune stale future dirs
on resume, and keep only `{step, step-1}` on disk. Trainer and consumer
must ship together — on-disk sentinels are a breaking change.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
53da37d3028a5755afc3615581c9664bfc47bf85. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Register the single training adapter under `config.model.name`: the
adapter shadows the base model (vLLM resolves `lora_requests` before the
base-model match; verified on the pinned vLLM 0.26), so requests keep
addressing one stable name and nothing switches model names mid-run.
- `update_weights` becomes artifact-driven: a weight dir holding
`adapter_config.json` is hot-swapped as an adapter (a vLLM-native
in-place reload, no engine pause); anything else is a full checkpoint
load.
- Deletes the adapter-naming machinery: the per-version model-name
rewrite in watcher/orchestrator/evals, evals' fixed `eval-adapter` name
and disk-sniff dance, `update_model_name`, and the dead
`unload_lora_adapter`.
- Guardrails: `modules_to_save` is rejected when the weight broadcast is
live (only adapter tensors ship - fully-trained modules would silently
diverge from inference); the LoRA/in-memory rejection states the real
reason (vLLM loads adapters only from a PEFT-shaped directory on disk).
The fallback, if a future vLLM rejects registering an adapter under a
served model name, is documented in the `/load_lora_adapter` wrapper: a
distinct constant name set once at startup.
## Breaking
- `orchestrator.model.lora.name` config field removed (with its
`r{rank}-a{alpha}` auto-derivation). External clients that addressed the
adapter name must use the base model name.
- Inference `max_loras` default 8 → 1 (in-place reload reuses one slot);
the `max_cpu_loras = 100` unload-era override is removed.
Part of the #3335 breakup (stack 5/6); re-lands #3356, whose
squash-merge landed on the stacked base branch instead of main. Verified
e2e as part of #3335 (LoRA reverse-text 15→20 with resume, reward
climbing under the base name).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches the LoRA inference serving path and is a breaking config
change (`orchestrator.model.lora.name` removed, `max_loras` default
8→1). Wrong adapter naming or slot count would mis-serve or fail weight
updates.
>
> **Overview**
> Registers the single training LoRA under `config.model.name` so the
adapter shadows the base model in vLLM. Requests keep using one stable
name; each policy version is an in-place reload (no engine pause, no
mid-run `model_name` rewrite).
>
> `update_weights` is now artifact-driven: a dir with
`adapter_config.json` loads as LoRA; anything else is a full checkpoint.
Adapter-naming machinery is gone (`orchestrator.model.lora.name`, evals'
`eval-adapter`, `update_model_name`, `unload_lora_adapter`). `max_loras`
defaults to 1 and `max_cpu_loras` is dropped.
>
> Rejects `modules_to_save` on live broadcasts (only adapter tensors
ship) and documents why LoRA needs filesystem broadcast. Clients that
used a custom adapter name must now hit the base model name.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7e4ba4ce153ee54b87816b573701cf9f95bda928. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Split `InferencePool` into two explicit classes under
`prime_rl.orchestrator.clients` (moved out of `utils.client`):
`InferenceClient` (data plane: train/eval client configs, model name,
prefill scoring - single-valued, one router endpoint) and `AdminClients`
(admin plane: one httpx client per engine process, in GPU-rank order -
the `rank_offset` math in the broadcast init depends on it; readiness
checks).
- Data-plane variables are named `clients` across the codebase
(`policy_pool`/`pool`/`policy_inference` renamed; the dispatcher uses
`policy_clients` to distinguish from frozen-source clients).
- Fixes the httpx-client leak: `InferencePool.stop()` closed only the
prefill scorer, leaking N+1 admin/router clients per pool; `aclose()`
now closes all of them.
- Deletes the dispatcher's `pinned_client` - a no-op since the
single-URL router (the client for a group never changes).
Behavior-preserving otherwise: the LoRA-name plumbing and the NCCL_READY
marker semantics are untouched (they change in the stacked follow-ups).
Part of the #3335 breakup (stack 4/6).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches orchestrator inference wiring, weight updates, and shutdown,
but is a behavior-preserving split plus a resource-leak fix. NCCL
world-size is now required rather than defaulted.
>
> **Overview**
> Splits the combined `InferencePool` into a **data plane**
(`InferenceClient`: train/eval clients, model name, prefill scoring) and
an **admin plane** (`AdminClients`: per-engine httpx clients in GPU-rank
order, readiness). Client helpers now live under
`prime_rl.orchestrator.clients`.
>
> Call sites (orchestrator, evals, dispatcher, algorithms, generation
sources, watcher) take `clients` / `admin_clients` instead of a pool.
Frozen endpoints use a one-shot `check_inference_ready` instead of a
persistent admin plane.
>
> Also **closes the httpx leak** (`aclose()` now shuts down admin/router
clients, not just the scorer), drops the unused dispatcher
`pinned_client`, and requires `inference_world_size` for NCCL init.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
19092eeb66bd30ff0fe34e5e64eb9a3276fa9c0f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Rename `transports.rollouts` → `transports.batch`: the module ships
packed training batches, not rollouts.
`MicroBatchSender`/`MicroBatchReceiver` (and the ZMQ/FileSystem
variants) become `BatchSender`/`BatchReceiver`;
`setup_micro_batch_{sender,receiver}` become
`setup_batch_{sender,receiver}`.
- The `MicroBatch` payload type, every `list[MicroBatch]` signature, and
the `rollout_transport` config field are unchanged.
Part of the #3335 breakup (stack 3/6).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary
- Remove the `client.extra_headers_from_state` config field and the
`auto_setup_session_headers` validator that populated it. The field has
no readers: v1 clients send the `X-Session-ID` sticky-routing header
themselves, from the rollout's trace id (`SESSION_ID_HEADER` in
`verifiers/v1/clients`, attached per request in `train.py` and
`eval.py`). Verified at the wire: requests through the real vf client
arrive at the router with the header and route sticky per session.
## Breaking
- `client.extra_headers_from_state` config field removed (dead - nothing
read it).
Part of the #3335 breakup (stack 2/6, on #3352).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary
- A run resumed from a checkpoint at or beyond `max_steps` never matched
the `is_last_step ==` check, so the trainer idled forever waiting for a
batch that would not come. `>=` makes it exit as the last step.
Part of the #3335 breakup (stack 1/6).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary
Log audit of the trainer and orchestrator, from a side-by-side read of a
full run's logs and the code that emitted them.
**Conventions** (applied everywhere):
- Every potentially slow action logs an active-tense info line first
(`Initializing X`, `Waiting for X`) — the last info line always names
the action that crashed or hung.
- Each one is paired with a debug completion carrying `format_time`
timing (`Initialized X in 1.2s`). All debug timings now use
`format_time`.
- Component inits log exactly `Initializing X ({config})`. Monitors log
a names-only summary plus one full-config line per monitor, from
`monitors.setup`.
**Gaps filled** (previously silent hang points): startup weight sync
(can block minutes), orchestrator teardown (info + one debug line per
stage, so a wedged component is identifiable),
`setup_torch_distributed`, device mesh init, trainer startup broadcast,
W&B finalize.
**Setup reorder** (orchestrator): local init first — sender, filesystem
weight broadcast — then the waits last before the main loop (env servers
→ inference pool → NCCL/NIXL handshake → startup sync). The NCCL/NIXL
handshake stays post-readiness (it POSTs to live engines); the
checkpoint's curricula restore follows `envs.start()` (`TrainSource`
needs loaded tasksets). One awaited metrics scrape primes the
concurrency controller so `Derived initial max inflight` logs before
`Starting orchestrator loop`.
**Renames and demotions** (highlights):
- `waiting for trainer to broadcast checkpoint N` → `Waiting for the
trainer to broadcast policy v{N}`; steps vs 0-indexed policy versions
untangled throughout.
- The inference wait is info every 30 s (`Waiting for inference server
at {url} to start up (30s elapsed)`), error at debug — was a warning
every 10 s.
- One identity line on all three processes: `Starting from scratch` /
`Resuming from step {N}`; `Broadcasting base policy weights (v{N})`.
- Launcher: `Starting {name} server`, `Starting orchestrator` (no
"process").
- Removed the per-group success debug in the train sink (flooded one
line per group); drop-path logs stay, renamed `Dropped group | ... |
reason=...`.
- Demoted to debug: ZMQ sender/receiver init/close, `Using shared W&B
mode`, `Loading model config`, executor setup, GC line. LoRA debug no
longer dumps the full model repr.
- Punctuation/tense/indexing: `Saving final checkpoint at step N`, no
trailing `.`/`!` on finish lines, 1-indexed micro steps.
## Verification
Ran alphabet-sort debug-level runs on this branch (from scratch,
`--resume.step 2`, and post-merge): clean startup → steps → drain →
teardown on both processes, all lines rendering as intended, e.g.
```
INFO Syncing inference to the trainer's startup broadcast (v0)
DEBUG Synced inference to policy v0 in 115ms
INFO Stopping orchestrator components
DEBUG Stopping dispatcher
SUCCESS Orchestrator finished
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Mostly logging, but orchestrator setup order, resume-step timing,
NCCL/NIXL after pool ready, and an extra metrics probe change real
startup/teardown sequencing. A hang or resume mismatch would show up at
run start.
>
> **Overview**
> Makes trainer/orchestrator/launcher logs follow a consistent pattern:
an **info** line for each potentially slow action (`Initializing` /
`Waiting`), then a **debug** completion with `format_time`. Identity
lines are aligned (`Starting from scratch` / `Resuming from step N`),
policy versions are labeled `v{N}`, and noisy lines (ZMQ init, GC,
per-group success, full model repr) are demoted or removed.
>
> **Orchestrator `setup` is reordered**, not just reworded: local work
(packer, micro-batch sender, filesystem broadcast) runs first; env
servers, inference readiness, NCCL/NIXL handshake, and startup weight
sync wait last. Resume step is applied before those waits. Teardown now
logs each stage. An awaited `inference_metrics.probe()` primes the
concurrency controller before the loop starts.
>
> Inference health wait is info every 30s (errors at debug). Drop-path
logs stay as `Dropped group | … | reason=…`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f1f33c0fc2fa3a2193118991c256cee0aae232ff. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
- Drop the orchestrator-side renderer: the orchestrator built a full
`Renderer` only to read `mm_token_type_id_map` off it and stamp
per-token modality markers in `trace_to_samples`. verifiers now stamps
the map onto the trace at turn commit and exposes the training-ready
stream as `Branch.mm_token_type_ids` (PrimeIntellect-ai/verifiers#2424)
— the orchestrator consumes that and builds no renderer at all.
- `trace_to_samples` reads `branch.mm_token_type_ids` directly; the
`mm_token_type_ids_mapping` parameter and its `TrainSink`/`Orchestrator`
plumbing are gone.
- `setup_policy_inference_pool` (now just an `InferencePool`
construction) is inlined into `Orchestrator.setup()`; its mock-based
unit test file is removed.
- Bumps `deps/verifiers` to verifiers main, which includes the merged
PrimeIntellect-ai/verifiers#2424. Rollout rendering is unchanged — it
already happens inside verifiers' renderer train client.
## Verification
Before/after 6-step multimodal RL runs (color-codeword,
`Qwen/Qwen3.5-4B`, 1 train + 1 infer GPU, batch 64, group 8):
- **Before** (main): rewards 0.17 → 0.36 across 6 steps, 0% errors, all
samples trainable, losses finite.
- **After** (this PR + vf#2424): rewards 0.13 → 0.42 across 6 steps, 0%
errors, all samples trainable, losses finite. The trainer hard-fails on
image samples missing `mm_token_type_ids` (`prepare_sample` raises), so
completing all steps proves the new path delivers them. The after-run's
orchestrator log contains no renderer initialization.
- Offline equivalence on the after-run's 833 dumped traces (2499
branches): every trace's stamped `mm_token_type_id_map` equals the
renderer map the orchestrator used to build (`{<|image_pad|>: 1,
<|video_pad|>: 2}`), and per-token ids computed the old way match
`Branch.mm_token_type_ids`' computation exactly.
- `tests/unit/orchestrator` green (the pre-existing `test_qwen3_vl_e2e`
failure needs a live vLLM and fails identically on main).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches the multimodal training-sample path: missing or mismatched
`mm_token_type_ids` would fail trainer `prepare_sample`. Behavior now
depends on verifiers stamping the map correctly rather than a local
renderer.
>
> **Overview**
> Stops building an orchestrator-side `Renderer` just to stamp
multimodal token types. Training samples now take `mm_token_type_ids`
from `branch.mm_token_type_ids` (stamped by verifiers at turn commit).
>
> `setup_policy_inference_pool` is inlined as a direct `InferencePool`
construction. `TrainSink` / `Orchestrator` no longer plumb
`mm_token_type_ids_mapping`, and the helper’s unit tests are removed.
Rollout rendering is unchanged (still inside the renderer train client).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4e6fde2b910f91e80fd460704077f87c98329032. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
- Add `.agents/skills` as a symlink to the shared `skills/` directory.
- Make repository skills available through Codex default discovery.
## Verification
- Confirmed `.agents/skills` resolves to `../skills`.
- Commit hooks passed.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Config-only symlink for agent skill discovery; no runtime, auth, or
data-handling changes.
>
> **Overview**
> Adds a `.agents/skills` symlink to `../skills` so Codex can discover
the repo’s shared skills via its default lookup path.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
625149a26b20bafa2d3901222d4c1b7f4bdef35b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Gate the autouse `cleanup_zombies` fixture in `tests/conftest.py` on
`USERNAME_CI`.
- The fixture pkills `-f torchrun` / `-f VLLM` host-wide at every test
module start. In CI this cleans up zombies from previous tests, but
locally it kills any concurrent training run on the box.
- `USERNAME_CI` is already set to `CI_RUNNER` by all CI pytest jobs
(`cpu_tests`, `gpu_tests`, `nightly_tests`) and already keys the `user`
fixture, so CI behavior is unchanged and no workflow changes are needed.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Test-only fixture change; CI behavior is preserved. Residual risk is
local leftover processes if tests leak zombies without USERNAME_CI.
>
> **Overview**
> Stops the autouse `cleanup_zombies` fixture from host-wide `pkill` of
`torchrun`/`VLLM` on local pytest runs, so concurrent training jobs are
no longer killed.
>
> The kill still runs when `USERNAME_CI` is set (already used by CI
pytest jobs), so CI zombie cleanup is unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
454f89e5c269d62410f2ea007b884537dd964045. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
- `examples/advanced/glm-4.5-air/swe.toml`: serve inference from the
bf16 checkpoint directly — drop `quantization = "fp8"` from
`[inference.vllm]`.
- Switch the train and eval harnesses from `rlm` to `bash`. Drop the
rlm-only `summarize_at_tokens` knobs.
- Update the header comments to match.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Example-only TOML config; no training, inference, or harness code
changes.
>
> **Overview**
> Updates the GLM-4.5-Air SWE example so inference serves the **bf16**
checkpoint directly (drops vLLM `fp8` quantization) and train/eval use
the **bash** harness instead of **rlm**, including removing
`summarize_at_tokens`. Header comments are aligned with that.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
72032855baa5712daab635147683cf9c09541bf0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
- Fold every `[[...source]]` entry's nested sub-configs into dotted keys
in one block (`env.taskset.id = "..."`, `env.agent.harness.id = "..."`)
instead of one full-path subsection header per nested config. Applies to
all train/eval source blocks in `configs/`, `examples/`, and `k8s/` (51
TOML files, −868/+322 lines).
- Move the top-level `[monitors.prime]` block up next to
`[monitors.wandb]` in the 4 files where it sat inside the orchestrator
section.
- Apply the same style to the TOML snippets in `docs/` and the `configs`
/ `training/start-run` skills, and document the convention in the
configs skill. Nested arrays of tables (e.g.
`[[...source.env.taskset.task.judges]]`) keep their full-path headers.
Purely cosmetic — no config semantics change. Verified by asserting
`tomllib` parses every file to an identical dict before and after, and
by diffing the resolved-config JSON from `rl --dry-run` (identical up to
the CLI-passed `output_dir`).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
- Bump the `deps/verifiers` submodule from `4bcb48e` to `a60a606`
(latest `main`).
- Pulls in:
- [vf#2410](https://github.com/PrimeIntellect-ai/verifiers/pull/2410):
prime-sandboxes 0.2.39 + pooled per-loop sandbox client.
- [vf#2422](https://github.com/PrimeIntellect-ai/verifiers/pull/2422):
evals run through the env server by default.
- [vf#2423](https://github.com/PrimeIntellect-ai/verifiers/pull/2423):
strip the hub org prefix before importing a plugin module.
- Relock `uv.lock`: prime-sandboxes 0.2.37 → 0.2.39, connect-python →
connectrpc 0.11.1, new protobuf-py transitive deps.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Dependency bump of the verifiers/sandbox stack can change eval routing
and RPC client behavior; lockfile-only surface but runtime impact is
non-trivial.
>
> **Overview**
> Advances the `verifiers` pin and relocks `uv.lock` so
`prime-sandboxes` moves **0.2.37 → 0.2.39**.
>
> That pull also replaces `connect-python` with `connectrpc` 0.11.1 and
adds transitive `protobuf-py` / `protobuf-py-ext`. Upstream verifiers
changes include a pooled per-loop sandbox client, evals defaulting
through the env server, and stripping the hub org prefix on plugin
import.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
13b8ad796e06175e26b6196815631c2bbf40e36a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
Refactors staleness handling around the exact consumption-lag definition
(#3050's framing), toward #3310.
- **Exact measurement**: `episode_staleness()` decomposes each trained
episode's staleness from its `PolicySpan` into the in-flight share (`end
- start`, weight updates during generation) and the in-queue remainder
(buffered between completion and ship). New per-step metrics:
`off_policy/{mean,max}`, `off_policy/{in_flight,in_queue}/{mean,max}`,
`off_policy/dropped`; the step log line's `Max Off-Policy` uses the
exact definition. Every quality metric in the step log and the wandb
`effective` subset is computed over exactly the traces shipped to the
trainer this step (`batch.cohort`); only `Error`/`Cancelled`/`Ratio` are
arrival-window rates, since over the shipped set they are
0/0/share-of-shipped by construction.
- **In-queue enforcement**: previously only in-flight episodes were aged
and dropped — an episode that finished quickly and sat in the sink
accumulated staleness that was measured at ship but never enforced. Now
the sink sweeps `pending_batch` before every readiness check and voids
anything past `max_off_policy_steps`, so the bound is a hard guarantee
on trained data. The dispatcher's version-boundary sweep remains as a
compute saver (it must run before the engine pause for KV-abort safety)
and uses the same exact step-based formula.
- **Tail semantics**: the trainer now broadcasts every version except
`v{max_steps}` (the only one nothing can sample from), instead of
skipping the final `TARGET_LAG+1`. The orchestrator stays alive for the
last rendezvous (`wait_for_final_broadcast`), so `max_off_policy_steps`
holds exactly on every step including the final batch, and the tail
special-casing this used to need is gone (the dispatch gate's
final-batch exception and the watcher's shortened ModelExpress window).
Draining now starts right after shipping the final batch — the old
trigger needed a further batch to *fill*, which burned a batch of
inference and, under a tight `max_off_policy_steps`, never filled at all
(end-of-run livelock).
- **First-class cancellation**: dropped groups emit one typed
`Cancellation(group_id, count, reason)` on `out_q` instead of
per-episode synthetic `Cancelled`-error episodes; queue-voided episodes
are tracked in a `cancelled` id-set on the episode collections,
alongside `sampled`/`admitted`. Cancellations no longer confound error
metrics: `has_error` stays pure (overload cuts and staleness drops are
no longer counted as errors), the effective subset excludes cancelled
episodes explicitly, and the step log / wandb gain separate `Cancelled`
rates. A stale-voided group also bypasses curriculum admission — a
pipeline decision is not a task result.
## Breaking
- **wandb**: new `train/*/all/**/cancelled/mean` and per-step
`off_policy/*` keys; cancellations no longer appear under
`*/error/Cancelled` or inflate `has_error/mean`.
`dispatcher/off_policy_level/{mean,max}` →
`dispatcher/off_policy/{mean,max}`, now reporting the exact step-based
staleness of in-flight work instead of the aged in-flight counter.
- **Zero-output abort accounting**: cancelled groups still advance the
zero-output budget (by their full owed episode count), but stale-voided
groups no longer feed the curriculum via `on_result`.
- **Trainer broadcast schedule**: in-memory transports now broadcast
`v{max_steps-1}` (previously skipped); the orchestrator waits for it
before tearing down. The final drain no longer requires (or generates) a
throwaway post-final batch.
- **The bound's meaning tightened**: staleness now counts queue time,
not just weight updates during generation. A config tuned under the old
in-flight-only definition drops more aggressively at the same numeric
value; `max_off_policy_steps = 0` now means strictly synchronous (heavy
oversampling drops), where the old `0` only meant "no update
mid-generation".
## Verification
- Behavioral smoke (stubbed envs, no GPU): stale `Cancellation` voids
arrived episodes without reading as error; a fully-cancelled group still
advances the zero-output budget by its owed count; overload cancellation
finalizes the partial group and its survivors still train; the queue
sweep un-fills a batch, marks the episode cancelled, and counts drops;
the dispatcher drops exactly the groups past the bound and emits one
typed `Cancellation`; `effective` excludes cancelled while
`has_error`/`cancelled` stay disjoint.
- `tests/unit/orchestrator`, `tests/unit/test_configs.py`,
`tests/unit/transports`: 201 passed (the `test_qwen3_vl_e2e` failure is
pre-existing on `main`).
- `ruff check` and `ruff format --check` clean.
- E2E: 15-step reverse-text run with
`--orchestrator.max-off-policy-steps 0` (true on-policy), clean exit in
3m 21s. **All 15 step lines report `Max Off-Policy 0` and `Error 0.0%`**
— including the final batch, which now trains on the freshly-broadcast
`v{max_steps-1}`. Both enforcement layers fired throughout (45
queue-sweep drops, 14 in-flight cancel sweeps) with per-step `Cancelled`
up to 70% and zero genuine rollout failures — e.g. `Step 2 | … | Max
Off-Policy 0 | Error 0.0% | Cancelled 70.3% | …`; under the old
error-marker representation those cancellations would have read as
`Error ~70%`. Draining started immediately at the final ship (`Shipped
the final batch — draining pipeline`). Reward climbed 0.14 → ~0.77.
- E2E (filesystem broadcast): 8-step reverse-text run with
`--weight-broadcast.type filesystem --orchestrator.max-off-policy-steps
0`, clean exit for both processes. All 8 steps report `Max Off-Policy 0`
and `Error 0.0%` — including the final batch, since filesystem writes
every version (no skip path) and the final-broadcast wait is correctly
inert (0 occurrences). Drain fired at the final ship; the trainer wrote
all broadcast dirs and finished cleanly. NIXL is safe by construction
(trainer skip window and the watcher's ModelExpress guard both derive
from `max_steps` and moved in lockstep) but has not been exercised
end-to-end.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
## Summary
Since #3299 made `data.num_workers` default to 1, **every resumed SFT
run silently restarts the training data from the beginning** and freezes
the data position it writes into subsequent checkpoints.
Root cause: `train()` called `iter(dataloader)` before the resume path's
`ckpt_manager.load(..., dataloader=dataloader)`. With worker processes,
`iter()` forks the worker with a copy of the dataset in its *initial*
state; the later `load_state_dict` only stashes state for a future
iterator that is never created. Two symptoms:
- the resumed run consumes the dataset from row 0 again (visible as a
loss-slope kink at every resume — repeated data);
- `state_dict()` keeps returning the stashed loaded state, so every
post-resume checkpoint stores the resume-point position instead of the
live one, compounding across restarts.
Fix: create the iterator only after the potential resume load, with a
comment stating the constraint.
Also: `get_dataset_state` unpacked exactly one worker snapshot, crashing
**any** run with `num_workers > 1` at the startup log line (start or
resume) — it now returns positions keyed per worker, and stops dumping
`pending_sample` token buffers into the log. It keeps parsing the
loader's stashed state rather than the dataset object: after a resume
the restored position exists only there (the main-process dataset object
stays at position 0; workers receive the state on fork). This is now the
single code path: `num_workers = 0` (the only case with a different,
inline state layout) is no longer supported.
## Breaking
- `data.num_workers = 0` is rejected at config time (`ge=1`). Inline
main-process data loading is gone; use `num_workers = 1` (the default).
## Verification
A/B on `configs/ci/integration/reverse-text-sft/{start,resume}.toml`
(Qwen3-0.6B, 1 node, 2 GPUs, 5 steps + resume to 10), comparing
`checkpoints/step_N/trainer/dataloader/rank_0.pt` worker-snapshot
dataset state:
| variant | ckpt step_5 | ckpt step_10 (post-resume) |
|---|---|---|
| main, `num_workers=1` | `{'step': 213}` | `{'step': 213}` — frozen,
data restarted from row 0 |
| main, `num_workers=2` | — | crashes at startup (`ValueError: too many
values to unpack` in `get_dataset_state`) |
| this PR, `num_workers=1` | `{'step': 213}` | `{'step': 407}` —
advanced correctly |
| this PR, `num_workers=2` | `{'worker_0': 111, 'worker_1': 111}` |
`{'worker_0': 213, 'worker_1': 213}` — per-worker state restored and
advanced; workers consume disjoint shards |
Discovered on a production 500-step GLM-4.5-Air SFT run (india): after
two crash-resumes, both post-resume checkpoints carried the identical
dataset position (`{'step': 6657}` at step 150 *and* step 300) and the
loss slope steepened at each resume boundary from re-trained data.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* test(trainer): add xfail demonstrating buffer-reinit-after-load bug
load_dcp_from_hf runs init_buffers_post_meta() after dcp_load() writes
checkpoint values into persistent buffers, so any model whose reinit
touches a persistent buffer (e.g. Laguna's MoE expert_bias) has the
loaded value silently clobbered back to its reinit default.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(trainer): reinit buffers before loading checkpoint, not after
load_dcp_from_hf ran init_buffers_post_meta()/fix_model_post_empty()
after dcp_load() had already copied checkpoint values into persistent
buffers, silently clobbering any buffer both a reinit hook touches and
a checkpoint legitimately ships (e.g. Laguna's MoE expert_bias). Move
the call to run once, immediately after to_empty(), matching the
existing correct ordering in setup_model's checkpoint-deferred branch.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(trainer): rename test_model_load_order.py to models/test_state_loading.py
Group it with the other cross-cutting model-mechanism tests
(test_checkpointing.py, test_fused_moe.py) rather than the top-level
train/ dir, and name it for what it covers (weight-checkpoint state
loading) since models/test_checkpointing.py already covers activation
checkpointing.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
* enable nccl for sft online evals
* support multi-node sft nccl evals
* fix: enforce NCCL-requires-inference at the launcher, not the model validator
The launcher strips [inference] and [deployment] from the trainer sub-config
of a decoupled multi-node deployment, so the re-parsed sub-config tripped the
validator's guard and crashed every trainer rank at startup.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: remove accidentally committed gitlink
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: broken line continuation in NCCL sbatch template blocks
The {% if %} blocks left a whitespace-only line after the backslash
continuation, terminating the launch command early: the trainer/evals
processes ran without their tee pipelines (empty node_*.log/evals.log)
and the stray '2>&1 | tee ... &' ran as a separate command, mis-assigning
EVALS_PID.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* share weight broadcast config policy
* revert shared weight broadcast policy
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Qwen3.8 reuses the Qwen3.5 architecture verbatim — the dense 27B reports
`model_type: qwen3_5` / `Qwen3_5ForConditionalGeneration`, the 2.4T-A95B
reports `qwen3_5_moe_text` — but both places that enable Qwen3.5 keyed off
the repo name, so neither picked it up.
Trainer: gate the three Qwen3.5 patches on the loaded config's `model_type`
instead of a substring of `model.name`. The name check missed
`Qwen/Qwen3.8-27B` and the `qwen3_5_moe` fallback only caught the MoE
sibling, so the dense 27B trained without `_patch_qwen3_5_linear_attn_varlen`
— GatedDeltaNet gets no cu_seqlens, conv/SSM state leaks across packed
sequences, and 48 of its 64 layers are linear attention. model_type also
covers Qwen3.6 and renamed fine-tunes, which the name check missed too.
Parsers: `^Qwen/Qwen3\.5-` doesn't match the dotted 3.6/3.8 names and the
`^Qwen/Qwen3-` catch-all only matches hyphenated ones, so both parsers
auto-resolved to None and vLLM launched without either flag. Qwen3.8's chat
template opens `<think>` at the generation prompt, so reasoning would land
in `content` and tool calls would go unparsed.
* feat!: remove weight checkpointing
The trainer saves only DCP checkpoints. HF weights on disk exist in two
forms: weight broadcasts — the transient trainer-to-inference transport,
which SFT now ships for online evals (same filesystem component RL
uses, broadcast at eval steps, newest kept only) — and offline
conversion of DCP checkpoints via scripts/dcp_to_hf.py (full models and
LoRA adapters).
WeightCheckpointManager, the weights/step_N dirs, and the ckpt.weights
config surface (weights, weights_only, skip_gather_master_weights,
save_adapter_separately) are removed. The evals process watches
broadcasts/step_N (OnlineConfig.weights_dir renamed to broadcasts_dir)
and loads adapter broadcasts of LoRA runs via /load_lora_adapter. The
weight save/gather helpers move to prime_rl.utils.weights.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: wait for the resume-step broadcast before retriggering
The trainer rebroadcasts the resumed policy only after loading the
model, so a one-shot STABLE check usually lost the race and the watch
loop never retried (last_step is pre-seeded to the resume step). Wait
for the broadcast; give up only when a newer stable broadcast proves it
was already cleaned away.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: enable LoRA on the eval inference server
SFT LoRA online evals reload raw adapter broadcasts via
/load_lora_adapter, which requires enable_lora on the server. Mirror
the RL validator: set enable_lora and max_lora_rank when LoRA is on,
warn when inference is externally managed.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: defer offline DCP->HF converter to a follow-up
The converter needs more standalone testing (incl. GPU-free use) and will
land in its own PR. The resume-preserves-weights test now compares the DCP
checkpoints directly via dcp_to_torch_save; the PEFT adapter-export tests
move to the follow-up with the script.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: DCP comparison keys and dtypes in resume test; idempotent rebroadcast
The trainer wraps DCP state as {app: {model: ...}}, so the converted
torch save must be indexed through 'app' — the bare 'model' lookup
raised KeyError. The two compared runs also train in different compute
dtypes (fp32 vs bf16 under full offload), so compare in bf16, which is
what the resumed model actually loaded.
The SFT startup rebroadcast now skips when the resume step's broadcast
already exists with STABLE: rewriting the same dir in place would race
an evals process already reloading it.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* feat: rank-parallel sharded save for filesystem broadcast
Gather full weights cooperatively and let every rank convert and write
its own layer-aligned slice as safetensors shards, instead of funneling
everything through the master rank. D2H copies go through persistent
pinned buffers and overlap the per-tensor all-gathers. The broadcast is
always sharded safetensors now; the save_sharded and save_format knobs
are gone.
Laguna-XS.2 (68GB bf16) on 2 GPUs: gather 25.1s -> 2.7s, total save
83.1s -> 51.9s (the write phase is disk-bound on a single NVMe;
rank-parallel writes scale with per-node writers on shared
filesystems).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: create save dir in save_state_dict_parallel
Callers no longer need to pre-create the directory; a fresh save dir
made every rank's shard write fail with a safetensors I/O error.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: note the same-stream invariant on the staging copy
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: clarify HF conversion branches and resolve_fqn
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: blocking D2H copies in the parallel gather
Drop the pinned staging buffers and non-blocking copies: their safety
rested on same-stream allocator-reuse ordering, which is subtle to
maintain. Each rank still copies only its slice, and the parallel shard
writes — the dominant cost at scale — are unchanged.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: derive layer ownership from the module tree
Replace the FQN regex with prefixes taken from the children of every
'layers' ModuleList. State-dict keys and module names come from the
same tree traversal, so the prefixes match keys verbatim, wrapper
components and all.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Revert "refactor: derive layer ownership from the module tree"
This reverts commit 740059c835ac8025af00ab58cdbe1aef941168ee.
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* Add custom vendored kernels
* Add fused MoE kernel
* Fix comments, simplify kernel toml metadata, make sure deps for prime-kernels match prime-rl directly
* Update to latest fused moe kernel
* Add prime-flash-moe integration in addition to locally compiled kernels
* Add mxfp8 routing support for prime-flash-moe
* Fix MXFP8 backward for fused MoE for correctly group aligned experts
* Torch fused grouped_mm backward for fused MoE forward
* Fix release upload in kernel build: install gh in container, grant contents write
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Set GH_REPO for release upload: container checkout trips git dubious-ownership
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Pin prime-kernels at the v0.8.0 prebuilt wheels behind a kernels extra
The wheels were backfilled onto v0.8.0 from this branch
(build_kernels.yaml run 31429866271); uv sync --extra kernels now
installs them instead of requiring a local nvcc build.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Format kernel MoE files with ruff 0.13
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Fix memory corruption of triton kernel for large numel quants, where N >= 2^31=INT_MAX
* Make the kernel a git-submodule
* Move the kernels into the prime-kernels submodule
The `prime-kernels` wheel — build system, registry and every kernel's Python
surface — now lives in its own monorepo, PrimeIntellect-ai/prime-kernels,
checked out here as the `kernels/` submodule. flash_moe's C++/CUDA sources,
previously a nested prime-flash-moe submodule, are committed there too, so one
non-recursive init brings in everything a source build needs.
Integration is unchanged: `uv sync --extra kernels` still resolves the prebuilt
wheels from a prime-rl release, `uv pip install --no-build-isolation -e kernels`
still builds from source, and build_kernels.yaml still attaches the wheels to
every release. Its `paths` trigger moves from `kernels/**` to the `kernels`
gitlink, which is the only path prime-rl tracks now, and ruff excludes the whole
submodule rather than just the vendored sources.
* Update kernels
* Fix comments
* Add tests for the fused MoE
* Bump prime-kernels to 2ceaf9e
* Remove stray uv.lock for prime-rl-configs
* Verify mxfp8 grad values and needs_input_grad handling
* Print epsilons in tests
* Print epsilons in tests
* Print epsilons in tests
* Print epsilons in tests
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
A linear scheduler with warmup_steps + decay_steps > max_steps only
failed deep into trainer setup, via a bare assert in
setup_linear_scheduler. Add validate_scheduler to the configs package
and call it from TrainerConfig and SFTConfig so the run fails at
config validation instead. Also covers cosine schedulers, which need
max_steps and warmup_steps < max_steps.
The runtime assert stays as a backstop (SFT resume with skip_scheduler
shrinks the step budget at runtime) but now carries a message.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
test_qwen3_moe compares HF and prime-rl gradients in bf16 with an
unseeded random draw; FA2 backward is not bit-deterministic, so the
embedding grad diff (observed 512-1344) occasionally crosses the
atol=1000 threshold, failing CI with 'Max grad diff: 1024.0' on main
and unrelated PRs.
- autouse fixture pins torch.manual_seed(0) so the input/init draw is
deterministic (verified grad diff stays in 512-768 on this seed)
- bump grad atol 1000 -> 2048 to absorb FA2 backward reduction-order
noise that seeding cannot remove (60/60 random seeds pass at 2048,
worst observed 1344)
* USe dataloder threads and pinnd memory tranfers async
* Fix PRNG
* Reset fused lm head token chunk size to 4k
* Revert lm head chunk size to default, another PR does this
* Remove unused prefetch factor
* Fix PRNG bug
* Split kv trims into soft and hard tiers
A trim at the 0.8 trigger now only lowers the cap and lets completions
drain the pool — at that level there is still headroom, and at steady
state completions usually outrun in-place context growth, so
cancelling immediately pays a certain cost to avoid a merely possible
one. Only if usage climbs past 0.9 despite the closed gate does the
trim also cancel the excess (the prior behavior), preserving the
thrash-cliff guarantee: worst case, a soft trim escalates to a hard
one a cooldown later, still well before the cliff. Emergency cuts are
unchanged.
* Add 2-node concurrency debug config
GLM-4.5-Air scaleswe on the bash harness, 1 train + 1 infer node,
default concurrency, 100-instance SWE-Bench eval.
* Rename trim thresholds to KV_USAGE_SOFT_CAP / KV_USAGE_HARD_CAP
* Fix stale header in the concurrency debug config
* feat: first-class evaluator with adaptive concurrency
Promote the evaluator out of the orchestrator package into
prime_rl.evaluator and let it run standalone multi-env evals (no
[online] block: one epoch against the served weights, then exit) as
well as SFT online evals ([online]: watch the weights dir per
checkpoint; the sft launcher writes this config).
Scheduling reuses the orchestrator pipeline 1:1: an eval-only
Dispatcher sized by the adaptive ConcurrencyController
([eval.concurrency], replaces eval.max_inflight_episodes), fed by the
InferenceMetricsCollector's /metrics polls. Overload cuts only block
admission - eval episodes are measurements and always run to
completion.
The evaluator spawns an env server per source without an explicit
serve.address; the sft launcher keeps spawning its own and stamps the
derived addresses into the evaluator config.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: stop evaluator collectors before monitor finalize
The periodic logger and the inference-metrics collector log to the W&B
run, so a poll landing after monitors.finalize() warns about a finished
run - mirror the orchestrator and stop them on the clean path first.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: fail fast when adaptive concurrency has no metrics
External inference APIs (e.g. Prime Inference) expose no vLLM /metrics,
so the concurrency controller never bootstraps and the cap would
silently sit at min_inflight forever. The evaluator now probes /metrics
once at startup: no engine metrics + an adaptive band raises with the
fix (pin min_inflight = max_inflight); a pinned band runs fixed with a
warning. A successful probe also bootstraps the controller before the
first dispatch.
Add examples/evals/swe.toml: SWE-bench Verified + Terminal-Bench 2
against deepseek/deepseek-v4-flash on Prime Inference, 1h agent cap,
pinned band.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: rename evaluator command and configs to evals
Per review: the command is uv run evals, the config classes are
EvalsConfig / EvalsEvalConfig in prime_rl.configs.evals, the package is
prime_rl.evals, and the launcher artifacts follow (evals.json,
evals.log, shared-W&B labels). Docs section is Evals. Add EvalsConfig
to the config-load CI check so examples/evals/*.toml are validated.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: drop the Evaluator name entirely
Class Evals in prime_rl.evals.evals, run_evals wrapper, Evals proc
title and log lines; prose refers to the evals process. No identifier
or doc references evaluator anymore.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: drop the standalone evals section for now
Keep the online-evals doc updates (command rename, [eval.concurrency])
and the start-run skill runbook.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: reject skip_first_step on standalone evals
The first trigger honors skip_first_step, and standalone mode has only
that trigger - the run would exit successfully without evaluating
anything. Reject the combination at config time.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: cap CI concurrency at 128 in-flight episodes
The adaptive ramp on CI's small engine floods the router until its
circuit breakers open (ProviderError: No available workers) - 512 is
still past what the deployment sustains.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: lower wiki-search initial_inflight to the CI cap
initial_inflight must not exceed max_inflight.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Consolidate the two send/recv stacks under one package:
- prime_rl.transport (rollouts, orch -> trainer) is now
prime_rl.transports.rollouts
- prime_rl.trainer.rl.broadcast (weights, trainer -> orch -> infer)
is now prime_rl.transports.weights
Both keep the base.py + concrete implementations structure. The vLLM
worker extensions and the orchestrator weight watcher stay in place
and import the shared primitives from the new location.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* docs: add adaptive concurrency design
Feedforward token budget (n_max = kappa * C / G) from learned per-env
episode costs, trimmed by a binary engine-overload signal (AIMD on
kappa). Covers eval/train cost weighting, the step-1 freeze, and KV
offloading. Supersedes the reactive KV-target controller from #2908.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: clock adaptive-concurrency updates to steps
Re-evaluate n_max once per training step (G reweigh + at most one
kappa growth) - aligned with the per-step eval gate and naturally
plant-clocked, since step time tracks mean episode time. HARD cuts
stay on the 5s poll: waiting for a step boundary would sustain thrash.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: spec ConcurrencyController abstraction + config
Self-contained controller with [orchestrator.concurrency] config:
max_inflight ceiling (replaces orchestrator.max_inflight_episodes),
optional initial_inflight to skip the ramp, adaptive kill switch.
Kappa initialized by continuity at freeze exit. Pure state machine
driven by collector pushes, dispatcher completions, and the step loop.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: adaptive concurrency always on
Drop the adaptive flag from the design - the controller is not
optional. max_inflight is the only escape hatch (hard ceiling).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: adaptive rollout concurrency controller
ConcurrencyController sizes the dispatcher's in-flight cap as
n_max = clamp(kappa * C / G, group_size, max_inflight): a feedforward
token budget from engine KV capacity and learned per-env episode
costs, trimmed by a binary per-engine overload signal (HARD
preemption cut on the 5s poll, per-step growth otherwise). Always on.
- [orchestrator.concurrency]: max_inflight ceiling + initial_inflight;
replaces max_inflight_episodes and oversampling_factor
- InferenceMetricsCollector always polls (wandb mirroring stays
gated), parses cache_config_info labels for KV capacity, and pushes
EngineLoadSample facts to the controller; the old waiting-queue
overload warning is subsumed by the SOFT signal
- Dispatcher: dynamic set_limit, burst-capped refill, episode
completion hook (env, kind, tokens, duration)
- configs/concurrency/: three e2e configs (low start, overload start,
GLM-Air SWE with 10-turn eval)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: backoff naming + config comment fixes
Rename cut factors to BACKOFF_FACTOR / ESCALATED_BACKOFF_FACTOR,
describe kappa as the over-commit factor, add wandb project +
max_num_seqs to the hendrycks e2e configs (the vLLM default of 128
would queue instead of building KV pressure), and point verification
at the W&B gauges (the periodic logger does not feed metrics.jsonl).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: add no-eval concurrency e2e config
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: frozen_steps knob + 50-step e2e configs
concurrency.frozen_steps (default 0) pins the cap for the first k
steps; the first re-evaluation lands at the k -> k+1 boundary. HARD
cuts stay live inside the freeze. The e2e configs run 50 steps at
default gpu_memory_utilization with AIME avg@4 evals every 10 steps,
8k max_model_len, and run names matching the config file names.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: motivate higher frozen_steps values
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: rename concurrency e2e configs
hendrycks-low-no-eval -> hendrycks-initial-low,
hendrycks-low -> hendrycks-initial-low-eval,
hendrycks-high -> hendrycks-initial-high-eval.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: migrate example configs to initial_inflight
The old max_inflight_episodes values become concurrency.initial_inflight
starting caps - a hard ceiling is usually not wanted with the adaptive
controller.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: use config blocks for concurrency in examples
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: raise max_off_policy_steps in hendrycks configs
The adaptive cap runs hundreds of episodes in flight against a
64-sample batch, so episodes span more steps than the default
off-policy budget of 8.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: slash-namespace dispatcher gauge keys
dispatcher/inflight/{train,eval,groups} and
dispatcher/off_policy_level/{max,mean}, mirroring the
cancelled/errored/queued key scheme.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: drop groups-in-flight gauge
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: derive initial cap from engine max context
With initial_inflight unset, the starting cap is the pessimistic
bound C / max_model_len: an episode cannot exceed the engine context,
so that many episodes always fit. max_model_len comes from /v1/models
(set explicitly or taken from the model config) and also replaces
seq_len as the cost-estimate bootstrap once known.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: richer concurrency logging + wandb inflight mirror
- Active-voice change lines with state snapshots:
'{Increased,Decreased} concurrency {x} -> {y} at step {n} ({reason})
- kappa=.. cost=.. capacity=.. signal=..' plus per-env EWMA
snapshots at debug
- One-time capacity report after the first poll ('Inference reports
3.0M tokens of KV cache capacity - max model len 8.2K') and a
derivation line when the initial cap is runtime-derived
- Collector accepts extra_metrics and mirrors
inference/dispatcher/inflight/{train,eval} into the per-poll W&B
payload so inflight reads on the engine time axis
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: show inflight vs cap in the wandb overview
Drop the inference/-prefixed mirror; the dispatcher gauges keep their
own keys and join the overview's inference section as one panel
(dispatcher/inflight/{train,eval} + concurrency/max_inflight), on the
same wall-time axis as the engine metrics.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: survive out-of-vocab ids in logprobs detokenization
Padded-vocab models (Qwen: logits dim > tokenizer vocab) can sample
out-of-vocab ids once RL updates shift the untrained tail logits.
vLLM's _restore_leading_spaces then iterates a None raw piece and the
TypeError kills the async output processor and the engine (hit twice
in the 50-step concurrency verification runs, at steps 37 and 12).
Guard the raw piece; the id still detokenizes via decode.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: apply concurrency bootstrap only once
The bootstrap guard in observe() held true on every metrics poll
until the first train step set kappa. The cap was recomputed from
the moving cost EWMA every ~5s, so it flapped by hundreds of
episodes before step 1. Latch it: one feedforward raise on the
first capacity observation, then updates only at step boundaries
(HARD cuts stay live).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: say episodes for in-flight units
The dispatcher's permit unit is one episode (one env.run, possibly
several traces), so in-flight logs and identifiers now say episodes:
InflightEpisode, cancel_inflight_{train_,}episodes, and the console
lines (pipeline view, off-policy cancel warning, drain notice, mode
switch).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: drop cap series from overview inflight panel
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: fix stale overview comment
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: step-clock the cost EWMA folding
The estimates updated per completed episode with alpha 0.1 - a
~10-episode memory over a heavy-tailed length distribution, which
swung G (and the cap) by 20-30% between steps. Completions now
accumulate between step boundaries and fold in as one interval mean
(alpha 0.3 per step), so a step's worth of episodes averages out
before the estimate moves. Simulated max step-to-step cap swing drops
to ~5% under a Pareto length mix at 150 completions/step.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: interpolate eval and train cost mixes
The eval census was a hard 0 -> 1 -> 0 gate: while any eval work was
in flight, G priced the whole pool from the eval mix, then snapped
back to the train mix at the drain boundary. Now the census decrements
per completed eval episode and G blends the two mixes on the eval
share of the cap, min(1, remaining / n_max): a full jump only when the
epoch actually fills the pool, and a continuous glide back to the
train price as it drains.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: 512-episode bias-corrected cost EWMA
Replace the step-folded estimator with a per-episode EWMA at
alpha = 1/512: the smoothing horizon is fixed in episodes, so it no
longer scales with batch size or step cadence. Bias-corrected
(decayed sum over decayed weight) so early estimates equal the plain
mean instead of anchoring on the first episode - an eval env at 120
episodes per epoch prices correctly from its first epoch. Simulated
step-to-step cap swing stays ~5% under a Pareto length mix.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: default frozen_steps to 1
At the step-1 boundary the cost EWMA has only seen the episodes that
completed fastest — the short ones — so the first re-evaluation
overshoots the cap (observed 256 -> 2139 with a 2K estimate on SWE
episodes that average far longer). Holding the cap for one step lets
the first full batch complete before the estimate is trusted.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: make frozen_steps=1 actually freeze the first boundary
on_step incremented completed_steps before checking frozen, so the
step-1 boundary compared 1 < frozen_steps and values 0 and 1 behaved
identically (observed: frozen_steps=1 still re-evaluated at step 1
off a 1.8K biased cost estimate). Snapshot frozen before the
increment: k now freezes the first k boundaries.
Also exempt the one-shot bootstrap derivation from the freeze — it
sets the starting value the freeze pins, so blocking it under the
new default of 1 would strand no-initial_inflight runs at the floor.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: simplify frozen_steps docstring
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: cap hendrycks e2e configs at 1024 inflight
The duty-cycle gap (episodes spend ~35% of wall time outside an open
engine request) lets kappa compound the cap well past useful engine
load on the sanity envs - ceiling it at 1024.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: allow SignSGD with full optimizer offload
SignSGD is stateless, so it runs through the wrapper's generic
per-chunk CPU step path (plain GradientOffloadManager + _step_chunk)
with no AdamW-specific machinery. Halves per-rank CPU optimizer
state vs AdamW full offload by dropping both moment buffers.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: queue-overload HARD cut for agentic rollouts
Agentic rollouts overload inference by queueing, not preempting:
vLLM's admission control parks excess load in the waiting queue, so
the preemption HARD gate never fires (observed: 213 capacity-queued
vs 192 running, prefix-cache hit rate 0.06, num_preemptions_total 0,
and a 5x step-time blowup while the controller raised the cap on a
SOFT signal).
Classify HARD when capacity-queued requests exceed QUEUE_RATIO of
running for QUEUE_PERSISTENCE_POLLS consecutive polls (persistence
filters natural turn-completion bursts), and cut to just under what
the engines actually serve (0.9x running) instead of backing off
from inflated inflight. The metrics collector now ships running and
the by-reason waiting breakdown in EngineLoadSample; engines without
the breakdown fall back to total waiting.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: shed youngest episodes on overload cut
A cut only blocks new admissions, so the over-admitted episodes keep
thrashing the prefix cache until they finish at degraded throughput
(observed: 690 -> 320 cut took 20+ min to drain, with 10-18 min steps
and a 0.05 hit rate the whole way). Bind an on_overload hook from the
controller to the dispatcher: cut() reports the episode excess and
the dispatcher drops that many in-flight train episodes, youngest
groups first (least inference spend), reusing the off-policy
drop_group path so the sink finalizes partial groups.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: slew-limit cap growth to 1.25x per re-evaluation
A raise floods in fresh episodes whose fast finishers drag the cost
EWMA down, inviting a bigger raise (observed 256 -> 567 -> 690 while
the estimate fell 7.7K -> 6.3K). Limiting upward moves to 1.25x per
step turns the spiral into a ramp the queue-overload cut interrupts
after one increment. Cuts stay unlimited.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: cuts never raise the cap; unwire shed-youngest for now
The queue cut targets 0.9x running, but running can be inflated by
work the dispatcher no longer tracks — observed live: 'Increased
concurrency 231 -> 256 (queue overload)'. Clamp cut targets to the
current cap.
Unwire on_overload -> shed_youngest: cancelling the orchestrator task
does not abort the env-side rollout (3195 starts vs 2616 done after
shedding 489 episodes, none stopped Cancelled), so shedding leaves
zombies hitting inference while the freed permits admit new episodes
on top — total load rises. Keep the dispatcher method; rewire once
rollout abort propagates to the env server.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: floor the cost estimate with measured request cost
Completion-based estimates only see finished episodes; after a cap
raise the fast short episodes finish first and drag the estimate
down, inviting a bigger raise (observed 7.7K -> 6.3K -> 5.5K while
the cap spiraled 256 -> 690). The live request stream has no such
bias: every turn resends its episode's full context, so in-flight
episodes are counted at their current size the whole time they run,
and single-turn workloads are covered by the generation term.
The collector derives mean prompt+generation tokens per request from
the vLLM histogram deltas each poll; the controller folds them into
a request-weighted decayed mean and takes the max of it and the
completion mix. Drop frozen_steps in the e2e config to test that the
cold-start freeze is no longer needed.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: size-bias the measured request cost
A plain per-request mean under-prices the in-flight pool: small
contexts take turns far more often than the large residents that
actually fill KV (observed: request mean 6.7K while resident cost
was 13.2K per running request, so the feedforward equilibrium sat
2x above true capacity and every ramp ended in a queue cut).
Weigh each request by its own token mass instead — E[X^2]/E[X]
from the prompt-histogram bucket deltas, midpoint-approximated,
+Inf bucket bounded by the engine max context. On the live GLM
distribution this reads 16.8K vs the 13.2K resident measure:
slightly conservative, and kappa growth learns back the slack.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: clock kappa growth on polls, not step boundaries
Step-clocked growth adapts at wildly different speeds across
workloads (steps range seconds to tens of minutes), and its binding
check sampled inflight at the boundary instant — exactly when
episode completions burst — so kappa stalled while the cap was
binding all step long (observed: kappa stuck at 1.13 for three clear
steps with the engine at 0.99 prefix hit). Grow kappa a small factor
per clear-and-binding poll instead; SOFT vetoes become per-poll for
free.
Also fall back to the observed request cost (not the pessimistic
engine max context) for envs without completions — the max-context
fallback made kappa's continuity init read a user-set start as an
intentional ~4x over-commit whenever step 1 completed before any
episode did.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: early growth brake and kappa ceiling memory
Thrash onset is a cliff, not a slope: prefix hit went 0.97 -> 0.06
within two minutes of kappa growing past the workload's true
over-commit (job 748: clean climb to kappa 1.51 / cap 380, then a
queue cut to 197). Two additions:
- Veto kappa growth on any poll with capacity-queued requests.
Unlike generic waiting, capacity-queuing means KV blocks are full
right now; the 2-poll waiting filter let growth feed the cap
through the cliff between bursts.
- Remember the ceiling: an overload cut pins growth at 0.9x the
kappa that overloaded, so the ceiling is rediscovered by a wobble
instead of a fresh thrash episode every cycle (without memory the
sawtooth re-pays the full discovery cost forever). A slow relief
(~+2% per 10 min) lets a genuinely lightened workload re-probe.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: update adaptive concurrency for the measured-cost controller
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: clock the controller on pipeline turnovers, not steps
Step duration varies from seconds to tens of minutes across
workloads, so anything step-clocked adapts at workload-dependent
speed. Re-evaluate the cap every poll (with a 2% deadband against
estimate noise) and bound raises by the pipeline turnover: each
completion advances the clock by 1/inflight, so one turnover means
the in-flight pool has been replaced once regardless of scale — 100
completions at concurrency 10 buy 10x the raise budget of 100 at
concurrency 1000, matching how much less biased their estimates
are. Raises compound at most 1.25x per turnover; cuts and decreases
are never limited.
The turnover slew subsumes frozen_steps (the cap can never outrun
the pipeline's demonstrated stability), so the config field is
removed. Kappa now initializes on the first poll with real cost
data instead of the first step boundary; on_step shrinks to eval
bookkeeping and backoff reset.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: SOFT signal on high KV usage
Thrash onset is a cliff at full KV, and the queue-based signals only
fire once it is already happening. Live-request KV usage rises ahead
of it (measured ~0.53 at healthy load, ~1.0 at thrash), so treat any
decode engine above 0.8 as SOFT: growth stops while there is still
headroom to absorb in-flight context growth, cuts stay queue-driven.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: lower KV-usage SOFT threshold to 0.7
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: shed on overload now that rollout abort propagates
Bump verifiers to feat/rollout-abort (26eafc07): cancelling the
orchestrator-side task now aborts the env-side rollout, so
Dispatcher.shed_youngest no longer creates zombies — rewire it to
the controller's on_overload hook. An overload cut now sheds the
youngest in-flight episodes immediately instead of draining the
excess for tens of minutes at thrashed throughput.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: proportional kv-headroom trim
Cap moves alone cannot relieve pressure from episodes maturing in
place — they only block admissions. Observed on the kv-soft gate:
growth froze at usage 0.7 and the cap eased 371 -> 326, but the
admitted pool's contexts grew ~15%/step under it and crossed the
thrash cliff (prefix hit 0.05) within minutes anyway.
With rollout abort now propagating, trim the pool itself: above
KV_USAGE_TARGET (0.85), set the cap to inflight * target / usage and
shed the excess youngest episodes, on a short cooldown so each trim
propagates before the next is sized. Holds usage at the target
continuously instead of riding to the cliff and paying a full
queue-overload cut; the queue gate remains the backstop.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: kv-headroom trims re-derive kappa
A trim that lowers only the cap gets undone by the feedforward: the
slew allowance regrows per completion and the cap creeps back into
the trim zone, shedding ~8-16 young episodes every cooldown
(observed: 4 trims in 2.5 min). Re-derive kappa from the trimmed cap
the way cuts do; with growth already vetoed above KV_USAGE_SOFT this
yields a grow (<0.7) / hold (0.7-0.85) / trim (>0.85) usage band
instead of a shed loop.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: address PR review comments
- Treat the admitted unit as a black box in the controller docstring;
docstring-style constants describing meaning only.
- Constants: ESTIMATE_ALPHA 1/1024, BACKOFF_FACTOR 0.8, KAPPA_MAX 8,
QUEUE_PERSISTENCE_POLLS 6 (react within a minute).
- Rename RolloutDispatcher -> Dispatcher, inflight_permits ->
current_inflight, shed_youngest -> cancel_inflight.
- Drop the out-of-vocab detokenization patch.
- Configs: initial_inflight = batch_size with a 2x max_inflight
ceiling across the example and nightly configs.
- Docs: trim the adaptive-concurrency intro.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: weight the cost mix by live in-flight counts
The sampling-ratio weighting predicted the standing mix and needed
two corrections bolted on: duration weighting (admission mix vs
standing mix) and the eval-census interpolation (predicting the mix
through eval epochs). The dispatcher knows the standing mix exactly
— weight the per-env estimates by its live per-(kind, env) in-flight
counts instead. Train and eval need no separate treatment (eval
units enter the mix as they are admitted), so the census, its
interpolation, and the duration weighting are deleted; the
configured ratios remain only as the empty-pool fallback.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: hysteresis for kv-headroom trims
Trimming exactly to the trigger guarantees an immediate re-trigger
under monotonic pool growth (observed: trims every cooldown, 16-40
units each, while survivors grew ~15%/step). Trigger at 0.85 but
resize to 0.75, so each trim buys growth headroom before the next.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: lower kv-usage thresholds (soft 0.6, trigger 0.8, target 0.7)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat!: reduce the controller to measured AIMD
The feedforward kappa*C/G no longer controlled anything: the
turnover slew was the binding constraint on every ramp (raw targets
sat 2-5x above the cap), the usage trim overrides it on the way down
(it was added precisely because G-tracking is too slow for in-place
pool growth), and the gates own overload. Everything that computed G
existed to produce a number the other mechanisms clipped.
Replace it with AIMD on measured KV pressure, turnover-clocked:
grow the cap x1.25 per pipeline turnover while engines are clear,
usage < 0.6 and the cap binds; trim pool+cap to usage 0.7 above 0.8;
cut on preemptions (0.8x inflight) or persistent capacity-queueing
(0.9x running), cancel the excess, drain-latch, escalate to 0.5x if
overload survives a drain. The starting cap is user-set or
C / max_model_len — the only cost-like quantity left, read once.
Deleted: kappa and its ceiling/relief, both cost estimators (per-env
completion EWMAs and the size-biased request census with its
histogram parsing), cost_estimate/mix_cost, the inflight-mix hook,
the re-evaluation deadband, slew_allowance as a separate mechanism
(the growth law absorbs it), and on_step. ~480 -> ~280 lines with
no model of unit cost anywhere.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: align tests, configs and docs with the AIMD controller
Fix the hendrycks configs (high-eval start needs its ceiling at the
starting cap; freeze-era header comments), rewrite the adaptive
concurrency docs for the measured-AIMD design, and revert the
SignSGD full-offload allowance — SignSGD crashes with an async CUDA
illegal memory access on this stack, so the guard stays until that
is fixed.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: min_inflight escape hatch
A hard floor on the adaptive cap (None auto-sets to 1). Setting
min_inflight = max_inflight pins the cap, recovering fixed-concurrency
behavior; not recommended in practice.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: address second review round
- Rename Dispatcher param max_inflight_episodes -> initial_max_inflight
and document its relation to max_inflight_ceiling (starting value of
the dynamic cap vs the configured hard maximum bounding out_q).
- Drop the dead n <= 0 guard in cancel_inflight (resize_down only
calls it with a positive excess).
- Public hook attributes on the controller (set_limit, get_inflight,
on_overload); single float-returning clamp; unconditional
apply_limit on growth (it no-ops when unchanged).
- Gauges: capacity_tokens -> capacity; drop queue_overload_polls.
- Remove the stale detokenization NOTE in the vLLM server.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: revamp the concurrency e2e config matrix
Two workloads x four scenarios, all descriptively named and capped at
max_inflight = 1024:
- hendrycks (single node, 4 train + 4 infer GPUs, mirrors the
hendrycks-sanity example; replaces the 2-GPU variants):
initial-low (16, grow from near zero), initial-none (derived
start), initial-high (1024, cut from overload), evals (256 + AIME
avg@4 every 10 steps). gpu_memory_utilization = 0.2 shrinks the KV
budget artificially so the controller operates below the ceiling
instead of at huge concurrency.
- glm-air (2 nodes, replaces glm-air-swe): the same three initial
scenarios plus evals (256 + 10-turn-capped SWE-Bench Verified
every 10 steps). Each config uses its own sandbox label so
parallel runs cannot delete each other's sandboxes.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: slurm blocks for the hendrycks e2e configs
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: pin flash_attention_2 for the hendrycks e2e configs
R1-Distill-Qwen-1.5B resolves to the HF model impl, and attn=auto
resolves to flash_attention_3, which requires the custom impl — the
trainer refused to start.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: drop the initial-low e2e variants
The low start exercises the same turnover ramp as the derived start,
just from a lower anchor — the none variant covers it. Final matrix:
{none, high, evals} x {hendrycks, glm-air}.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: 4 API server processes for the hendrycks e2e configs
The initial-high run (1024 concurrent clients) killed vLLM's single
ApiServer process; the frontend needs to scale with the client
count.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: pin the hendrycks KV budget via num_gpu_blocks_override
Even at low gpu_memory_utilization the 1.5B model gets ~12.8M KV
tokens, putting the usage band above the max_inflight ceiling — the
derived start clamped to the ceiling and the none scenario
degenerated into the high one. Pin ~2.1M tokens so the derived start
(~256) and the band (~350-400) sit well below the ceiling.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: min_inflight is the only cap floor
Drop the implicit group_size floor: group episodes are admitted
individually, so a group trickles through in waves below its size —
nothing requires a group to fit in flight at once. min_inflight
(default 1) is now the single lower bound, and recovery from tiny
caps is fast in turnover terms (at inflight 1 every completion is a
full turnover).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: start hendrycks-initial-high at 700
Two attempts at a 1024 start died to vLLM ApiServer processes being
signal-killed under the client connection storm (with 1 and with 4
frontend processes). 700 is still decisively over the pinned ~350-400
usage band, so the overload-cut scenario is intact without stressing
the frontend.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: prime VM sandboxes for hendrycks-initial-high
The ApiServer deaths under the 1024 start were host thrash from 1024
subprocess-runtime episodes spawning local processes, not the client
connections. Run the high scenario on prime VM sandboxes and restore
the 1024 start.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: hold the drain latch until the engines settle
Cuts cancel episodes, so dispatcher inflight drops below the cap
almost immediately while the engines still churn through their own
backlog — preemption deltas from that stale churn re-triggered
escalated cuts every poll (observed cascade: 1024 -> 8, one halving
per 5s). Release the drain only when inflight is under the cap AND
the poll shows no preemptions or queue overload.
Also fix the hendrycks KV pin for 64-token blocks (32768 blocks gave
8.4M tokens, not 2.1M — the derived start clamped to the ceiling and
triggered the storm in the first place).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: say episodes, not units, in console logs
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Refund admission burst budget on episode completion
The burst window capped gross admissions at max(group_size, cap/10)
per 5s. For fast single-turn episodes the completion rate exceeds that
admission rate, so inflight equilibrates at admission_rate x duration
(observed: 24 at cap 58) and the cap never binds, locking out growth.
Completions now refund the window budget: the window meters net pool
growth, so ramps stay smoothed while steady-state replacement is
never throttled.
Also switch the hendrycks e2e configs to prime VM sandboxes and fix
num_gpu_blocks_override for 16-token blocks (FA2 backend), restoring
the intended 2.1M-token KV budget.
* Fix four controller/dispatcher bugs from review
- Growth was dead below cap 10: the permit is released before the
completion hook fires, so the binding check read inflight <= cap - 1
and 0.9 * cap was unsatisfiable for small caps. Count the completing
episode back in.
- Queue cuts targeted 0.9 x engine running requests but the cap counts
episodes; agentic episodes idle between turns, so this over-cut by
the duty cycle. Cut in pool units like the preemption path.
- Escalation latched forever: it only reset on a CLEAR-poll drain
release, but steady state post-cut sits in the SOFT usage band, so
every later cut halved. Reset via a grace window of polls after the
drain instead.
- Overload sheds count only live cancellations toward the excess;
never-dispatched markers free no permits and made sheds undershoot.
Also expire the growth gate 15s after the poll that set it: if the
metrics path stalls (the very state runaway growth creates), growth
freezes instead of compounding blind. And skip growth on error-marker
completions (tokens <= 0) — they consumed no engine capacity, and a
slow-failing error storm otherwise grows the cap against idle engines.
* Drop cluster-specific node exclude from e2e configs
* Budget hendrycks e2e concurrency for the sandbox gateway
VM-sandbox runtimes hold one sandbox per in-flight episode, so peak
concurrency across concurrent runs must stay under ~1k or the gateway
429s. Cap the three runs at 400/300/256 and shrink the KV budget to
786K tokens (12288 blocks x 16-token FA2 blocks x 4 engines) so the
optimal band (~175) sits below every ceiling and each run still
exercises its intended path (cut down / grow up / absorb eval waves).
* Read KV capacity from kv_cache_size_tokens
The num_gpu_blocks label in vllm:cache_config_info does not reflect
num_gpu_blocks_override, so the derived capacity was 4x too high on
runs that pin the block count. kv_cache_size_tokens reports the
actual budget; keep the block product as a fallback for engines that
do not expose it.
* Adapt GLM-4.5-Air SWE example to a 4-node FP8 recipe
1 trainer node (sign-SGD full CPU offload, cp=4) + 3 FP8 inference
replicas with online quantization. The concurrency section is removed:
the controller runs on defaults, deriving its start from the measured
KV budget.
* Remove concurrency debug configs
The hendrycks/glm-air matrix configs were development scaffolding for
the e2e verification runs; the results live in the PR description.
The GLM-4.5-Air SWE example is the maintained recipe.
* Use fp8_per_block online quantization in the GLM-Air example
Matches the research-prod GLM recipe: the bf16 checkpoint is loaded
and quantized online, since NCCL weight broadcasts push bf16 trainer
weights into the engines on every update.
* Guard None raw tokens in logprobs detokenization
tokenizer.convert_ids_to_tokens returns None for ids outside the
tokenizer vocabulary. Models with embedding padding past the tokenizer
(e.g. R1-Distill-Qwen) can sample such ids; _restore_leading_spaces
then iterates None and the TypeError kills the AsyncLLM output loop
and the whole API server with it. Observed as recurring random
'ApiServer died with exit code None' crashes under sustained sampling.
* Revert "Guard None raw tokens in logprobs detokenization"
This reverts commit 0c1b5d4992eb99f1ea4c0a7c6a999daeca5cc95c.
* Order concurrency fields initial, min, max
* Route GLM-Air FP8 through DeepGEMM kernels
Without a block-wise FP8 GEMM backend the engine falls back to
torch._scaled_mm, which asserts on block-scale shapes during engine
init. Enable DeepGEMM and disable the FlashInfer block-scale GEMM,
matching the research-prod GLM recipe.
* Serve GLM-Air FP8 checkpoint with kernel-format weight transfer
The online fp8_per_block path crashes for glm4_moe on this stack (the
block-scale GEMM falls back to torch._scaled_mm and asserts), so the
example serves the native FP8 checkpoint instead. Weight updates then
need trainer-side quantization: implement convert_layer_to_vllm_kernel
for glm4_moe (standard GQA qkv fusion; the MoE handling mirrors
GLM-MoE-DSA, whose MoE layout is identical) and enable
quantize_in_weight_transfer.
The kernel copy path has no TP shard handling, so the engines run
EP experts + DP attention (data_parallel_size=8), matching the GLM
prod deployment shape. Trainer keeps the bf16 checkpoint; the
orchestrator addresses the served FP8 name.
* Disable MoE DP chunking for the FP8 GLM-Air engines
The cutlass FP8 MoE DP-chunking path under-sizes its permute scratch
for large profile/prefill batches (moe_permute asserts
n_token <= max_num_tokens), killing the engine at init. Same
mitigation as the GLM prod recipe.
* Serve GLM-Air FP8 via per-tensor online quantization
Both block-scale FP8 attempts crash for glm4_moe on this stack (the
blockscale GEMM asserts at engine init; the cutlass MoE DP-chunk
scratch under-sizes). Per-tensor online quant uses the standard
scaled_mm and fused-MoE FP8 kernels, keeps plain TP=8, and re-uses the
same quantize-on-load path for weight broadcasts.
* fix: stop metrics collector before finalizing monitors
The collector's poll loop outlived monitors.finalize() on clean exit,
so its next wandb.log hit the finished run and surfaced as a spurious
'Inference metrics poll failed: UsageError' warning. Stop it first;
the teardown's second stop() is a no-op.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Bump verifiers to a3188c06
Rollout-abort cleanup hardening: shielded sandbox create, strongly
referenced cancel tasks, and cancel drain on client close.
* Fix four review findings; drop unused glm4_moe kernel converter
- Overload signals read decode engines only: in P/D deployments a
prefill queue or prefill preemption is normal flow and must not
trigger cuts.
- Batch/group divisibility is checked after the batch-size default
lands, so a config setting only group_size cannot pass with a
non-divisible default.
- A group's age for youngest-first shedding is its oldest member's
start; taking the newest made long-running groups look young and
cancelled the most sunk cost.
- Admission-window refunds apply only to natural completions: refunding
cancelled episodes handed a mass shed's worth of burst budget to the
refill while the overload was still draining.
The glm4_moe kernel-format converter served the abandoned
quantize_in_weight_transfer experiment; the example now uses plain
online quantization, which needs no trainer-side support.
* Explain adaptive concurrency by intuition in the docs
Drop thresholds, constants, and the config listing from the docs
section; describe grow/trim/cut as probe-and-back-off against the
engines. Bump verifiers for the cancel-path race fixes.
* Drop unrelated changes from the branch
The detokenizer patch ships separately in #3304; the pydantic-config
pointer bump was an accidental sweep of local submodule state.
* Address review: config defaults and small cleanups
- max_inflight defaults to 1024: an unbounded default made the growth
path's failure modes existential; None still removes the ceiling.
- min_inflight defaults to 1 instead of None-meaning-1, simplifying
the bounds validator.
- Signal is a Literal instead of an Enum.
- Reword the admission-smoothing comment.
* Raise max_inflight in examples exceeding the new default ceiling
* a few minor tweaks
* Bump verifiers to 6bcedc76 (merge main into rollout-abort)
* Update lockfile for verifiers 0.3.1.dev57
* chore: cap CI RL runs at 512 inflight
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: dedupe concurrency block in wiki-search CI config
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Bump verifiers to main (rollout-abort merged)
feat/rollout-abort landed as PrimeIntellect-ai/verifiers#2396; the
submodule now tracks verifiers main.
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
checkout v5 -> v7, setup-uv v7 -> v10.0.1, upload-artifact v4/v5 -> v7,
download-artifact v6 -> v8, github-script v8 -> v9. All self-hosted
runners are on 2.336.0, above the 2.327.1 floor the node24-based
majors require. setup-uv stopped publishing floating major tags with
v8, so it now pins the exact release.
Also sync the CI ruff pin (0.13.0 -> 0.15.14) with uv.lock so CI
lints with the same ruff version as local runs.
Allow optim.type = "sign_sgd" with model.full_offload. SignSGD is
stateless, so full offload needs only 8 B/param of host RAM (FP32
master + FP32 accumulated gradient) instead of AdamW's 16 B/param
(master + two FP32 moments + accumulated gradient).
- Add a native multi-tensor CPU sign_sgd_step kernel mirroring the
AdamW span kernel (BF16/FP32 grads, BF16/FP32 compute-param
write-out, at::parallel_for). The kernel drops the gradient scale:
sign(scale * g) == sign(g) for scale > 0.
- Generalize FullCPUOffloadOptimizer's native plumbing (bounded
gradient manager, chunk stepping, sync fallback, checkpoint load,
scheduler _opt_called marker) over a combined native-optimizer flag.
- Skip CPU optimizer state materialization for SignSGD everywhere:
checkpoints carry only the FP32 masters.
- Relax the trainer/SFT config validators and setup_optimizer guard to
accept sign_sgd; update docs and the start-run skill.
- Add a bit-exact parity test against the python SignSGD reference
(BF16/FP32 grads, wd 0 and >0, zero grads, scalar-tail sizes).
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* simplify artifact ignore rules to outputs/
Since the run-dir unification, every run artifact (logs, checkpoints,
weights, rollouts, evals, broadcasts, wandb, torchrun logs, sbatch
scripts) lives under output_dir, which defaults to outputs/. The
recursive **/<dir> patterns and their negations are redundant.
The **/wandb pattern also kept the wandb monitor source package out
of the docker build context (see #3292). Ignoring only outputs/
removes that class of bug.
Delete scripts/clean.sh: it mirrored the same recursive list, is
referenced nowhere, and rm -rf outputs/ replaces it.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* ignore .codex directory
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
`**/wandb` (added in #3279) targets W&B's local run-output dirs, but it
also matches src/prime_rl/monitors/wandb/, which became a package in
#3275. `COPY src/ /app/src/` reads the filtered context, so the package
never reached the image and every entrypoint died at import:
File "/app/src/prime_rl/monitors/__init__.py", line 19
from prime_rl.monitors.wandb import WandbMonitor
ModuleNotFoundError: No module named 'prime_rl.monitors.wandb'
monitors/__init__.py is imported unconditionally, so this took down the
orchestrator and trainer whether or not W&B was configured.
.gitignore already carries this exemption; mirror it here. The pair sits
above the bytecode patterns so those still strip __pycache__/*.pyc back
out of the re-included directory - last matching line wins.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
PR #3256 renamed SFT deployment.num_gpus to num_train_gpus, but the
full-offload resume fixture from #3234 merged in parallel and kept the
old flag, failing config validation on main.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* Add online evals to the SFT entrypoint
The sft launcher now composes an inference server, one env server per
eval source, and a new evaluator process next to the trainer. The
handoff is the filesystem, not NCCL: the trainer writes HF weight
checkpoints at every step an eval env is due, and the evaluator points
the inference server at each stable checkpoint (/update_weights from
disk) before running the due evals, sequentially per checkpoint.
The evaluator reuses the orchestrator's eval components (EvalEnvs,
EvalSource, EvalSink, EvalRollouts) and logs eval/{env}/... metrics and
rollout traces exactly like RL, into the same W&B run as the trainer
(shared mode; the new WANDB_SHARED_PRIMARY env var selects the primary
process, defaulting to the previous orchestrator behavior).
Online evals are single-node only for now.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Harden the SFT online-eval launcher and evaluator
Address review findings on the initial implementation:
- Skip an eval step (with an error log) when the weight reload fails
instead of killing the training run; drain the queued examples so they
cannot leak into a later epoch with the wrong eval_step.
- Clean stale weights/step_N dirs at launch (all on fresh start, past
the resume step on resume) so the evaluator never replays checkpoints
from an abandoned run.
- Reconcile deployment.num_infer_gpus with inference.vllm TP/DP,
mirroring RLConfig.auto_setup_deployment.
- Install a SIGTERM handler in sft_local (it now spawns GPU-holding
children beyond torchrun), avoid busy-spinning while the evaluator
drains final evals, and probe GPUs only when partitioning them so
plain SFT keeps its old no-NVML behavior.
- Make the evaluator the shared-W&B primary - it exits last, so it must
own run finalization.
- Warn when ckpt.keep_last/keep_interval can clean a checkpoint before
the evaluator consumes it, and document the retention interplay and
the standalone admin_base_url requirement.
- Fix pre-existing is_last_step off-by-one: resuming from a checkpoint
at step >= max_steps no longer trains forever.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Add multi-node SFT online evals with decoupled SLURM jobs
With [eval] set on a multi_node deployment, the sft launcher submits
two independent SLURM jobs: the trainer (deployment.num_nodes) and an
eval job (deployment.num_infer_nodes) running the inference pool (one
vLLM engine per DP rank behind a router), one env server per eval
source, and the evaluator. The only coupling is weight checkpoints on
the shared filesystem, so the trainer job releases its allocation when
training finishes while the eval job keeps draining checkpoints and
exits after evaluating the final one. Any train x inference node
layout works.
The eval job is submitted first and the trainer depends on it having
started (--dependency=after), so the trainer joins the shared W&B run
the evaluator creates instead of timing out while the eval job pends;
a failed second submission cancels the first. On a clean evaluator
exit, node 0 publishes a job-scoped sentinel that releases the other
inference nodes, since a zero exit never trips --kill-on-bad-exit.
Also hardens the eval handoff paths: weight-checkpoint cleaning always
keeps the newest checkpoint (keep_interval-only cleaning used to
delete a non-aligned final checkpoint right after saving it, hanging
the evaluator), the evaluator skips abandoned STABLE-less checkpoints
instead of wedging on them, clean_stale_weights honors
NEVER_CLEAN_OUTPUT_DIR, and validate_output_dir sees ckpt.output_dir.
Verified e2e: Qwen3-30B-A3B-Thinking-2507 SFT on one node with AIME25
online evals on another; both jobs completed with exit code 0.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Make the trainer own the shared W&B run
Split run creation from run finalization in shared W&B mode: the
WANDB_SHARED_PRIMARY process creates the run and the new
WANDB_SHARED_FINISHER process (defaulting to the primary) writes its
final state. The SFT trainer is now the primary in both the single-node
and decoupled multi-node online-eval deployments, so the run exists
even if the eval side never starts; the evaluator, which outlives the
trainer, stays the finisher so the run isn't marked finished while
final evals still log.
The decoupled submission order flips accordingly: the trainer job goes
first and the eval job depends on it having started, keeping the
joiner's bounded wandb-init retry window covering only startup lag.
Verified on a 2-node run: trainer inits with primary=True/
finisher=False, evaluator joins with primary=False/finisher=True, both
jobs exit 0, and the shared run ends in state "finished" with trainer
and eval metrics.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Add an SFT-flavored W&B overview view
The auto-provisioned overview saved view previously only had an RL
shape; SFT runs fell back to rollout-metric train panels that SFT
never logs. build_sections gains an "sft" flavor: the train section is
the loss and perplexity curves (train + validation) plus epoch
progress, the eval sections stay the rollout-based ones shared with
RL, and stability/performance show the metrics the SFT trainer
actually emits. The SFT trainer and the evaluator select the flavor
through setup_monitor.
The trainer now also logs loss/perplexity and val/perplexity
(exp of the mean loss, clamped to avoid overflow on divergence).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* address online-eval review findings
- Warn when an eval-due weight checkpoint was deleted by ckpt.keep_last
/ keep_interval cleaning before the evaluator could evaluate it, and
advance past it instead of silently gapping the eval curve.
- Restore RL's enable_lora guard in the api_server_count DP fill, which
the copy from RLConfig.auto_setup_deployment had dropped.
- Also clean stale rollout trace dirs at launch (clean_future_steps),
not just weight checkpoints: the append-only trace files would
otherwise mix two policies' rollouts under one step after a crash and
resume.
- Parse sbatch job ids with --parsable; the human-readable output
varies on multi-cluster setups and broke the dependency/cancel paths.
- Mention the evaluator log in the monitor-run skill.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* address pr review comments
- Rename SFT deployment.num_gpus to num_train_gpus, matching the rl
launcher's num_train_gpus / num_infer_gpus API. Breaking: the old key
fails as unknown.
- Flatten EvaluatorConfig.model to model_name and document how it is
used: the served-model name on every eval request, auto-filled from
model.name by the sft launcher; weights swap in place under one name,
so per-step results are told apart by eval/{env}/policy_version.
- Trim the online-evals docs detail paragraph and fold the W&B overview
mention into one clause covering RL and SFT runs.
- Drop the [eval] explainer comment from the reverse-text example.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* address self-review comments
- Rename multi-node deployment.num_nodes to num_train_nodes (matching
the rl launcher). Breaking: the old key fails as unknown.
- Rename EvaluatorConfig.model_name to model and raise the default
max_inflight_episodes to 128.
- Hardcode the evaluator's weights dir to <output_dir>/weights (it was
always launcher-derived); with [eval] set, ckpt.output_dir is now
rejected instead of silently pointing the evaluator elsewhere.
- Drop the online-evals bullet from the start-run skill.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* bring back the evaluator weights_dir field
Weight checkpoints follow ckpt.output_dir when checkpoints are
redirected to another volume, so a hardcoded <output_dir>/weights
cannot cover that deployment. The launcher fills weights_dir from the
checkpoint base again, and ckpt.output_dir is supported with [eval].
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix eval with redirected checkpoint dir and final-eval retrigger
The ckpt.output_dir rejection was meant to be removed when weights_dir
came back but the edit never landed (the format hook had reshaped the
raise and the scripted match failed silently) - remove it for real; the
evaluator watches <ckpt.output_dir>/weights via the launcher-filled
weights_dir.
Also force-fire every env when retrigger_on_resume resumes at the final
checkpoint (a crashed final eval was never retried when max_steps is
not interval-aligned), and trim a verbose comment.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* alias num_eval_gpus/num_eval_nodes for the infer deployment knobs
num_infer_gpus / num_infer_nodes stay canonical (rl-launcher parity)
and accept num_eval_gpus / num_eval_nodes via AliasChoices. The
deployment pre-validator collapses the alias onto the canonical key:
pydantic rejects a dict carrying both spellings, which is exactly the
common layering (canonical in the TOML, alias on the CLI).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix alias precedence via pydantic-config bump
The deployment pre-validator collapsed the num_eval_* aliases onto the
canonical keys with the alias always winning, which inverted
CLI-over-file precedence when the file used the alias and the CLI the
canonical spelling. The real gap was in pydantic-config:
_normalize_alias_keys never recursed into discriminated-union variants.
Bump the submodule to the fix (pydantic-config#23) and drop the
collapse - alias spellings now merge onto one key with normal
precedence in every layering.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* bump pydantic-config to v0.4.3 (merged alias fix)
Re-point the submodule from the PR-branch commit to the squash-merged
main commit, released as prime-pydantic-config 0.4.3.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* floor prime-pydantic-config at 0.4.3
The online-eval deployment aliases rely on 0.4.3's union-aware alias
normalization.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
The prime monitor's TrainRun hardcodes the production public API
(https://api.primeintellect.ai/api/v1/rft). Managed launches need to point
it at the platform's internal ingestion path instead, and non-prod
environments currently post metrics to prod (where their per-run tokens
401) — silently, since uploads are fire-and-forget.
$PRIME_API_BASE is taken verbatim when set (the platform already injects
it on managed orchestrator pods as {SERVICE_URL}/api/internal/rft);
otherwise the default is unchanged. Resolved once in __init__ and stored,
since the atexit _mark_failed hook must agree with the client.
Picks up 8 commits (91a267616..02cc940d8), notably the prime-sandboxes
0.2.37 floor (VM idle timeout + vm-opt-out validation) and the
intercepted-response replay gate (vf#2368). Adds a bounded harbor
cutoff mirroring deps/verifiers: verifiers pins harbor==0.21.0, which
the rolling exclude-newer window rejects.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* perf(docker): cache the dependency sync independently of source edits
A one-line change under src/ currently busts the uv sync layer (source is
COPY'd before the sync) and re-downloads ~5 GB of wheels + recompiles
mamba-ssm. Split the sync in two:
- a manifests stage collects every pyproject.toml + uv.lock; the deps layer
syncs against that skeleton with --no-install-workspace and the four path
editables skipped, so it only busts when project metadata changes
- the source layer copies the real trees and reruns the original sync, which
now only installs the first-party editables
Also fix the uv cache mount (UV_CACHE_DIR is /usr/local/share/uv/cache but
the mount targeted /app/.cache/uv, so it never cached anything) and add a
.dockerignore so local builds stop shipping .venv trees into the context
(packages/prime-rl-configs/.venv is 439 MB and was baked into local images
via COPY packages/). .git stays in the context: the pretend-version script
resolves submodule versions from .git/modules.
Validated: uv sync --locked --dry-run with the deps-layer flags against the
skeleton tree (linux, uv 0.11.9) resolves all 551 packages and plans 422
installs with no first-party editables and no lockfile errors.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* perf(ci): registry-backed BuildKit cache for image builds
setup-buildx-action creates a fresh builder per job, so every CI build is
cold even when nothing changed. Cache to ghcr buildcache-<arch> tags with
mode=max so the builder-stage dependency layer is reusable across runs;
blobs already present in GHCR are not re-uploaded.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* perf(docker): stop shipping .git in the cache and re-pushing immutable layers
Profiling the first warm build (run 31912669079) showed three avoidable
costs on top of the structural cache round-trip:
- the manifests stage COPY'd the full context into /ctx, so the ~735 MB
.git landed in a layer that mode=max exports to the registry cache on
every build; exclude it (it holds no pyprojects)
- the runtime stage copied the volatile /app remainder before the big
immutable venv trees, so every code change re-executed and re-compressed
the nvidia/torch/vllm/flash_attn copies; move the volatile layer last
- the "Remove unnecessary packages" step costs ~70s on the amd64 runner;
only run it when the disk is actually tight
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore(docker): condense build comments
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* feat: chunked per-layer optimizer step with stream-overlapped CPU offload
The CPUOffloadOptimizer now performs the optimizer.step() per-transformer-layer
instead of all-at-once. Each layer's optimizer states are moved to GPU, the step
runs for that layer only, and states are moved back to CPU before the next layer.
This bounds peak GPU optimizer-state memory to ~one layer's worth (plus one
prefetched layer for overlap) instead of the full model's, preventing OOM when
weight + grad + all_opt_states exceeds available VRAM.
H2D and D2H transfers are pipelined on dedicated CUDA streams so the next layer's
states are prefetched while the current layer computes, and the previous layer's
states are evicted while the next layer computes.
Pinned-memory D2H is fixed to pre-allocate the pinned destination and async-copy
into it, avoiding a race where pin_memory() reads a tensor whose async copy hasn't
completed.
Muon's per-group step counter is synced after all chunks complete, since the
param_groups are temporarily swapped during chunked stepping.
* feat: add on/off config for chunked offload and stream overlap
Add and config options
to independently toggle per-layer chunking and stream-overlapped H2D/D2H.
When stream is disabled, the chunked step uses a simple sequential
move→step→move loop with no CUDA stream logic, making the code path clearer
and easier to debug.
* chore: default optim_cpu_offload_chunked and optim_cpu_offload_stream to false
* fix: address bugbot review issues
1. Async D2H checkpoint corruption (HIGH): Add torch.cuda.synchronize()
after _move_states('cpu') in state_dict() and in ckpt.py's
AppState.state_dict() to ensure async pinned D2H copies complete
before CPU tensors are read.
2. Incomplete stream dependency chain (MEDIUM): Replace wait_stream-only
finish in _step_chunked_streamed with torch.cuda.synchronize() to
block CPU. Add h2d_stream.wait_stream(d2h_stream) before prefetching
chunk i+1 to prevent racing with the previous chunk's D2H into the
same pinned CPU buffers.
3. First step OOM (HIGH): The init step now uses the same chunked path
instead of a full optimizer.step() that materializes all states on
GPU at once. States are created per-chunk and immediately evicted.
4. Defaults disagree (MEDIUM): Align setup_optimizer defaults for
cpu_offload_chunked and cpu_offload_stream with config defaults
(both False).
Also add torch.cuda.synchronize() at the end of _step_chunked (no-stream
path) to ensure async D2H completes before returning.
* fix: always sync step counters in _sync_step_counters
Remove the 'if step in group' guard so _sync_step_counters always writes
group['step'] = orig_step + 1. This handles optimizers that lazily create
the step key on per-chunk copies (e.g. Muon) where the original groups
might not have had the key set yet.
* fix: evaluate closure only once per chunked step (not per chunk)
Pass closure only to the first chunk's optimizer.step() and None to the
rest, so loss/grad recomputation happens once per training step rather than
once per layer.
* refactor: clean up CPUOffloadOptimizer for readability
- Remove redundant section separators and verbose docstrings
- Inline _build_chunk_param_groups into _step_chunk
- Inline _chunk_param_ids into _move_chunk_states
- Simplify _move_states to iterate values() directly
- Shorten comments to be targeted, not narrative
* fix: record_stream on D2H to prevent caching allocator race, align stream default
1. HIGH - Streamed D2H memory race: call record_stream on GPU tensors before
replacing them during async D2H copy, so the caching allocator doesn't reuse
their storage while the copy is still in flight on d2h_stream. Guard with
is_cuda since some optimizer state tensors (e.g. AdamW step counter) live on CPU.
2. LOW - Stream default disagrees: change CPUOffloadOptimizer.__init__ stream
default from True to False to match config and setup_optimizer defaults.
* fix: accurate docs for stream-mode GPU memory bound
Update docs, config docstring, and class docstring to say 'about one
layer's worth (two with stream overlap)' instead of 'a single layer's
worth', since stream overlap keeps up to ~3 layers resident on GPU
during the prefetch/D2H/compute overlap window.
* fix: restore param_groups in finally block to handle optimizer.step() errors
If optimizer.step() raises inside _step_chunk, the try/finally ensures
param_groups are restored to the original full set, preventing subsequent
steps from only updating a single chunk's parameters.
* revert: remove try/finally from _step_chunk per AGENTS.md philosophy
Let errors propagate — if optimizer.step() raises, training crashes
anyway and there's no point restoring param_groups.
* refactor: always use stream overlap when chunked, remove stream toggle
The stream path already caps GPU residency at 2 layers (prefetch waits for
eviction via h2d_stream.wait_stream(d2h_stream)), so the non-stream sequential
path and the stream config toggle are unnecessary. Removes optim_cpu_offload_stream
config field, the _step_chunked method, and the stream parameter from
CPUOffloadOptimizer and setup_optimizer.
* refactor: always chunk+stream when CPU offloading, remove chunked toggle
Removes optim_cpu_offload_chunked config field entirely. When
optim_cpu_offload is enabled, the optimizer step is always performed
per-transformer-layer with stream-overlapped H2D/D2H transfers (max 2
layers on GPU). This eliminates the non-chunked code path, the separate
_step_chunked_streamed method, and one config flag.
For large models (where offloading matters) chunked+stream is faster
than all-at-once because transfers overlap with compute. For small
models the absolute overhead is negligible.
* refactor: make stream param required in _move_chunk_states
Stream is always passed now — removes the None fallback, default_stream()
context manager, and all stream is not None guards.
* test: add parity tests for CPUOffloadOptimizer vs plain AdamW
Tests that per-layer chunked+stream stepping produces identical parameters
and optimizer states as all-at-once stepping, plus a state_dict round-trip
test.
* fix: remove redundant isinstance branch in test helper
* docs: remove chunked offload paragraph from scaling docs per review
* feat: make chunked optimizer offload opt-in per S1ro1 review
Adds optim_cpu_offload_chunked config flag (default False). When disabled,
CPUOffloadOptimizer uses the simple all-at-once path (move all states to
GPU, step, move back). When enabled, uses per-layer chunked stepping with
stream-overlapped H2D/D2H (max 2 layers on GPU).
Also adds torch.cuda.synchronize() to load_state_dict for async D2H safety.
* fix: reuse CUDA streams across steps to prevent memory leak
Creating new torch.cuda.Stream() on every step() caused the caching
allocator to hold onto memory via record_stream references on dead
streams. Streams are now created once in __init__ and reused.
* feat: stream FSDP gradients through CPU offload
* feat: fuse CPU offload with public FSDP hooks
* refactor: expose optimizer offload config
* refactor: always stream pinned offload transfers
* refactor: name CPU optimizer execution explicitly
* refactor: clarify CPU step config name
* chore: clarify offload runtime logging
* feat: run gradient-offloaded optimizer steps on CPU
* refactor: name fused optimizer offload full
* feat: restore gradient-only optimizer offload
* fix: keep GLM-5.2 weight broadcast within GPU memory at 4-node scale
With 4 train nodes the resident FP32 master shards are ~87 GiB/rank and the
per-layer broadcast (full expert gather + fp8 conversion) peaked ~49 GiB above
that, OOMing the post-step broadcast once training transients filled the cache.
- empty_cache() before broadcast so cached training pools are reusable
- drop consumed expert tensors eagerly and quantize into preallocated stacks
instead of list+torch.stack copies (~49 -> ~31 GiB transient per layer)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: preallocate pinned gradient buffers before the first collective
The post-accumulate offload hook runs inside FSDP foreach_reduce on the
autograd thread; lazily cudaHostAlloc'ing the staging buffer there stalls
against the device while peer ranks' NCCL kernels spin waiting for this
rank's next collective — a distributed deadlock (faulthandler-confirmed:
autograd thread at optim.py empty_like(pin_memory=True) under
_fsdp_collectives foreach_reduce; deterministic at 78 layers, independent of
seq len, act-offload, hook design, or staging pageability). Pinning is only
safe before any collective exists, so allocate accumulator + staging for
every param at manager init.
Cost: the staging set is now always allocated (~equal to the accumulator
set) even for single-micro-batch steps; a config gate can refine this later.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: propagate dist timeout to device-mesh sub process groups
init_process_group applies the configured timeout only to the default PG;
device-mesh sub-groups fall back to torch's 10-minute module default, so
dist_timeout_seconds never reached the PGs doing the real work. Long
single-rank host phases (e.g. init-time pinned-buffer preallocation skew
across nodes) then trip peer watchdogs at 600s.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* perf: slab-allocate pinned gradient offload buffers
~800 per-param cudaHostAllocs (~1.4 TiB/node) took 10-20 minutes at init with
large node-to-node skew; one pinned slab per dtype for accumulators and one
for staging pins the same bytes in a handful of driver calls. Per-param
buffers become 256-byte-aligned views into the slabs.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: overlap CPU optimizer with backward
* perf: fuse CPU gradient scaling into AdamW
* perf: add native CPU AdamW kernel
* perf: halve full-offload PCIe traffic
* harden native optimizer offload pipeline
* document optimizer offload handover
* chore(bench): add offload baseline configs and measured GLM-5 RAM feasibility
Config pack for the handover baseline matrix: Qwen3-30B-A3B four-variant
offload comparison and the GLM-5 one-node proxy, all validated with --dry-run.
Meta-device parameter counts show the 22-layer proxy (190.8B params, 2.78 TiB
CPU state) exceeds a 2 TiB node, and the four-node full-model job needs
2.71 TiB/node; handover.md updated with the measured feasibility numbers.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(bench): 8-GPU deployment and CPU thread budget for offload baselines
The SFT entrypoint defaults deployment.num_gpus to 1, and the launcher
defaults OMP_NUM_THREADS to 1, which serializes the CPU optimizer
(measured 15.7 s/step vs 6.5 s at 28 threads/rank on 8xH200).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: offload pipeline timing diagnostics and opt-in NUMA binding
Per-step wall-time counters for the bounded pipeline (D2H event wait, ring
slot waits, BF16-to-FP32 materialization, native Adam, post-backward drain),
logged at debug level. Profiling on 8xH200 showed the pipeline floor is
host-DRAM-bandwidth-bound: the Adam kernel takes ~3.4s/step against a ~0.4s
compute estimate and does not scale with OMP threads.
optim_cpu_offload.numa_bind pins each rank's CPUs to its GPU's NUMA node
before state allocation so first-touch keeps slabs and OMP threads local
(measured 6.39s -> 6.13s per step at seq 8K on Qwen3-30B-A3B).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: one-node 8xH200 offload baseline results in handover
Four-variant matrix and 2K-64K sweep for Qwen3-30B-A3B with bit-identical
losses throughout. The short-sequence pipeline floor is DRAM-bandwidth-bound;
with numa_bind, native full offload beats no-offload from 16K per-GPU sequence
upward while roughly halving peak HBM. Benchmark configs enable numa_bind.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: skip weight pre-download for random-init debug runs
pre_download_model fetched the full weight snapshot even when
debug.random_init never reads it — for GLM-5 that is ~1.4 TB pulled into
the shared HF cache. Random-init runs now fetch only config and tokenizer
files. GLM-5 proxy config drops to 20 layers to fit measured H200 node RAM.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: GLM-5 20-layer proxy results on one 8xH200 node
16K/32K/64K native full offload with numa_bind: ~18s/step CPU Adam for
21.4B params/rank, exposed drain shrinking from 17.4s at 16K to 6.9s at
64K. 20 layers is the RAM/HBM ceiling for a 2.95 TiB H200 node.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: GLM-5 8-layer no-offload vs full-offload comparison
10 layers OOMs an H200 with resident optimizer state at 16K; at 8 layers
full offload trails at 16K (38% TPS retained), wins outright at 32K (117%),
and is the only variant that runs at 64K. Halves peak HBM throughout.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: state full offload's BF16 gradient-rounding semantics
Gradients reduce in FP32 but FSDP2 materializes them in the sharded
parameter's dtype — BF16 for the full-offload compute model — so full
offload rounds each reduced gradient to BF16 once before the FP32 CPU
update. An FP32-transport option is structurally blocked (FSDP2 has no
grad-dtype override), so document the semantics in the config, the
training skill, and the handover, and point to state-only offload as
the gradient-bit-faithful mode.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: correct handover baselines — repo default is state offload
The 'no offload' rows measured the default state-offload path;
add the true GPU-resident baseline table (requires
--model.optim-cpu-offload None) and relabel accordingly.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat!: CPU optimizer offload is full offload only, disabled by default
optim_cpu_offload previously defaulted to state-only offload and carried
three modes (state-only, gradients, full) with separate streaming paths.
State-only streamed ~60 GiB/rank of optimizer state over PCIe every step
and cost ~45% of throughput at seq 8K against a GPU-resident baseline.
Now the option means one thing: full offload (FP32 masters, moments, and
gradients on CPU, optimizer overlapped with backward), enabled by setting
model.optim_cpu_offload, disabled by default so the baseline keeps
optimizer state on GPU. numa_bind defaults to true. Removes the GPU-
chunked step, state-move machinery, and per-mode branching; example
configs that enabled the old default drop the line.
Validated: config suite, dry-runs, full-native smoke with DCP checkpoint
at step 2 and resume (exact loss parity), torch-backend smoke, no-offload
default smoke.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Make CPU optim multithreading by overwriting num-thread but without oversubscring intra-op parallelsism threads
* chore(bench): drop the OMP_NUM_THREADS workaround superseded by auto thread budget
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: trim optimizer offload artifacts
* docs: trim optimizer offload scaling guide
* refactor trainer optimizer modules
* restore state-only optimizer offload
* revert unrelated GLM-5 changes
* fix conflicts with current main
* refactor: make full offload setup explicit
* refactor: rename full optimizer offload config
* fix: refresh offload masters on model-only resume
* refactor: simplify optimizer offload interface
* fix: return checkpoint state to CPU
* fix: adapt offload resume test to run dirs
* fix: preserve mixed dtypes in full offload
* fix: restrict full offload to AdamW
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Mario Sieg <mario.sieg.64@gmail.com>
* feat!: refactor monitors into prime_rl.monitors
Replace the Monitor class hierarchy (ABC with five abstract methods,
NoOpMonitor, MultiMonitor) with a flat prime_rl.monitors module: only
log() is abstract, monitors register once per process, and module-level
functions fan out to them without ever raising. Construction is now
side-effect free - run registration and file handles move to init(),
and a monitor whose init() fails is disabled instead of crashing.
Sample logging becomes episode logging: PrimeMonitor regroups rollouts
into vf.Episodes and uploads one platform sample per episode, sharing
verifiers' build_samples with eval --push so training and eval samples
land identically (native episode in info.native_wrapper). The W&B
sample/eval tables and distribution logging are removed, and
PrimeMonitor now runs on the shared BackgroundAsync helper.
Config surface is grouped under [monitors]: monitors.wandb,
monitors.file, and orchestrator-only monitors.prime, replacing the
wandb / file_monitor / prime_monitor siblings and WandbWithExtrasConfig.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: wandb subpackage, finalize instead of final summary
Split the W&B monitor into monitors/wandb/{base,overview} for
readability. Rename save_final_summary to finalize - its real job is
finalizing the platform run (with the last metrics as summary); the
local final_summary.json files had no consumers and are no longer
written. Drop close() from the interface and registry: nothing called
it, and PrimeMonitor's shutdown (mark unfinalized runs failed, stop the
background loop) lives in __del__.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: track monitors/wandb package, drop prime monitor tests
The repo-wide **/wandb gitignore (W&B run dirs) silently swallowed the
new src/prime_rl/monitors/wandb/__init__.py, so CI imported the
subpackage as an empty namespace package. Negate the pattern for the
source directory.
The prime monitor unit tests mostly re-asserted the parquet column
mapping; drop them per the conservative-tests policy.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor!: loop-native monitor uploads, drop usage reporter
Rewrite PrimeMonitor's async plumbing: uploads are fire-and-forget
tasks on the orchestrator's event loop with short-lived httpx clients
(connect retries inside the transport), replacing the hand-rolled
background thread + event loop + fork handling and the per-request
retry/backoff helpers. Construction now takes only the monitor config;
runtime context moves to init(), whose kwargs each monitor names
itself.
Remove the usage reporter entirely (per-step training-token billing
posts, PI_USAGE_* env-gated) and with it background_async.py, which
has no users left.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: gate wandb-coupled paths on the registered monitor
The inference-metrics collector and the dispatcher's wandb flag were
gated on the config block, but they log to the global W&B session,
which only exists when WandbMonitor's init succeeded. A failed init
now disables the monitor instead of crashing, so the config gate let
the collector reach wandb.define_metric before any wandb.init. Gate
on monitors.get(WandbMonitor) instead.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix!: crash on monitor init failure
A configured monitor that cannot initialize (bad credentials, dead
platform) previously logged a warning and disabled itself, so the run
silently continued without its metrics. Let the exception propagate -
if monitoring was requested, losing it should stop the run.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* perf: offload episode serialization, atexit for failed-run marking
Move the parquet/JSON encode of episodes off the orchestrator's event
loop into the upload task via asyncio.to_thread - build_samples dumps
every episode's full model, and running it inline stalled dispatch on
every logging step (the one heavy call in finalize_train_batch not
already off-loop).
Replace PrimeMonitor's __del__ with an atexit hook for marking
unfinalized runs failed: __del__ can fire during interpreter teardown,
where httpx can no longer create a client, so the status PUT silently
died in 'Exception ignored' noise.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: sentinel-free non-finite JSON sanitizer
Test each child before recursing into it instead of signalling drops
through the recursive return value, which needed a module-global
sentinel object and dense sentinel-comparing comprehensions.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: type the JSON sanitizer, recurse via inner function
Rename drop_non_finite_json_values to sanitize with a recursive Json
type alias; the path-threading recursion moves into an inner walk()
so the public signature carries no recursion plumbing.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: untype the sanitizer
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: sanitize returns dropped paths
Return (sanitized, dropped_paths) instead of filling a caller-supplied
list - call sites were allocating an empty list just to read it back.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: gather monitor configs into configs.monitors
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat!: slim the monitor config surface
- FileMonitorConfig.filename -> path (relative to output_dir, absolute wins)
- drop EpisodeLogConfig: episodes upload every step, all of them - the
serialization is off-loop and the platform is the sample store, so
interval/sampling knobs bought nothing but config surface
- hardcode the platform base URL and API key env var, resolve the
frontend URL from the Prime CLI config; PrimeMonitorConfig shrinks to
name + team_id, with run_name renamed to name to match wandb (still
auto-set from run.name / the W&B run name)
- WandbConfig -> WandbMonitorConfig; the rl entrypoint's Shared*
monitor configs move back next to RLConfig in rl.py
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: rename _SAMPLE_SCHEMA to SAMPLE_SCHEMA
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: move sanitize into utils
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: inline the prime monitor sanitize wrapper
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: drop prime monitor state flags and last-metrics replay
Register the atexit mark-failed hook only when this process created
the platform run and unregister it in finalize - the hook's presence
replaces the _registered/_finalized flags. Drop _last_metrics: every
step's metrics were already posted, so replaying the last dict as the
finalize summary was redundant; /finalize now gets an empty summary.
Use the BASE_URL constant directly instead of mirroring it on self.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: extract TrainRun owning the platform HTTP lifecycle
PrimeMonitor delegates create/log/finalize/status/sample-upload to a
small synchronous TrainRun that owns one persistent httpx client
(transport-level connect retries, connection reuse). The monitor keeps
episode grouping, parquet building, sanitization, and the
fire-and-forget task plumbing - each TrainRun call runs in a worker
thread via asyncio.to_thread. TrainRun is the seam the train SDK can
subsume later, the way wandb.Run backs the W&B monitor.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: TrainRun.create takes explicit fields
The OrchestratorConfig-to-payload mapping moves to the monitor;
TrainRun's surface is plain API fields, keeping it prime-rl-agnostic.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: rename init run_config param to config
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: type prime monitor init config as BaseConfig
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: polymorphic log, episodes through monitors, defaults on
monitors.log and Monitor.log accept either a metrics dict or a list of
vf.Episode with cohort coordinates (train/eval x all/effective); the
base class dispatches to log_metrics / log_episodes. The orchestrator's
trace-file writes move into FileMonitor (get_trace_path and
save_rollouts are inlined there), so all episode sinks share one entry
point: the streamed all cohort, the trained effective batch, and eval
epochs each fan out once, off-loop. group_episodes moves to
orchestrator utils and episode grouping happens at the source -
PrimeMonitor takes episodes and filters to the trained cohort.
The wandb and file monitors are now on by default (--no-monitors.wandb
/ --no-monitors.file to opt out), the registry list is MONITORS, and
wandb/base.py is renamed to wandb/monitor.py.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor!: PRL_RUN_ID is the run identity, drop monitor run ids
Rollout provenance is stamped with the launcher's $PRL_RUN_ID (or a
local uuid for standalone runs) instead of the monitor identity, so
Monitor.run_id and the monitors.run_id() helper go away. The RUN_ID
env handshake is removed with them: PrimeMonitor always creates a
platform run, and its id stays internal to TrainRun.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: singular episode overload, wandb log_episodes stub
log accepts a bare vf.Episode alongside dicts and episode lists (the
base dispatch wraps it); log_episodes is abstract now, so WandbMonitor
gets an explicit no-op.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: fully async monitors, TrainRun mirrors wandb exit behavior
The whole Monitor surface is async now (init/log/log_metrics/
log_episodes/finalize); the orchestrator awaits the fan-out directly
and the sync trainers wrap calls in asyncio.run. FileMonitor offloads
record serialization via asyncio.to_thread (awaited, so appends to one
trace file never interleave); PrimeMonitor's fire-and-forget goes back
to plain create_task since nothing submits cross-thread anymore.
TrainRun now owns its exit behavior the way wandb.Run does: create arms
an atexit hook that marks the run failed, finalize marks it completed
and disarms the hook. The orchestrator finalizes monitors only on a
clean exit, so a crashed run reports failed on the platform just like
it does on W&B.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: keep the platform mark-failed atexit path synchronous
asyncio.run at atexit dies with 'cannot schedule new futures after
interpreter shutdown': async httpx resolves DNS via run_in_executor,
and concurrent.futures marks itself shut down via
threading._register_atexit, which runs before module atexit hooks.
The failure PUT uses sync httpx; everything else on TrainRun stays
async.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: make wandb monitor init async
The async conversion missed WandbMonitor.init's multi-line signature,
so the registry awaited None and setup crashed.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: finish the W&B run explicitly, align monitor logs
In (experimental) shared mode the SDK's atexit finish does not land the
run state, so even clean runs decayed to 'crashed' - WandbMonitor's
finalize now calls wandb.finish(exit_code=0) off-loop. Every monitor
logs one info line at init and finalize; per-step uploads only warn on
failure.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: task cache and parquet builder out of the monitor
TrainRun owns the fire-and-forget submit machinery; the episode
parquet builder becomes a module helper below both classes.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: propagate monitor disables, shared prime block, drain on finalize
With the monitor sub-configs defaulting to enabled, the rl entrypoint's
--no-monitors.wandb / --no-monitors.file were silently ignored - the
CLI disable (the string 'None') now propagates to both sub-configs like
the enable does. [monitors.prime] joins the shared block, propagated to
the orchestrator only (no trainer platform integration yet), and
PrimeMonitorConfig loses team_id (the Prime CLI team applies).
TrainRun.finalize now drains in-flight uploads first, so the final
step's metrics and episodes land before the run is marked completed.
Also prunes FileMonitor's unreachable pre-init guard.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: fix stale TrainRun docstring
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: sample platform episode uploads to 10% capped at 128
All episodes every step overwhelms the platform's ingestion; sample
min(10% of the step's episodes, 128) instead. Lift once the prime
traces SDK is integrated.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: take the first episodes instead of sampling
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: note monitor run names inherit run.name
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: wandb off by default, migrate integration test flags
The integration tests still passed the old --wandb.* flags, failing
config validation; and wandb-on-by-default would crash credential-less
environments at init. W&B is opt-in again (the file monitor stays on
by default); the tests use --monitors.wandb.*.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: sample platform episode uploads randomly
The effective batch is ordered by group finalization, so a prefix
over-represents early-finishing envs on multi-env runs.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: restore the RUN_ID attach handshake
Managed launches pre-create the platform run and inject its id via
$RUN_ID; attaching instead of registering prevents duplicate runs.
RUN_ID stays a dedicated backend channel - PRL_RUN_ID can't signal
attachment because the rl launcher always mints one locally. Attached
runs skip the atexit failure marking (the backend owns that); finalize
still marks them completed on clean exit.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: restore pre-refactor episode upload defaults
Every 10th step, unsampled - what log_extras defaulted to on main.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: episode upload cadence
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
First release from the router's rebase onto upstream vllm-project/router
(PrimeIntellect-ai/router#51): upstream v0.1.15+18 with the re-ported
fork features (P/D routed-experts merge validated byte-identical against
a single-engine baseline, model-aware routing, phantom-load fixes,
validation 500->400 rewrite incl. vLLM 0.26 wording, per-run usage
metrics, JWT auth).
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Remove the --bench flag from all entrypoints (RLConfig, SFTConfig,
TrainerConfig, OrchestratorConfig) along with BenchConfig, the
auto_setup_bench validators, the bench branches in the trainers and
orchestrator, and the rich benchmark table / JSON export helpers.
The benchmark CI keeps working: run_single_benchmark.py now runs a
normal short training (--max-steps, fake data) with the file monitor
enabled and aggregates throughput / MFU / step time / peak memory
from the run's metrics.jsonl. The output JSON schema is unchanged, so
the regression test, the aggregation script, and the stored baselines
are untouched.
Monitors no longer retain metric history: keep_full_history and the
history list are gone. The file and prime monitors keep only the last
metrics dict for the final summary, and the trainers track the peak
memory maximum locally for the end-of-run log.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* never overwrite logs across launch attempts
Every launch of a run — fresh or resumed — writes its logs to its own
logs/attempt_<n>/ directory, with logs/latest symlinked to the current
attempt. Previously a resume reopened the same log files with mode "w"
and destroyed the previous attempt's logs. The SLURM templates compute
the attempt in bash the same way; readers (tmux.sh, log hints, tests)
go through logs/latest. Logs are the only clobbered artifact: the
step-keyed dirs are pruned deliberately on resume, and configs/ holds
the current attempt's resolved configs by design.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* route all template log paths through the attempt dir
The shared _launch_rank/_launch_router snippets and the multi-node SFT
template still wrote under $OUTPUT_DIR/logs/, so per-rank vLLM tees
targeted a directory that no longer exists and SFT resumes kept
overwriting trainer logs. Every sbatch template now computes the same
attempt block and writes only through $LOG_DIR; verified by rendering
all four entrypoint scripts and grepping for stale paths.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* Add named run directories under output_dir
output_dir now groups related runs: each run writes all its artifacts
(logs, configs, checkpoints, weights, rollouts) to output_dir/run.name.
The new run.name field defaults to a random UUID, so every launch gets
a fresh run directory and concurrent runs no longer need a manually
unique output_dir. Set an explicit name to make the run directory
predictable, which is also what resume points back at.
Launching into a run directory that already contains run artifacts now
fails unless resuming or clean_output_dir is set; clean_output_dir
wipes only the run directory, not its output_dir siblings.
The rl entrypoint derives trainer/orchestrator output_dir from the run
directory, so sub-processes and standalone sub-configs are unchanged.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Add run id and propagate run identity everywhere
RunConfig gains an id (locally generated for now; the Prime SDK will
issue it once runs are registered there). The run identity now flows
to every surface that names or groups a run's artifacts:
- traces: the orchestrator stamps RunInfo with name + id (id prefers
the monitor identity, falling back to run.id); requires the
verifiers RunInfo.name companion (submodule bump)
- W&B: unset wandb.name inherits run.name; the shared W&B run id
defaults to run.id
- Prime platform: unset prime_monitor.run_name inherits run.name
- sandboxes: env-server TOMLs carry sandbox_labels=[run.name], applied
process-wide via verifiers' set_base_sandbox_labels, so every Prime
sandbox of a run is labeled with the run name; runtime-config labels
extend the base labels
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Bump verifiers for RunInfo ruff fix and rename
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Keep the run id out of config; inject identity
The run id is not user config: the rl entrypoint mints it (TODO: fetch
it from the Prime SDK once runs are registered there) and injects it —
with the resolved run name — as a launcher-managed [run] block into the
orchestrator and every env-server TOML. The orchestrator stamps it on
traces (monitor identity still preferred); env servers label every
Prime sandbox with the run name via set_base_sandbox_labels, now
imported from verifiers.v1.runtimes (the root export is gone).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Auto-generate readable run names; add run.dir
run.name now auto-generates as <train-envs>--<model>--<short-id> (SFT:
<dataset>--<model>--<short-id>, env names joined with +) instead of a
bare UUID, so default run directories and inherited W&B/platform names
read like the experiment they are while the short-id suffix keeps
launches collision-free. run.dir names the run directory and defaults
to run.name, for when the directory must differ from the display name.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Rename clean_output_dir to clean; lowercase names
The flag cleans the run directory, not the output directory, and now
matches the eval CLI's --clean. No alias for the old spelling; the
NEVER_CLEAN_OUTPUT_DIR escape hatch becomes NEVER_CLEAN. Auto-generated
run names are lowercased.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Use /tmp as the grouping dir in the dry-run example
* Split output_dir and run name in the GLM-5.2 example
* Carry the run id as PRL_RUN_ID, never in config
The run id is a runtime concept: the launcher sets $PRL_RUN_ID (once,
respecting an externally provided value — the future Prime SDK hookup
point) and every spawned process inherits it; the SLURM templates
export it job-wide the same way as the shared W&B id, which now
defaults to it. Configs carry only the run name. $PRL_RUN_ID is the
general vehicle for transporting runtime info between processes, so it
joins the protected env vars.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Retire WANDB_SHARED_RUN_ID in favor of PRL_RUN_ID
The shared W&B run id was always just the run identity under another
name; the monitor now reads $PRL_RUN_ID directly. WANDB_SHARED_MODE
(the toggle) and WANDB_SHARED_LABEL (the per-process label) carry
distinct information and stay.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Make resume a top-level config block
resume: ResumeConfig | None replaces ckpt.resume_step on the rl and
sft entrypoints: None (default) does not resume, a bare --resume (or
empty [resume] block) resumes from the latest checkpoint, and
--resume.step N resumes from step N — mirroring the eval CLI's
--resume. The block maps onto the sub-configs' internal resume_step
(-1 = latest), so trainer and orchestrator are unchanged. Also guard
--clean against a run.dir resolving outside output_dir (matches the
eval fix) and validate it in validate_run_dir.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Unify resume consumers on ResumeConfig
The sub-config checkpoint configs (trainer, orchestrator, SFT) carry
the same resume block as the entrypoints instead of an internal
resume_step with a -1 sentinel: step None means latest everywhere, and
the checkpoint managers and resume resolution read resume.step.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Bump verifiers for name-only eval resume
* Add resume.dir to fork an external checkpoint
--resume.dir points at another run's checkpoint step directory (e.g.
other/checkpoints/step_50) and forks it into this run: the step comes
from the directory name, the trainer and orchestrator load their state
from that path, and everything else (saving, weights, rollouts) stays
in this run's own directory. Mutually exclusive with resume.step.
Also bump verifiers: eval --resume is now a plain flag on the resolved
config, prl-style.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Bump verifiers for eval resume cleanup
* Bump verifiers for unified validate resume
* Bump verifiers for eval resume config hash check
* Carry the run name as PRL_RUN_NAME, drop RunInfoConfig
The whole run identity is now runtime-only: the launcher exports
$PRL_RUN_NAME next to $PRL_RUN_ID and every spawned process reads it
for trace stamping and sandbox labels; the multi-node template exports
it job-wide. Sub-configs carry no run info at all — components run
standalone simply have no run identity.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Bump verifiers for schema-level resume hash
* Bump verifiers for configs/ layout and digest check
* Move resume to the top level on trainer and orchestrator
resume sits next to ckpt on every config, not inside it — the same
shape at every level. The checkpoint managers take it as a parameter
instead of reading it off CheckpointConfig.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Write resolved configs as JSON
Machine-written configs (rl/sft/trainer/orchestrator/inference/env
server) become JSON: it keeps nulls, so explicit None overrides
round-trip exactly and to_toml_dict's "None"-string convention is
deleted. Hand-written configs stay TOML; the format split marks
intent vs resolved artifact. Aligns with verifiers' configs/<cli>.json
(submodule bumped).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Bump verifiers for gepa guard ordering
* Bump verifiers for logs/ run-dir layout
* Pin verifiers to main with #2358 merged
* Always construct checkpoint managers; fix skip-scheduler horizon
The checkpoint manager now always exists: resume decides whether it
loads, ckpt whether it saves. A standalone trainer or orchestrator
launched with --resume and no [ckpt] previously skipped the load path
silently; now it resumes (and saves no new checkpoints). The
resume-requires-ckpt validators are gone accordingly.
SFT's skip_scheduler sized the rebuilt schedule from resume.step,
which is unset for a bare --resume and for --resume.dir; it now uses
the resolved checkpoint step, so warmup/decay run on the remaining
steps.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Skip the HF weight load on any resume
loading_from_ckpt_later still required config.ckpt, so a resume
without [ckpt] loaded HuggingFace weights before the checkpoint
overwrote them — failing offline or OOMing on large models. The
resolved checkpoint step alone decides: resuming initializes an empty
model and loads from the checkpoint.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* Bump verifiers for prime VM runtime default
vf#2356 makes the prime VM runtime the default agent runtime:
PrimeConfig now defaults vm=true, AgentConfig.runtime defaults to
PrimeConfig(), and prime auth is checked when a prime runtime or
tunnel is instantiated. Also picks up vf#2357 (stable task keys).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Drop vm = true from example configs
Prime sandboxes default to vm=true after the verifiers bump, so the
explicit flag in the example runtime sections is redundant.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Drop redundant prime runtime keys from example configs
The default agent runtime is now the prime VM sandbox, so
type = "prime" (pydantic_config falls back to the default union
variant when the tag is omitted) is redundant. The
idle_timeout = "None" lines go too: PrimeRuntime always drops
idle_minutes for VM sandboxes, so the key is a no-op there.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Poll-time check in InferenceMetricsCollector: when aggregate waiting
requests exceed 20% of max_inflight_episodes, inference is saturated
and rollout latency (and thus training throughput) suffers. Emit a
throttled warning (at most once per 60s) advising to wait if the
spike is intermittent and to lower max_inflight_episodes if it
persists.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* feat: dynamic pass-through vLLM inference metrics to wandb
Replace the hand-curated inference metric allowlist with a dynamic
pass-through collector: every vllm:* Prometheus family is logged,
per-engine under inference/engine/{id}/ and cross-engine aggregations
(min/max/mean/median/sum) under inference/{agg|prefill|decode}/.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: drop InferenceMetricsConfig, keep collect_inference_metrics flag
Hardcode poll interval, aggregations, and per-engine logging in the
collector; config surface is unchanged from main (collect_inference_metrics
+ inference_metrics_roles).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Add inference health section to the overview view
Seven panels, each pairing the fleet aggregate (mean/sum) with the
cross-engine tail that flags a single sick engine - max for pressure
(KV usage, preemptions, waiting, prompt-token recompute), min for
health (prefix hit rate, generation throughput). A saturated engine
thrashing its KV cache hides inside fleet means; the tails surface it.
Also compute the prefix-cache hit-rate ratio per engine (not only
pooled over the fleet) so the min/max aggregations exist for it.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Flatten metric keys to inference/{scope}/{metric}/{stat}
Drop the vllm: family prefix (the collector only admits vllm:* families,
so it carries no information), flatten per-engine series from
inference/engine/{id}/... to inference/{id}/..., and move scope-level
quantiles (:p50 -> /p50) and the pooled ratio (-> /pooled) into the
stat segment so every key reads inference/{scope}/{metric}/{stat}.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Add min series to KV usage and waiting panels
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
get_zero_gradient_ratio launched a device-scalar transfer and a
count_nonzero kernel per parameter plus two all-reduces and a sync every
step, serializing the post-backward path on models with many tensors: on
Qwen3-30B-A3B (8xH200, seq 8K) it cost 1.4 s of a 4.6 s step. The metric
also read 1.0 on every validation run, so it was likely not measuring
what it intended on FSDP2 DTensor gradients. Removes the metric, its
trainer call sites, and the Prometheus gauge.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* Bump verifiers for prime-sandboxes 0.2.36
prime-sandboxes 0.2.36 gives each live ACP process its own HTTP
transport (prime#831), fixing the h2 stream-cap deadlock that made
rlm rollouts fail with 'process stdin RPC failed (deadline_exceeded)'
above ~100 concurrency.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Repoint verifiers submodule to merged main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
k8s/README.md links to /prime-rl/kubernetes, /prime-rl/deployment and
/prime-rl/troubleshooting. All three return 404: those pages are not in
docs/ and have no entry in docs/mint.json. Drop the two Kubernetes links
and the troubleshooting bullet — the README's own sections are the chart
documentation — and retarget the deployment bullet at /prime-rl/scaling,
which is where the multi-node and SLURM content lives now.
The uninstall snippets also name the wrong PVC. templates/pvc.yaml names
it {{ .Release.Name }}-shared-data, so after the documented
`helm install my-exp`, `kubectl delete pvc prime-rl-shared-data` fails
NotFound and reads as if the data is already gone.
Closes#3054
pre_download_model fetched the full weight snapshot even when
debug.random_init never reads the weights — for large models that pulls
hundreds of GB (GLM-5: ~1.4 TB) into the shared HF cache before a fake-data
debug run. Random-init runs now fetch only config and tokenizer files.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Revert bb23623d6 (#3236). The tighter 0.1 trust region masks the few
high-leverage decision tokens once their probability moves >0.1 across
off-policy staleness, slowing LoRA convergence (reverse-text LoRA CI
smoke: 0.5-0.6 reward @ step 15 vs 0.8 with 0.2).
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
The orchestrator wrote its resolved config to <output_dir>/control/orch.toml,
a relict of the deprecated multi-tenant setup. The launcher already persists
resolved configs under the output directory.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* feat!: drop v0 env compat from the orchestrator and configs
The verifiers legacy bridge is removed upstream, so every v0 code path
goes:
- configs: drop the [legacy] block, is_legacy, the legacy/env conflict
validators, and resolve_legacy_env_kwargs from EnvConfig and
EnvServerConfig; env-server TOMLs no longer carry a legacy section
- env-server entrypoint: always serve a taskset (no bridge fork)
- orchestrator: Env always loads its taskset client-side (info()/
run_group()/task_idx addressing removed); requires_group_scoring and
its consumers (variable permit costs, group-scored partial drops,
run_group fan-out) are gone — one permit is one episode everywhere
- TrainSource rows always carry the task; the pending-draw head-of-line
hold and per-env permit costs are gone (next_example takes no args)
- GroupState.task is required; task_idx derives from task.data.idx
- env taskset ids drop the -v1 suffix across configs, examples, docs,
skills, and the workspace members (companion renames in verifiers and
research-environments)
- port the qwen3-vl features-payload test from the v0 RendererClient to
renderers.client.generate (the path the v1 train client drives)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers + research-environments to the rename branches and relock
deps/verifiers -> feat/legacy-package (6a8de86), deps/research-environments
-> feat/drop-v1-suffix (27ed790). Re-pin to the merged commits before landing.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers pin to the reworked branch head
v0 code stays in place upstream; the branch now only removes the v1
legacy bridge and the -v1 suffixes (lock unchanged).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers pin (v1 CLI simplifications)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers pin (main merged, python floors)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers pin (v1 drops on-demand Hub installs)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers pin (v0 tree under verifiers.legacy, aliased)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers pin (ID plain str, public alias names)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers pin (ruff fixes)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers pin (static-tooling fixes)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers pin (gepa schema id fix)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers pin (docs/legacy move)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers pin (hub installs restored in v1)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: pin verifiers to the merged main commit
deps/verifiers -> main 91d4f69e6 (#2303 merged); research-environments
-> the rename branch head with the automationbench_env collision fix.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: floor verifiers at 0.3.1.dev12
The first dev release carrying the v0 deprecation (verifiers#2303);
submodule follows main.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: verifiers submodule points at main head (the #2303 merge), not its parent
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: pin submodules to the merged mains and floor verifiers at 0.3.1.dev13
deps/verifiers -> f24b8ec0 (#2311), deps/research-environments ->
c0a0d1d7a (#754); 0.3.1.dev13 is the release cut from that verifiers
commit.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers to main d53ab56f (0.3.1.dev14)
Picks up the model-catalog revert (verifiers#2314).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Laguna's config carries a `gating` field that prime-rl's port dropped, so
g_proj was always sized for per-head gating:
self.g_proj = nn.Linear(config.hidden_size, num_heads, bias=False)
That matches Laguna S (`gating = "per-head"`, g_proj [48, 3072]) and is wrong
for Laguna M (`gating = "per-element"`, g_proj [8192, 4096] = num_heads x
head_dim). Loading M.1 fails with
ValueError: Size mismatch between saved torch.Size([8192, 4096]) and
current: torch.Size([64, 4096]) for model.layers.0.self_attn.g_proj.weight
Carry `gating` on LagunaConfig and size g_proj from it, following upstream's
semantics exactly (poolside/Laguna-M.1 modeling_laguna.py):
True / "per-element" one gate per (head, head_dim) channel
"per-head" one gate per head, broadcast across head_dim
False no gating
Note the default is `True`, not "per-head": a checkpoint that omits the field
gets per-element upstream, so defaulting the other way would silently mis-size
it. bool and str are both accepted for the same reason.
Verified against both checkpoints: g_proj matches [48, 3072] for S-2.1 and
[8192, 4096] for M.1, and the gate math is bit-identical to upstream in both
modes (max abs diff 0.0). End to end, a 4-node trainer probe loads the real
452GB M.1 checkpoint through load_dcp_from_hf with no size mismatch, where it
previously failed at model construction.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Bumps deps/verifiers 29e3a0f7 -> a298bcfe, picking up two commits:
a298bcfe fix(v1): restore the unbounded model-call timeout (#2304)
9ca7f5d6 Fix plain HTTP CONNECT for Docker framework routes (#2298)
verifiers#2218 had consolidated client construction into
build_async_openai/DEFAULT_TIMEOUT and, in doing so, replaced the relay
client's explicit `timeout=None` with a 600s read timeout mirroring the OAI
SDK default. That cap reached every model-call path, since DEFAULT_TIMEOUT
feeds clients/eval.py as well as build_async_openai, which judge.py and
clients/train.py use.
600s is fine for chat-shaped evals and wrong for RL: a single agentic turn on
a long SWE trajectory routinely runs past ten minutes, and when it does the
rollout dies as `ProviderError: Request timed out` even though the model was
still producing. Because it truncates the longest trajectories specifically,
the loss is biased rather than uniform. Seen on the laguna-s SWE RL run here.
#2304 restores unbounded read/write/pool and keeps connect at 5.0 so an
unreachable endpoint still fails fast.
No lockfile change: verifiers is an editable path dependency
(`source = { editable = "deps/verifiers" }`), and neither commit touches its
pyproject, so only the submodule pointer moves.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
#3189 hoisted ORCH_PROCID out of the srun body into the outer batch script so
ORCH_ADDR could be derived from it. ORCH_ADDR was exported; ORCH_PROCID was
not.
The srun body is a quoted heredoc, so `$ORCH_PROCID` in
if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
is expanded per task, and a plain (unexported) shell variable never reaches
the task environment. The test becomes `[ "4" -eq "" ]`, which errors with
"integer expression expected" and evaluates false on every rank, so the block
that starts the orchestrator and both env servers is skipped entirely.
The failure is silent and expensive. Inference comes up, the trainer reaches
weight-broadcast init, and then the job sits there until the 3600s NCCL
watchdog fires on a 1-element ALLREDUCE, holding the whole allocation. There
is no error in the job log pointing at the orchestrator, and no
orchestrator.log to look at, because the `tee` that would create it is inside
the skipped block. Observed on a 6-node run: 20 minutes in, only
PRIME-RL::Trainer processes on the orchestrator node and no logs/envs/
directory, which the block's own `mkdir -p` would have created.
Export it. Verified by rendering multi_node_rl.sbatch.j2 and running the guard
with SLURM_PROCID=4: the branch is taken now and skipped before.
Audited the other templates for the same pattern — variables assigned in the
outer script but read inside a quoted heredoc. multi_node_sft, single_node_rl
and single_node_sft are clean. Two apparent hits are false positives:
HOSTNAMES is rebuilt inside the body from the exported HOSTNAMES_STR, and
inference.sbatch.j2's DP_PER_NODE is rendered directly into the body by Jinja.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* feat(client): single-string base_url, remove elastic inference pool
The data plane is now a single endpoint (put a router in front for
multi-replica deployments); admin_base_url stays a list for per-server
admin operations (weight updates, health checks, NCCL rank offsets).
Removes ElasticInferencePool (DNS discovery + per-tenant adapter sync),
the InferencePool protocol/factory, and client-side load balancing.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: orchestrator-side packing, single-tenant trainer, flat output dir
Removes the multi-tenant infrastructure:
- Bin-packing moves into the orchestrator (BatchPacker), which now ships
per-DP-rank micro batches directly to the trainer — one transport hop
instead of two (the rank-0 packer and its second filesystem write are
gone). ZMQ data moves to port, READY barrier to port+1; the transport
binds in the orchestrator process.
- MultiRunManager, run discovery, eviction, the control/orch.toml
handshake, MultiPacker, MultiCheckpointManager, MultiLoRAOptimizer,
MultiLoRAScheduler, per-run metrics, and trainer.max_concurrent_runs
are deleted. A slim LoRAState in trainer/lora.py keeps single-tenant
LoRA (RL + SFT) working: module registry, adapter state dicts, resets,
and the shared lora_num_tokens/scaling tensors (n_adapters=1).
- The run_default nesting is gone: orchestrator.output_dir equals
trainer.output_dir, with rollouts, broadcasts, checkpoints, and token
exports in one flat experiment dir.
- RL LoRA optimizers now include modules_to_save params (matching SFT).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: always broadcast step-0 weights at startup
The trainer's startup broadcast of the incoming policy (v0 from scratch,
v{resume_step} on resume) now runs for every transport, not just the
in-memory ones, and the orchestrator's startup weight sync is
unconditional to match. This validates the broadcast path at startup
instead of after the first optimizer step and aligns fresh starts with
the restart flow. The orchestrator always waits for the startup weight
directory (default 1200s; ckpt.wait_for_weights_timeout overrides).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: assign base_url as str in auto_setup_inference_client
Leftover list assignment from before the base_url list[str] -> str
migration; pydantic doesn't validate assignment, so the list survived
until rl_local's urlparse crashed on it (sft-distill path only).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* feat(configs): per-source env-server address via serve.address
Setting serve.address on a train/eval source marks its env server
externally managed: the launcher neither writes its TOML nor spawns a
server for it, and the orchestrator connects to the given address.
Unset sources keep the derived loopback address, with indices still
positional across all sources.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: subclass vf.ServeConfig instead of mirroring its fields
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: consume vf.ServeConfig as-is
Companion verifiers bump makes ServeConfig.address optional with no
default, so the per-source serve block needs no prime-rl subclass.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers to merged optional-serve-address rev
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* feat!: flatten inference config into vLLM pass-through [vllm] section
Replace ModelConfig/ParallelConfig and the flat vLLM fields on
InferenceConfig with a single flat VllmConfig under [inference.vllm]
(standalone: [vllm]) that uses vLLM's own argument names and passes
unknown keys through to the server verbatim (extra="allow"), replacing
the vllm_extra escape hatch. to_vllm()'s rename table becomes a direct
to_namespace() dump.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test: pin VALID_VLLM_LORA_RANKS against vllm.config.lora.MaxLoRARanks
The constant stays hardcoded (prime-rl-configs has no vLLM dependency,
and importing vLLM costs ~5s per config-parsing process); a unit test
now fails on any vLLM bump that changes the accepted ranks.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: no apostrophe in the srun-quoted launch helper, guard with bash -n
The per-rank launch helper is rendered inside the single-quoted
`srun bash -c '...'` body, so the apostrophe in the new "can't be inlined
as CLI flags" comment ended the quoted body and the rest of the script was
parsed by the outer shell — every SLURM inference launch (single-node,
multi-node and disaggregated alike) died at parse time with
`syntax error near unexpected token ')'`.
Reword the comment, drop the quotes around printf's format string for the
same reason, and add a unit test that renders both sbatch templates across
the deployment shapes and runs `bash -n` on the output, so this class of
quoting bug fails CI instead of the cluster.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix: feed srun launch bodies to bash on stdin via a quoted heredoc
The multi-node launch bodies were passed as a single-quoted `bash -c '...'`
argument, so a lone single quote anywhere inside them — including in the
shared _launch_*.sh.j2 includes, and including in a comment — ended the
quoted body and left the rest of the script to be parsed by the outer shell.
The apostrophe in this branch's "can't be inlined as CLI flags" comment did
exactly that and killed every SLURM inference launch at submit time with
`syntax error near unexpected token ')'`.
Deliver the bodies the way the cleanup block already does: `bash -s` with a
quoted heredoc, which srun broadcasts to every task and which passes the
script through verbatim, so no character in the body needs escaping. This
removes the hazard from inference, multi-node RL and multi-node SFT rather
than policing it, drops the `'"'"'` escape dance around
DECODE_COMPILE_CFG, and fixes the trainer log filter, whose sed script was
silently losing its backslashes to the outer shell.
Nothing in the bodies reads stdin, which would otherwise consume the rest
of the script.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* test: drop the VALID_VLLM_LORA_RANKS pin against vllm.config.lora.MaxLoRARanks
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers + research-environments to latest main
verifiers d30a3f48e -> f940bf7a7 (0.2.2.dev76 -> dev91), floors follow.
research-environments f9c43a74f -> b10db7640 (adds mmk12-v1).
Adapts to vf#2244 (run info moved from Trace onto Episode): the
orchestrator stamps the run into each rollout's info instead of the
removed Trace.record_run, keeping per-trace records placeable.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat!: write traces.jsonl in verifiers' native episode format
One vf.Episode record per line, matching what verifiers' own eval CLI
writes and read_episodes loads. The run is stamped on the episode via
Episode.record_run, and prime-rl's orchestration metadata (env_name,
group_id, policy_version) lives in Episode.info; a multi-agent episode
is one line holding all its traces.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Revert "feat!: write traces.jsonl in verifiers' native episode format"
This reverts commit b5972ef9b16970420df558071e33bea63f9fddba.
traces.jsonl stays one trace record per line - the episode-native format
only pays off with the episode-first pipeline, which is not being taken.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: re-pin verifiers to run-info revert, drop the dev91 adaptation
deps/verifiers moves to vf#2264 (revert of vf#2244), which restores
Trace.record_run - the orchestrator code is untouched by the bump again.
Re-pin to verifiers main once vf#2264 merges.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: re-pin verifiers to main (vf#2264 merged)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers to dev102, enumerate used vf env members
verifiers eb2c3fe11 -> b23b5c2ca (0.2.2.dev102). The vf environments/*
workspace glob becomes an explicit list of the envs prime-rl trains or
tests on, so upstream examples with conflicting pins (nemo-gym-weather-v1
pins openai<=2.7.2 via nemo-gym against verifiers' openai>=2.9.0) never
enter the shared lock. Floors stay dev92 - nothing in the range is
API-required, and PyPI publishing lags main.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: pin verifiers to fix/interception-owned-clients for validation
One commit on top of main (dev102). Re-pin to main once it merges.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: re-pin verifiers to main (interception fix merged)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers to dev112 + renderers to 0.1.10.dev1 for 0.3.0 prep
verifiers 2efe0a138 -> 0a4d872f0 (0.2.2.dev112). renderers follows to main
(0.1.10.dev1, adds Laguna M.1) since vf now floors renderers>=0.1.9.
Re-pin to the 0.3.0 release tag and flip floors once it is published.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: floor verifiers at dev112 (published to PyPI)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: verifiers floors to 0.3.0 (released)
The submodule pin 0a4d872f0 is the v0.3.0 tag commit.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: relock for the 0.3.0 floors
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: renderers floor to 0.1.9 (released)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* fix(docker): pin prebuilt aarch64 flash-attn wheel instead of building from source
The arm64 image built flash-attn 2.8.3 from source on every build: 53m46s of the
1h13m arm64 job, 74% of it, and the critical path for the whole multi-arch build.
mjun0812/flash-attention-prebuild-wheels publishes the exact aarch64 counterpart of
the x86_64 wheel already pinned here — same flash-attn 2.8.3, cu128, torch 2.11,
cp312. Pin it behind a platform_machine marker and drop the source build.
GPU coverage is unchanged. The old source build and both wheels carry identical
fatbinaries: 288 entries, sm_80 / sm_90 / sm_100 / sm_120 with 72 kernels each. The
53-minute compile was reproducing what the wheel already shipped. Verified by
walking the fatbin entry headers of flash_attn_2_cuda.so in the old arm64 image
alongside both wheels; the .so sizes agree to within 0.013%.
Also drops the post-install script's side effects. It re-resolved without
--no-deps, re-downloading 897 MB and downgrading the image's cudnn from 9.22.0.52
to 9.19.0.56 relative to the lockfile, so arm64 now matches amd64 and the lock
again. Its flash-attn-cute reinstall existed only because the source build shipped
a flash_attn/cute stub that clobbered FA4; the wheel has no cute directory, so
arm64 takes the same install path as amd64.
Removes the local aarch64 build step from scripts/install.sh and the README too —
uv sync resolves flash-attn from the wheel there as well, so the 20-30 minute
compile and its "don't run uv sync afterwards or it gets uninstalled" caveat are
both gone.
The lock diff is large but mechanical: the second platform-forked URL makes uv
restate fork markers across the file. The resolved (name, version, source) set is
unchanged except for the one added aarch64 wheel.
* perf(docker): split the venv into parallel-compressible layers and push zstd
The image was 18 layers / 8.5 GB compressed, but a single layer held 7.76 GB of it —
the monolithic `COPY --from=builder /app /app` of the whole venv. BuildKit
compresses and pushes layers concurrently, so that one layer serialized the export
behind a single gzip stream: 562.7s of the amd64 job and 411.8s of the arm64 job,
plus 210.8s / 114.4s pushing.
Split the venv's largest trees (nvidia, torch, vllm, flash_attn, and the ~1 GB
flash_attn_2_cuda .so) into their own layers via `COPY --exclude`, and switch the
image export to zstd.
Measured on the first green build of this branch:
exporting layers amd64 562.7s -> 42.2s arm64 411.8s -> 42.1s
export + push amd64 778s -> 100.1s arm64 528s -> 85.2s
image size amd64 8.52 -> 7.04 GB arm64 7.91 -> 6.64 GB
The size drop is zstd beating gzip on ratio here, and it also confirms the excludes
line up with the per-tree copies — a mismatch would have shipped the data twice and
grown the image. The registry shows 18 zstd + 5 gzip layers, the gzip ones being
base-image layers passed through untouched.
`COPY --exclude` needs Dockerfile syntax >= 1.19, hence the syntax directive. Keep
the excludes in sync with the per-tree copies that follow them. Excluding
`flash_attn` deliberately does not swallow `flash_attn_3`.
zstd is set without `force-compression` so base-image layers are reused as-is
instead of recompressed for nothing. Pulling zstd layers needs containerd >= 1.5 or
Docker >= 23. `push: true` is replaced by `push=true` inside `outputs` because the
two would otherwise register two image exporters and export the image twice. The
`digest` output the Summary step reads comes from the metadata file, so it is
unaffected.
Splitting also lets cluster nodes pull these layers in parallel.
When torch.compile is used with Ulysses context parallelism and FSDP,
the all-to-all collectives are traced into the compiled backward graph
while FSDP's reduce-scatter hooks fire eagerly via the autograd engine.
The compiler may reorder the all-to-all backward differently across
ranks, causing rank 0 to wait on reduce_scatter while rank 1 waits on
all_to_all — a classic collective ordering mismatch that deadlocks NCCL
after the 1-hour watchdog timeout (PR #3186, job 1578).
Wrapping _all_to_all_seq_to_head and _all_to_all_head_to_seq with
torch._dynamo.disable forces a graph break around the collectives so
they execute eagerly in the autograd engine, restoring a single
consistent backward ordering between the two collective systems.
The scrub from #2506 was a temporary mitigation for NaN logits caused by
stale padded decode inputs poisoning CUDA-graph replay. The root cause is
fixed in the pinned vLLM 0.26.0: the non-contiguous logits bug in the
native Triton top-k/top-p kernel (vllm-project/vllm#42739) is included,
and _preprocess now zeros the padded positions tail natively.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
On resume, the orchestrator defaults to assuming a clean exit where all
evals already completed. When a run crashes mid-eval, the user can set
eval.retrigger_on_resume=True to re-trigger interval-aligned evals
at the checkpoint step instead of the next interval boundary.
No changes to EvalSource — the existing first_trigger = not is_resumed
already skips the base eval on resume and just checks step % interval,
so passing resume_step to trigger() is sufficient.
Both NemotronH Mamba paths built their packed-document metadata with a
`cu_seqlens.tolist()` and a Python loop over documents, once per Mamba
layer. On Super that is 40 host-device syncs per forward (80 with
activation recompute): each one blocks the Python thread until the CUDA
stream drains, so the CPU never runs ahead and, under context
parallelism, every rank re-synchronizes to its slowest CP partner at
every layer instead of absorbing jitter in queue depth.
Replace the per-document conv loop and the hand-built seq_idx with
fla's Triton `causal_conv1d` and `prepare_sequence_ids`, matching the
call shape already used for Qwen3.5 GDN in `trainer/model.py` and
`qwen3_5_moe`. Both fla helpers derive boundaries from `cu_seqlens`
directly and are `@tensor_cache`d by argument identity, so the 40
layers of a forward share one build.
fla is already a required dependency and its Triton backend needs no
arch-specific CUDA compilation, which was the stated reason for
avoiding a fused conv here.
* fix: accept seq_lens contract kwargs in GlmMoeDsaModel.forward
The fused LM head wrapper forwards seq_lens/seq_lens_are_pre_shard to the
inner model, but only GlmMoeDsaForCausalLM accepted them.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* review: drop inline comment above seq_lens kwargs
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* feat!: remove env-server sidecaring, launcher spawns at deterministic addresses
The orchestrator never spawns env servers anymore — it always connects to
each source's serve.address and polls until the server is up. Addresses
are assigned deterministically at config validation (tcp://127.0.0.1:5000+
across train then eval sources), so the launcher (local rl + multinode
sbatch template) spawns the servers in parallel with the orchestrator and
both sides agree on where each server lives from the config alone.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: docstring + test tidy
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor!: derive env-server addresses, require address on env-server config
Addresses are wiring, not intent — like the transport blocks, they are no
longer configurable on sources. The orchestrator derives each server's
address from the source's position in the config; the env-server entrypoint
takes a required address the launcher writes per source.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: env-server config mirrors verifiers' serve CLI, per-run base port
EnvServerConfig composes vf's env/serve/legacy blocks verbatim, so an
env-server TOML reads like a vf serve config. orchestrator.env_server_base_port
offsets the derived port range, giving concurrent runs on one host (e.g.
multi-run orchestrators) each their own 1:1 env server.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(configs): multi-env debug config (2 reverse-text train sources + eval)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: rename env server entrypoint to `env` (keep `env-server` alias), env_server_addresses -> env_addresses
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: env/ prefix for env server stop-event keys
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor: rename env server naming to env throughout
EnvServerConfig -> configs/env.py:EnvConfig, source-level EnvConfig -> SourceConfig,
entrypoint moves to entrypoints/env.py, env_server_base_port -> env_base_port,
proctitle PRIME-RL::Env
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: trim env entrypoint row
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat: drop the verifiers serve CLI, adopt vf.ServeConfig
Bumps deps/verifiers to PrimeIntellect-ai/verifiers#2237 (serve CLI removed,
ServingConfig renamed ServeConfig); prl's source-level ServingConfig follows suit
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: drop the removed serve CLI reference from EnvConfig
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: pin verifiers to main (serve CLI removal merged)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* ci: slim install imports configs.env
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* revert: keep env-server naming, validate env identity on EnvServerConfig
The env console script shadows coreutils env in activated shells — back to
env-server as the sole entrypoint (still at entrypoints/, orchestrator source
class stays EnvConfig as on main). EnvServerConfig regains the identity
validation the nested source config used to provide (missing env, mixed v0/v1)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(slurm): remove apostrophe from env-server launch comment
The multi-node srun body is one single-quoted bash -c string, so the
apostrophe in "source's" closed it early: every rendered sbatch failed to
parse with a syntax error near unexpected token '(' and the job died before
any component started. Reword the comment and note the constraint.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* chore: scope the jaxtyping lint ignores so F821 runs everywhere else
F821 (undefined name) was disabled repo-wide for jaxtyping's shape
strings, so ruff could not report a missing import anywhere in prime-rl —
and style CI runs only ruff. Four modules actually use those annotations;
the ignore now names them.
The fifth file the rule fired on was not jaxtyping: rotary_emb annotated
a config it never imported, so the name resolved to nothing. Imported.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: trim the ignore comment
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* fix(ci): allow branch/commit refs in ghcr image build
The `ref` input already advertises "Branch, tag, or commit to build",
but Resolve image vars rejected anything that wasn't main, v*, or *.dev*,
so dispatching a build off a feature branch failed.
Drop the allowlist (the ref is checked out — hence existence-validated —
before this step) and name non-tag builds with `git describe` so a
branch build tags as e.g. v0.7.1.dev55-3-gfea5aadcf-<branch>, carrying
the nearest release + commit distance + short sha and never colliding
with a clean release tag. Exact-tag refs still build under the tag
verbatim, and the commit-<sha> tag is kept since the platform pins it.
* ci: restrict manual image builds to maintain/admin
workflow_dispatch already requires write access, but that includes any
write-level collaborator. Add an authorize job that gates the build on
the dispatcher having maintain or admin (via the collaborator permission
API). Automated in-repo dispatches run as github-actions[bot] and are
allowed so devx_tag dev-image builds and the release build keep working.
prepare now needs authorize, gating the whole build + manifest chain.
* ci: gate only manual dispatches in authorize job
The authorize job ran for every trigger, including on:release. Scope the
permission check to workflow_dispatch (manual builds) so release/other
events pass through. Guard the step (not the job) so a skip still leaves
prepare's `needs: authorize` satisfied.
* fix: port dp=1 EP dense-style launch to standalone inference template
Same bug as #3094, same fix: the multi-node branch of inference.sbatch.j2
still passed external-LB DP args (data_parallel_rank/address) at dp=1
(e.g. tp=8 on 8-GPU nodes), which vLLM >=0.24 rejects with
'data_parallel_external_lb can only be set when data_parallel_size > 1'.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: accept poolside_v1 tool calls without newline after function name
Laguna S 2.1 emits <tool_call>name<arg_key>... with no newline; the
non-streaming func_detail_regex required one, so every tool call failed
detail parsing and leaked verbatim into content (finish_reason=stop).
Upstream vLLM >=0.25 accepts both forms; patch only the regex via the
shared vLLM plugin.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Revert "fix: accept poolside_v1 tool calls without newline after function name"
This reverts commit b054923274aecb39f82671b2f9eae22ef0590fb9.
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* fix: relock uv.lock after research-environments bump
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: bump verifiers to 0.2.2.dev76 and rename ServingConfig to ServeConfig
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Bump the deps/research-environments submodule pin 21a284618 -> f9c43a74 (latest
main), which includes research-environments #744 fixing senior_swe_bench_v1's stale
verifiers.v1.clients.config import (moved to verifiers.v1.configs.client) so
senior-swe-bench-v1 resolves against latest verifiers.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* feat(orchestrator): episode- and agent-level rollout metrics
Adapt to verifiers#2187 (Episode derived aggregates): episode.last_error
rename, submodule bump. Mirror the episode/trace hierarchy in the wandb
layout: count metrics read at the episode level (per-episode sums), and
a new {scope}/{subset}/<agent>/<metric>/<stat> level reports trace-level
metrics per agent, averaging in-episode fan-outs first.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers to vf#2187 head, episode wording cleanups
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor(orchestrator): RolloutMetrics -> EpisodeMetrics, AgentMetrics -> TraceMetrics
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(orchestrator)!: trace-level metrics are agent-only, timing generation span renamed agent
Env level now carries only episode-level facts (count sums, pipeline
rates, eval scores); reward, truncation, errors, stop conditions, timing,
custom metrics and solve rates move under {scope}/{subset}/<agent>/.
Adapts to the vf span rename (Timing.agent, AgentSpan, split_agent_time)
and re-pins deps/verifiers. Overview reward/error/truncation panels match
the per-agent keys by regex.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(configs): agentic-judge reverse-text debug config
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore(configs): deterministic two-call judge policy for the agentic-judge debug config
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers to vf#2187 head
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers to vf#2187 head (main merged)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers pin
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers pin
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: re-pin verifiers to the vf#2187 merge commit
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers and research-environments to latest main
verifiers f646beb37 -> f6e420b99 (0.2.2.dev66, 17 commits) and
research-environments 6a2dee6fc -> ccb375ce5 (main + the scicode-v1
pin relax from research-environments#740).
Adaptations to the verifiers changes:
- Episode.error is now Episode.errors + a last_error property (vf#2187)
- verifiers.v1.loaders / verifiers.v1.push moved into
verifiers.v1.utils.{loaders,platform} (vf#2204)
- verifiers floors bumped to 0.2.2.dev66 (root and prime-rl-configs)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump research-environments to latest main
ccb375ce5 -> 9a57c713c: research-environments#740 refreshed on current
main, picking up the ViRL39K v1 taskset (RE#689) and the taskset prompt
config fixes (RE#742). verifiers main is unchanged since f6e420b99.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers to 0.2.2.dev73 (per-rollout clients)
f6e420b99 -> 576506d66 (7 commits). vf#2218 builds one client per
rollout with a process-wide elastic renderer pool: TrainClientConfig
drops pool_size for a multiplex knob, and the config module moved from
clients.config to configs.client. The orchestrator config follows suit
(pool_size -> multiplex, None = client default). Floors to dev73.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore!: pin research-environments to the scicode merge commit, drop orchestrator.multiplex
deps/research-environments -> 21a284618 (research-environments#740 on
main). The orchestrator-level renderer knob (pool_size, briefly
multiplex) is removed instead of renamed: clients resolve inside env-
server workers, whose concurrency is already bounded per env by
serve.pool.multiplex (default 128, below the client-side renderer
default of 256), so each worker warms one renderer and the elastic pool
grows on demand.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(orchestrator)!: pipeline verdicts and eval scores are per-agent too
is_trainable / is_filtered / filters and avg@k / pass@k all score a
single trace, so they read per agent like every other trace-level
metric instead of pooling an episode's seats.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: drop the agentic-judge debug config from this PR
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: spell out the per-agent metric level in the monitor-run skill
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: eval's overview score is the per-agent avg@k
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(orchestrator): agent-level rates are flat over traces
is_truncated / is_completed rode the per-episode mean path with the
distributions, so an uneven fan-out — what the effective subset leaves
whenever a sibling errors — reweighted them away from the plain
fraction their siblings and the docs promise.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor(orchestrator)!: agent-level metrics are flat over traces
One aggregation per level: the episode level sums an episode's traces,
the agent level takes each trace as a sample. Reward, avg@k and the
per-agent counts had been collapsing each episode's fan-out to a mean
first, which left them the odd ones out among the seat's own metrics and
made avg@k's k — a trace count — disagree with what it averaged.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* fix(metrics): count unscored reward components as zero
Verifiers now seeds expected reward/metric names with None when scoring
starts, so a scoring failure leaves seeded-unscored entries instead of an
empty dict. CustomMetrics counts unscored rewards as 0.0 (matching the
scalar reward, which sums them as 0) and keeps averaging metrics over the
rollouts that scored them, so all-subset per-key reward means no longer
collapse onto effective when scoring errors occur.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers submodule
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers submodule
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(metrics): count unscored metrics as zero too
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers to main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers and research-environments to latest main
verifiers f646beb37 -> f6e420b99 (0.2.2.dev66, 17 commits) and
research-environments 6a2dee6fc -> ccb375ce5 (main + the scicode-v1
pin relax from research-environments#740).
Adaptations to the verifiers changes:
- Episode.error is now Episode.errors + a last_error property (vf#2187)
- verifiers.v1.loaders / verifiers.v1.push moved into
verifiers.v1.utils.{loaders,platform} (vf#2204)
- verifiers floors bumped to 0.2.2.dev66 (root and prime-rl-configs)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump research-environments to latest main
ccb375ce5 -> 9a57c713c: research-environments#740 refreshed on current
main, picking up the ViRL39K v1 taskset (RE#689) and the taskset prompt
config fixes (RE#742). verifiers main is unchanged since f6e420b99.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: bump verifiers to 0.2.2.dev73 (per-rollout clients)
f6e420b99 -> 576506d66 (7 commits). vf#2218 builds one client per
rollout with a process-wide elastic renderer pool: TrainClientConfig
drops pool_size for a multiplex knob, and the config module moved from
clients.config to configs.client. The orchestrator config follows suit
(pool_size -> multiplex, None = client default). Floors to dev73.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore!: pin research-environments to the scicode merge commit, drop orchestrator.multiplex
deps/research-environments -> 21a284618 (research-environments#740 on
main). The orchestrator-level renderer knob (pool_size, briefly
multiplex) is removed instead of renamed: clients resolve inside env-
server workers, whose concurrency is already bounded per env by
serve.pool.multiplex (default 128, below the client-side renderer
default of 256), so each worker warms one renderer and the elastic pool
grows on demand.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(orchestrator): read the agent timing span
vf#2187 renamed Timing.generation to Timing.agent (GenerationSpan ->
AgentSpan); the timing metrics group crashed every RL run's first
to_wandb. Metric keys follow (timing/agent, timing/agent/{model,
harness}). The unit fixture missed it because mk() duck-types Trace;
its namespace now mirrors the real field names.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* fix(orchestrator): checkpoint and resume the train data position
Shuffle each finite env's task table with seed=epoch (1-indexed) so the
permutation is reproducible, snapshot per-env {epoch, cursor} into
Progress.data_positions at checkpoint time, and restore + log the
position on resume.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(orchestrator): track and fast-forward infinite taskset cursors on resume
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore(orchestrator): drop old-checkpoint load compat
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor(orchestrator): make the data position first-class checkpoint state
TrainSource is a torch Stateful (state_dict/load_state_dict) saved under
its own train_source key next to progress, mirroring the SFT dataloader.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: simplify orchestrator checkpoint table row
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* refactor(orchestrator): simplify TrainSource surface
Hardcode the env-choice seed, drop the torch Stateful base (nothing
consumes the protocol), log the restored position from ckpt.load, and
rename _shuffled to _shuffle.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(orchestrator): make the cross-env dispatch sequence reproducible
Advance the env-choice RNG exactly once per dispatched example - a draw
whose permit cost doesn't fit is held (head-of-line) instead of redrawn -
and checkpoint the RNG state and pending draw with the per-env positions.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(orchestrator): save the interval checkpoint on the event loop
state_dict() on a to_thread worker raced the dispatcher mutating
TrainSource; the payload is tiny, so snapshot and write synchronously.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
B300 device names fell through to the A100 fallback (312 TFLOPS),
inflating reported MFU ~7x. Add dense BF16 peaks per NVIDIA datasheets:
GB200/GB300 superchips at 2.5 PFLOPS, HGX B200/B300 at 2.25 PFLOPS.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Every checked-in config, example, and doc snippet now uses [section]
headers instead of key = { ... } inline tables. Purely stylistic: all
48 rewritten TOML files parse identically to their previous versions.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* rename training environments to sources
* fix CPU test config fixtures
* rename evaluation environments to sources
* chore(orchestrator)!: rename max_inflight_rollouts to max_inflight_episodes
A dispatcher permit has always bought one episode, not one rollout: for a v1
env one `run` request is one episode (however many agents play it), and a
legacy group-scoring call reserves one permit per bridged v0 rollout, each of
which is its own single-agent episode. Name the knob what it counts.
`max_inflight_rollouts` still parses as an alias, as `rollouts_per_example`
does for `group_size`.
* feat(orchestrator)!: compose the verifiers env, serve and legacy blocks
verifiers split `EnvServerConfig` into three blocks, so an env entry composes
them instead of inheriting one class:
[[orchestrator.train.source]]
env = { taskset = { id = "..." } } # what runs
serve = { pool = { ... }, address, max_concurrent } # how it's hosted
legacy = { id, args } # a classic v0 env instead
`serve.pool` sizes the spawned server (was `pool`), `serve.address` points at an
external one (was `address`), and `serve.max_concurrent` bounds one worker's
episodes in flight — usually left unset, since `max_inflight_episodes` is the
run's bound. Each moved key raises with a pointer home, including the
`num_workers` shorthand the old validator migrated silently.
BREAKING: `pool` / `address` / `num_workers` on an env entry move under `serve`,
and a v0 env's `id` / `args` / `extra_env_kwargs` move under `legacy`.
TEMPORARY: `deps/verifiers` points at the `feat/one-agent-per-episode` branch
(PrimeIntellect-ai/verifiers#2157) so the two sides can be run together; re-pin
to a merged `main` commit before this lands.
* fix the source-config readers the compose commit missed
The Prime monitor still built its run-registration payload from `env.id`, which
the composed entry doesn't have — `AttributeError` at registration whenever
Prime monitoring is on. It reads `env_id` now, the property that spans both the
v1 and the v0 shape.
The packer's fixture still used the bare `id` shorthand, so its three runs were
rejected at config parse and skipped by `discover_runs`. Full CPU unit suite:
416 passed.
Re-pins `deps/verifiers` to the branch tip of verifiers#2157, which fixes the
same class of stale access on that side (`config.legacy.id`). Still a branch
commit — re-pin to a merged `main` before this lands.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* spell the env annotation out instead of vf.EnvField
verifiers dropped the `EnvField` alias, which was only ever
`SerializeAsAny[EnvConfig]` under a name that collided with `env_field()`.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* declare the env default with the factory verifiers exports
`vf.env_field()` is gone: it only wrapped `Field(default_factory=...)`.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* inline the legacy helpers, use the config class as the default
Follows verifiers dropping the three `configs/legacy.py` helpers and the
`single_agent_env_config` factory: `is_legacy` and `env_id` are one-liners here,
the mixed-run refusal is spelled out in `validate_env`, and the `env` default is
`vf.SingleAgentEnvConfig()`. `env.max_concurrent` now works as an alias for
`env.max_concurrent_agents`.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* drop the serving-key pointers here too
The same call as verifiers a0ebc408: `num_workers` / `pool` / `address` on a source
entry now fail as an ordinary `extra_forbidden` instead of naming their new home.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* bump verifiers: no max_concurrent alias on the env block
`env.max_concurrent` used to bound a served worker's agent runs across episodes, so
accepting it as `max_concurrent_agents` multiplied it by the episodes in flight. It
errors now, like every other moved key. 416 unit tests pass.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* bump verifiers to 0.2.2.dev43 (merged main)
deps/verifiers d0bb0ffe5 -> fcb48822e, which is the squash-merge of the composed
env/serve/legacy config blocks (#2157) plus everything else since the last bump:
Harbor 0.20.0 (#2161), runtime-blamed box failures (#2156), standalone MCP clients
pinned to v1 (#2155), and the v1 test/E2E split (#2127).
Lock: harbor 0.14.0 -> 0.20.0, which drops claude-agent-sdk and datasets from its
own deps and adds filelock/platformdirs, so those move with it.
Replaces the temporary branch pin this PR carried.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: spawn the env server again, and let a pip-only install resolve verifiers
Two CI failures from the compose commit.
The orchestrator stopped spawning env servers. It decides spawn-vs-connect by
`address is None`, and prime-rl's own field defaulted to None; `vf.ServingConfig`
defaults to `tcp://127.0.0.1:5000`, so every env looked external and the run waited
120s for a server nobody started. It now asks whether the address was *pinned*
(`model_fields_set`), so an unset `[serve]` spawns on a free port as before, and
pinning any address — including verifiers' own default — connects.
The slim `prime-rl-configs` wheel is installed from /tmp with no workspace context,
so `verifiers` resolves from PyPI, where `>=0.2.1` picks stable 0.2.1 — no
`SingleAgentEnvConfig`. Floor is `>=0.2.2.dev43` now, a pre-release specifier so the
dev release is eligible.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* chore: adapt to the verifiers trace record cleanups
Companion to PrimeIntellect-ai/verifiers#2172: record_* mutators, required
agent seat and RunInfo.id, last_error, and agent.name/.trainable reads.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: re-pin verifiers to merged main (f646beb37)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: read overview quality metrics from effective subset
The all subset counts errored rollouts as zeros for num_branches,
num_turns, num_total_tokens, and is_truncated, which skews the
distributions and makes the panels uninterpretable. Point the wandb
overview panels and the eval success line at the effective subset;
has_error stays on all since effective drops errors by construction.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: reword zero-skew rationale, drop subset guidance from skill
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* fix(orchestrator): compute trainable rate over effective rollouts
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* chore: drop comment
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
* chore: single global router in front of engines for all deployments
Every deployment shape now runs one client-facing router on server.port
with engines behind it on backend_port: local single-node runs spawn a
vllm-router in the inference entrypoint, and the SLURM templates collapse
per-replica routers into a single global router on inference node 0.
router/backend_port move to InferenceConfig top level; router = "None"
runs a bare engine (used for per-rank SLURM engine processes).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: finish single-node router integration
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
* feat(config): shared [rollout_transport] propagated to trainer + orchestrator
Add rollout_transport as a shared RLConfig field (mirroring weight_broadcast /
ckpt / wandb), propagated to trainer.rollout_transport and
orchestrator.rollout_transport via propagate_shared_fields. A single
[rollout_transport] block configures both sub-configs.
auto_setup_rollout_transport (like auto_setup_weight_broadcast) resolves the
shared field from the sub-configs so the launcher's ZMQ host-injection gate is
correct whether transport is set via the shared block or directly on
trainer/orchestrator.rollout_transport (the documented fallback), and rejects
mismatched sub-config transports.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(launcher): inject rollout_transport.host for multi-node zmq transport
ZMQ rollout transport binds/connects a single rollout_transport.host (default
localhost). On multi-node trainer deployments the training-batch PUSH/PULL and
micro-batch PUB/SUB span nodes, so data ranks on non-head nodes connect to their
own localhost and hang at step 0. The launcher already injects
weight_broadcast.host=$MASTER_ADDR for nccl but had no equivalent for
rollout_transport.
When config.rollout_transport resolves to zmq, inject --rollout_transport.host
$MASTER_ADDR into the trainer torchrun and the orchestrator (mirrors the existing
weight_broadcast.host injection). Filesystem transport is unaffected.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(config): default rollout transport to zmq
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(orchestrator): RAE — SPIRAL's role-conditioned advantage estimation for self-play envs
Add the `rae` algorithm (SPIRAL, arXiv:2506.24119): each trainable agent
keeps an EMA baseline of its own rewards, and every trace's advantage is
its reward minus its agent's pre-update baseline. Group-relative baselines
mis-credit multi-agent self-play — in a zero-sum game the group mean is ~0
whatever the policy does, and centering both agents against it turns any
structural asymmetry (first-mover edge) into permanent credit. Baselines
are keyed per (env, agent) — the paper's per (game, role) — and any
group_size works, including 1.
configs/debug/algo/rae.toml runs shared-policy Kuhn poker self-play
(kuhn-poker-v1, both agents late-bound to the run's model).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore(tests): drop RAE unit tests
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* fix(nightly-fft): restore auto-resolve latest v*.dev* when no image_tag input
The nightly's whole point is to catch regressions on tip-of-main, so a
plain 'gh workflow run "Nightly FFT"' must dispatch against the newest
built v*.dev* by default. #3133 removed that fallback and made no-input
dispatches emit an empty tag, which falls through to the platform's
default 'main' alias — currently baked ~50 commits stale — so the run
crashes on validation.
Restores the original behavior: no input → auto-resolve latest dev.
Explicit image_tag input still overrides (from #3132). Dispatch step
always passes --image-tag since the tag is always populated now.
* fix(ci): guard dev-tag resolver against pipefail
GitHub Actions runs the shell under `bash -eo pipefail` by default.
Two failure modes:
- `grep -E ...` returns 1 when no v*.dev* tags exist yet
- `head -n 10` closes the pipe after 10 lines, SIGPIPE-ing `sort`
Either aborts the step before the explicit no-candidates guard runs.
Wrap the pipeline in set +o pipefail / set -o pipefail.
* fix(nightly-fft): pin image_tag to commit-c505e07a1 in each config
The default 'main' image the platform validator ships is baked ~50
commits behind tip and predates cb74ae2be (which added the env.
wrapper on train.env entries). It rejects env.taskset with
'train.env[0].env — Extra inputs are not permitted' and doesn't know
the 'prime-qwen3' renderer name, so every nightly orchestrator
crash-loops on validation.
- Pin top-level image_tag = 'commit-c505e07a1' in each nightly-fft
toml. c505e07a1 is post-cb74ae2be and accepts the current v1 shape.
- Workflow: when no dispatch input is set, emit an empty tag and skip
--image-tag on prime train so the toml pin wins. Explicit
workflow_dispatch image_tag still overrides.
- Drop this pin once v0.7.1+ (with the v1 schema) is released and the
backend default resolves to it.
* revert: drop image_tag pin from nightly-fft configs
Keep the workflow change (only pass --image-tag when explicit input);
rely on prime-cli's built-in fallback: --image-tag > toml image_tag >
backend default. No commit-hash pin baked into the checked-in configs.
2026-07-24 06:59:43 +02:00
511 changed files with 51981 additions and 27792 deletions
- **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.
@@ -31,6 +32,7 @@ Namespaces are one honking great idea -- let's do more of those!
## Running code
- **Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
- **Tools vs entrypoints**: standalone scripts in `tools/` use plain argparse with positional args; `[project.scripts]` entrypoints use pydantic-config (`@ file.toml` + dotted CLI overrides).
- **Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
@@ -41,9 +43,9 @@ Namespaces are one honking great idea -- let's do more of those!
## Skills
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs). When you make changes to the codebase, check if any skills need to be updated to stay accurate.
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs).
You are responsible for maintaining the skills folder. When a workflow fails and you fix it – whether with help from the user or through trial and error – you must update the skills to make implicit knowledge explicit. You are also responsible for keeping the skills up to date whenever you or anyone else modifies the code.
If a repository skill could benefit from an update, suggest the specific change, explain why it would help, and ask the user for approval before making it. Wait for approval before creating, modifying, renaming, or deleting skills, including their supporting files and symlinks. If the user has already explicitly requested or approved the skill change, proceed without asking again. Requests to change code, fix workflows, update documentation, or open a PR do not implicitly authorize skill changes. You may read and follow skills without changing them.
@@ -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
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
4.1. On aarch64 hosts: build flash-attn from source for your GPU
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`.
```bash
bash scripts/docker-arm64-post-install.sh
```
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
@@ -166,7 +157,7 @@ uv run trainer @ configs/debug/fake/rl.toml
5. Check that you can run the inference server (*this requires 1 GPU*)
```bash
uv run inference --model.name Qwen/Qwen3-0.6B
uv run inference --vllm.model Qwen/Qwen3-0.6B
```
6. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
@@ -213,10 +204,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
3. [**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
@@ -224,10 +212,11 @@ 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
Every config writes to the default `outputs/` directory, so running two back-to-back — or re-running one — fails with `FileExistsError`. Pass a distinct `--output-dir outputs/<algo>` per config (recommended for a sweep) or `--clean-output-dir` to wipe and restart.
Every config writes to the default `outputs/` directory, so running two back-to-back — or re-running one — fails with `FileExistsError`. Pass a distinct `--output-dir outputs/<algo>` per config (recommended for a sweep) or `--clean` to wipe and restart.
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, multi-tenant training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
The custom path enables you to set EP, CP, selective activation checkpointing, low-precision training (`[trainer.model.quantization]`), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
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
Set `[trainer.model.quantization]` to train dense linears and MoE expert GEMMs in low precision. Two backends are available via the `type` discriminator:
Dense linear precision and routed-expert precision are configured independently. `[trainer.model.quantization]` applies only to dense `Linear` modules:
-`type = "fp8"` — DeepGEMM FP8 blockwise (requires SM90+ / Hopper). Options: `enable_grouped_gemm` (FP8 MoE expert GEMM). Both default on.
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
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
`[trainer.model.moe.dispatch]` selects how routed tokens are dispatched and combined:
- **`torch`** (default): TorchTitan's all-to-all collective. Works everywhere, no extra install.
- **`deepep`**: Utilizes DeepEP's custom all-to-all collectives. This provides better performance if EP dimension spans multiple nodes. We provide pre-built binaries for H100/H200 with cuda runtime 12.9 installed, you can install them by running`uv sync --all-extras`.
DeepEP requires some careful tuning to achieve optimal performance, tuning parameters are `deepep_num_sms` and `deepep_token_chunk_size`.
- **`torch`** (default): torch all-to-all with `transport = "bf16"` or, when MXFP8 expert compute is selected, `transport = "mxfp8"` on SM100.
- **`deepep`**: DeepEP custom dispatch/combine kernels. Set `num_sms` and optional `token_chunk_size` in the same table. Pre-built H100/H200 binaries use CUDA 13.0 and are installed by`uv sync --all-extras`.
```toml
[trainer.model.moe.dispatch]
type="deepep"
num_sms=20
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
@@ -116,18 +177,7 @@ dropout = 0.0
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. To save the raw adapter alongside the merged HF weights:
```toml
[ckpt.weights]
save_adapter_separately=true
```
LoRA pairs naturally with [multi-tenant training](#multi-tenant-training) — each tenant gets its own adapter and the backbone is shared across all of them in trainer memory.
## Multi-Tenant Training
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/src/prime_rl/trainer/runs.py).
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
## Disaggregated Prefill/Decode Inference
@@ -138,7 +188,7 @@ For large MoE serving, splitting prefill and decode onto separate vLLM groups ca
| 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:
@@ -153,7 +203,7 @@ If prefill queues and decode is idle, add prefill nodes (and vice versa).
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
This page covers the math and the configurable algorithmic components: the algorithm abstraction and its algorithms, how off-policy training works, the loss components and advantage functions, how to plug in your own, the filters applied between rollout and training, and how multi-turn rollouts get merged into training samples.
This page covers the math and the configurable algorithmic components: the algorithm abstraction and its algorithms, how off-policy training works, the loss components and advantage functions, curricula, and how multi-turn rollouts get merged into training samples.
## Table of Contents
@@ -13,13 +13,15 @@ This page covers the math and the configurable algorithmic components: the algor
@@ -33,7 +35,7 @@ A training algorithm in `prime-rl` is configured under `[orchestrator.algo]`, wh
1.**Sampling** (`algo.sampling`) — how train rollouts are produced: which model generates them. `source` is a [model reference](#model-references): `"policy"` (the live policy, the default) or an inline frozen hosted model. Group sizing stays on the env config (`group_size`).
2.**The per-token training signal** — credit assignment and loss routing, fused; the algorithm's own parameters sit directly on `algo`. One mapping from a finalized rollout to per-token *(loss component, weight)* pairs — the credit a token gets and the loss that consumes it are two coordinates of the same output. Group-relative algorithms compute credit on the orchestrator and ship per-token advantage streams; reference-KL algorithms query a reference model at batch-ship time (bounded concurrency) and ship its prefill logprobs for the trainer to evaluate against the live policy. The `type` determines which loss component consumes the action tokens (`rl` / `ce` / `ref_kl`) and what happens to env-provided observation tokens in multi-turn rollouts (masked out by default; `echo` trains on them with weighted CE).
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, packer, or trainer hot path.
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, batch packing, or trainer hot path.
### Model References
@@ -45,7 +47,7 @@ type = "opd"
[orchestrator.algo.teacher]# opd's teacher: the frozen model it scores against
name="Qwen/Qwen3-32B"
base_url=["http://localhost:8001/v1"]
base_url="http://localhost:8001/v1"
```
Model *roles* are algorithm-local vocabulary — each algorithm names its reference on the field where the model is actually used, and there is no shared `teacher` slot. `opd` declares a `teacher` field (the frozen model whose reverse KL the policy distills toward); `sft`'s teacher *is* its `sampling.source` (the frozen model it imitates); `opsd` self-distills against the live policy and names no model at all. No role exists outside the algorithm that declares it: the dispatcher, sink, and trainer branch on liveness alone, never on what an algorithm calls a model.
@@ -67,6 +69,8 @@ type = "grpo" # the default
|---|---|---|---|
| `grpo` | policy | `rl` on actions | Standard group-relative RL. |
| `max_rl` | policy | `rl` on actions | MaxRL ([arXiv:2602.02710](https://arxiv.org/abs/2602.02710)): GRPO's centered reward normalized by the group **mean** instead of the standard deviation — the gradient is unbiased for the order-`group_size` truncation of the maximum-likelihood objective, upweighting hard examples like `1/p`. |
| `rae` | policy | `rl` on actions | RAE (SPIRAL, [arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): reward minus a per-agent EMA baseline of that agent's own rewards — the estimator for multi-agent self-play envs, where the group mean would mix the agents' opposite reward scales. See [Self-Play Advantage](#self-play-advantage-rae). |
| `hierarchical_grpo` | policy | `rl` on actions | GRPO for proposer-solver envs. Solvers are compared only with attempts on the same proposed problem; proposers are compared with the other proposals in the group. See [Hierarchical GRPO](#hierarchical-grpo). |
| `opd` | policy | `ref_kl` on actions | On-policy distillation ([Thinking Machines](https://thinkingmachines.ai/blog/on-policy-distillation/)): the policy samples, per-token reverse KL against a reference model as the gradient signal. Needs a `teacher`. |
| `sft` | *(the teacher)* | `ce` on actions | Hard distillation: a frozen model generates rollouts, the policy trains with CE on its tokens. Needs a frozen `sampling.source` (the teacher it samples from). |
| `opsd` | policy | `ref_kl` on actions | SDFT ([arXiv:2601.19897](https://arxiv.org/abs/2601.19897)): the model is its own reference, conditioned on an expert demonstration. The teacher *is* the live policy (the paper's setting, no extra deployment) — no model to configure. |
@@ -96,7 +100,9 @@ Echo also takes an optional user-supplied token filter that narrows the role sel
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
@@ -116,40 +122,44 @@ Both components resolve per environment. Each env inherits `[orchestrator.algo]`
[orchestrator.algo]
type="grpo"
[[orchestrator.train.env]]
name="math"
taskset={id="math-v1"}
harness={id="null",runtime={type="subprocess"}}
# inherits the top-level grpo
[[orchestrator.train.source]]
name="math"# inherits the top-level grpo
env.taskset.id="math"
env.agent.harness.id="null"
env.agent.runtime.type="subprocess"
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name="terminal"
taskset={id="terminal-v1"}
harness={id="bash",runtime={type="subprocess"}}
algo={type="echo"}# this env runs its own algorithm
env.taskset.id="terminal"
env.agent.harness.id="bash"
env.agent.runtime.type="subprocess"
# this env runs its own algorithm
algo.type="echo"
```
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_rl.orchestrator.sampler`) from the `sampling` component — the pool rollouts are generated from, and the home of future sampling strategies like replay buffers or branching — and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `hierarchical_grpo` | `HierarchicalGRPOAlgorithm` | `score_group`: GRPO baseline per episode for solvers, per group for the proposer |
| `opd` | `OPDAlgorithm` | `score_episode`: own-context prefill under the teacher |
| `opsd` | `OPSDAlgorithm` | `score_episode`: demo-conditioned prefill under the live policy |
| `sft` | `SFTDistillAlgorithm` | no credit assignment; CE on sampled tokens |
Each class owns its hooks outright — reading one top to bottom reads the algorithm, and everything on the class is an override point. The two hooks are one scope-and-timing ladder — the wider scope is unlocked by a later barrier, so the two axes coincide. Each is handed the `Rollout` directly — the env's typed trace (`reward`, `nodes`, `num_turns`, ...) with `samples` attached, plus `assign_advantages` to write credit:
Algorithms operate on native verifier artifacts and annotate their message graphs directly:
-`async score_rollout(rollout)` — one rollout, **on arrival** (as it's tokenized, before its group is complete): rollout-local credit (`rollout.assign_advantages(...)`, scalar broadcast or per-token), observation ce weights, **or** model I/O — query a reference pool (e.g. `self.teacher_pool`, connected in `setup()` via `self.connect(...)`, or the live `self.policy_pool` for opsd) and attach per-token results (e.g. teacher logprobs) with bounded concurrency. No siblings. `echo` weights observation tokens here, identifying env-provided observation nodes by their non-sampled status and source step role attribution, applying the optional user filter, and writing the `ce_weights` stream. Model I/O runs *before* the pre-batch filters, so it pays compute on rollouts that may then be filtered out.
-`score_group(group)` — the cohort, **before filtering** (filters read the streams), synchronous: group-relative credit (GRPO/MaxRL baselines). `group` is a list of `Rollout`.
-`async score_episode(episode)` — rollout-local scoring as one episode arrives.
-`async score_group(episodes)` — group-relative scoring after the cohort completes.
The pipeline drives the hooks through two non-virtual methods it never looks inside: `algorithm.finalize_rollout(rollout)` per arrival (rollout-local scoring + reference I/O) and `algorithm.finalize_group(rollouts)` per group (scoring + wire stamping; after this the records are frozen — groups die at stamping). Sample construction (interleaving) is pure pipeline — observation-token provenance is available through structural attribution (`node.sampled`, `node.is_content`) for any algorithm that trains on env-provided tokens.
The pipeline drives these through `finalize_episode` and `finalize_group`. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy pool (`self.policy_pool`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
-`rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the group-relative algorithms (`grpo`, `max_rl`, and `echo`'s action tokens).
-`rl` — the configured RL loss (`[trainer.loss]`): 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`).
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens, so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
### Default RL Loss
### IPO Loss
The default RL loss is a DPPO policy-gradient term combined with a KL regularizer similar to Kimi-K2.5. For each prompt $x_j$ we sample a group of $G$ rollouts $\{y_i\}_{i=1}^G$, score them to get $s_i$, then optimize:
The default RL loss is Importance Policy Optimization (IPO). It combines an importance-weighted policy-gradient term with a squared log-ratio KL regularizer. A symmetric trust region removes tokens whose absolute probability change exceeds $\epsilon$:
$\mu$ is the policy that generated the rollout. $\pi$ is the current trainer policy. $\hat{A}_t$ is the token-level advantage. The trust region uses the sampled token probabilities, not their ratio.
$\mu$ is the policy that generated the rollout (inference), $\pi$ is the current policy (trainer), $\hat{A}_{i,t}$ is the token-level advantage, $\delta$ is the importance-sampling clipping ratio, and $\tau_{KL}$ is the KL temperature. The `min` clamps the importance ratio from above so a stale rollout assigning very low probability to a high-reward token doesn't produce a runaway gradient.
The knobs (under `[trainer.loss]` with `type = "default"`):
| `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. |
Set `[trainer.loss] type = "default"` and configure via the knobs above. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
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
| `rae` | `rl` | Reward minus a per-agent EMA baseline (SPIRAL's role-conditioned advantage estimation) — for multi-agent self-play envs. |
| `hierarchical_grpo` | `rl` | GRPO for proposer-solver envs: solvers are compared within one proposed problem, while proposers are compared across proposals. |
| `echo` | `rl` + `ce` | Group-norm on action tokens, plus weighted CE on env-provided tokens selected by message role (each role's `alpha` is its ECHO λ), optionally narrowed by a user filter. |
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream; `group_size` only fans out sampling. |
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream. |
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` and ship no advantage stream; `group_size` only fans out sampling. |
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` and ship no advantage stream. |
| `sft` | `ce` | Cross-entropy on the sampled tokens. Assigns no advantage — trains on every sampled token. |
### Default Advantage
@@ -297,33 +330,107 @@ type = "grpo"
type="linear"
```
### Hierarchical GRPO
GRPO gives each rollout its reward minus the average reward of comparable rollouts. In an ordinary single-agent group, every rollout answers the same task, so one group average is enough.
A proposer-solver env is different. Starting from one source task, it produces several proposed problems, then runs several solver attempts on each problem:
```text
one source task
├── proposed problem A
│ ├── proposer trace
│ ├── solver attempt 1
│ └── solver attempt 2
└── proposed problem B
├── proposer trace
├── solver attempt 1
└── solver attempt 2
```
The solver attempts for A should not be compared with the solver attempts for B: the two problems may have very different difficulty. Proposer and solver rewards should not be compared either: they measure different jobs.
`hierarchical_grpo` therefore chooses the average separately for each role:
| Trace | Compared with | Why |
|---|---|---|
| Solver | Other solver attempts on the same proposed problem | They attempted the same problem. |
| Proposer | Other proposer traces in the group | They started from the same source task and proposed alternatives. |
For example, if three solvers receive rewards `[1, 1, 0]` on one proposed problem, their average is `2/3` and their advantages are `[1/3, 1/3, -2/3]`. Solver rewards from other proposed problems do not affect those values. The proposers are scored separately according to how useful their problems were for the solvers, then compared with the other proposers in the group.
Configure which roles are compared within a single proposed problem with `episode_agents`. For `proposer-solver`, that role is `solver`:
```toml
[orchestrator.algo]
type="hierarchical_grpo"
episode_agents=["solver"]
[[orchestrator.train.source]]
name="proposer-solver"
group_size=4# proposed problems per source task
env.n=4# solver attempts per proposed problem
env.taskset.id="proposer-solver"
env.proposer.harness.id="null"
env.proposer.runtime.type="subprocess"
env.solver.harness.id="null"
env.solver.runtime.type="subprocess"
```
`group_size` controls how many problems are proposed from each source task. `env.n` controls how many solvers attempt each proposed problem. If a comparison contains only one trace—for example, a solver when `env.n = 1`—its advantage is zero.
This algorithm is accepted only for proposer-solver envs. Use the env's `train_proposer` and `train_solver` settings if you want to train only one role.
### Self-Play Advantage (RAE)
Group-relative baselines assume the group is exchangeable attempts by one agent. A multi-agent self-play env breaks that: one episode yields one trace per agent, all trainable, and in a zero-sum game the rewards sum to ~0 whatever the policy does — the group mean carries no information, and centering against it converts any structural asymmetry (a first-mover edge) into permanent credit for one agent.
`rae` implements SPIRAL's role-conditioned advantage estimation ([arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): each agent keeps an exponential-moving-average baseline of its own rewards, and every trace's advantage is its reward minus its agent's baseline — measured against the *pre-update* baseline (the unbiased order), then folded in at `decay` (SPIRAL's α, default 0.95). The algorithm instance is per-env, so baselines are keyed per (env, agent) — the paper's per (game, role). Advantages are not normalized, and `group_size` is free (RAE needs no sibling rollouts; `group_size = 1` is fine). Baselines live in orchestrator memory and re-warm from 0 over ~`1/(1 − decay)` traces per agent after a restart.
```toml
[orchestrator.algo]
type="rae"
decay=0.95
[[orchestrator.train.source]]
name="kuhn-poker"
env.taskset.id="kuhn-poker"
env.player0.harness.id="null"
env.player0.runtime.type="subprocess"
env.player1.harness.id="null"
env.player1.runtime.type="subprocess"
```
Both of `kuhn-poker`'s agents late-bind to the run's own model — shared-policy self-play against a continuously improving opponent. Pin one agent to a frozen endpoint (`env.player1.model = ...`) for asymmetric play; its traces are marked untrainable by the env and never reach the advantage computation. A single-agent env under `rae` degrades to REINFORCE with an EMA baseline.
### Authoring an Algorithm
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class. The hook receives the group's `Rollout`s (each the env's typed `verifiers.Trace` — turns, tool calls, metadata in `info` — with `samples` attached) and writes credit via `assign_advantages`:
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class:
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick the hook by *when* your signal is ready: `score_rollout` for per-arrival credit or credit that needs a model call (it's `async`),`score_group` for group-relative credit (GRPO/MaxRL). `assign_advantages` takes a scalar (broadcast over the rollout's trainable tokens — the common case) or a full-length per-token list aligned to the concatenated sample token_ids (process rewards, step-level credit; `0.0` off-mask).
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick `score_episode` for rollout-local work or model calls, and`score_group` for group-relative credit. `assign_advantages` takes a scalar or a list aligned to the trace graph's sampled tokens.
Each per-token list must match the rollout's completion-token count exactly — validated loudly when the view writes it. Advantage-based filters and metrics derive from the streams (the zero-advantage filter checks for all-zero streams; logged distributions use per-rollout means). Signals that depend on the live policy's weights (like OPD's reverse KL) cannot be precomputed here; those are reference-scoring algorithms, evaluated in the trainer.
Curriculum admission and metrics can inspect the resulting graph-native streams after group scoring.
### Reference Scoring
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_rollout`: as each rollout arrives they query a reference (the sample's own context for `opd`, the demo-conditioned context for `opsd`) and attach per-token reference logprobs to each sample. Rollouts are consumed serially by the orchestrator's main loop and each carries only a handful of samples, so the in-flight request count is naturally bounded — no explicit concurrency cap:
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_episode`: as each episode arrives they query a reference and attach sampled-token reference logprobs to its graph nodes:
-`opd` — score each sample's own context under the `teacher` (a frozen [model reference](#model-references)) via prefill; fills `ref_logprobs` for the `ref_kl` loss component (on-policy distillation). The `teacher` is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero).
-`opsd` — SDFT: prepend an expert demonstration as a leading system message (`template`, with a `{demonstration}` placeholder) and score the sample under that demo-conditioned context. The sample is scored verbatim (`hint_block + token_ids`, slicing the hint's logprobs back off), so the join is BPE-clean and it's robust to tool/multimodal prompts and any number of turns. The scoring reference *is* the live policy — self-distillation names no teacher. opsd builds its own renderer to tokenize the hint block: the tokenizer is always the live policy's (not configurable — there is no separate model), and only the `renderer` family is settable (defaults to `"auto"`, resolved from the policy tokenizer; set it to match a non-auto policy renderer). The demonstration is read from the example's `info[demo_key]`, falling back to a top-level rollout field of the same name (e.g. `answer`).
@@ -334,34 +441,49 @@ type = "opsd"
demo_key="demonstration"
```
Scoring runs at arrival, *before* the pre-batch filters, so a rollout that is later filtered still cost its reference compute — accepted for the simpler one-rollout-at-a-time shape (advantage-based filters never fire for opd/opsd anyway, since neither assigns an advantage).
Scoring runs before curriculum admission, so a rollout that is later rejected still costs its reference compute.
## Filters
The orchestrator filters samples with no training signal. This includes samples with zero advantage on all RL tokens. Samples that still carry CE or reference-KL components are retained. Filtering an RL token also removes its trainer/inference mismatch-KL contribution.
Filters drop rollouts between scoring and training. Built-ins (composable):
`orchestrator.constant_trainer_batch_size` defaults to `true`. The orchestrator filters samples before they count toward the batch target. It collects replacements, so rollout-based batches contain `orchestrator.batch_size` training traces. Set the option to `false` to filter after collection without replacement. This setting can improve orchestrator throughput, but it produces smaller trainer batches.
| Filter | Effect |
|---|---|
| `gibberish` | Drops rollouts whose mean log-prob fall below a threshold — usually a sign of degenerate output. |
| `repetition` | Drops rollouts with high n-gram repetition. |
| `zero_advantage` | Drops rollouts whose advantage is zero, so the trainer doesn't waste tokens on them. |
## Curricula
The default `[orchestrator]` config registers all three in both filter slots: `post_batch_filters`enforce by default (flagged rollouts are recorded but not shipped to the trainer), while `pre_batch_filters` run in monitor mode (`enforce = false`); flip `enforce = true` there to drop matching rollouts before they consume a slot in the batch. Setting a slot replaces its defaults wholesale:
Each training source has a `Curriculum` composed from one `TaskSampler`and any number of named `AdmissionGate`s. The sampler chooses tasks and observes every finalized `list[vf.Episode]`; each gate inspects the same native episodes. The group trains only if every gate admits it. Rejected groups remain observable while the orchestrator samples again to fill the batch.
Samplers and gates can be stateful. Their `state_dict`, `load_state_dict`, and `metrics` methods are included in orchestrator checkpoints and logged under `curriculum/<env>/`.
Three small implementations are included:
-`StandardSampler` is the default: it advances the task iterator and cycles finite tasksets in source order.
-`DifficultyPoolSampler` samples finite tasksets with replacement and tracks each task's latest valid mean group reward. Each named pool has an inclusive reward threshold and a relative per-task sampling weight; weight `0` disables sampling from that pool. Unseen tasks use neutral weight `1.0`, so pool observations affect sampling immediately without waiting for a full taskset pass.
-`AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in token filter, it can reject a configurable advantage range. Groups without an advantage stream are admitted.
Filtered rollouts still appear in W&B distributions, just not in the trainer batch — useful for spotting whether filtering is doing its job.
## Multi-Turn Trajectories
Multi-turn rollouts (tool use, browser environments, long conversations) used to be stitched into a single fake "single-turn" sample, which silently corrupted the importance ratio when chat templates didn't roundtrip. Since [`verifiers` v0.1.8](https://github.com/PrimeIntellect-ai/verifiers/releases/tag/v0.1.8), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
For multi-turn rollouts (tool use, browser environments, long conversations), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions) that aren't surfaced here.
## Table of Contents
@@ -17,7 +17,7 @@ Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeInt
@@ -50,18 +50,18 @@ CLI flags mirror the TOML tree using dots:
--max-steps 50# top-level
--model.name Qwen/Qwen3-4B # nested
--trainer.optim.lr 1e-5 # double-nested
--inference.parallel.tp4
--inference.vllm.tensor-parallel-size4
```
> Field names are snake_case in TOML (`max_model_len`) and kebab-case on the CLI (`--max-model-len`).
> Renamed fields keep their old name as a validation alias — e.g. `rollouts_per_example` is still accepted in TOML and CLI after being renamed to `group_size`. Mixing the two names across sources is safe.
> A renamed field keeps no alias for its old name: the old spelling fails as an unknown key rather than being silently translated.
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables (e.g. environments), see [Environments](#environments-orchestratortrainenv).
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables, see [Environments](#environments).
### Dicts
CLI takes a JSON literal. TOML uses a table or inline-table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
CLI takes a JSON literal. TOML uses a table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
```bash
uv run rl @ rl.toml --orchestrator.train.env.0.args \
uv run rl @ rl.toml --orchestrator.train.source.0.args \
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
`ratio` is a training-source field: it defaults to `1` (equal weight per env), and values are relative weights normalized to probabilities across envs. Eval sources of a training run carry `interval` instead, the step interval at which they fire (inherited from the group-level `interval` when unset); a standalone eval has neither.
Everything environment lives under the `env` block (verifiers' `[env]` shape): `env.taskset` configures the v1 taskset, and each agent is a field on the env — `env.agent.harness` selects how the single-agent env's tasks are run, and per-run caps are per-agent (`env.agent.max_turns`, `env.agent.timeout`, `env.agent.max_output_tokens`). A multi-agent env declares its own seats (`env.<role>.*`).
The `rl` launcher applies these the same way in both single-node and multi-node (SLURM) runs. Precedence, low to high:
@@ -219,11 +225,11 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
**Advanced** (32–2048 GPUs, SLURM):
- [**Qwen3-30B-A3B**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-30b-a3b) — `Qwen3-30B-A3B` on math, SWE, and tool use.
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal.
- [**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
@@ -231,17 +237,24 @@ Start from a shipped base config, override two fields on the CLI, and dry-run:
Each per-process TOML reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/configs/trainer.toml`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
Each per-process JSON contains the final, validated configuration that the run
uses. This is also what each standalone process reads. For example, the trainer
reads `configs/latest/resolved/trainer.json`.
`configs/latest/command.txt` records the shell-safe launch command and its CLI
overrides. Each launch also remains under `configs/attempt_<n>/`. To compare
configs, dry-run a known-good base and your overlay. Then diff the two attempts.
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
| Workflow | Trigger | What runs | Where |
|---|---|---|---|
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`,`reverse_text_multi_run`,`reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
@@ -109,7 +109,7 @@ uv run sft \
--data.name PrimeIntellect/Reverse-Text-SFT \
--max_steps 200\
--optim.lr 1e-4 \
--ckpt.weights
--ckpt
```
Then run the full RL stack on reverse-text:
@@ -118,8 +118,8 @@ Then run the full RL stack on reverse-text:
uv run rl @ configs/ci/integration/reverse-text-moe/start.toml \
--model.name samsja/mini-glm-moe \
--trainer.model.impl custom \
--inference.gpu-memory-utilization 0.7 \
--inference.model.max-model-len 2048
--inference.vllm.gpu-memory-utilization 0.7 \
--inference.vllm.max-model-len 2048
```
What to look for:
@@ -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).
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:
Single-source shorthands: `<taskset-id>` names the run's only source, `--env.<field> <value>` sets a field of that source's env block (`--env.agent.harness.id bash`, `--env.taskset.tasks '["fix-git"]'`), `-n`/`-r` set `num_examples`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). The shorthands cannot be combined with a TOML that defines `[[source]]` blocks. `uv run eval -h` lists them.
Against a local vLLM deployment, set `min_inflight < max_inflight` in `[concurrency]` to dynamically adjust the number of concurrent episodes for maximum throughput. An external API exposes no vLLM `/metrics` to adapt to, so pin the concurrency there (`-c N`, i.e. `min_inflight = max_inflight`).
## Configuration
Multi-source runs use a TOML (`EvalConfig` in `packages/prime-rl-configs/src/prime_rl/configs/eval.py`). The eval block is flattened to the top level — `[[source]]`, `[client]`, `[concurrency]`, `[sampling]`, `num_examples`, `group_size` — and each source takes the same `env` block as `[[orchestrator.eval.source]]`:
```toml
model="Qwen/Qwen3-4B"
num_examples=32
group_size=4
[client]
base_url="http://localhost:8000/v1"
[concurrency]# adaptive against a local vLLM deployment
min_inflight=8
max_inflight=256
[sampling]
max_completion_tokens=2048
[[source]]
env.taskset.id="gsm8k"
env.agent.harness.id="bash"
[[source]]
env.taskset.id="aime25"
env.agent.harness.id="null"
env.agent.runtime.type="subprocess"
```
Per-source `num_examples`, `group_size` and `sampling` override the top-level defaults. Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
## Resume
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: the episodes that landed rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch) and only the rollouts still owed run. Errored episodes and the ones the interruption cut off run again.
```bash
uv run eval @ eval.toml --run.name my-eval
# <interrupted>
uv run eval @ eval.toml --run.name my-eval --resume
```
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
A landed episode counts toward the task with its `task.key`, so `num_examples` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The model, the sampling and each source's env must match the config the landed episodes were measured with (kept beside them in `monitors/file/eval.json`); a resume that changes them stops with the differing config paths. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
## Monitors
Monitors receive the run's metrics and episodes through one abstraction. The file monitor is on by default; `--monitors.wandb` logs the run to Weights & Biases; `--monitors.prime` streams it to the Prime platform.
### File
The file monitor writes the run's metrics and trace stream under `output_dir / run.name / monitors/file/` and feeds the local [dashboard](training.md#dashboard). Env servers stream every rollout to the eval process as it happens: the trace's header when it is minted, then one delta per committed turn (the new messages and the model call behind them), per phase change (boot, setup, agent, finalize, scoring), and a preview of each model request's uncommitted messages, so a tool result shows the moment the model is asked about it rather than with the reply. The file monitor appends those deltas to `monitors/file/traces/live/<trace_id>.jsonl` and deletes the file when the episode lands in the finished trace stream, so that directory is exactly the live set and finished traces stay where they always were. The dashboard's traces tab shows live rollouts in the episode table itself: a pulsing dot in the `#` cell marks the row, a phase badge says where the rollout is (boot, setup, running, finalize, scoring), the `dispatched → arrived` column shows the dispatch time with the elapsed time in brackets, and the turn, token and branch counts grow as deltas land. The status filter toggles live and completed rows, and a live row opens in the trace viewer, which follows the rollout turn by turn (the transcript stays pinned to the newest turn until you scroll up; folded entries stay folded; the pending messages of the request in flight render dimmed with an `awaiting model` chip). The table and an open live trace poll once a second and transfer nothing while the rollout is unchanged. The progress line in `eval.log` counts the live rollouts by phase (`2 inflight episodes ... - boot 1 · running 1`). Read a live trace from a shell with `uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`. The same stream exists for RL runs, covering train and online-eval rollouts alike.
The dashboard's overview tab reads the trace stream directly. It shows one env at a time; the filter menu picks the env and whether errored episodes join the distributions. A block bar has one cell per expected episode: landed episodes (errored ones in red; click one to open it), live rollouts as pulsing outlines (click one to follow it), and the rest empty, with the percentage beside it. The expected count is what the eval runner wrote to `monitors/file/plan.json` when it counted the epoch's tasks. Below the bar, a summary row gives the headline numbers: avg@k and pass@k, the error and truncation rates (yellow past 10%, red past 50%), mean turns and branches in one tile, mean episode time and tokens, and the total cost when the run has costs; hover a tile for its distribution. The env's own rewards and metrics follow, a beeswarm pane each, resizable like the training charts. The usage section is one pane splitting each episode's tokens into input and output, and the timing section is the same pane over the phases of a rollout (boot, setup, model, harness, finalize, scoring, and `other` for wall time no phase accounts for): an icicle bar shows the mean split, one strip per episode below shows the split per rollout, and a legend sits above. Hovering a phase highlights it across the pane; the strips show 40 episodes by default and all of them on `show all`. A metric every episode shares appears as a chip instead of a pane, and a metric with only a few distinct values, such as a binary reward, as a counted dot plot with the count and share of each value. Every dot is an episode (or a task): hover it for its value and click it to open the trace; hover the pane's background for the summary (min, p10, median, p90, max), with a faint boxplot behind the dots. Errored episodes stay out of the distributions until the filter includes them, where they read red. The metrics tab charts every key of the run's `metrics.jsonl`: the epoch's `eval/<env>/…` summaries and the time-keyed `inference/` and `concurrency/` rows the runner samples while the epoch is in flight.
### Prime
`--monitors.prime` streams each source's epoch as an evaluation on the Prime platform:
The monitor opens one platform evaluation per env when its epoch starts, streams every episode to it as it lands, and closes it with the epoch's aggregates. The run leaves its platform identity in `monitors/prime/run.json` (the training run's id and URL, or one entry per eval epoch), and the dashboard's top bar shows a `view on platform` link from the moment the evaluation opens: a direct link for a training run or a single evaluation, a menu when a run has several.
## Metrics
Eval metrics mirror the training rollout hierarchy under the `eval/<env>` scope:
| Metric | Reading |
|---|---|
| `eval/<env>/all/<agent>/reward/mean` | mean reward over the epoch |
| `eval/<env>/all/<agent>/is_truncated/mean` | share of rollouts cut by the length limit |
| `eval/<env>/all/<agent>/has_error/mean` | share of rollouts that raised |
| `eval/<env>/all/seq_len/mean` | mean episode length in tokens |
Task-specific env metrics (e.g. `correct_answer`, `format`) appear under the same prefix. The console summary line per source (`Evaluated <env> ... Reward 0.8125`) reports the epoch mean.
@@ -30,7 +31,9 @@ We support 3 distinct deployment shapes:
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `backend_port`, and a `[...deployment.router]` block, etc.
Every deployment shape has the same client-facing layout: a single global router listens on `inference.server.port` and fronts all vLLM engines, which listen on `inference.backend_port` (+ rank offset). Clients always talk to one URL, regardless of how many engines run behind it.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape and topology knobs such as `num_nodes` and `num_replicas`.
```toml
[inference.deployment]
@@ -40,7 +43,7 @@ type = "single_node" # or "multi_node" or "disaggregated"
To configure the inference server, you can use the `InferenceConfig` field. This is a config-field that allows you to set the inference server-specific knobs. Most of these are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
```toml
[inference]
[inference.vllm]
model="PrimeIntellect/INTELLECT-3"
...
```
@@ -56,23 +59,23 @@ The single-node deployment is the default deployment shape. It runs the inferenc
type="single_node"
```
The launcher starts a `vllm-router` on `inference.server.port` (default `8000`) fronting the vLLM engine on `inference.backend_port` (default `8100`). Clients connect to the router URL; admin operations (weight updates, health checks) bypass the router and hit the engine port directly — the RL entrypoint wires `orchestrator.model.client.admin_base_url` accordingly.
This deployment shape runs the inference server on a single node, if configured with NVLink enabled, it allows you more freedom in terms of parallelism configurations.
```toml
[inference]
[inference.vllm]
enable_expert_parallel=true# defaults to False
[inference.parallel]
tp=2
dp=4
tensor_parallel_size=2
data_parallel_size=4
[inference.deployment]
type="single_node"
```
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required `orchestrator.max_inflight_requests`. Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required concurrency (see [Adaptive Concurrency](#adaptive-concurrency)). Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.enable_expert_parallel` or `inference.parallel.tp` to maximize the available GPU memory.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.vllm.enable_expert_parallel` or `inference.vllm.tensor_parallel_size` to maximize the available GPU memory.
You can also increase the available KV cache memory by enabling `inference.kv_cache_offload`. More details in the [Advanced Configuration](#advanced-configuration) section.
@@ -82,7 +85,7 @@ You can also increase the available KV cache memory by enabling `inference.kv_ca
This deployment shape branches into 2 sub-shapes:
- [Multi-replica](#multi-replica) - Runs the inference server on multiple nodes, but each node runs an independent vLLM replica. You can think of this as a for-loop over single-node deployments.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.vllm.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
### Multi-replica
@@ -94,35 +97,31 @@ Parallelism configuration is the same as the single-node deployment. The shape i
type="multi_node"
num_nodes=2
[inference]
[inference.vllm]
model="PrimeIntellect/INTELLECT-3"
[inference.parallel]
tp=2
dp=4
tensor_parallel_size=2
data_parallel_size=4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a router instance running on the same node as the 1st replica — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[...deployment.router]` block. You can read more about the supported routing options in the [router](#router) section.
This configuration will run 2 independent vLLM replicas, each with `tensor_parallel_size=2` and `data_parallel_size=4`. Routing is handled by a single global router running on the first inference node, fronting the per-rank endpoints of all replicas — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[inference.router]` block. You can read more about the supported routing options in the [router](#router) section.
### Wide-EP
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.enable_expert_parallel = true`.
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.vllm.enable_expert_parallel = true`.
```toml
[inference.deployment]
type="multi_node"
num_nodes=2
[inference]
[inference.vllm]
model="PrimeIntellect/INTELLECT-3"
enable_expert_parallel=true
[inference.parallel]
tp=2
dp=8
tensor_parallel_size=2
data_parallel_size=8
```
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tp = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tensor_parallel_size = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
## P/D Disaggregation
@@ -160,45 +159,57 @@ num_train_nodes = 4
num_infer_replicas=3
```
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes and start 3 separate router instances.
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes, fronted by the single global router.
## Router
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
Every deployment fronts its vLLM engines with a single global router — it listens on `inference.server.port` and is the one URL clients connect to. The backend is configured via a discriminated `[inference.router]` block (`type = "vllm-router" | "llm-d"`):
```toml
[inference.deployment.router]# or [deployment.router] for the standalone inference entrypoint
[inference.router]# or [router] for the standalone inference entrypoint
type="llm-d"# "vllm-router" (default) or "llm-d"
# llm-d-only knobs (all optional):
scorers={"prefix-cache-scorer"=3.0,"active-request-scorer"=2.0}# base, applied to every profile
prefill_scorer_overrides={"queue-scorer"=2.0,"kv-cache-utilization-scorer"=2.0}# merged onto the P/D prefill profile
decode_scorer_overrides={}# merged onto the P/D decode profile
non_cached_tokens=16# below this many non-cached prompt tokens, skip remote prefill (P/D)
non_cached_tokens=16# llm-donly: below this many non-cached prompt tokens, skip remote prefill (P/D)
# llm-d only: base scorer weights, applied to every profile
[inference.router.scorers]
"prefix-cache-scorer"=3.0
"active-request-scorer"=2.0
# llm-d only: merged onto the P/D prefill profile (decode_scorer_overrides for decode)
[inference.router.prefill_scorer_overrides]
"queue-scorer"=2.0
"kv-cache-utilization-scorer"=2.0
```
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy. Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`. The only backend supported for single-node (local) deployments.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy (multi-node / disaggregated SLURM deployments only). Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
Both backends support the 2 most important things:
- Request routing - KV cache re-use and balanced routing
- 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 - this works by hashing a request header to determine where to route the request to. You can configure what to hash by setting
`orchestrator.model.client.extra_headers_from_state` to the header the `router` expects to be set.
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.
We set it to a sensible default, that works with all verifiers environments.
X-Session-ID="trajectory_id"# this is the default - each rollout has a unique trajectory_id and router expects X-Session-ID
```
-`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.
## Adaptive Concurrency
The orchestrator continuously sizes how many episodes run against the inference engines at once. A static cap cannot be right: too low starves the engines, too high crosses into KV thrash — the engines evict prefix cache, re-prefill the evicted work, and throughput collapses. The optimal value depends on the model, the deployment, and the workload's episode lengths, and it moves as training changes the policy.
The controller's idea is to treat the engines as ground truth and probe, instead of modeling episode cost: while the engines show headroom, admit a little more; when they show pressure, back off. Three behaviors, in increasing severity:
- **Grow**: while the engines look healthy and the current cap is fully used, raise it multiplicatively. Growth is clocked by the pipeline itself — the cap rises by a fixed factor each time the in-flight pool has turned over once — so a fast single-turn workload ramps in seconds while a slow agentic workload ramps at its own pace, with no tuning per workload.
- **Trim**: episodes grow their context *while running*, so a pool that fit comfortably an hour ago can outgrow memory without a single new admission. When KV usage nears the ceiling, the controller first lowers the cap and lets completions drain the pool naturally (soft — no work lost); only if usage keeps climbing despite the closed gate does it also cancel the youngest episodes (hard — least work lost).
- **Cut**: when the engines are demonstrably overloaded — requests being preempted, or piling up in the waiting queue — cut the pool hard, cancel the excess, and hold further cuts until the system settles.
The cap starts from a safe bound derived from the engines (KV capacity divided by the maximum context length), or from `initial_inflight` when a good value is known, and always stays within `[min_inflight, max_inflight]`.
## Advanced Configuration
### KV Cache Offload
@@ -251,34 +262,57 @@ For configuring various knobs with environment variables, we enable you to confi
These are role-specific and layer on top of [`env_vars`](configuration.md#environment-variables) shared by all inference processes regardless of role.
### Other vLLM features
We support various other vLLM features. Some of those, such as `enable_dbo`, `enable_eplb` are exposed as a top-level config fields. For those that are not, you can configure them by setting `inference.vllm_extra` to the desired value.
The `[inference.vllm]` section is a pass-through: every key is forwarded to the vLLM server under vLLM's own argument name, whether prime-rl types it or not. Anything `vllm serve` accepts can be set here.
```toml
[inference.vllm_extra]
[inference.vllm]
headless=true
max_num_seqs=256
```
On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (or `--vllm.max-num-seqs 256` for the standalone inference entrypoint); dict-valued arguments take a JSON string, e.g. `--vllm.compilation-config '{"cudagraph_mode": "NONE"}'`.
### Router Replay
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.enable_return_routed_experts = true`.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. 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.
```toml
[trainer]
enable_router_replay=true# this will also auto-set the inference.enable_return_routed_experts = true
enable_router_replay=true# this will also auto-set inference.vllm.enable_return_routed_experts = true
[inference]
[inference.vllm]
enable_return_routed_experts=true
```
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend increasing `orchestrator.*.env.num_workers` to allow for more parallelization on the verifiers side.
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
### Sampling Replay
Truncated sampling (`top_p < 1`, `top_k`) renormalizes the sampling distribution over a sampling mask of surviving token ids. The rollout logprobs reflect that (`logprobs_mode = "processed_logprobs"`), so the trainer must renormalize over the same mask — otherwise every importance ratio is biased and training collapses (DeepSeek V3.2's "Keep Sampling Mask", [arXiv:2512.02556](https://arxiv.org/abs/2512.02556) §3.1; Cognition's [SWE-1.7 post](https://cognition.com/blog/swe-1-7)). prime-rl handles this automatically: vLLM records the sampling mask at sampling time (`--return-sampling-mask`, native since vLLM 0.28) and the trainer renormalizes its logprobs over it.
```toml
[orchestrator.train.sampling]
top_p=0.95
top_k=512# optional, defaults to 512 under truncation (bounds each sampling mask)
```
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`; Gemma-family (softcapped) lm_heads fail loudly. Frozen-source envs are exempt.
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
@@ -10,9 +10,9 @@ A `prime-rl` RL run is three cooperating processes:
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/inference/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). We are trying to stay up-to-date with the latest vLLM features, you can read more about the supported features and deployment options in the dedicated [inference documentation](inference.md).
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, and LoRA. You can read more in the dedicated [training documentation](training.md).
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses ZMQ, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap the rollout link to the local filesystem (`rollout_transport.type = "filesystem"`) if you want rollouts persisted to disk. See [Scaling](scaling.md) for the deployment options.
## Installation
@@ -20,7 +20,7 @@ The three processes communicate through configurable transports — by default t
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`research-environments`](https://github.com/PrimeIntellect-ai/research-environments) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`prime-envs`](https://github.com/PrimeIntellect-ai/prime-envs) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
You need at least one NVIDIA GPU (RTX 3090/4090/5090, A100, H100, H200, or B200). Single-GPU runs are supported for debugging; production RL is typically 1× inference node + 1+ trainer nodes.
@@ -32,7 +32,7 @@ Train an SFT-warmed `Qwen3-0.6B` on the `reverse-text` task — the env is bundl
uv run rl @ examples/basic/reverse-text/rl.toml
```
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into `outputs/logs/{trainer,orchestrator,inference}.log`. Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes and final HF-compatible weights land at `outputs/weights/step_20`.
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into the run directory at `outputs/<run_name>/logs/{trainer,orchestrator,inference}.log` (`run.name` auto-generates as `<envs>--<model>--<short-id>`; pass `--run.name <name>` for a predictable path). Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes with a final DCP checkpoint at `outputs/<run_name>/checkpoints/step_20`.
## Documentation
@@ -41,5 +41,5 @@ The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into
- **[Inference](inference.md)** — vLLM-backed server (or fleet) holding the current policy.
- **[Scaling](scaling.md)** — Single-GPU through multi-node clusters via FSDP / EP / CP and SLURM.
@@ -38,24 +38,25 @@ The `rl`, `sft`, and `inference` entrypoints all accept a `[deployment]` block (
uv run rl @ rl.toml \
--deployment.num-infer-gpus 6\
--deployment.num-train-gpus 2\
--inference.parallel.dp6
--inference.vllm.data-parallel-size6
```
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
For quick A/B ablations on the same node, run two RL instances side-by-side in separate tmux sessions, each pinned to half the GPUs and a separate inference port:
For quick A/B ablations on the same node, run two RL instances side-by-side in separate shells, each pinned to half the GPUs and a separate inference port, and track both in one dashboard:
```bash
# session 1, GPUs 0–1, default port 8000
bash scripts/tmux.sh -s exp1 -o outputs/exp1
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --output-dir outputs/exp1
# shell 1, GPUs 0–1, default port 8000
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --run.name exp1
`--local-ranks-filter 0` keeps console output to rank 0 only; per-rank stdout/stderr is still captured in `<output_dir>/logs/trainer/torchrun/`.
`--local-ranks-filter 0` keeps console output to rank 0 only; per-rank stdout/stderr is still captured in `<run_dir>/logs/latest/trainer/torchrun/`.
### Multi-Node
@@ -86,7 +87,8 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
| `trainer.model.dp_replicate` | Number of dimensions to **replicate** instead of shard. Set to 2 to run 2-way DP replication × FSDP sharding within each replica — useful for very large clusters where pure FSDP communication dominates. |
| `trainer.model.reshard_after_forward` | If `true` (default), parameters are resharded after the forward pass to free memory; the backward pass re-gathers. Set `false` to keep params resident — faster but more memory. |
| `trainer.model.fsdp_cpu_offload` | Offload params + grads + optimizer state to CPU. Big memory win, large throughput hit. |
| `trainer.model.optim_cpu_offload` | Offload only optimizer state. Mid-ground — small throughput cost, decent memory savings, especially at low GPU count. |
| `trainer.model.optim_cpu_offload` | Offload optimizer state to CPU between steps. Enabled by default. |
| `trainer.model.full_offload` | Offload gradients, FP32 masters, and optimizer state and run the optimizer (AdamW or SignSGD) on CPU during backward. Disabled by default. |
### Expert Parallelism
@@ -97,17 +99,20 @@ EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP
```toml
[trainer.model]
impl="custom"
ep=8# explicit EP degree; must divide num_experts
ep_comm_backend="torch"# or "deepep"
ep=8# explicit EP degree; must divide num_experts
[trainer.model.moe.dispatch]
type="torch"
transport="bf16"
```
`ep_comm_backend = "deepep"` uses DeepEP's custom dispatch/combine kernels for speed, with two extra knobs (`deepep_num_sms`, `deepep_token_chunk_size`) — tune on your hardware.
For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_size` in the same dispatch table. Routed-expert precision is selected separately with `[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, or `mxfp8`).
### Context Parallelism
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
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`.
| `trainer.model.ac.mode = "selective"` | medium | small |
| `trainer.model.ac_offloading` | extra | a bit more |
AC and AC offloading are enabled by default (full mode). For the best memory/throughput tradeoff, switch to selective AC (custom impl only):
AC and AC offloading are enabled by default (full mode). Both AC modes retain stateful MoE routing updates and DeepEP communication that cannot safely replay. Selective AC uses the same transformer-block boundaries and additionally retains distributed communication, expensive matrix multiplications, grouped GEMMs, and supported attention kernels:
```toml
[trainer.model.ac]
mode="selective"
targets=["norm","attn_proj"]# see Reference for the full list per architecture
```
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
Set `targets` to operator names (for example, `"aten::mm"`) or namespaces (for example, `"prime_rl_collectives"`) to replace the default selective targets. Correctness-required operations remain retained.
Activation offloading still applies to tensors saved by autograd, but tensors retained by the checkpoint policy remain on the accelerator.
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only losing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
### Optimizer Offloading
Offloading optimizer states to CPU is enabled by default (`optim_cpu_offload = true`) — a near-free memory win at low GPU counts:
```toml
[trainer.model]
optim_cpu_offload=true# already the default
```
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training) — set `optim_cpu_offload = false` for multi-run. Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`. For full offload, set `model.optim_cpu_offload = false` and `model.full_offload = true`; this keeps BF16 compute weights on GPU and runs CPU optimizer chunks as gradients become ready during backward. Full offload only supports AdamW and SignSGD (`optim.type = "sign_sgd"`) and disables gradient clipping. SignSGD is stateless, so it halves the host RAM footprint versus AdamW (8 instead of 16 bytes per parameter: FP32 master + FP32 accumulated gradient, no moments).
### LM Head Chunking
@@ -199,9 +200,11 @@ Launch:
```bash
uv run rl @ base_rl.toml @ my_slurm.toml # submits via sbatch
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script + resolved config, exits
Every SLURM entrypoint stores its generated scripts and coordination files under `<run_dir>/launcher/`. SLURM stdout and stderr go to `launcher/logs/`. Local launches do not create `launcher/`.
### `[deployment]` Block
`[deployment]` is a discriminated union picked by `type` — `single_node` or `multi_node` for RL/SFT, with an extra disaggregated variant for inference. RL multi-node:
@@ -220,7 +223,8 @@ SFT multi-node:
```toml
[deployment]
type="multi_node"
num_nodes=2
num_train_nodes=2
num_infer_nodes=1# required only for online evals
gpus_per_node=8
```
@@ -228,10 +232,29 @@ 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), and the launcher prints one URL per node. Front the URLs with a router or point clients at any of them.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
### NIXL weight broadcast
Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transfer. Before the first SLURM run, install the NIXL/UCX build and the ModelExpress service binaries on the shared filesystem:
The generated job starts a job-scoped ModelExpress server and Redis backend on the trainer head node and passes that address to every component. To use an existing service, set `slurm.launch_modelexpress = false` and configure `weight_broadcast.host` and `weight_broadcast.port`.
The launcher requires the CUDA and InfiniBand transports from `third_party/ucx`. Each NIXL process selects the active InfiniBand port nearest its GPU; an explicitly configured `UCX_NET_DEVICES` takes precedence. Inference ranks start their pulls at different trainer ranks so concurrent workers distribute traffic across all available source rails.
ModelExpress exchanges peer metadata during startup. Weight updates reuse prepared NIXL requests, post every trainer-rank read in a transfer group concurrently, and use versioned NIXL notifications for source readiness and buffer credits.
By default, the trainer and inference worker each allocate one transfer arena. Set `weight_broadcast.overlap_transfer_and_replay = true` to allocate two arenas on both sides and replay one weight group while receiving the next. The additional arena is the size of the largest transfer group per GPU; allocation errors are reported instead of silently disabling overlap.
### Custom Templates
@@ -245,22 +268,14 @@ The default templates live under [`src/prime_rl/templates/`](https://github.com/
## Benchmarking
Every entrypoint supports a `--bench` flag that runs a few warm-up + measurement steps with fake data and prints a rich-formatted throughput / MFU table:
To benchmark a parallelism config before committing a multi-day run, run a short training with fake data and a step cap, and read throughput / MFU / step time / peak memory from the logs:
```bash
# SFT trainer alone
uv run sft @ sft.toml --bench
uv run sft ... --data.type fake --data.length variable --bench # variable-length fake data
uv run sft @ sft.toml --data.type fake --max-steps 4
# RL trainer alone (no inference involved)
uv run trainer @ train.toml --data.fake --bench
# Inference alone — start the server normally, then bench the orchestrator
uv run inference @ infer.toml
uv run orchestrator @ orch.toml --bench
# Full RL stack (trainer with fake data, inference with real data from orchestrator)
uv run rl @ rl.toml --bench
uv run trainer @ train.toml --data.fake --max-steps 4
```
Persist results with`--bench.output-json`. Use this to compare parallelism configs before committing a multi-day run.
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes`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.
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).
@@ -36,7 +36,9 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer + inference. |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
| `uv run 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
@@ -57,11 +59,12 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| Knob | What it does |
|---|---|
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.constant_trainer_batch_size` | Keep trainer batches constant when samples have no training signal, such as zero advantage on all tokens. Enabled by default. Disable it for faster collection with variable trainer batch sizes. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | How many distinct policies may have contributed to one rollout before it's discarded (default 8). The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `errored_rollouts` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.env]]` | Training environments. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Environments](configuration.md#environments-orchestratortrainenv). |
| `[[orchestrator.eval.env]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`,`rae`, `hierarchical_grpo`,`opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
**Monitoring:**
@@ -69,17 +72,18 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|---|---|
| `log.level` | Process log level for trainer + orchestrator (`info` default; falls back to `$PRIME_LOG_LEVEL`). Set per-process via `trainer.log.level` / `orchestrator.log.level`, or globally on the `rl` entrypoint to propagate to both. |
| `orchestrator.log.vf_level` | Env-worker / [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) log level (`info` default; `debug` is noisy but useful for env debugging). |
| `--monitors.prime` | Stream metrics and episodes to the Prime Intellect platform (Prime Lab). See [Platform monitoring](#platform-monitoring). |
**Run management:**
| Knob | What it does |
|---|---|
| `--clean-output-dir` | Wipe `<output_dir>` before starting. Useful when re-running an experiment with the same name during iteration. |
| `--output-dir outputs/<name>` | Per-run output directory. Always set this when running more than one experiment in parallel. |
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). Defaults to `$PRL_OUTPUT_DIR` if set, else `outputs`. |
| `--run.name <name>` | Run name, also the run directory name under `<output_dir>` (override the directory separately via `--run.dir`). Auto-generated as `<envs>--<model>--<short-id>` when unset, so every launch gets a fresh, readable run directory. Set an explicit name for a predictable path — required to resume the run later. |
| `--clean` | Wipe the run directory before starting. Useful when re-running a named run during iteration. |
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
| `--dry-run` | Resolve + validate the full config, write per-process TOMLs to `<output_dir>/configs/`, and exit without launching. The fastest way to debug a misbehaving config. |
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/latest/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
### Algorithms
@@ -89,6 +93,8 @@ The RL entrypoint supports several training algorithms, switched via `[orchestra
|---|---|---|
| `grpo` (default) | None | Standard group-relative RL |
| `rae` | None | [SPIRAL](https://arxiv.org/abs/2506.24119)'s role-conditioned advantage estimation: reward minus a per-agent EMA baseline, for multi-agent self-play envs (e.g. `kuhn-poker`) |
| `hierarchical_grpo` | None | GRPO for proposer-solver envs: compare solvers only with attempts on the same proposed problem, and compare proposers with the other proposals in the group |
| `opd` | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): the policy generates rollouts, the trainer minimizes per-token reverse KL to a reference model |
| `sft` | Required, any OpenAI-compatible endpoint | Hard-distill: a frozen model generates rollouts, the policy trains on its tokens |
| `opsd` | None — the live policy is its own reference (no deployment) | [SDFT](https://arxiv.org/abs/2601.19897): the model is its own reference conditioned on expert demonstrations |
@@ -100,7 +106,7 @@ Frozen models are declared inline on the algorithm, named where the model is use
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name <frozen-model> --server.port 8001
--vllm.model <frozen-model> --server.port 8001
```
The standalone `uv run sft` entrypoint is the more traditional SFT path — pure dataset-based, no orchestrator. Use the `sft` algorithm only when you want a frozen model to generate the supervision on the fly.
@@ -121,7 +127,7 @@ Pulled from the console logs and mirrored to W&B.
-`mismatch_kl/{all,env}/{mean,std,max}` — KL between trainer's current policy and the (older) inference policy that generated the rollouts. A sustained, growing mean is the early-warning sign for off-policy collapse.
-`entropy/{all,env}/mean` — too low means mode-collapse; too high means the model isn't committing.
-`masked_advantage_{positive,negative}/mean` — fraction of DPPO-masked tokens, split by sign.
-`is_masked/mean` — fraction of tokens masked by the IPO trust region.
-`optim/grad_norm` — spikes precede divergence; check the loss config or lower the LR.
The trainer warns when batch wait time exceeds active trainer time. Add inference nodes when this warning persists. The orchestrator warns when policy wait time exceeds active orchestrator time. Add trainer nodes when this warning persists. The orchestrator also warns when it discards more than half of an episode window. This warning reports stale, errored, and no-signal counts.
## SFT Trainer
@@ -167,11 +175,54 @@ See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectorie
The minimal SFT run trains `Qwen3-0.6B` on the `reverse-text` SFT dataset:
```bash
uv run sft @ examples/basic/reverse-text/sft.toml --wandb
uv run sft @ examples/basic/reverse-text/sft.toml --monitors.wandb
```
Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manages this for you — see [Scaling § SFT and Torchrun](scaling.md#sft-and-torchrun) for non-default layouts; multi-node SFT goes through [SLURM](scaling.md#slurm)).
### Online Evals
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `num_examples` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
```toml
[eval]
interval=25
num_examples=32
[[eval.source]]
name="reverse-text"
env.taskset.id="reverse-text"
env.agent.harness.id="null"
env.agent.runtime.type="subprocess"
[inference]
[deployment]
num_train_gpus=1# trainer
num_infer_gpus=1# inference
```
The launcher starts the inference server, one env server per eval source, and an 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 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 + online evals
[inference.vllm]
tensor_parallel_size=8
[slurm]
job_name="my-run"
```
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
| Knob | What it controls |
@@ -181,6 +232,7 @@ Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manag
| `data.seq_len` | Per-sample sequence length |
| `loss_mask.*` | Which roles contribute to loss (system / user / assistant / tool). |
| `val.interval` | Run validation every N steps; `val.data` mirrors `data` |
| `eval.interval` | Run online evals every N steps; see [Online Evals](#online-evals) |
### Important Metrics
@@ -188,15 +240,16 @@ Pulled from the console log and mirrored to W&B.
**Progress and loss:**
-`loss/mean` — main signal. Should decrease through the run.
-`val/loss` — validation loss when `[val]` is set, logged every `val.interval` steps.
-`loss/mean`, `loss/perplexity` — main signal. Should decrease through the run.
-`val/loss`, `val/perplexity` — validation metrics when `[val]` is set, logged every `val.interval` steps.
-`eval/{env}/...` — online eval metrics when `[eval]` is set, logged at each evaluated checkpoint step.
Re-run the same launch command and pass `--ckpt.resume-step <N>` (or `-1`for "latest"). Make sure `--max-steps` is at least the target final step, not the remaining delta:
Re-run the same launch command and pass `--resume` (latest checkpoint) or `--resume.step <N>`. Resuming reuses the run directory, so the run needs a name you can point back at — launch with `--run.name`(or pass the first run's auto-generated name). Make sure `--max-steps` is at least the target final step, not the remaining delta:
```bash
# First run: steps 1–10
uv run rl @ rl.toml --max-steps 10 --ckpt
uv run rl @ rl.toml --max-steps 10 --ckpt --run.name my-run
# Resume: continue to step 20
uv run rl @ rl.toml --max-steps 20 --ckpt.resume-step 10
# Resume from the latest checkpoint: continue to step 20
HF-compatible weight snapshots are written under `<output_dir>/weights/step_N/` whenever a full checkpoint runs (or you can write weights-only via`--ckpt.weights-only`for cheaper snapshots). Upload directly:
Trainer checkpoints are DCP-sharded; export them to HF-format safetensors with `tools/convert_dcp_to_bf16.py`. The script reads the model config from the run's resolved config and writes sharded safetensors plus config/tokenizer assets to`<ckpt_dir>/weights`(or a second positional arg). It exports full fine-tunes only — LoRA checkpoints are rejected.
```bash
uv run hf upload <user>/<model>-RL outputs/weights/step_100
# single process (1 GPU)
uv run python tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
# multi-rank for faster gathers and models that don't fit one GPU
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
```
For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write the raw adapter alongside the merged weights — useful when serving the adapter through a separate `/load_lora_adapter` call.
The exported directory loads directly into `uv run inference --vllm.model <dir>` or any HF consumer. Quantize it to blockwise FP8 (DeepSeek/GLM format, loads natively in vLLM) with `tools/convert_bf16_to_fp8.py <dir>`, or go straight from the checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (each rank quantizes its gathered slice, writes only `<ckpt_dir>/weights-FP8` — no intermediate bf16 export); dequantize an fp8-only release (e.g. GLM-5-FP8) for training with `tools/convert_fp8_to_bf16.py <dir>`.
## Observability
### Config Files
Each launch writes its command, input TOML, and resolved JSON files to
`<run_dir>/configs/attempt_<n>/`. Resumed runs keep the earlier configs.
`command.txt` uses shell-safe quoting.
`configs/latest` points to the current attempt.
### Log Files
The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The full layout (single-node runs skip the `node_*.log` and `router_*.log` files):
The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>/` — every launch (fresh or resumed) gets its own numbered attempt directory, and `logs/latest` symlinks to the current one. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
```
<output_dir>/logs/
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
│ └── router_*.log # vllm-router per replica (multi-node only)
└── envs/{train,eval}/<env_name>/
├── env_server.log
└── env_worker_<id>.log
│ └── router.log # the single global router (multi-node only)
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
```
Env worker logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/latest/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
```
### Console Output
### Dashboard
`scripts/tmux.sh` opens a 4-pane tmux session that follows `trainer.log`, `orchestrator.log`, `inference.log`, and the union of env worker logs. Start it before launching:
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with 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.
```bash
bash scripts/tmux.sh
# then in the Launcher window:
uv run rl @ ... --output-dir outputs/my-run
```
Pass `-s <session>` and `-o <output_dir>` to run multiple parallel experiments side-by-side in different sessions. The helper also works on a SLURM head node — `bash scripts/tmux.sh my-rl-job /shared/outputs/my-rl-job`.
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
### Weights & Biases
W&B is off by default. Enable with `--wandb`:
W&B is off by default (the file monitor, which writes the metrics and the trace stream under the run's `monitors/file/` directory, is on by default):
```bash
uv run rl @ rl.toml --wandb # default project, random name
uv run rl @ rl.toml --wandb.project my-proj --wandb.name run-42
uv run rl @ rl.toml --no-wandb # force-disable even if the TOML enables it
uv run rl @ rl.toml --monitors.wandb# default project, random name
uv run rl @ rl.toml --monitors.wandb.project my-proj --monitors.wandb.name run-42
uv run rl @ rl.toml --no-monitors.file# disable the local metric/trace files
```
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `wandb.offline = true`.
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `monitors.wandb.offline = true`.
By default, every 10 steps each process also logs a sample of prompts/completions (with rewards and advantages) and reward/advantage/entropy distributions as W&B tables. Tune via `--wandb.log-extras.interval` and `--wandb.log-extras.sample-ratio`, or disable subsets:
```bash
uv run rl @ rl.toml --wandb \
--orchestrator.wandb.log-extras.interval 50\
--no-trainer.wandb.log-extras.distributions
```
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, W&B mode **auto-creates an `overview` saved view** on the first run into a project — curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, every training run (RL and SFT) gets an **auto-created `overview` saved view** curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
### Platform Monitoring
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics, samples, and distributions to the platform dashboard. Bare flag uses defaults:
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics and episodes to the platform dashboard. Bare flag uses defaults:
```bash
uv run rl @ rl.toml --orchestrator.prime-monitor
uv run rl @ rl.toml --monitors.prime
```
Or set it in TOML:
```toml
[orchestrator.prime_monitor]
run_name="my-experiment"
[monitors.prime]
name="my-experiment"
```
Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted team. Currently internal-only.
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` (`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
- **Start small.** Run `examples/basic/reverse-text/rl.toml` end-to-end on 2 GPUs before scaling. If the smoke run finishes cleanly, your install is good.
- **Batch size ≥ 64.** Smaller batches give noisy gradient estimates and the trainer's overhead-per-step dominates throughput. 64 is the practical floor; 128–512 is the range for quick ablations; production RL often runs at 1024+.
- **Group size ≥ 8.** Bigger groups (`orchestrator.group_size`) make it more likely that a task produces a mix of high- and low-reward rollouts, which is what gives the trainer a usable signal — if all rollouts in a group succeed or all fail, the within-group advantage collapses to zero and the trainer learns nothing from that task. Bigger groups also tighten advantage normalization. 8 is the floor; 16–32 is common.
- **Pin `output_dir` per run.** Sharing a directory across runs will mix rollouts and break resumes. `--output-dir outputs/<unique-name>` is the simplest discipline.
- **Runs never share a directory.** Every launch writes to its own run directory `<output_dir>/<run_name>`, auto-named `<envs>--<model>--<short-id>` by default. Name runs you want to find again or resume with `--run.name <name>`; re-using a name blocks unless you resume or pass `--clean`.
- **Use `--dry-run` before SLURM.** Validators (e.g. CP needs flash-attention) fail fast in dry-run and slow in queue.
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:
- 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).
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.
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:
- `[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.
Large-scale RL and serving for the GLM-5 family — including `zai-org/GLM-5.3-BF16` for training and its `GLM-5.3` block-FP8 serving release — at 131k context: 16 trainer nodes on the custom MoE implementation (expert parallelism; the llm-d variant adds context parallelism) and P/D-disaggregated FP8 inference. The `-llmd` variants front the inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. They also offload KV to a Mooncake distributed CPU pool (1TB per node by default).
| Config | What it runs | Topology |
|---|---|---|
| [`swe.toml`](swe.toml) | GLM-5 RL plane: 16 train nodes, eval on `swebench-verified` every 20 steps, default vLLM router over 2 P/D replicas (4 prefill + 4 decode nodes each). Declares **no train source** — compose yours on top with an `[[orchestrator.train.source]]` overlay. | 16 train + 16 infer nodes |
- A Slurm cluster with 8-GPU nodes, a shared filesystem, and at least **32 nodes** (16 trainer + 16 inference) for the RL configs. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path. If you have fewer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` (llm-d variant) accordingly.
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d variants).
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, 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 configs log to W&B (`[monitors.wandb]`).
### Install llm-d (llmd variants 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:
- `swe-llmd.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`. `swe.toml` needs `--slurm.partition <your-partition>` or `--output-dir` overrides on the command line.
- `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
- `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
- `swe-llmd.toml` ships without `[ckpt]` — add a checkpoint overlay if you want resume support.
## 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 with llm-d + Mooncake (recommended)
uv run rl @ examples/advanced/glm-5.3/swe-llmd.toml
# GLM-5 base plane — compose your train source onto it
uv run rl @ examples/advanced/glm-5.3/swe.toml @ my-train-source.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
`swe.toml` checkpoints every 100 steps (`[ckpt] interval = 100`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
See [Scaling](../../../docs/scaling.md) for SLURM details and [Inference](../../../docs/inference.md) for the disaggregated-inference and router reference.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.