Large out-of-band NumPy arrays returned by vLLM can still alias a
shared-memory ring slot after `MessageQueue.dequeue()` releases it.
Subsequent messages overwrite retained routed-expert IDs, so router
replay can consume different IDs from those originally produced.
Backport merged [vLLM
#61000](https://github.com/vllm-project/vllm/pull/61000) through Prime
RL's general plugin. Copy SHM out-of-band buffers inside the read
context, and reuse the owned `bytearray` when rebuilding Torch tensors.
Inline metadata, overflow/remote ZMQ paths and the wire format retain
their existing behavior. The patch is idempotent; its code comment links
upstream and identifies when the backport can be removed.
Validation ran in isolated CPU processes without editing installed
dependencies:
- The upstream unpatched queue fails both SHM NumPy retention cases;
this backport passes the applicable upstream queue suite: **52 passed, 2
GPU skips, 6 deselected** due to the login node's 64 MiB SHM limit.
- The pinned **vLLM 0.31.0** source passes the lifetime and tensor
compatibility cases: **21 passed, 1 skipped**. The private harness
explicitly closes test ZMQ contexts with zero linger: that version's
`shutdown()` only wakes readers, and the initial combined run hung
during context destruction. The production patch does not change
shutdown.
- Patch installation is idempotent. Ruff check, Ruff format and `git
diff --check` pass.
No fresh GPU serving or training benchmark was run for this backport;
upstream's merged PR includes GPU validation.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Patches core vLLM inter-process messaging (`MessageQueue.dequeue`);
incorrect behavior could affect distributed inference correctness,
though the change mirrors an upstream fix and is scoped to buffer
lifetime.
>
> **Overview**
> Backports vLLM’s shared-memory buffer ownership fix into Prime RL’s
vLLM plugin so large out-of-band payloads no longer alias reusable ring
slots after `MessageQueue.dequeue()` returns.
>
> The new `monkey_patch_shm_buffer_ownership()` copies non-primary SHM
slices into owned `bytearray`s while still inside the read lock, and
registers a matching `_rebuild_tensor` helper so pickled torch tensors
rebuild from those copies. Overflow/remote ZMQ paths and the on-wire
layout are unchanged; the patch is idempotent and is meant to be dropped
once the pinned vLLM version includes upstream #61000.
>
> This addresses incorrect **routed-expert** IDs during router replay
when retained NumPy arrays were overwritten by later SHM messages.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c629d022462755dc268b82423fe6c6aea3827eda. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Release the CUDA allocator cache once after every checkpoint load:
`gc.collect()` + `torch.cuda.empty_cache()` right after `dcp_load`
returns in `CheckpointManager.load_from_path`.
- Remove the cleanup from `AppState.load_state_dict`. It ran only with
CPU offload, and the new cleanup now covers that path too.
Net diff: one `ckpt.py` change. The cleanup moves from the offload-only
path to every load path (SFT and RL, with and without CPU offload).
## Problem
Without CPU offload (`model.offload = "none"`), a resume peaks at much
more reserved memory than an uninterrupted run at the same step. A
24-node SFT run (192 ranks, 512K sequence length, 267.7 GiB GPUs)
showed:
| Step 901, same batch | Peak reserved |
|---|---|
| Fresh run, 900 steps in | 216.8 GiB |
| Resumed from step 900 | 257.0 GiB (96%) |
The resumed run logged `expandable_segments: memory mapping failed with
OOM` during its first step.
Cause: DCP's `_init_optim_state` builds the optimizer state with a
zero-grad `optimizer.step()`. This allocates a `zeros_like` gradient for
every parameter, so allocated memory peaks about one fp32 parameter
shard above the steady state during the load. When the load ends, those
blocks stay in the allocator cache. The first step does not reuse them
and reserves on top of them. Peak *allocated* memory does not change, so
the extra memory is cache fragmentation, not live tensors. With CPU
offload, the old cleanup in `AppState.load_state_dict` already released
the cache, so only the non-offload path was affected.
## Verification
Single-node runs: Qwen3-30B-A3B SFT on 1 node of H200s (6 trainer GPUs,
2 inference GPUs), online evals on, seq len 8192. A base run trains 1
step and saves a checkpoint. Each variant resumes from that checkpoint
and trains step 2. Each change was toggled with an env var, so all
variants share the same code and checkpoint. Numbers are rank 0, in GiB.
**`offload = "none"`.** Ablation of each candidate change (the first two
were in an earlier version of this PR):
| Step 2 | Reserved after load | Peak allocated | Peak reserved |
|---|---|---|---|
| Fresh run (no resume) | — | 83.7 | 93.6 |
| Resume, `main` | 80.0 | 83.5 | **114.9** (+21.3) |
| Resume, unconditional cleanup in `AppState.load_state_dict` | 60.5 |
83.5 | 95.4 (+1.9) |
| Resume, `empty_cache()` before the SFT startup broadcast | 80.0 | 83.5
| 93.5 |
| Resume, both of the above | 60.5 | 83.5 | 93.5 |
| **Resume, this PR** | **58.6** | 83.5 | **93.5** |
- Peak allocated is the same in every row. Only the cached, unused
memory changes.
- On `main`, the load leaves 21.4 GiB cached (reserved 80.0 vs allocated
58.6). Step 2 reserves about 31 GiB on top of it.
- With this PR, reserved memory after the load equals allocated memory,
and step 2 matches the fresh run.
- The cleanup inside `AppState.load_state_dict` leaves 1.9 GiB cached:
some load buffers are freed only after `dcp_load` returns.
- The `empty_cache()` before the startup broadcast also removes the gap,
but only because it runs right after the load, and only when online
evals are on. This PR does not need it.
- Memory outside the PyTorch cache stays at about 2.4 GiB in every run.
The cached blocks do not take memory away from NCCL or cuBLAS.
- The `offload = "none"` variants ran twice, with identical numbers.
**CPU offload.** Removing the cleanup from `AppState.load_state_dict`
changes nothing:
| Resume | Reserved after load | Step-2 peak reserved |
|---|---|---|
| `offload = "optimizer"`, `main` | 19.5 | 82.0 |
| `offload = "optimizer"`, this PR | 19.5 | 82.0 |
| `offload = "full"`, `main` | 9.8 | — (killed by an unrelated HF Hub
429 in inference) |
| `offload = "full"`, both cleanups | 9.8 | 35.1 |
| `offload = "full"`, this PR | 9.8 | 34.9 |
Not tested: RL resumes (they use the same
`CheckpointManager.load_from_path`), and the 24-node run above with this
exact diff.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Behavior change is limited to memory reclamation after resume; no
changes to model, optimizer, or checkpoint I/O logic beyond when
`empty_cache` runs.
>
> **Overview**
> **Moves GPU cache cleanup to run on every checkpoint resume**, not
only when optimizer CPU offload is enabled.
>
> Post-load `gc.collect()` and `torch.cuda.empty_cache()` are removed
from `AppState.load_state_dict` (previously gated on `has_cpu_offload`,
with optional `state_dict.clear()`). The same cleanup now runs in
`CheckpointManager.load_from_path` immediately after `dcp_load`, with a
note that DCP’s optimizer materialization can leave gradient allocations
in the CUDA cache and inflate reserved memory on the first training step
after resume.
>
> This targets inflated peak reserved memory (and near-OOM on large SFT
resumes with `model.offload = "none"`) without changing checkpoint
contents or load semantics.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9193c739e325a8764a33c9cb1617fa63eed47281. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
- bump the prime-rl project version from 0.9.0 to 0.10.0
- update the matching prime-rl entry in uv.lock
- prepare the [draft v0.10.0 GitHub
release](https://github.com/PrimeIntellect-ai/prime-rl/releases/tag/untagged-4435562ccd29fd8d2e32)
with notes for 264 commits since v0.9.0 (up to #4048)
## Verification
- uv lock --check
- git diff --check
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Version-only release metadata with no runtime or dependency graph
changes in the diff.
>
> **Overview**
> Bumps **prime-rl** from **0.9.0** to **0.10.0** in `pyproject.toml`
and updates the editable `prime-rl` package version in `uv.lock` so the
lockfile stays consistent. No application or dependency changes beyond
the release version tag.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7e719dbc7e5cd2f4d503bdd15209ec2f99511bb3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
With `length="variable"` and `input_ids="random"`, `FakeDataset` drew a
per-sample `seq_len` but always generated `self.seq_len + 1` random ids.
Samples ended up with `input_ids`/`target_ids` of length `self.seq_len`,
while `position_ids`, `loss_mask` and `seq_lens` used the drawn length.
After packing with `CatDataset` + `cat_collate` this gave e.g.
`input_ids` of shape (1, 128) next to `position_ids`/`loss_mask` of
shape (1, 101).
- `_draw_sample` now generates `seq_len + 1` random ids. Normal
iteration and fast-forward both go through `_draw_sample`, so resume
still replays the same generator stream. The stream itself changes for
variable+random, which is fine for fake data.
- `num_tokens["fake"]` now counts `seq_len` (the emitted `input_ids`
length), matching `SFTDataset`'s post-shift count, instead of `seq_len +
1` (or `self.seq_len + 1` in the random case).
- Added `test_fake_dataset_sample_lengths`, parametrized over `length` ×
`input_ids`. It asserts that `input_ids`, `target_ids`, `position_ids`
and `loss_mask` all have the same length and that `sum(seq_lens)` equals
it. On the old code it fails only for `[random-variable]`.
## Test plan
- `pytest tests/unit/train/sft/test_fake_dataset.py`: 12 passed (the new
test fails on `main` for `random-variable`)
- Packed 20 variable+random samples with `CatDataset(..., 128)` +
`cat_collate`: `input_ids`, `target_ids`, `position_ids` and `loss_mask`
shapes match
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
#3638 set a reduce-scatter buffer cap of 2 on the fp32 MoE router's FSDP
unit. Back then the experts were their own FSDP unit, so with one buffer
the router's reduce-scatter had to wait for the experts' large
reduce-scatter to finish, stalling backward. #3753 later moved the
experts into the block's FSDP unit (for `fullgraph` compile). With that
layout and full activation checkpointing, the expert reduce-scatter
finishes inside the next layer's recompute, so the second buffer no
longer buys anything. This PR makes the cap configurable
(`model.reduce_scatter_max_input_buffers`), sets it once on the root
FSDP module, and changes the default to 1 (torch's default).
- Before: fp32-router runs had an effective cap of 2 (torch takes the
max over all units), bf16-router runs had 1. Now every run uses the
configured value, 1 by default.
- A single root-level call is enough: torch keeps one reduce-scatter
queue and resolves the cap once as the max over all FSDP units.
- Cap 2 helps only when reduce-scatters are exposed, which in our runs
needed short sequences without activation checkpointing (last rows and
the second figure). It is free with the fp32 router but costs ~9 GiB/GPU
on the bf16 path with `ep=1`. Cap 3 never beat 2.
**Why one buffer is enough now.** The block and the fp32 router are
still separate FSDP units with separate reduce-scatters. The cap is a
single global count of reduce-scatters allowed in flight, and at cap 1
each unit's hook must wait for the previous reduce-scatter to finish
before launching its own. What #3753 changed is which reduce-scatter
that is when the router's hook runs in layer `L`'s backward:
```
Before #3753 (experts are their own unit), cap 1, backward of layer L:
compute [ recompute L ][ MoE bwd L ][ router bwd ][ STALL ][ attn bwd L ]
RS stream [====== experts L RS ======][ router L ]
^ launched just before the router hook,
with no compute in between to hide it
After #3753 (experts in the block's unit), cap 1, backward of layer L:
compute [ recompute L ][ MoE bwd L ][ router bwd ][ attn bwd L ]
RS stream [== block L+1 RS ==] [ router L ]
^ launched at the end of layer L+1, so it has
all of layer L's recompute and MoE backward to finish
```
Before #3753 that big reduce-scatter launched just before the router's
hook, with no compute in between to hide it, and cap 2 was the fix. Now
it is the previous layer's, launched a whole layer earlier, so the
current layer's recompute and MoE backward run while it finishes. It
only stalls when that compute is shorter than the reduce-scatter (the
second figure).
Median s/step and rank-0 peak GiB, GLM-4.5-Air truncated to 24 layers
(16 for 8k without AC), 2x8 H200, fp32 router, untraced, lower is
better. Spread is the gap between two same-code runs on different node
pairs.
| layout | tokens/GPU, AC | cap 1 (PR) | cap 2 (main) | cap 3 | spread |
peak GiB, cap 1 / 2 / 3 |
| ------ | -------------- | ---------- | ------------ | ----- | ------ |
----------------------- |
| `ep=8` | 16k, full | 4.697 | 4.650 | 4.693 | 0.068 | 75.3 / 75.1 /
76.1 |
| `ep=1` | 16k, full | 4.535 | 4.521 | 4.543 | 0.041 | 88.9 / 88.4 /
98.0 |
| `ep=8` | 4k, full | 1.238 | 1.234 | 1.237 | 0.002 | 63.6 / 63.6 / 63.6
|
| `ep=1` | 4k, full | 2.056 | 2.064 | 2.050 | 0.006 | 80.1 / 80.1 / 88.8
|
| `ep=8` | 1k, none | 0.848 | 0.841 | 0.826 | 0.011 | 68.2 / 68.2 / 68.1
|
| `ep=1` | 8k, none | 1.318 | 1.279 | 1.280 | 0.001 | 102.7 / 102.7 /
111.4 |
| `ep=1` | 4k, none | 1.761 | 1.629 | 1.627 | 0.002 | 109.6 / 109.6 /
118.3 |
| `ep=1` | 1k, none | 1.651 | 1.515 | 1.506 | 0.005 | 85.6 / 85.6 / 94.4
|
In a whole-step trace (`ep=8`, 16k tokens/GPU, full AC, rank 0), neither
`main` nor this PR has a compute-stream gap of 2 ms or more anywhere
inside the model's backward. The only such gaps are at the start of
forward, the start of backward, and the end of backward, where the last
hooks and FSDP's final callback wait on the last reduce-scatters.
Notation in the figures (`RS` = reduce-scatter, `AG` = all-gather):
- `E`: the experts' gradient reduce-scatter, over the ranks that hold
copies of the same experts.
- `D`: the reduce-scatter of the block's dense parameters (attention,
norms, shared experts).
- `R`: the fp32 router's reduce-scatter (the router is its own FSDP
unit).
- `D+E`: the whole block's reduce-scatter, used when there is no EP and
the block has one parameter group.

**Figure:** one layer of backward at a production shape (`ep=8`, 16k
tokens/GPU, full activation checkpointing), before and after this PR.
The expert reduce-scatter (orange, top row) finishes while the next
layer is still recomputing, well before anything waits on it, so
dropping to cap 1 adds no stall.

**Figure:** what failure looks like: the compute stream waiting on a
reduce-scatter (red). It shows up at this odd shape we don't run in
production (one node, 8 layers, `ep=2`, 2k tokens/GPU, no activation
checkpointing), where each layer's expert reduce-scatter outlasts the
compute that would hide it. Raising the cap to 2 (bottom) removes most
of the wait and makes the step 6.5% faster (0.277 to 0.259 s) at no
extra memory. We include it to show what to look for in traces and when
to bump the cap.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The docs expanded IPO as "Importance Policy Optimization". It stands for
**INTELLECT Policy Optimization**. Fixes the expansion at its first
mention in `docs/algorithms.md` (IPO Loss) and `docs/ipo.md`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Documentation-only wording fix with no runtime or configuration
impact.
>
> **Overview**
> Corrects how **IPO** is spelled out in the docs: the expansion is now
**INTELLECT Policy Optimization** instead of Importance Policy
Optimization.
>
> Updates the first-definition lines in `docs/algorithms.md` (IPO Loss
section) and `docs/ipo.md` (page intro). No training behavior, config,
or loss math changes.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9c732151621e848c5e300e684293adeff5b1f1a7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Adds a docs page explaining IPO, the default RL loss, with the ablation
behind `eps = 0.3` and configs to reproduce it.
- **`docs/ipo.md`** (nav after Algorithms):
- Why IPO masks by absolute probability (`|p_train - p_infer| > eps`)
instead of ratio like IcePop, with the two worked examples and the link
to KPop
- Ablation setup table and result: on GLM-4.5-Air agentic SWE RL (no
router replay, 64 steps off-policy), IcePop collapses around step 1.2k
while IPO `eps` 0.2 and 0.3 train through
- How `eps = 0.3` was chosen: mask rates replayed on 1.8M tokens (0.1 →
1.98%, 0.3 → 0.25%, IcePop → 0.06%)
- **`docs/assets/ipo/`**: the two figures (solve rate + mismatch KL; eps
choice).
- **`examples/advanced/glm-4.5-air/ipo-ablation/`**: `base.toml` +
`ipo.toml` / `icepop.toml` overlays (eps 0.2 via `--trainer.loss.eps
0.2`). Ported from the research-prod `exp/air-scaleswe-ablation-sweep`
configs to the current schema; dropped cluster-specific paths and
sandbox-label cleanup so arms can run side by side.
- Links from `docs/algorithms.md` (IPO Loss) and the GLM-4.5-Air README.
Validated: `tests/unit/test_configs.py` passes for the new configs, and
the three arms resolve through `cli(RLConfig, ...)` to the intended
loss, no router replay, 64 off-policy steps, and batch 256 × 16.
Content is condensed from the internal IPO blog draft.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
The trainer defaults are tuned for memory (optimizer CPU offload, AC
offloading, compile without `fullgraph`) so large models fit on few
GPUs. This documents how to trade that memory back for throughput, with
an example to reproduce it.
- **`docs/scaling.md`**: new "Max-Throughput Recipe" section after the
memory-tight one: `offload = "none"`, `ac_offloading = "None"`,
`fullgraph = true`, bf16 router, add nodes instead of CP, one
full-length sequence per GPU. Points to the two examples below.
- **`examples/advanced/qwen3-235b-a22b/sft-max-perf.toml`** (+ README):
Qwen3-235B-A22B SFT on 4 x 8 B300 at 16k with that recipe (EP 8, full
AC, fp32 AdamW, balanced routing, 20 steps), around 46% MFU.
- The existing GLM-5.3 `16k-12-node.toml` overlay is referenced as the
second example.
Config ported from @MarioSieg's #3765 to the current schema (no
`model.impl`, `offload = "none"`, no cluster-specific paths); supersedes
it. Validated with `tests/unit/test_configs.py`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Documentation and example TOML only; no trainer or runtime code
changes.
>
> **Overview**
> Adds a **Max Trainer Throughput Recipe** to `docs/scaling.md` as the
counterpart to the memory-tight section: when GPU memory allows, disable
optimizer and activation offloading, enable `torch.compile` with
`fullgraph`, use bf16 MoE routing, prefer scaling nodes over context
parallelism, and keep `micro_batch_size = 1` per full-length sequence.
The doc calls out RL’s fp32 router default as a caveat for `fullgraph`.
>
> Ships a new **`examples/advanced/qwen3-235b-a22b/`** reference run
(`sft-max-perf.toml` + README): 20-step SFT on `Qwen3-235B-A22B` across
4×8 B300 at 16k with that recipe (~46% MFU), balanced routing for stable
benchmarking, and no checkpoint block. **`examples/README.md`** lists
the example; the scaling doc also points at the existing GLM-5.3
`16k-12-node.toml` overlay.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
de9878cd0251e5b40a2f47d11a9210a16f0cea07. 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: Mario Sieg <mario.sieg.64@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
DeepSeek V4 serving on vLLM 0.31.0 corrupts long-context KV under
piecewise CUDA graphs and drops the attention sinks on every layerwise
weight reload. Two vLLM patches fix both.
- C128: vLLM 0.30+ skips the compressed-KV write on mixed batches under
piecewise graphs, so it now always runs. Step-1 mismatch KL on the 131k
SWE run drops from 0.0070 to 0.0005.
- attn_sink: upstream's bare slice copy landed in a meta tensor on
reload, so updates kept boot-time sinks. Sinks now load through
`param.weight_loader`.
- Both register last in `apply_shared_vllm_patches`, so a failing
DeepSeek V4 import cannot skip the other patches.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Reverts #3925. With an fp32 router and activation checkpointing, #3925
changed checkpointed MoE blocks from `compile(AC(block))` to
`AC(compile(block))`, which makes the checkpoint recompute re-enter
Dynamo on the autograd thread. Since then, MoE RL runs with context
parallelism, activation checkpointing and compile crash in an early
backward with `aten.empty_like.default` or `aten.empty.memory_format
encountered during backward but not found in storage`. That happens with
both ring and ulysses CP, which shows that reverting #3925 removes the
crash on the same batches).
The runs in #3925 (no CP) never hit this, and the root cause is not yet
understood. This PR restores the previous layout and the `AC -> Compile
-> FSDP` order until it is. The cost is #3925's speedup: MoE blocks with
an fp32 router and AC run eager again (GLM-4.5-Air about 5.2 to 6.2
s/step, Qwen3-30B-A3B 4.5 to 6.0 s/step in #3925's benchmarks). A
follow-up will root-cause the crash and decide whether to re-land #3925
together with #3951.
This conflicts with #4029, which edits the unwrap block removed here.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
A hung collective (dead rank, NCCL hang) now fails the trainer after 15
minutes instead of an hour, and leaves a trace of which rank hung where.
- `dist_timeout_seconds` default: 3600 → 900, for the RL trainer and
SFT. It is the c10d timeout of every trainer process group
(`setup_torch_distributed` patches it onto the dp/cp/ep sub-groups).
`weight_broadcast.timeout` (#3980) is a different knob and stays 3600.
- Two waits ran inside an NCCL barrier while only the master worked, so
they were bounded by `dist_timeout_seconds`:
- the weight broadcast handshake: non-master ranks sat in
`dist.barrier()` while the master waited for `.receiver_ready`, which
can take up to `weight_broadcast.timeout` (at startup it covers
inference start-up);
- the one-time HF ↔ PrimeRL conversion on the master.
Both now hold the other ranks on the c10d store (`wait_for_master` in
`trainer/world.py`; the conversion key is per model) instead, bounded by
`weight_broadcast.timeout` and 4 h. The handshake hold moved into
`WeightSender.broadcast`, so it covers every transport (before, the
filesystem LoRA path had no hold). The barriers it replaces in the NCCL
and filesystem senders are gone.
- DCP checkpoint save and load, and the HF weight load
(`load_dcp_from_hf`), run their collectives on a gloo group with a 4 h
timeout (`get_dcp_group`), not on NCCL. DCP's collectives wait for the
slowest rank: its writes on save, its reads on load, and on the first HF
load its `snapshot_download`. On large checkpoints or a slow shared FS
this can take longer than 900 s. The two mkdir barriers in
`CheckpointManager.save` use the same group. A dead rank during a
checkpoint now hangs up to 4 h instead of 900 s. The 4 h is a constant
(`DCP_TIMEOUT`), not a config field. Gloo across nodes uses
`GLOO_SOCKET_IFNAME` (set by the multi-node template when `GLOO_IFNAME`
is given) or gloo's own interface detection; this was not tested across
nodes.
- Not covered: general step skew, e.g. the master writing a filesystem
weight broadcast while the other ranks enter the next step's FSDP
collectives. Large recipes may still need a higher
`dist_timeout_seconds` when a long wait is not one of the store or DCP
waits above.
- The DeepSeek-V4-Flash SFT recipe drops `dist_timeout_seconds = 14400`;
it was only there for the conversion.
`examples/advanced/glm-5.3/swe.toml` keeps its explicit 1800.
- The NCCL flight recorder is on for trainer processes
(`DEFAULT_TRAINER_ENV_VARS`): `TORCH_FR_BUFFER_SIZE=2000`,
`TORCH_NCCL_DUMP_ON_TIMEOUT=1`, and dumps to
`/tmp/nccl_trace_<uid>_rank_<rank>` on each node. `torchfrtrace` reads
them. All three can be overridden through `env_vars`.
## Checks
- 2 ranks on 1 node (H200), NCCL timeout 20 s, `CheckpointManager.save`
then `.load` of a small model, with rank 1 sleeping 60 s before each:
both finish (rank 0 waited 61 s and 60 s), and an NCCL all-reduce
afterwards works. The same script with DCP on the default NCCL group
dies on the 20 s watchdog.
- GPU tests `test_load_dcp_from_hf_keeps_checkpoint_selection_bias` and
`test_deepseek_v4_hash_table_survives_the_load_path` pass; they now stub
`wait_for_master` and `get_dcp_group`.
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/train -m "not gpu"`: 534 passed. ruff is clean.
- `wait_for_master`, 2 processes, gloo with a 2 s PG timeout: the
non-master waited 5 s on the store and the next barrier passed.
- GPU, 1 node (H200), reverse-text Qwen3-0.6B, 2-rank trainer (DP=2):
NCCL broadcast for 6 steps plus a resume to step 8 (startup and per-step
broadcasts go through the store hold), and filesystem broadcast to step
2. Merged test branch with #3906/#3998/#4018/#4020. A collective timeout
and its dump were not provoked. This run predates the gloo DCP group.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes distributed synchronization and checkpoint/weight-load process
groups; mis-tuned timeouts could fail long DCP I/O or mask hangs
differently, but behavior is intentional and recipe overrides remain
possible.
>
> **Overview**
> **Shortens the default distributed collective timeout** from 3600s to
**900s** for RL trainer and SFT configs, with clearer docs that this
bounds hung NCCL/c10d collectives. Trainer processes also get **NCCL
flight recorder** env defaults so timeouts dump recent collective traces
to `/tmp`.
>
> **Moves long master-only waits off NCCL barriers** via
`wait_for_master` (c10d store): HF↔PrimeRL one-time conversion (up to
4h), weight-broadcast handshake in `WeightSender.broadcast` (all
transports, including filesystem LoRA), and NIXL ModelExpress
discovery/completion. Per-transport `dist.barrier()` holds in
NCCL/filesystem senders are removed.
>
> **DCP checkpoint save/load and HF weight `dcp_load`** now use a cached
**gloo `get_dcp_group()`** with a **4h** `DCP_TIMEOUT` instead of the
default NCCL PG, including mkdir barriers in `CheckpointManager`. The
DeepSeek-V4-Flash SFT recipe drops its explicit `dist_timeout_seconds =
14400` that only existed for conversion.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
873a952a777f246957051d61a86ec11b972cb59e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
- NIXL: the master-only ModelExpress discovery (startup) and completion
waits now also hold the other ranks on the c10d store before the NCCL
`broadcast_object_list` / `barrier`, so the 900 s timeout can't kill
them while the master waits up to `weight_broadcast.timeout`.
When the orchestrator's step loop raises, its `finally`:
- saves `step_{progress.step - 1}/orchestrator`. That step usually has
no trainer checkpoint, so a bare `--resume` picks a step the trainer
cannot load (`FileNotFoundError: Checkpoint not found at
.../step_K/trainer`). If the step does have a trainer checkpoint, the
crash-time save overwrites the interval checkpoint with mid-step state.
- if teardown exceeds `SHUTDOWN_TIMEOUT_S`, calls `os._exit(0)`. On
SLURM that exit 0 counts as a finished orchestrator:
`.orchestrator.done` is touched, `--kill-on-bad-exit` does not fire, and
the trainer waits until a timeout fails it.
Now the final orchestrator checkpoint is saved only once the step loop
has finished (the last step is fully shipped), matching the trainer,
which saves its final checkpoint only after its loop. A failure later,
while waiting for the final broadcast, still saves it, so the last step
stays resumable. The forced exit uses code 1 when the exit was not
clean. A clean exit that hits the teardown timeout still exits 0.
`os._exit(0)` in `Orchestrator.stop` is the only `os._exit` in
prime-rl's `src/` (none in verifiers).
## Checks
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 335 passed. ruff is clean.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes shutdown and checkpoint persistence on failure paths, which
affects resume correctness and cluster job exit semantics, but logic is
narrowly scoped to the orchestrator `finally`/`stop` teardown.
>
> **Overview**
> Fixes orchestrator teardown so **crashes no longer write a misleading
final checkpoint** and **non-clean shutdowns can fail the job** instead
of looking successful.
>
> On a clean run, a new `loop_done` flag gates the existing “save
`step_{progress.step - 1}`” logic so it only runs after `main_loop()`
finishes (and the usual final-broadcast path), matching the trainer’s
“checkpoint only after the loop” behavior. If the step loop raises
mid-step, teardown skips that save so `--resume` won’t point at a step
the trainer never checkpointed or overwrite an interval ckpt with
partial state.
>
> `stop()` now takes `clean_exit`; when graceful shutdown hits
`SHUTDOWN_TIMEOUT_S` and forces `os._exit`, the process exits **0 only
on a clean exit** and **1 otherwise**, so SLURM/launcher hooks treat
interrupted orchestrator runs as failures while a clean run that wedges
during teardown can still exit 0.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
255c716aeb04a52f869aa3aa5707fff55aa11a1c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Changes the default of `trainer.data.num_workers` from 0 to 1. The RL
trainer now prepares micro batches on one background thread.
Why: the evidence comes from #3917, which added the option. Its
benchmark: Qwen3.5-9B, trainer only, 4×H200, 1024 px JPEG micro batches,
median s/step.
| arm | main thread | 1 thread | saved |
|---|---|---|---|
| default | 24.98 | 18.86 | 24.5% |
| optimizer CPU offload | 26.56 | 20.24 | 23.8% |
The same PR reports that one thread gives the full speedup, that loss
and grad norm match bit for bit, and that host memory rises by only 0.3
GiB.
Scope and safety:
- `DataLoaderConfig` is RL-only. SFT has its own `data.num_workers`,
which already defaults to 1, so SFT is unchanged.
- `WorkerPool` yields results in input order and keeps at most 2 items
in flight (`src/prime_rl/utils/worker_pool.py`).
- `prepare_micro_batch` (`src/prime_rl/trainer/rl/data.py:180`) is
CPU-only and uses no RNG, so results do not depend on threading. For
text-only batches it only sets the multimodal fields to `None`.
- `0` still prepares micro batches on the main thread.
Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/utils/test_worker_pool.py -m "not gpu"`: 340 passed.
- `ruff check` and `ruff format --check` on `trainer.py`: clean.
- I did not re-run the GPU benchmark; the numbers above come from #3917.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Single default-value change for RL-only data loading; explicit `0`
preserves prior behavior and threading is documented as numerically
safe.
>
> **Overview**
> **Default RL micro-batch prep now uses one background thread** instead
of the main training thread.
>
> `DataLoaderConfig.num_workers` in the RL `TrainerConfig` changes from
`0` to `1`, so new runs overlap CPU micro-batch preparation with the
training step without editing config. Setting `num_workers` to `0` still
prepares batches on the main thread. SFT already defaults
`data.num_workers` to `1` via its own config type, so behavior there is
unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7274894702d1d048f3c80e3a994f9441cb2b5c33. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## What
- `VLLM_CACHE_ROOT=/tmp/.vllm-cache-<uid>` and
`FLASHINFER_WORKSPACE_BASE=/tmp/.flashinfer-cache-<uid>` are added to
`DEFAULT_INFERENCE_ENV_VARS`. `TRITON_CACHE_DIR` got the same treatment
in #3877.
- The by-hand copies (`/tmp/.vllm-cache`, `/tmp/.flashinfer-cache`) are
removed from the four GLM-4.5-Air recipes. Those paths were shared by
every user on a node.
- docs/scaling.md gets one paragraph that lists the node-local cache
defaults.
The paths are dot-prefixed so the SLURM start-up cleanup (`rm -rf
/dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-*
/tmp/torchelastic_*` in the multi_node_rl, multi_node_sft and inference
sbatch templates) does not wipe them. These are the same names the
recipes used before.
Precedence is the same as for the other launcher defaults: `[env_vars]`
or `[inference.env_vars]` override them; a value exported in the shell
does not.
## Why
- Without these, vLLM's AOT/Inductor compile cache lives in
`~/.cache/vllm` and FlashInfer's JIT cache under `$HOME`, which is
usually the shared filesystem.
- Measured while testing #3877 (GLM-4.5-Air TP8, vLLM 0.31): a crashed
start left a partial shared vLLM cache. On the next start, 4 TP ranks
loaded those artifacts and the other 4 recompiled. The ranks diverged
and hung in a collective. So one crash breaks every later start that
uses that cache.
- The original scaleswe recipe (#2862) moved this cache to `/tmp`
because the NFS cache hung inference startup.
- Cost: the first start on each new node has a cold vLLM cache.
GLM-4.5-Air: 465 s cold vs 375 s with a warm vLLM cache, so about 1.5
min once per node.
## Overlap
- #3627 (garrett361, draft) adds
`VLLM_CACHE_ROOT`/`FLASHINFER_WORKSPACE_BASE` under `/tmp/garrett/` to
new DeepSeek-V4 recipes. With this PR those lines can go.
## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/utils -m "not gpu"`: 365 passed (rebased on origin/main
41a8ed019).
- Ran the cleanup globs in a scratch dir that held `.vllm-cache-<uid>`,
`.flashinfer-cache-<uid>` and, as a control, `vllm-cache-<uid>`. Only
the control matched.
- `ruff check` and `ruff format --check` on `process.py`: clean.
- `rl @ examples/advanced/glm-4.5-air/swe.toml --dry-run`:
- The rendered `rl.sbatch` exports both vars only in the inference block
(`/tmp/.vllm-cache-<uid>`, `/tmp/.flashinfer-cache-<uid>`).
- With `--inference.env-vars '{"VLLM_CACHE_ROOT": "/scratch/vc"}'`, the
sbatch exports `/scratch/vc`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Launcher default env vars for inference only; configs can still
override, with no auth or training logic changes.
>
> **Overview**
> Inference launches now default **vLLM** and **FlashInfer** compile/JIT
caches to per-user paths under `/tmp` (`VLLM_CACHE_ROOT`,
`FLASHINFER_WORKSPACE_BASE`), matching the existing Triton cache
behavior and avoiding shared `$HOME` or NFS caches that can leave
tensor-parallel ranks on mismatched artifacts and hang.
>
> The four GLM-4.5-Air example recipes drop redundant
`[inference.env_vars]` blocks that duplicated those settings.
**docs/scaling.md** documents the launcher defaults and notes overrides
via `[env_vars]` or component `env_vars`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fe8a34dcb68c8fc314f2ea4f363fcd865fbde951. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Problem
`eval.retrigger_on_resume` is rejected at config-validation time unless
`weight_broadcast.type == "filesystem"`:
```python
if self.eval.retrigger_on_resume:
raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
```
With the default `nccl` transport the flag is therefore unusable, and
resuming an SFT run at an interval-aligned step silently skips that
step's evals: the trainer broadcasts the resume checkpoint at startup
and the evals process loads it, but nothing re-fires, so the next eval
is a full interval away and the step resumed from is never evaluated.
## Why the gate isn't needed
The in-memory path already meets the precondition the gate was
protecting. `OnlineEval.watch()` rendezvouses with the trainer's startup
broadcast before the re-fire, for every transport:
```python
startup_step = config.resume_step or 0
await self.receiver.sync_startup(startup_step, timeout=STARTUP_BROADCAST_TIMEOUT_S)
```
and `sync_startup` is transport-agnostic in
`transports/weights/base.py`:
```python
async def sync_startup(self, step: int, timeout: float) -> None:
await asyncio.wait_for(self.wait_published(step), timeout=timeout)
await self.receive(step)
```
So by the time `maybe_run_eval(step=config.resume_step)` runs, the
served weights are already the resume checkpoint's — and that call
passes `reload_weights=False`, so it never needs to re-read them from
disk, which is the only thing a filesystem broadcast would have added.
Cancellation is unchanged: the re-fired epoch gets the usual
`superseding_step` callback, so a newer broadcast supersedes it exactly
as for any other eval epoch.
NIXL remains rejected by the check immediately above. The RL
orchestrator already honours `retrigger_on_resume` with no transport
restriction, so this also removes an SFT/RL inconsistency.
## Change
Two-line deletion. No tests assert the removed error.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Config-validation-only change; removes an overly strict guard with no
runtime logic changes.
>
> **Overview**
> **Allows `eval.retrigger_on_resume` with NCCL (in-memory) weight
broadcast for SFT online evals.**
>
> SFT config validation no longer raises when `retrigger_on_resume` is
set alongside non-filesystem `weight_broadcast` (e.g. default `nccl`).
Resuming at an interval-aligned step can re-fire that step’s evals
without forcing `weight_broadcast.type = 'filesystem'`. **LoRA +
in-memory broadcast** and **NIXL** restrictions in the same block are
unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
acf86f21d9345e3677852baaefe690f73b938026. 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>
Qwen3.5 training with context parallelism can fail on the first forward
after #3925 places compilation inside activation checkpointing. FLA's CP
setup reads tensor-valued sequence boundaries and calls
`torch.searchsorted`; Inductor fails to specialize the resulting scalar:
```
GuardOnDataDependentSymNode:
Could not extract specialized integer from data-dependent expression (u0//4)
```
Wrap `build_cp_context` with `torch.compiler.disable`, alongside the
existing eager CP convolution wrapper. CP setup runs eagerly while the
surrounding block remains eligible for compilation. CP calculations,
model parameters and checkpointing settings are unchanged.
Validation ran on an allocated India H200 compute node with PyTorch
2.13.0+cu130 and FLA 0.5.2. A bounded CUDA/FSDP/checkpoint reproducer
used two sequence-boundary fixtures and logical CP size 4:
| Layout | Result | Maximum absolute
output/input-gradient/parameter-gradient difference vs eager |
| --- | --- | --- |
| Earlier outer compilation | Pass | 0 |
| Inner compilation introduced by #3925 | Same `(u0//4)` compiler
failure | — |
| Inner compilation with eager FLA CP metadata | Pass |
1.9073486328125e-6 |
This reproducer uses one CUDA/FSDP rank; it does not exercise real
four-rank CP collectives or a full Qwen training step. Full distributed
training validation remains outstanding. Ruff and `git diff --check`
passed for the patch. No test or experiment files are included in this
diff.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Narrow trainer workaround for a known torch.compile + FLA CP setup
issue; behavior matches eager CP setup with negligible numeric drift in
repro.
>
> **Overview**
> Fixes Qwen3.5 **context-parallel (CP)** training failures when the
block is compiled inside activation checkpointing (#3925). Inductor
cannot specialize scalars from FLA’s `build_cp_context`
(`torch.searchsorted` on tensor sequence boundaries), which triggers
`GuardOnDataDependentSymNode`.
>
> The change wraps **`build_cp_context`** with
**`torch.compiler.disable`** (same pattern as the existing eager CP
**`causal_conv1d`** wrapper) and calls **`build_cp_context_eager`** in
the forward path when CP is enabled. CP math, parameters, and
checkpointing are unchanged; only CP metadata setup runs outside the
compiled graph.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c192fc98cedc342e16af9307577f38fa77213b4e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Replaces the three switches `model.fsdp_cpu_offload`,
`model.optim_cpu_offload` and `model.full_offload` with one field:
```toml
[model]
offload = "optimizer" # default; also "full", "none"
```
This applies to both the RL trainer and SFT. The `fsdp` switch is not
migrated: the mode is removed outright (rationale below). The
`[model.full_offload] numa_bind` knob is dropped: no recipe, deployment,
template or doc sets it. Full offload now always pins each rank's CPUs
to its GPU's NUMA node. That was already the default. Ranks whose GPU
reports no NUMA node still skip binding with a warning. On hosts without
GPU sysfs topology (`/sys/bus/pci/devices/<bus>/numa_node`), binding is
no longer optional: full offload fails there instead of being switched
off.
Why: the three switches could only be used one at a time, enforced by
`cpu_offload_mutual_exclusion`. Because `optim_cpu_offload` defaulted to
`true`, enabling full offload also meant writing `optim_cpu_offload =
false`, otherwise validation failed (see the old
`configs/advanced/deepseek-v4-flash/sft.toml` comment). With one value
the conflicting combinations cannot be expressed, so that validator is
deleted. The default behaviour does not change: optimizer-state offload
stays on.
Why drop `fsdp`: the mode was the stock torch FSDP2 `CPUOffloadPolicy`
with no in-tree config, example, or test user; Muon rejected it and it
broke NCCL weight broadcast. It was kept only for long-context runs
whose fp32 masters/moments no longer fit on GPU (the reason it was
restored in #3052); the `full` mode added in #3234 keeps FP32 masters,
moments, and gradients in host RAM, covering that memory pressure
instead. Gone with it: the `CPUOffloadPolicy` selection in `setup_fsdp`,
CPU-side model init in `setup_model`/`load_dcp_from_hf`,
`_move_buffers_to_cuda`, and the fsdp leg of the Gloo special case.
Changes:
- `ModelConfig.offload: Literal["none", "optimizer", "full"] =
"optimizer"` replaces the three fields.
`OptimizerInBackwardOffloadConfig` (and with it `numa_bind`) and its
bool-normalizing `BeforeValidator` are gone.
- Validators in `TrainerConfig` and `SFTConfig`:
- full offload accepts only AdamW or SignSGD and disables clipping, now
reading `offload == "full"`;
- the `Muon optimizer does not support FSDP CPU offload` validators are
deleted with the mode.
- Runtime:
- `setup_optimizer(..., offload=...)` replaces `cpu_offload` +
`full_offload_config`, and its "both enabled" check is gone.
- `FullCPUOffloadOptimizer` drops its unused `offload_config` argument.
- `setup_full_cpu_optimizer_offload()` takes no arguments and always
binds.
- `model.py`: FSDP always uses the default `OffloadPolicy()`; CPU-side
model init in `setup_model`/`load_dcp_from_hf` and
`_move_buffers_to_cuda` are gone.
- Tomls: `glm-4.5-air/swe-budget.toml` and
`ci/integration/reverse-text-sft/full-offload-resume.toml` → `offload =
"full"`; `glm-5.3/sft/h200/16k-12-node.toml` → `offload = "none"`;
`glm-5.3/sft/h200/base.toml` → `offload = "optimizer"`. Also updated
`docs/scaling.md`, the `deepseek-v4-flash/sft.toml` comment, and
`skills/training/start-run/SKILL.md`, which documented the removed
fields.
Breaking: the old keys now fail with `extra_forbidden`, and `offload =
"fsdp"` fails the `Literal`. There is no shim.
Interaction with #3849 (one trainer-common config base): #3849 moves the
full-offload and Muon/FSDP validators from `TrainerConfig`/`SFTConfig`
onto `BaseTrainerConfig`. This PR edits the full-offload validator's
condition and deletes the Muon/FSDP one, so the conflict is textual
only: keep #3849's single copy of the full-offload validators with
`self.model.offload == "full"` and drop its Muon/FSDP copy. Whichever
lands second takes a small rebase.
Other open PRs that set or read the old keys need a rebase:
- tomls: #3883, #3879, #3766, #3765, #3729, #3629, #3627, #3616, #3544
- code: #3885 (`optim_cpu_offload`), #3739 (`full_offload` validators),
#3724, #3719, #3699, #3610, #3487 (`fsdp_cpu_offload` / `enable_gloo`)
Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/train/test_cpu_adam.py tests/unit/train/test_state_offload.py
-m "not gpu"`: 336 passed, 1 skipped (Qwen3-VL snapshot not cached on
this host), 4 deselected (GPU; this host has no GPU). The existing
offload config tests are updated to the new field. `test_load_configs`
covers the 4 edited tomls.
- `cli(TrainerConfig|SFTConfig, ...)`: `--model.offload full|none` and
the default (`optimizer`) resolve as expected; `optim_cpu_offload` and
`offload = "fsdp"` are rejected.
- `import prime_rl.trainer.rl.train, prime_rl.trainer.sft.train` works.
- `ruff check` and `ruff format --check` on the changed Python files:
clean.
- Not run: GPU or multi-node training with `offload = "full"`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking TOML/API surface touches distributed training memory paths
(FSDP offload, optimizer-in-backward, Gloo); behavior should match prior
modes when mapped correctly, but mis-migrated configs will fail at parse
time.
>
> **Overview**
> **Breaking config change:** `model.fsdp_cpu_offload`,
`model.optim_cpu_offload`, and `model.full_offload` are replaced by a
single **`model.offload`** setting (`"optimizer"` default, or `"full"`,
`"fsdp"`, `"none"`). RL and SFT share the same field; example TOMLs and
scaling docs are updated accordingly.
>
> The mutual-exclusion validator between the old flags is removed
because only one mode can be expressed. **`[model.full_offload]` /
`numa_bind` is dropped** — `"full"` always runs NUMA binding and CPU
optimizer thread setup via parameterless
`setup_full_cpu_optimizer_offload()`. Runtime paths (`setup_optimizer`,
FSDP CPU offload in `model.py`, Gloo when offload is `"full"` or
`"fsdp"`) key off the new enum; `FullCPUOffloadOptimizer` no longer
takes an offload config object.
>
> Default training behavior is unchanged: optimizer-state CPU offload
remains the default (`"optimizer"`). Old TOML keys are not aliased and
should fail validation.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
35da73ad2f1a73533595a979a971b0cdd8d6e63f. 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: sami jaghouar <sami.jaghouar@gmail.com>
## What
- `weight_broadcast.timeout` default goes from 1200 s to 3600 s
(`configs/shared.py`).
- It now also bounds the orchestrator's wait for the trainer's startup
broadcast. `orchestrator.ckpt.wait_for_weights_timeout` and the
hardcoded `STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200` fallback are removed.
Configs that set the old field fail validation (`extra="forbid"`); no
in-repo config sets it.
- The `[weight_broadcast]` blocks in five recipes only repeated `type =
"nccl"` (already the `rl` default when inference is managed and LoRA is
off) and `timeout = 3600`. They are removed: glm-4.5-air
swe/swe-budget/search/terminal and nemotron-3-super swe. glm-5.3 keeps
its `timeout = 12000`.
- Orchestrator `ckpt` and `resume` docstrings: `resume` had two
docstrings and `ckpt` had none. The stray one now documents `ckpt`.
## Why
- Every large multi-node recipe raises the timeout: 3600 s in five
recipes, 12000 s in glm-5.3.
- Measured startups come close to 1200 s or pass it. GLM-4.5-Air TP8
cold start takes 465-623 s. GLM-5.3 and DeepSeek-V4 inference startup
with cudagraph capture took about 16 min.
- vLLM's own engine-ready timeout is already 4200 s
(`VLLM_ENGINE_READY_TIMEOUT_S`).
- The startup wait and the per-step waits had two knobs with the same
1200 s default. The startup one was under `ckpt`, but it applies without
`ckpt` too.
- Trade-off: a consumer that dies is detected after 60 min instead of
20.
## Overlap
- #3652 (mikasenghaas, draft) reformats the `wait_timeout = ...` line
that this PR removes. Whichever lands second has a one-line conflict.
- Rebased over #3983, which removed the neighbouring orchestrator
`ckpt.keep_last`/`keep_interval` fields. The orchestrator
`CheckpointConfig` now has only `interval`.
## Test plan
- Rebased onto origin/main 32c48f5d9. `pytest tests/unit/orchestrator
tests/unit/test_configs.py -m "not gpu"`: 335 passed. `test_configs`
validates every TOML under `configs/` and `examples/`.
- `ruff check` and `ruff format --check` on the changed files: clean.
- Resolved `RLConfig` of the 5 edited recipes, main vs this branch:
identical (apart from the checkout path in `template_path`).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes orchestrator startup behavior and timeout defaults for
trainer–inference weight sync; mis-tuned timeouts could delay failure
detection (up to 60 min) or still timeout on very slow large-model
startups.
>
> **Overview**
> **Unifies weight-broadcast timing** so one knob
(`weight_broadcast.timeout`) covers both the trainer handshake and the
orchestrator’s wait for the trainer’s **startup** broadcast. The default
rises from **1200 s to 3600 s**, and docs note raising it for large
models on slow filesystems.
>
> **Removes** `orchestrator.ckpt.wait_for_weights_timeout` and the
orchestrator’s `STARTUP_WEIGHT_WAIT_TIMEOUT_S` fallback; startup sync
now uses `config.weight_broadcast.timeout` in `sync_startup`.
**Orchestrator config** docstrings are fixed so `ckpt` is documented on
the right field.
>
> **Five example/advanced recipes** drop redundant `[weight_broadcast]`
blocks that only repeated NCCL type and `timeout = 3600` (now defaults).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e318f1cb0b10a8a5507520f2c6b1176f9fbd0813. 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 jobs that crash currently sit idle for an hour.
On any non-zero exit (crash, OOM, SIGTERM, wall-time),
`multi_node_rl.sbatch.j2` ran an unconditional `sleep {{
cleanup_grace_period }}` (default 3600 s, #2670) before tearing down.
The sleep keeps the task alive so `--kill-on-bad-exit` does not reap
trainers that are mid-checkpoint. But it waits the full hour even when
no checkpoint is being written, so a crashed N-node job idles for 1 h.
Now the node waits only while the newest `checkpoints/step_*/trainer`
has no DCP `.metadata` yet, i.e. a trainer save is still in flight. It
polls every 10 s, with `cleanup_grace_period` as the cap, and tears down
as soon as that save finishes or there is none. Runs without `[ckpt]`
tear down immediately. The checkpoint dir follows `ckpt.output_dir` when
it is set. The default stays 3600 s; it is now only an upper bound.
Limitation: if the crash happens right before a save starts (step dir
not created yet), we no longer wait for that save. Only that save is
lost; the previous checkpoint is intact.
**Interaction with #3875 (requeue + step watchdog):** before this
change, every requeue of a crashed multi-node RL job first waited the
full grace period. Now it waits only for an in-flight checkpoint.
`.metadata` is the same completeness marker that #3906 uses for "latest
complete checkpoint". The SFT and inference templates do not use
`cleanup_grace_period` and are unchanged.
Test plan (all run):
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed.
- `rl @ examples/advanced/glm-4.5-air/swe.toml --dry-run`: the rendered
sbatch has the wait loop with the run's `checkpoints/` path and passes
`bash -n`. With `--no-ckpt` the loop is not rendered.
- Ran the rendered teardown snippet in bash against a temp checkpoint
dir:
- empty dir: no wait;
- newest step complete: no wait;
- newest step in flight: waits until the cap;
- older incomplete step but newest complete: no wait;
- in-flight save that completes after 1 s: waits ~1 s.
- `ruff check` and `ruff format --check` on the changed Python files.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes multi-node job teardown timing and checkpoint detection logic;
incorrect polling could tear down early or delay allocation release, but
scope is limited to SLURM RL launcher scripts.
>
> **Overview**
> Multi-node SLURM RL jobs no longer **sleep the full
`cleanup_grace_period` (default 1h) on every failure**. Teardown after a
non-zero exit now waits only while an **in-flight trainer checkpoint**
is detected.
>
> The `multi_node_rl.sbatch.j2` teardown block is gated on both
`cleanup_grace_period` and a rendered **`ckpt_dir`** (from
`get_ckpt_dir` when `[ckpt]` is enabled). Instead of a fixed `sleep`, it
polls every 10s: if the newest `step_*/trainer` directory lacks DCP
**`.metadata`**, it keeps the task alive (preserving
`--kill-on-bad-exit` behavior for peer trainers); otherwise it tears
down immediately. **`cleanup_grace_period` is documented as an upper
bound**; runs without checkpoints skip the wait entirely.
>
> `write_slurm_script` in `rl.py` passes `ckpt_dir` into the multi-node
template renders.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8168264718f38f6e2e9636ea7bc7098e91743ba3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## What
Renames `tasks_per_minute` to `dispatch_per_minute` on `orchestrator`,
the `eval` entrypoint and the SFT online `[eval]` block. This uses the
same name and wording as #3652.
The old name was wrong. The dispatcher takes one rate-limiter token per
**episode** it starts (`Dispatcher.acquire`, called once per scheduled
episode), not one per task. With `group_size = 8`, `tasks_per_minute =
80` started only 10 tasks per minute. The docstrings now say what is
counted: at most N episodes start per minute, and a group counts
`group_size` times.
Breaking: configs that set `tasks_per_minute` now fail validation
(`extra="forbid"`). No shipped config, doc, test or skill sets it or
mentions it.
## Overlap
#3652 (draft, orchestrator as hook-wired components) makes the same
rename. This PR lands it on its own and does not depend on that
refactor.
## Test plan
- `pytest tests/unit/orchestrator tests/unit/eval
tests/unit/test_configs.py -m "not gpu"`: 357 passed.
- `ruff check` and `ruff format --check` on the changed files.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Breaking config field rename only; runtime rate limiting behavior is
unchanged aside from clearer documentation.
>
> **Overview**
> **Breaking rename:** `tasks_per_minute` → `dispatch_per_minute` on
orchestrator config, eval/SFT online eval config (`ServedEvalConfig`),
and everywhere it is passed into `Dispatcher` (orchestrator + eval
runner).
>
> The limit semantics are unchanged in code (still `AsyncLimiter` with
one token per scheduled episode in `Dispatcher.acquire`), but the name
and docstrings now match behavior: the cap is **episodes started per
minute**, and a rollout group with `group_size` N consumes N tokens.
Configs that still use `tasks_per_minute` will fail validation under
`extra="forbid"`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0436304d5e40baed76abfadaa5b989048e818b6a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Removes `model.index_cache` (`IndexCacheConfig.topk_freq` and
`.topk_pattern`). The trainer still turns on IndexShare from the model's
own `indexer_types` schedule (`src/prime_rl/trainer/model.py`), as
before.
Why: the override changes the trainer only. No inference-side config
matches it, so setting it makes the trainer pick different top-k indices
than vLLM unless the user also passes the same vLLM `hf_overrides` by
hand. The setting appears in no config, example or test. The HF-level
`use_index_cache` / `index_topk_freq` / `index_topk_pattern` attributes
on `GlmMoeDsaConfig` stay, so a checkpoint's own `config.json` still
drives them.
Breaking: `[trainer.model.index_cache]` / `[model.index_cache]` now
fails validation.
Overlap with open PRs:
- #3833 rewrites the same `index_cache` lines in `model.py`
(`set_model_options(model_config, "index_cache", ...)`). Whichever lands
second drops or rebases that block; the conflict is small.
- #3879 is based on that code too.
- #3616 already leaves `trainer.model.index_cache` unset for the reason
above: a trainer frequency override replaces the checkpoint schedule and
requests weights the checkpoint does not have.
Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed.
- `pytest tests/unit/utils/test_weights.py` (includes
`GlmMoeDsaForCausalLM`): 7 passed.
- `ruff check` and `ruff format --check` on the changed Python files:
clean.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking config validation for anyone using `index_cache`, and it
changes sparse-attention index scheduling to follow the checkpoint
only—important for trainer/inference logprob alignment on DSA models.
>
> **Overview**
> **Removes the trainer-only `[trainer.model.index_cache]` override**
(`topk_freq` / `topk_pattern`). Configs that still set it will fail
validation.
>
> IndexShare for GLM-5.2-style DSA models is unchanged in behavior: when
the checkpoint’s `indexer_types` includes `"shared"` layers, the trainer
still sets `use_index_cache` on the HF config and logs the full/shared
layer counts. It no longer applies manual `index_topk_freq` /
`index_topk_pattern` or clears `indexer_types`, which could diverge from
vLLM rollouts.
>
> Docs no longer mention manually overriding the schedule via
`[trainer.model.index_cache]`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bf75c92edd9982a776bff29601c1e8c4519aebeb. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
vLLM 0.31's routed-experts capturer already returns uint8 or uint16,
chosen from the model's expert count (`uint8 if num_experts <= 256 else
uint16`). `serialize_routed_experts` cast every request back to uint8
whenever its ids happened to be below 256. On a >256-expert model
(NemotronH Super/Ultra: 512 experts), a request whose ids all fall below
256 therefore came out uint8 while the others were uint16. Packing two
such samples into one micro batch trips `assert routed_experts.dtype ==
sample.routed_experts.dtype` in `orchestrator/batch.py`. Multi-turn
traces hit the same mix: verifiers concatenates the per-turn arrays, and
NumPy widens the result.
`serialize_routed_experts` now keeps the capturer's dtype and asserts
that it is uint8 or uint16. Every request of a model then has the same
dtype. Models with 256 or fewer experts are unchanged (uint8).
Tests: the existing serialize test now passes a uint16 array with ids
below 256 and checks that it stays uint16. `tests/unit/orchestrator`,
`tests/unit/inference`, `tests/unit/utils`, `tests/unit/test_configs.py`
pass with `-m "not gpu"`; `ruff check` and `ruff format --check` are
clean.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Narrow inference serialization fix; ≤256-expert models stay uint8, and
behavior only changes where mixed dtypes previously caused orchestrator
batch asserts.
>
> **Overview**
> **Fixes inconsistent routed-experts dtypes** that broke micro-batch
packing on models with more than 256 experts (e.g. NemotronH 512).
>
> `serialize_routed_experts` no longer re-encodes expert indices to the
smallest integer width based on per-request max values. It keeps the
array dtype from vLLM’s capturer (`uint8` or `uint16` from model expert
count), with assertions that the input is 3-D and one of those two
types. The serialized payload’s `"dtype"` field reflects that array
unchanged.
>
> Unit tests now decode using `encoded["dtype"]` and assert a `uint16`
capture with all ids < 256 stays `uint16` through serialize/decode.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e4a8e9ea05cb4e960192cdb7929e2c2566ca9734. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Under `rl`, `inference.deployment.gpus_per_node` was never set from
`deployment.gpus_per_node`. `InferenceConfig.auto_setup_disaggregated`
sizes `data_parallel_size_local`, `data_parallel_size` and
`api_server_count` from the nested copy, which defaults to 8. The
launcher, sbatch `dp_per_node` and weight-broadcast world size use the
top-level copy. So a P/D run on nodes that do not have 8 GPUs got
mismatched engine counts.
Example: `examples/advanced/glm-5.3/swe.toml` with
`deployment.gpus_per_node = 4` resolved to `data_parallel_size_local =
8` and `api_server_count = 8`, while the template launched 4 engines per
node.
Changes:
- `propagate_shared_fields` now fills
`inference.deployment.gpus_per_node` from `deployment.gpus_per_node`. As
with the other shared fields, setting both to different values raises.
- `RLConfig.validate_shared_configs` requires the two to be equal. This
catches a nested-only override that leaves the top-level value at its
default.
## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 335 passed (includes the new
`test_disaggregated_inference_inherits_deployment_gpus_per_node`)
- Parsed all 78 tomls under `configs/` and `examples/` with every config
class on main and on this branch: same results, none fail
- glm-5.3 `swe.toml` with `deployment.gpus_per_node = 4` now resolves
`inference.deployment.gpus_per_node = 4`, `dp_local = 4`,
`api_server_count = 4`
- `ruff check` / `ruff format --check` on the changed files
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Mis-sized inference parallelism and launcher/engine counts on
multi-node disaggregated runs; the change is narrow config propagation
plus validation with low blast radius beyond P/D sizing.
>
> **Overview**
> Fixes a config bug where **`deployment.gpus_per_node`** at the RL top
level did not flow into **`inference.deployment.gpus_per_node`**, so
disaggregated P/D runs could size **`data_parallel_size_local`**,
**`api_server_count`**, and related fields from the nested default (8)
while SLURM/launchers used the top-level value (e.g. 4).
>
> **`propagate_shared_fields`** now copies top-level
**`deployment.gpus_per_node`** into
**`inference.deployment.gpus_per_node`** (with the same
shared-vs-sub-config conflict rules as other shared fields).
**`RLConfig.validate_shared_configs`** additionally requires the two
values to match when inference is enabled, catching nested-only
overrides that disagree with the top-level deployment.
>
> A unit test asserts inheritance and that mismatched nested/top-level
**`gpus_per_node`** fails validation.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
863bbf67298b456c48418c7326c820cc930ca203. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Drops seven typed `[inference.vllm]` fields: `seed`, `enforce_eager`,
`dtype`, `trust_remote_code`, `enable_dbo`, `max_loras`,
`all2all_backend`, and the `All2AllBackend` alias. Each one only
repeated vLLM 0.31's own default, and nothing in prime-rl reads it.
`VllmConfig` is `extra="allow"`, so all seven keys still pass through to
vLLM unchanged. The `VllmConfig` docstring says to type only fields that
prime-rl types, defaults or reads back; these were none of those.
`all2all_backend` also suggested control it doesn't have for P/D: the
sbatch templates set the per-role backend in `ROLE_EXTRA`
(`inference.sbatch.j2:261,276`, `multi_node_rl.sbatch.j2:405,419`). That
stays as is.
Behavior: I resolved the vLLM serve args (`to_namespace` →
`make_arg_parser().parse_args`) on main and on this branch for the
default config and for `--vllm.enforce-eager`, `--vllm.enforce-eager
true`, `--vllm.max-loras 2`, `--vllm.dtype bfloat16`, `--vllm.seed 7`,
`--vllm.all2all-backend deepep_low_latency`, `--vllm.enable-dbo true`,
`--vllm.trust-remote-code true`, `@
examples/advanced/glm-5.3/infer/pd.toml`. All seven values are
identical. The nested rl form `--inference.vllm.enforce-eager
--inference.vllm.max-loras 2` also resolves to `True, 2`. `"enable_dbo"
= true` in `examples/advanced/glm-5.3/swe.toml` sits under
`prefill_vllm_overrides` and is unaffected.
Differences:
- `--no-vllm.enforce-eager` (the negated bool flag) only exists for
typed fields. Use `--vllm.enforce-eager false`. All four removed bools
default to False, so this only matters when undoing a toml that set one
to true.
- `dtype` now accepts every value vLLM accepts (for example `half`)
instead of prime-rl's narrower Literal.
`skills/configs/SKILL.md` used `enforce_eager = true` as its TOML
boolean example. It now uses `enable_prefix_caching = true`, which is
still typed, so `--no-flag` applies to it.
## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/test_parsers.py -m "not gpu"`: 489 passed
- Parsed all 78 tomls under `configs/` and `examples/` with every config
class on main and on this branch: same results
- The resolved-args comparison above
- `ruff check` / `ruff format --check` on the changed file
## What
Drop recipe lines that only repeat what the config already resolves to.
The resolved configs do not change, except for `skip_optimizer` (see
below).
- `[weight_broadcast] type = "nccl"`: `rl` already picks NCCL when
inference is managed and LoRA is off. Removed from minimax-m2.5 swe,
intellect-3.1 rl, and qwen3-30b-a3b swe/math. The block stays in
examples/extra/dynamo/rl.toml (no managed inference, so the default
there is filesystem) and in glm-5.3 (it also sets port and timeout).
- `ac.freq = 1` (the default) is removed from 8 recipes. The
`[*.model.ac]` table header stays, matching the GLM-4.5-Air recipes.
- `trainer.dist_timeout_seconds = 3600` / `dist_timeout_seconds = 3600`
(the default) is removed from 5 RL recipes and vlm/sft-moe.
- `inference.vllm.enable_return_routed_experts = true` is removed where
`trainer.enable_router_replay = true` already sets it (glm-4.5-air ×4,
nemotron-3-super).
- `[trainer.ckpt] skip_optimizer = true` is removed from glm-4.5-air
swe-budget/search/terminal and nemotron-3-super swe.
- It only affects loading: on resume, it drops the AdamW/Muon state.
- It came from the #2862/#2915 ablation configs. None of these recipes
warm-starts from another run's checkpoint. They train from the HF model
and resume their own checkpoints, which include optimizer state.
- configs/ci/integration/reverse-text-sft/full-offload-resume.toml keeps
it on purpose: it tests that path.
- docs/scaling.md: the `fused_lm_head_token_chunk_size` default is 8192
(since #3302), not 1024.
## Not touched
- `fused_lm_head_token_chunk_size = 1024` pins (7 recipes) and `attn =
"flash_attention_3"` pins (10). Should they stay as memory/hardware
choices?
- `[ac_offloading] max_inflight_activations` lines (a separate PR
removes the field).
- The `[weight_broadcast]` blocks of the GLM-4.5-Air and nemotron
recipes (handled in the weight_broadcast.timeout PR, to avoid a
conflict).
## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed (validates every TOML under configs/ and examples/).
- Resolved configs of all 14 edited recipes, main vs this branch
(RLConfig/SFTConfig `model_dump`):
- identical, except `trainer.ckpt.skip_optimizer` True → False in the 4
recipes above;
- the checkout path in `template_path` also differs (main checkout vs
this worktree), which is not a recipe change.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Mostly documentation and deduplication; the only resolved-config
change is `skip_optimizer` false on four recipes that resume with full
optimizer state, which matches their intended training flow.
>
> **Overview**
> Trims RL/SFT example and advanced recipe TOMLs by deleting settings
that already match framework defaults, so recipes only spell out
non-default choices.
>
> Removed redundant **`[weight_broadcast] type = "nccl"`**,
**`trainer.model.ac` `freq = 1`**, **`dist_timeout_seconds = 3600`**,
and **`inference.vllm.enable_return_routed_experts`** where NCCL
broadcast, AC frequency, dist timeout, and routed-expert return are
implied (e.g. managed inference + **`enable_router_replay`**). Dropped
**`[trainer.ckpt] skip_optimizer = true`** from four GLM-4.5-Air and
Nemotron SWE/search/terminal recipes so resume loads optimizer state
from their own checkpoints instead of discarding it.
>
> **`docs/scaling.md`** now documents
**`fused_lm_head_token_chunk_size`** default **8192** (was incorrectly
**1024**). Explicit pins like **`fused_lm_head_token_chunk_size =
1024`** in memory-tight recipes are unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c87c43defc655e83c39559736ca874740327d266. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Sets `dsa_backend = "cudnn_flashmla"` for the trainer in the GLM-5.3 RL
example (`examples/advanced/glm-5.3/swe.toml`). The SFT example already
uses it (#3829); the RL example still ran the TileLang forward and
backward.
Measured on 1x8 H200 with the trainer settings of `swe.toml` (131k seq,
cp 4, ep 8, fp8 + `deepgemm_fp8`, full AC + offload, compile). Random
init, 8 layers (3 dense + 5 MoE), fake data, 2 micro-batches per dp
rank, balanced routing:
| `dsa_backend` | step 2 / 3 | sparse attn fwd per call | sparse attn
bwd per call |
|---|---|---|---|
| `tilelang` | 16.6 s / 15.5 s | 35 ms | 190 ms |
| `cudnn_flashmla` | 12.8 s / 12.1 s | 12 ms | 53 ms |
- Entropy and mismatch KL are identical to 4 decimals.
- With a 4-layer run (5.7 s), one MoE layer costs 1.6 s instead of 2.07
s. Extrapolated to 78 layers at this shape: ~124 s vs ~160 s per step
(-22%).
- Kernel check at the CP shape (8k local queries vs 32k keys, cp rank 0
and 3, top-k 2048, sentinel slots): out / dq / dkv relative error vs
TileLang 5e-4 to 9e-4, LSE 7e-8.
- Needs the `flash-mla` extra, which the README's `uv sync --all-extras`
installs.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Single example TOML knob with no production code changes; requires the
optional flash-mla dependency for the new backend.
>
> **Overview**
> Aligns the GLM-5.3 RL example trainer config with the SFT example by
setting **`dsa_backend = "cudnn_flashmla"`** in
`examples/advanced/glm-5.3/swe.toml`, so sparse DSA attention uses the
cuDNN/FlashMLA path instead of the default TileLang forward/backward.
>
> This is a **performance-only** example change for long-context RL
training (131k seq, CP/EP, fp8 MoE); behavior should match TileLang
within measured numerical tolerance when the `flash-mla` extra is
installed.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e2135c38262af40b51d866026cdfa3a83fb7c7b4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Use Verifiers' shared sampling config and resolution path for evaluation
and rollout dispatch. Parameter names, provider options, source
defaults, and agent overrides follow the same rules in native Verifiers
and Prime-RL. Training retains its strict config for the distribution
the trainer replays.
## Sampling flow
```mermaid
flowchart TD
T["Train source and agent config<br/>TrainSamplingConfig and replay bounds"] --> V["Validate live-policy sampling<br/>Source owns the distribution"]
V --> S["Shared Verifiers SamplingConfig<br/>Normalize aliases and extra_body"]
V --> A["AgentConfig.sampling<br/>Sparse overrides across config transport"]
E["Eval source and agent config"] --> S
E --> A
S --> R["RunRequest to env server"]
A --> M["Verifiers resolve_agent<br/>Shared merge_defaults"]
R --> M
M --> P["Provider request<br/>Non-null resolved parameters"]
M --> C["Trace<br/>Complete resolved sampling"]
```
## Shared parameters
Verifiers normalizes `max_tokens` / `max_completion_tokens` and flattens
`extra_body` before merging each override layer. Source values replace
group defaults; agent values replace inherited sampling. An explicit
null clears an inherited parameter.
Within one sampling block, top-level values take precedence over
`extra_body`. A typed training `top_k=20`, or the automatic replay bound
of `512`, therefore takes precedence over `extra_body.top_k=-1`. With no
typed `top_k`, the disabled sentinel remains effective.
Prime-RL carries `vf.SamplingConfig` through dispatch and converts
`TrainSamplingConfig` once. Source defaults and agent overrides use
Verifiers' `merge_defaults`; duplicate eval schemas and
sampling-dictionary converters are removed. Request-specific cache salts
are copied onto the shared config.
Unresolved agent overrides remain sparse across env-server config
boundaries. `resolve_agent` materializes the sampling used for
generation, and traces record the complete resolved config. Provider
dialects and the renderer client omit nulls when constructing requests.
## Training ownership
Live-policy sources validate their sampling when the config loads.
Unsupported source parameters, including `frequency_penalty`, are
rejected before generation.
The source owns the distribution replayed by the trainer. Every agent in
a live-policy source, including non-trainable roles, may override only
`max_tokens`, `reasoning_effort`, and `chat_template_kwargs`.
Distribution parameters belong on the source, even when an agent would
repeat the same value. Policy logprobs remain enabled. Evaluation and
frozen-model sources retain general agent overrides.
This removes the post-rollout sampling comparison from `TrainSink`.
## Dependency
Pins Verifiers `2cb0a6d`, the merged commit for [Verifiers
#2762](https://github.com/PrimeIntellect-ai/verifiers/pull/2762), for
shared sampling normalization and resolution. This includes merging
per-call judge sampling overrides before constructing SDK requests,
preserving unrelated configured provider parameters. The lockfile
updates `prime-tunnel` to `0.1.14` to meet the merged dependency's
minimum.
Before publishing packages outside this source checkout, release that
Verifiers change and raise the `verifiers` minimum in both `prime-rl`
and `prime-rl-configs`. The current `>=0.3.2.dev158` package constraints
do not guarantee these semantics.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how sampling is resolved and validated for all rollouts;
mis-merged configs or rejected agent overrides could break existing
TOMLs, though unit tests cover the main inheritance and policy rules.
>
> **Overview**
> **Unifies rollout sampling** on Verifiers' shared `SamplingConfig` and
merge rules instead of Prime-RL–specific eval schemas and
`to_sampling_args()` dict builders.
>
> Eval sources and group defaults now use `vf.SamplingConfig`;
train/eval env wrappers carry a typed `SamplingConfig` through to the
env server (including per-request `cache_salt` via `model_copy`). Policy
train sources get **load-time validation**: the source owns distribution
parameters (`temperature`, `top_p`, etc.), while agents may only
override `max_tokens`, `reasoning_effort`, and
`chat_template_kwargs`—frozen-model and eval paths stay permissive.
`TrainSink` reads temperature from `env.config.sampling` instead of a
resolved args dict.
>
> **Docs** describe alias normalization (`max_tokens` /
`max_completion_tokens`), `extra_body` merging, and live-policy override
limits. **Tests** cover inherited sampling merges and policy sampling
rejection cases. Lockfile bumps `prime-tunnel` to `0.1.14`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
671a5aa9857a39a4d44fa7902f1c89021b8fd380. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- `WeightWatcher.poll_interval` default: 1.0s → 0.1s
- `WeightReceiver.wait_published` sleep: 0.2s → 0.1s
## Why
The trainer blocks in `WeightSender._wait_for_receiver_ready` until the
orchestrator notices `.sender_ready`. With a 1s poll, that adds 0–1s
(~0.5s avg) of idle trainer time on every step. NVIDIA flagged this
while benchmarking the ModelExpress broadcast (#3890).
A poll is one `glob("step_*")` on the broadcast dir (≤2 entries thanks
to `_clean`) plus a few `exists()` calls, so 10Hz is negligible.
Correctness relies on the marker handshake + `update_lock`, not on the
poll timing.
Caveat: these are sync FS calls on the orchestrator event loop. On a
very slow shared FS, that might show up in `EventLoopLagMonitor`. If it
does, we can move them to `asyncio.to_thread`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Timing-only tuning on poll loops; no change to weight handshake logic,
though more frequent sync FS calls could add event-loop lag on very slow
filesystems.
>
> **Overview**
> **Faster weight-version discovery** so the trainer spends less time
blocked waiting for the orchestrator to see `.sender_ready`.
>
> The orchestrator `WeightWatcher` default `poll_interval` drops from
**1.0s to 0.1s**, cutting typical idle wait on each broadcast handshake
from ~0.5s toward ~0.05s. `WeightReceiver.wait_published` uses the same
**0.1s** sleep (was 0.2s) while waiting for the sender marker.
>
> Handshake correctness is unchanged (markers + `update_lock`); cost is
slightly more frequent lightweight FS checks on the orchestrator event
loop.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5c825d0f126e16885eae77f4f6ebc2ddf306de59. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## security(ci): pin BuildKit builder to v0.33.1 and rotate the GHCR
registry buildcache (CVE-2026-93318)
### What changed (rebased onto current main)
`.github/workflows/build_image.yaml`:
1. **Builder pin** — `docker/setup-buildx-action@v4` now sets
`driver-opts: image=moby/buildkit:v0.33.1`. Without it the job starts
the rolling `moby/buildkit:buildx-stable-1` tag, and because these are
persistent self-hosted runners (`image-builder`,
`image-builder-arm-2204`), the builder version is not even guaranteed to
follow the tag — a stale local image can keep a pre-patch builder alive
indefinitely. The pin makes the builder version deterministic.
2. **Registry cache rotation** — both shared cache refs rotated:
- `:dependency-buildcache-<suffix>` ->
`:dependency-buildcache-v2-<suffix>`
- `:application-buildcache-<suffix>` ->
`:application-buildcache-v2-<suffix>`
### Why rotation (evidence)
- The registry-backed cache was introduced in d8f3d0101 (2026-08-16,
#3279) and has been written on nearly every run since — including all
runs before the patch was published.
- BuildKit v0.33.1 (the CVE fix) was released **2026-09-30T17:08Z**; the
rolling `moby/buildkit:buildx-stable-1` tag only moved to that digest at
**2026-09-30T17:32Z**. Every cache write before that timestamp came from
a builder older than v0.33.1, on runners that may also hold stale local
images.
- Per the CVE-2026-93318 playbook: stop importing a shared cache that
pre-fix builders wrote, rebuild from trusted inputs, and pin the patched
builder so every future write is attributable to a fixed version.
### Expected cost
The first run per platform suffix after merge does a cold build of the
dependency layer + application layer (no cache import). The old
`*-buildcache-*` tags can be deleted from the `prime-rl` GHCR package as
cleanup — they are cache-only refs, never deployed.
### Out of scope / notes
- `docker-push.yaml` (old Docker Hub publisher) no longer exists on main
— nothing to pin there.
- No GHA-scope (`type=gha`) caches exist in this repo's workflows
(verified by grep), so no Actions-cache cleanup applies.
- Build image runs are frequent and mostly manual dispatch; this PR
should merge before the next `main` image build.
### Security review requested
- Cache invalidation: confirm the `*-v2-*` refs fully replace the old
buildcache lineage.
- Published-image provenance: GHCR `prime-rl` images built before
2026-09-30T17:32Z were produced by a pre-patch builder; assess whether a
clean rebuild of the current release tags is warranted.
- No applicable CODEOWNERS entry exists in this repo; CI/build owner
please review.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> CI-only security remediation with intentional cache busting (slower
first builds); no application runtime code changes, but GHCR images
built before the fix may need a separate provenance/rebuild decision.
>
> **Overview**
> Remediates **CVE-2026-93318** in the GHCR image build workflow by
making the BuildKit builder version fixed and breaking reuse of
artifacts produced before the patch.
>
> **BuildKit pin:** `docker/setup-buildx-action` now sets `driver-opts`
to `moby/buildkit:v0.33.1` (digest-pinned) so self-hosted
`image-builder` runners do not keep serving a stale local
`buildx-stable-1` builder.
>
> **Cache and deps lineage:** Shared registry cache refs move to
`dependency-buildcache-v2-*` and `application-buildcache-v2-*` so layers
written by pre-v0.33.1 builders are not imported. Dependency base tags
gain a `-v2-` epoch (`deps-${key}-v2-${suffix}`) so existing
`deps-${key}` images are not reused as the runtime base when only
Dockerfile/lock inputs are unchanged.
>
> The first build per platform after merge is expected to be cold (no
old cache import); published runtime tags are unchanged—only CI
remediation naming and builder configuration.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0310e6d89608d9d34fd0c1a4c0e9a5c6ba5261bf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Warn when SFT constructs a renderer that does not guarantee prefix
stability. The warning explains that each conversation is rendered once
into one training sample, that N assistant turns are not expanded into N
samples, and that earlier reasoning may be omitted by the template.
Cached renderers warn only on construction; stable renderers stay quiet.
Custom renderers without the capability are conservatively treated as
unknown.
Pin `deps/renderers` to merged main revision `41f9290`, which includes
https://github.com/PrimeIntellect-ai/renderers/pull/184. It provides the
resolved capability and the manual, opt-in witness audit. Sample
construction is unchanged.
Validation: all **73 SFT dataset tests passed**, including
stable/unstable renderer selection and cache-warning behavior. Prime-rl
unit-test CI passed on the preceding revision; this update changes only
the renderer gitlink to the merged revision. Dependency requirements are
unchanged apart from renderer Python >=3.11, compatible with prime-rl
Python 3.12. The manually invoked renderer audit passes **59 tests** and
is excluded from normal CI discovery.
Reduce CI time and GPU usage by selecting the relevant test suites for
each PR, moving hosted eval to CPU, and running independent setup steps
in parallel.
- Select GPU unit tests, SFT, RL, and hosted eval from changed paths
before allocating runners. Shared runtime and dependency changes retain
broad coverage; pushes to `main` and manual runs execute the full suite.
- Keep RL/SFT coverage for checkpoint converters, dashboard code, and
the shared dashboard smoke helper.
- Run `gsm8k_eval` on `ubuntu-latest` because it uses hosted inference.
- Run public submodule initialization and `uv` setup concurrently, then
wait for both before installing dependencies. Keep dependency caching
keyed on `uv.lock` and the five-job limit on GPU integration tests.
- Cancel superseded CPU and style runs on the same PR.
- Give the GPU workflow read-only contents access and the test selector
PR read access.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Path-based GPU job gating can skip integration coverage on PRs if
filters miss a dependency; full suite still runs on main and manual
dispatch.
>
> **Overview**
> **GPU CI now picks which jobs to run from the PR diff**, instead of
always running the full GPU unit + integration matrix on every non-draft
PR. A new **Select tests** job uses path filters for unit, SFT, RL, and
eval; pushes to `main` and `workflow_dispatch` still run everything.
RL/SFT integration scenarios are built dynamically (still capped at
`max-parallel: 5` on `prime-rl-2xh200`).
>
> **`gsm8k_eval` is split out** into a dedicated job on `ubuntu-latest`
(hosted inference), so it no longer consumes GPU runners. Integration
pytest invocations use `tests/integration/test_${{ matrix.test }}.py`
from the dynamic matrix rather than per-row `pytest_args`.
>
> **Setup and queueing tweaks:** submodule init and `setup-uv` run in
parallel in CPU/GPU jobs; CPU and style workflows cancel in-progress
runs per PR; GPU workflow gets `workflow_dispatch`, read-only
`contents`, and PR-scoped concurrency cancel. `docs/development.md`
documents the new triggers and runner split.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
20da35f30de85b2b18cf82e29598846a1228ca12. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
SFT now pads packed rows only to a multiple of cp, as RL does, instead
of to `seq_len`. The fp8 indexer drops its autotuning, which
re-benchmarked configs on every new row length and made unpadded rows
slower than padded ones on DeepSeek-V4 (#3726).
- The indexer pads keys to a multiple of 16 and runs one fixed config,
within 1.05x of the best.
- Every rank, including RL on DeepSeek-V4 and GLM-5, runs that config
with bitwise-identical top-k.
- SFT and RL throughput count trained tokens, not `seq_len` × rows or
the first row × count.
- The SFT `seq_len % (2 * cp)` check is gone: CP only needs `seq_len %
cp`, which configs enforce.
Same samples per arm, time summed over steps 5 to 20, one H200 node:
| Workload | Padding on main | main | This PR | Speedup |
|---|---|---|---|---|
| DeepSeek-V4-Flash 6L, scaleswe, 256K rows, cp 8 | 19.8% | 61.2 s |
38.2 s | 1.60x |
| GLM-4.5-Air 8L, math, 131K rows, dp 4 cp 2 | 7.3% | 223.8 s | 200.1 s
| 1.12x |
| GLM-4.5-Air 8L, scaleswe, 131K rows, dp 4 cp 2 | 19.7% | 701.0 s |
623.0 s | 1.13x |
On DeepSeek-V4, the 1.60x exceeds the 1.25x that removing 19.8% of
tokens predicts because two effects multiply: main's token-0 pads crowd
onto the same experts, and the padding itself costs compute. The
DeepSeek-V4 ablation section below separates the two.
On GLM with scaleswe, removing 19.7% of the tokens would predict about
1.25x, but it measured 1.13x. Its 4 data-parallel ranks now get rows of
different lengths, and each step likely waits for the rank with the
longest rows.
Loss matches main to within 1e-3 per step. This overlaps
https://github.com/PrimeIntellect-ai/prime-rl/pull/3932 in
`CatDataset._finalize_pack`. Harness:
[`benchmarks/scripts/sft_pad_to_cp/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/0ed0e78b33e8533d7fd1e0d603759dc2ab50e5dd/benchmarks/scripts/sft_pad_to_cp)
(removed before merge).
## DeepSeek-V4 ablation
Each row changes one thing on the DeepSeek-V4 workload above, to
separate the cost of the padding length, of token-0 pads crowding onto
the same experts, and of indexer re-tuning:
| Arm | Time | Speedup vs main |
|---|---|---|
| main: pads every row to `seq_len` with token 0 | 61.2 s | 1.00x |
| main, but pads with the row's own tokens (#3932) | 49.6 s | 1.23x |
| pads only to a multiple of cp, indexer still autotuned | 73.6 s |
0.83x |
| pads only to a multiple of cp, fixed-config indexer (this PR) | 38.2 s
| **1.60x** |
## Alternatives considered
- Bucketing the autotune key on `next_power_of_2(S_q)` reached 1.47x on
DeepSeek-V4. Each bucket kept its first row's config (up to 1.44x slower
later), short rows paid extra tunes, and each rank still tuned on its
own rows, so ranks could run different kernels.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
SFT samples can contain prefilled assistant turns that must remain in
context without becoming training targets. Read an optional
`message_loss_mask` dataset column and pass it directly to
`renderers.build_training_sample`; for a user/assistant/user/assistant
conversation, `[0, 0, 0, 1]` trains only the final assistant turn.
The renderer owns token attribution and mask validation, including GLM's
assistant-generated closing markers. prime-rl performs no owner walking
or template-specific mask reconstruction. Selection only removes
existing loss targets and preserves input/target token IDs. Missing or
null masks preserve normal supervision; fully masked samples follow the
existing skip behavior.
`data.columns.message_loss_mask` supports renamed columns. For
prompt/completion rows, the mask covers their concatenated message list.
This API reads a separate column; datasets with inline
`messages[].trainable_mask` need conversion before use.
Pins `deps/renderers` to upstream main commit
`e3ace557545274385abb30435975c134c7c2429d`, which merges
https://github.com/PrimeIntellect-ai/renderers/pull/181. The renderer
dependency is now merged.
Validation:
- Signed pin update `838828713` points to the merged renderer commit.
Its Git tree is identical to the previously tested renderer head; no
source changes accompany the pin update.
- The following tests and checks passed on signed implementation commit
`7e0800051`:
- 73 SFT dataset tests passed, including real GLM-5 and Qwen3
tokenizers, both dataset layouts, custom column names,
missing/null/all-enabled masks, excluded initial/final turns, fully
masked samples, and invalid values/lengths.
- Ruff 0.13.0 lint and formatting checks passed for the changed Python
files; `git diff --check` passed.
- CPU tests ran in an isolated Python 3.12 environment with Transformers
5.6.2 and PyTorch 2.14.1. No GPU training run performed.
- Commit signature verified locally.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes which tokens receive loss during SFT when datasets supply
masks; incorrect masks could silently train the wrong turns, though
behavior is opt-in and heavily tested against real renderers.
>
> **Overview**
> Adds **optional per-message SFT loss selection** via a dataset
`message_loss_mask` column (0/1 or booleans, one entry per resolved
message—including prompt+completion rows). The trainer forwards the
column to `build_training_sample` so renderers drop supervision on
excluded turns **without changing token IDs** (e.g. `[0, 0, 0, 1]` keeps
context but trains only the last assistant reply). Missing/null masks
behave as today; all-zero masks still skip the sample.
>
> **Config and docs:** `SFTColumnsConfig.message_loss_mask` defaults to
`"message_loss_mask"` and can be remapped (e.g. `"selection"`); dataset
init errors if a remap points at a missing column. `docs/training.md`
documents the format and semantics.
>
> **Tests:** Coverage for GLM-5 and Qwen3, both dataset layouts, custom
column names, partial masks, fully masked rows, and invalid mask
values/lengths.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
838828713529afa49a57cf441071f946ec195cdf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Why
Since **Sep 2** the `4xa6000` runner has been offline. Since then,
`benchmark_regression` has queued on a dead label on **every single GPU
Tests run**, hit GitHub's 24h self-hosted queue timeout, and failed the
workflow. There has not been one green GPU Tests run in over a month, so
the per-PR GPU check is permanently red and real regressions hide in the
noise. Measured over Sep 29-Oct 6: all 28 completed runs failed at
exactly 1440 +/- 1 min, and 20+ phantom `benchmark_regression` jobs were
sitting in the queue at any time.
## What changes
1. **uv cache on the GPU jobs** (`enable-cache: true`, keyed on
`uv.lock`, mirroring `cpu_tests.yaml`) — each h200 pod currently
re-resolves and re-downloads the full dependency set from PyPI on every
job.
2. **`benchmark_regression` removed from the PR matrix.** It cannot
simply move to `prime-rl-2xh200`: the test unconditionally runs a 1-GPU
**and** a 4-GPU benchmark (a 2-GPU pod cannot host the latter), and it
asserts against A6000-captured baselines with a 15% tolerance (H200
results would blow through it). It belongs on benchmark hardware
(`benchmarks.yaml`) or behind a 4-GPU scale set when one exists — happy
to re-add once either exists.
3. **`max-parallel: 5` on the integration matrix** — a concrete per-PR
ceiling:
- 9 integration jobs + unit-tests = **6 h200 pods peak per PR**, 2 waves
- at current job durations (~10-15 min each) a PR finishes in ~25-35 min
- with 2-3 PRs in flight: <= ~18 pods steady-state; the ARC scale set
`maxRunners` (suggest 16-20) is the complementary global cap
4. `docs/development.md` CI table updated to match (also adds
`gsm8k_eval`, which was missing, and the current runner).
## Result
GPU Tests runs **only** on the `prime-rl-2xh200` scale set, and every PR
gets a real green or red within ~30-60 min instead of a guaranteed 24h
failure.
## Not in this PR (follow-ups)
- Bake git/uv into the CI image to kill the per-job `apt-get install
git`
- PVC-backed `~/.cache/uv` mount to avoid per-pod cache archive
downloads
- Nightly Tests still target a `research-cluster` runner that does not
exist — needs the same treatment or a cron disable
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> CI workflow and documentation only; no runtime or auth changes.
Benchmark regression no longer runs on every PR until re-homed to
suitable hardware.
>
> **Overview**
> **GPU Tests** is adjusted so PR runs can finish on live hardware
instead of timing out on a dead runner label.
>
> Both GPU jobs now enable **uv dependency caching** keyed on `uv.lock`
(same pattern as `cpu_tests.yaml`), cutting repeated PyPI
resolves/downloads on each H200 pod. The integration matrix **drops
`benchmark_regression`** (it targeted offline `4xa6000` hardware and
cannot run meaningfully on 2×H200), and adds **`max-parallel: 5`** so at
most five integration jobs run at once per PR. **`docs/development.md`**
updates the CI table to list the current integration scenarios
(`gsm8k_eval` included), `max-parallel`, and **`prime-rl-2xh200`** as
the runner.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8207cc05d9a731a4c5d7c561354284f1a79792d4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Bump `deps/verifiers` from `1fa2bbc42` to main `da75527ca`. This pulls
in the Harbor adapter changes from PrimeIntellect-ai/verifiers#2808:
- Honor reward-file precedence and select named rewards explicitly.
- Resolve separate verifier definitions by Harbor image precedence.
- Align the adapter with Harbor 0.24.0 and reject multi-step tasks.
- Move the `harbor` upload cutoff in `[tool.uv.exclude-newer-package]`
from 2026-08-11 to 2026-10-08, which matches `deps/verifiers`. verifiers
now pins `harbor==0.24.0`, which the old cutoff excluded.
- Relock: `harbor` 0.21.0 → 0.24.0, and `semver` 3.1.0 is new.
`deps/prime-envs` is already at its main head (`89dcc7ffc`). The current
verifiers pin already has the network notice
(PrimeIntellect-ai/verifiers#2769), so this bump supersedes #3734.
## Verification
- `uv sync --all-extras --all-packages --locked` succeeds.
- `uv run pytest -m "not gpu" tests/unit`: 663 passed.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Lockfile and uv policy changes only; risk is mainly behavioral shifts
from Harbor 0.24.0 and updated verifiers Harbor adapter usage in
eval/training paths.
>
> **Overview**
> Updates dependency resolution so **`harbor` 0.24.0** (via the
`verifiers[harbor]` pin) can install under uv’s rolling
**exclude-newer** policy by moving the bounded **`harbor` cutoff** from
`2026-08-11` to **`2026-10-08`** in `pyproject.toml`, mirrored in
`uv.lock`.
>
> The lockfile refresh bumps **`harbor` 0.21.0 → 0.24.0**, records new
transitive deps **`jsonschema`** and **`semver`**, and aligns the
verifiers harbor extra specifier to **`==0.24.0`**. This pairs with the
verifiers main bump described in the PR (Harbor adapter alignment and
reward/verifier precedence behavior), even though those code changes
live outside this diff.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
69e62c1fc116896ce99c79dbfc454959c748cb47. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
On torch 2.13.0 with compile and router replay, some MoE layers silently
replay layer 0's routing instead of their own from the second training
step on. This PR calls `.contiguous()` on each layer's routed-experts
slice, which removes the bug.
Each decoder layer `l` receives `routed_experts[:, :, l]`, a view into
one shared int32 tensor with axes (batch, sequence, layer, expert slot).
When `top_k` is not a multiple of 4, that view starts at a byte offset
that is not 16-byte aligned for some layers (odd layers on DeepSeek V4,
`top_k = 6`).
Inductor copies a misaligned input into a fresh aligned buffer, which
starts at offset 0. Once automatic dynamic shapes recompile the layer,
AOTAutograd mistakenly applies that offset 0 to the original shared
tensor when it rebuilds the layer's routed-experts output. Offset 0 of
the shared tensor holds layer 0's experts. A contiguous slice is its own
aligned tensor, so Inductor never makes the copy.
- Applied to the eight models that passed the raw view. `glm4_moe`
already called `.contiguous()`.
- Fixed upstream in pytorch/pytorch#191002 (torch 2.14.0 and 2.14.1, no
2.13.x release). The copy is cheap, so it can stay after an upgrade.
- Models with `top_k = 8` (Qwen3-30B-A3B, Trinity-Mini, GLM-4.5-Air)
were unaffected.
DeepSeek V4 Flash RL probe (compile on, router replay on, lr 0),
mismatch KL mean, lower is better:
| trainer | step 1 | steps 2-10 |
|---|---|---|
| compiled, strided slice (main) | 0.0008 | 0.022-0.11 |
| compiled, contiguous slice (this PR) | 0.0009 | 0.0007-0.0025 |
With compile off, the same probe spans 0.0008-0.0032 over steps 1-10.
## Verification
A standalone torch reproducer was added in
66641b0b0b31da76082edaadd70b4f601b13a53a and removed again at the end of
this branch, so main never carries it. Run it on one CUDA device from
that commit with `TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 uv run python
tools/repro_misaligned_replay_alias.py`. In earlier runs it printed `BUG
REPRODUCED` on torch 2.13.0 and was clean on the 2.14.0.dev20260809 and
2.16.0.dev20261008 nightlies.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Hosted runs with online evals score real rewards but the run dashboard
shows no `eval` metric group (ENG-6573).
The dashboard's `eval` group is built from the run's own metric keys
(`eval/{env}/...`). The orchestrator's in-process evals reach it through
the train monitor, but when evals run in a process of their own (SFT
online evals) the metrics are dropped: `PrimeEvalMonitor.log_metrics`
was a deliberate no-op.
- `PrimeEvalMonitor` now attaches to the parent training run via
`$RUN_ID` and forwards each epoch's `eval/...` metrics there.
- The eval process never reports the parent run's status: the SDK's
atexit crash hook is unregistered and `finalize()` only drains the
queue. Without that, an eval process exiting while the trainer is still
going would mark the whole run failed.
- No parent attached without `$RUN_ID`, so a standalone `prime eval` is
unchanged.
Note the ticket proposes exposing `environmentshub/resolve` on the
platform's internal API instead. That's a separate gap: it silences the
`EnvironmentResolutionError` warning and would create per-epoch
Evaluation records, but it does not produce the `eval` metric group, and
it needs four more `/evaluations` routes that the internal surface also
lacks.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how eval processes interact with the parent platform run
(metrics + SDK lifecycle hooks); mistakes could misreport run status or
drop metrics, but behavior is gated on $RUN_ID and explicitly avoids
finishing the parent.
>
> **Overview**
> Fixes hosted runs where **SFT online evals** compute rewards but the
run dashboard never shows the **`eval`** metric group (keys like
`eval/{env}/...`).
>
> **`PrimeEvalMonitor`** now attaches a metrics-only handle to the
parent training run when **`$RUN_ID`** is set, and **`log_metrics`**
forwards sanitized epoch aggregates there instead of being a no-op.
Standalone **`prime eval`** (no **`$RUN_ID`**) is unchanged.
>
> Lifecycle is guarded so the eval subprocess cannot poison the parent
run: the SDK **atexit** hook on the attached parent is **unregistered**,
and **`finalize()`** only **`flush`**es the upload queue—never finishes
or reports status on the trainer’s run.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
892035628173119b14a591b2975a5b6176f4c357. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
This is an alternative to #3907. The RL trainer decoded and preprocessed
each micro batch's images on the main thread right before its forward
pass, leaving the GPU idle. `WorkerPool`, a small ordered thread pool
configured by `data.num_workers` like torch's DataLoader, now prepares
micro batches ahead of the loop through a single `prepare_micro_batch`
hook.
- `num_workers` defaults to 0, which prepares on the main thread as
before, and one thread gives the full speedup. Here it counts threads,
unlike SFT's DataLoader processes.
- An earlier version used forked worker processes. They pickle data
through `/dev/shm`, risk copy-on-write memory, and were 0.6 s/step
slower than a thread.
- Pinned memory and `non_blocking` copies are left to a follow-up that
first removes the per-micro-step CUDA syncs.
Qwen3.5-9B trainer-only on 4 H200s, mock micro batches of 1024 px JPEGs
(about 1 s of CPU decoding each), median s/step, lower is better
(benchmark code added in
[`331fc83fe`](https://github.com/PrimeIntellect-ai/prime-rl/commit/331fc83fed9ff8b6fb435df5207a07e37b08c0e5)
and removed in the next commit):
| Arm | main thread | prepared ahead | time saved |
|---|---|---|---|
| this PR, 1 thread | 24.98 | 18.86 | 24.5% |
| this PR, 1 thread, optimizer CPU offload | 26.56 | 20.24 | 23.8% |
| earlier process version, 2 workers | 24.79 | 19.02 | 23.3% |
| #3907 (thread with pinned memory) | 24.98 | 18.63 | 25.4% |
Every arm matches the main-thread baseline bit for bit in loss and grad
norm. Host memory stays flat over 30 steps, 0.3 GiB above the baseline
for the prefetched images.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
## Summary
Two bugs in how `rl` sets `weight_broadcast.inference_world_size` on
main:
1. **World size computed before the DP fill.**
`auto_setup_weight_broadcast` set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
before `auto_setup_deployment` fills the single-node inference GPUs with
DP ranks. With `num_infer_gpus = 4` and `data_parallel_size` unset, the
NCCL group was sized for 1 inference worker while vLLM started 4, so the
first weight update cannot form the group.
2. **A single-node SLURM job cannot re-parse its `rl.json`** (since
#3788). The resolved `rl.json` always contains
`weight_broadcast.inference_world_size` (default 1), and #3788's guard
rejects any config that sets it. So `rl @ rl.json` in the single-node
sbatch fails validation for every NCCL config.
## Fix
- Single-node: set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
right after the DP fill in `auto_setup_deployment` (non-filesystem
only). Multi-node already sets it there.
- `auto_setup_weight_broadcast` copies `weight_broadcast` to the trainer
and orchestrator without touching the world size, and the guard is
removed. The top-level value is now only passed through: `rl` overwrites
it whenever it knows the inference size.
This also fixes what #3924 fixes.
## Behavior change
Yes (bug fixes).
- Resolved configs for every TOML in `configs/`, `examples/`, `k8s/`
that parses as `RLConfig` (41 of 78) are identical before and after,
except `trainer`/`orchestrator.weight_broadcast.inference_world_size`
goes from 1 to 4 in `examples/basic/hendrycks-sanity/rl.toml` and
`configs/ci/nightly/multimodal_color_codeword.toml` (4 infer GPUs, DP
unset).
- Re-parsing the dumped config (as the single-node sbatch does) fails on
main for all 18 single-node NCCL configs and passes for all of them
here.
- With `inference = None` and NCCL against external servers, a user-set
`weight_broadcast.inference_world_size` is now passed through instead of
rejected.
## Checks
- `pytest tests/unit/test_configs.py tests/unit/orchestrator -m "not
gpu"`: 298 passed
- `ruff check`, `ruff format --check`: clean
- New test `test_single_node_nccl_resolved_json_roundtrips`: dumps a
single-node NCCL config like `rl`'s `write_config`, re-parses it, and
checks it is equal. It fails on main with the guard error.
- `rl @ examples/basic/reverse-text/rl.toml --deployment.num-infer-gpus
2 --slurm.partition all --dry-run`, then re-parse the written `rl.json`:
fails on main, passes here (world size 2).
- GPU (one node): running: `rl @ examples/basic/hendrycks-sanity/rl.toml
--max-steps 3` on main and on this branch, plus the rendered single-node
sbatch for reverse-text (2 infer GPUs) run end to end.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes when NCCL weight broadcast groups are sized for single-node
runs; mis-sizing previously caused deadlocks or init failures during
weight updates.
>
> **Overview**
> Fixes incorrect **NCCL/NIXL** `inference_world_size` on single-node RL
runs when vLLM **data parallel size** is inferred from `num_infer_gpus`
rather than set explicitly.
>
> **`auto_setup_weight_broadcast`** no longer derives
`trainer`/`orchestrator.weight_broadcast.inference_world_size` from
`data_parallel_size × tensor_parallel_size` (which ran before DP was
filled) and no longer rejects a user-set `inference_world_size`.
**`auto_setup_deployment`** (single-node) now sets
`inference_world_size` to `dp × tensor_parallel_size` immediately after
the DP/`api_server_count` fill, so the in-memory transfer group matches
every inference GPU that joins NCCL.
>
> Unit tests assert the resolved world size (2 infer GPUs → size 2) and
that a dumped `rl.json` round-trips unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f5553f5c5dd2f91aa11003338ef13e285a6c9ee6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Delete `trainer/models/layers/rms_norm.py`. It only re-exported
`RMSNorm`/`RMSNormConfig` from `layers/norms.py`, and nothing imported
it.
- Move `quantize_to_fp8_blockwise` from `trainer/models/fp8.py` into
`tools/convert_bf16_to_fp8.py`, its only user.
`tools/convert_dcp_to_fp8.py` still imports it through
`convert_bf16_to_fp8`. While moving it, the 9-line zero-pad block
becomes `F.pad(weight, (0, pad_cols, 0, pad_rows)).contiguous()`; the
output is bitwise identical to the old function (bf16/fp16/fp32, padded
and unpadded shapes, contiguous and transposed inputs).
## Behavior change
None.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Dead-code removal and relocating a tool-only quantizer; no trainer
inference or training path changes.
>
> **Overview**
> Removes dead trainer surface area and keeps FP8 checkpoint conversion
self-contained in the tooling layer.
>
> **`trainer/models/layers/rms_norm.py`** is deleted (it only
re-exported `RMSNorm` / `RMSNormConfig` with no importers).
**`trainer/models/fp8.py`** is removed and
**`quantize_to_fp8_blockwise`** now lives in
**`tools/convert_bf16_to_fp8.py`**, which was its only consumer;
**`convert_dcp_to_fp8.py`** continues to pull quantization helpers from
that script. Padding inside the moved helper uses **`F.pad`** instead of
manual zero-fill, with the same blockwise e4m3 logic otherwise
unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c35ca75057037c6d98f0080bdffae8efd24e2f85. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Processes that share `~/.triton` on a shared filesystem can hang or
crash (seen with Nemotron-H, where many ranks compile the Mamba Triton
kernels at once; reproduced below with Qwen3.5 and GLM-4.5-Air).
This PR adds `TRITON_CACHE_DIR = /tmp/triton-<uid>` to
`DEFAULT_COMMON_ENV_VARS`. It is per-user because `/tmp` is shared by
all users on a node. Like the other launcher defaults, it reaches every
launched component: the local `rl`/`sft`/`inference` launchers (also
used by the single-node sbatch scripts) and the trainer, orchestrator,
inference (incl. prefill/decode), and online-eval env blocks of the
multi-node and inference sbatch scripts. `[env_vars]` (or a component's
`env_vars`) overrides it; a value exported in the shell or `.env` does
not. It also removes the `TRITON_CACHE_DIR` overrides from six example
configs (glm-4.5-air swe/swe-budget/search/terminal, glm-5.3 and
qwen3-30b-a3b sft h200 base): they pointed every user at the same `/tmp`
dir and are now covered by the default. `docs/scaling.md` says so in one
paragraph.
vLLM 0.31's own default: when `TRITON_CACHE_DIR` is unset, its Inductor
adaptor points it at
`$VLLM_CACHE_ROOT/torch_compile_cache/<hash>/rank_<i>_<j>/triton_cache`
(`~/.cache/vllm` by default, so usually on the shared home). That only
covers Triton kernels compiled after torch.compile initializes, and it
is still on the shared filesystem. vLLM keeps a `TRITON_CACHE_DIR` that
is already set, so with this PR vLLM uses `/tmp/triton-<uid>` too.
### Measured cost (one H200 node, vLLM 0.31 venv, Triton 3.7.1)
Each run starts from a fresh process with the same config. "Ready" is
launch → first trainer step logged (Qwen) or launch → `/health` OK
(GLM). For GLM, the first generated token came 1.3–2 s after ready in
every run that came up. Inductor's cache dir was emptied before each run
except the warm node-local one.
| Triton cache | Qwen3.5-4B SFT, 8 GPUs, compiled blocks (step 1 time) |
GLM-4.5-Air vLLM TP8 |
|---|---|---|
| shared, cold (today on a new cluster / after a Triton or torch update)
| **failed 2/2**: `FileNotFoundError` on a cache file that another rank
was writing (`causal_conv1d_fwd_kernel.llir`, `l2norm_fwd_kernel.ptx`) |
**failed 2/2**: 4 of 8 ranks hit `FileNotFoundError` in the cache during
Inductor autotune, the other 4 hung in a collective until killed (1st
run). The 2nd run crashed instead of hanging. |
| shared, warm | not measured cleanly (see below) | 344 s |
| node-local, cold (this PR, first job on a node) | 233 s (step 1: 91
s), 164 kernels compiled | 375 s with vLLM's compile cache warm (106
kernels); 465 s if vLLM's cache is also cold (87 kernels) |
| node-local, warm (this PR, later jobs on the same node) | 138 s (step
1: 8.3 s) | 344 s |
- A cold node-local cache costs about **95 s per node for Qwen3.5** (FLA
+ Inductor kernels) and about **31 s for GLM-4.5-Air inference** when
vLLM's own compile cache is warm. Warm node-local and warm shared take
the same time.
- The rest of the GLM startup does not depend on the Triton cache: about
3.5 min of Python imports and process spawn from the shared venv, 13 s
to load weights.
- vLLM: `VLLM_CACHE_ROOT` (`~/.cache/vllm`, shared home) holds vLLM's
AOT/Inductor artifacts. With this PR it stays shared. On a new node,
vLLM loads those artifacts (`torch.compile` 0.6 s instead of 30 s), and
the Triton binaries are compiled into `/tmp/triton-<uid>` (106 kernels,
+31 s). `TORCHINDUCTOR_CACHE_DIR` (default `/tmp/torchinductor_<user>`,
already node-local) stayed empty in these runs. Inductor's Triton
kernels go to `TRITON_CACHE_DIR`.
- A crash on the shared cache can also break later starts. After the
first failed GLM run, the shared vLLM cache only had AOT artifacts from
the 4 ranks that got through. On the next start, those 4 ranks loaded
the artifacts and the other 4 recompiled, so the ranks diverged and hung
(Triton cache warm-ish, 60 kernels). For the same reason the Qwen
"shared, warm" run started from a partial cache and failed again. The
warm-shared GLM number comes from a shared dir seeded with a complete
cache.
### Possible middle ground (not implemented)
Because the cold cost is above 1 min per node for FLA-heavy models, a
run could seed the node-local cache from a shared read-only copy at job
start. For example, on each node before the components start:
`[ -n "$TRITON_CACHE_SEED" ] && cp -rn "$TRITON_CACHE_SEED"/.
"$TRITON_CACHE_DIR"/`
The seed would be a warm `/tmp/triton-<uid>` copied once to the shared
FS. Triton keys entries by source, compiler, and GPU, so stale entries
are never reused, only skipped. Only reads hit the shared FS, so the
concurrent-write race does not occur. I left it out to keep this PR
minimal.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Launch-time env default only; behavior is overridable via config and
fixes known multi-rank Triton cache races, with a one-time cold-compile
cost on each node.
>
> **Overview**
> **Sets a global launcher default** so every trainer, orchestrator, and
inference process gets `TRITON_CACHE_DIR=/tmp/triton-<uid>` via
`DEFAULT_COMMON_ENV_VARS`, avoiding concurrent Triton kernel writes
under `~/.triton` on a shared filesystem (hangs / `FileNotFoundError`
under multi-rank compile).
>
> **Removes redundant `[env_vars]` overrides** from six GLM-4.5-Air RL
and GLM-5.3 / Qwen3-30B SFT example configs that previously pinned
Triton cache paths under `/tmp`; those runs now inherit the per-user
node-local default (still overridable through config `env_vars`).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f21642046ea59cab0b9460863560b4df825f29c0. 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: faresobeid <111092724+faresobeid@users.noreply.github.com>
## Summary
Fold `GenerationSource` into `TrainEnv`, its only owner. Move
`connect_frozen_client` from `algo/base.py` to `clients.py`, so `algo`
no longer imports `clients` lazily. Give `TrainEnv` `setup()`/`aclose()`
so orchestrator setup and teardown no longer reach into its parts.
## What changed
- `orchestrator/generation_source.py` is deleted. `TrainEnv` (`envs.py`)
now holds `clients`, `renderer_config`, `connected` (the frozen source
clients it connected) and `uses_live_policy`. Dropping `logprobs` for
frozen sources happens in `TrainEnv.__init__`.
- `TrainEnv.setup()` connects the frozen generation source and runs
`algorithm.setup()` concurrently. `TrainEnv.aclose()` closes `connected`
and `algorithm.connected`, never the shared policy clients.
- `connect_frozen_client` is a plain function in `clients.py`, next to
`check_inference_ready`. `algo/base.py` imports it at module level. It
is no longer re-exported from `prime_rl.orchestrator.algo`.
- `dispatcher.py` reads the `TrainEnv` directly at the four former
`generation_source` call sites. `orchestrator.py` calls `env.setup()`
and `env.aclose()`.
- `docs/algorithms.md` and the `algo/__init__.py` docstrings refer to
`TrainEnv`.
## Behavior change
None.
## Checks run
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 297 passed.
- `ruff check`, `ruff format --check`: clean.
- Equivalence script, old `GenerationSource` (`origin/main`) vs new
`TrainEnv`, on 4 configs: policy, policy with `top_p=0.9`, sft with a
frozen `sampling.source`, opd with a frozen teacher. Identical
`sampling_args`, `requires_sampling_masks` and `uses_live_policy`. After
`setup()`, the same generation clients (policy object, or the frozen
endpoint with the same train client config) and the same algorithm
clients. Teardown closes the same clients.
- GPU smoke on one node (vLLM 0.31): reverse-text RL (15 steps), sft
with a frozen `sampling.source` (5 steps), opd with a frozen teacher (5
steps). All three ran to "Training finished" and exited 0.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Internal orchestrator refactor with stated behavioral equivalence and
no changes to training algorithms or dispatch semantics beyond
indirection.
>
> **Overview**
> **Refactors train rollout sourcing** by deleting `GenerationSource`
and moving its responsibilities onto `TrainEnv`: inference `clients`,
live-vs-frozen policy detection (`uses_live_policy`), sampling-arg
tweaks (e.g. dropping `logprobs` for frozen endpoints), and frozen-pool
connection in `setup()`.
>
> `TrainEnv.setup()` now connects frozen `sampling.source` endpoints and
runs `algorithm.setup()` together; `TrainEnv.aclose()` closes only
env-owned clients (`connected` + algorithm pools), not the shared policy
pool. The orchestrator and dispatcher call these surfaces instead of
reaching into a nested `generation_source`.
>
> `connect_frozen_client` moves from `algo/base.py` to `clients.py`
(next to `check_inference_ready`); it is no longer re-exported from
`prime_rl.orchestrator.algo`. Docs and package docstrings now describe
`TrainEnv` as owning the sampling half of the algorithm config.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e89ca1a663ae6ae808b05ff3326ce9ed63c9b467. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Apply a policy-version cache salt only when inference weights can change
during a run. Standalone evaluations and frozen-model requests omit the
training salt; live RL rollouts and online evaluation retain it so
caches distinguish policy versions.
## Before
The dispatcher added the policy version as `cache_salt` to every request
using the live policy source. Standalone evaluation used that same
source path, so fixed-weight evaluations received a training cache salt
even though no weight updates occurred. Frozen-model requests already
omitted it.
```mermaid
flowchart TD
Standalone["Standalone evaluation with fixed weights"] --> Live["Live policy source"]
Training["RL or online evaluation with changing weights"] --> Live
Live --> Salt["Always add policy-version cache_salt"]
Salt --> Request["Verifiers provider request"]
Frozen["Frozen model source"] --> Plain["Omit training cache_salt"]
Plain --> Request
```
## After
```mermaid
flowchart TD
Request["Prime-RL dispatcher builds request sampling"] --> Mode{"Live policy source with changing weights?"}
Mode -->|"Yes: RL or online evaluation"| Salt["Set cache_salt to policy version"]
Mode -->|"No: standalone evaluation or frozen model"| Plain["Omit training cache_salt"]
Salt --> Client["Verifiers client builds provider request"]
Plain --> Client
Client --> Provider["Inference provider"]
```
The dispatcher records whether policy weights can change. The standalone
evaluator disables version salting, SFT online evaluation enables it,
and RL orchestration keeps it enabled. The request decision also checks
whether the source uses the live policy.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Narrow behavior change to cache salting on eval paths; RL and online
eval keep prior salting via the default flag.
>
> **Overview**
> Adds a **`policy_weights_change`** flag on `Dispatcher` so inference
**`cache_salt`** (policy version) is only attached when weights can
actually change during the run.
>
> **Standalone eval** (`EvalConfig`) sets the flag to **false**, so
fixed-weight evaluation no longer invalidates prefix caches on every
training policy version. **SFT online eval** and **RL orchestration**
(default **true**) still salt live-sourced requests so caches stay
correct across weight updates.
>
> The cache decision is now **`live_sourced and policy_weights_change`**
instead of salting all live policy paths.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5a2d7d9652740106e63fee31a6e79da13816dae7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Keep successful empty environment outcomes in evaluation results. A
trace-less episode or clean zero-turn trace retains the verdict returned
by Verifiers, while training and curriculum logic exclude zero-turn
traces.
## Before
The dispatcher changed successful trace-less episodes into
`EmptyEpisode` failures. Clean, non-timeout zero-turn traces became
`EmptyTrajectory` failures, marking both the trace and episode
unsuccessful. Evaluation therefore recorded a failure even when the
environment had returned success, while training and curriculum filters
relied on those injected errors to exclude empty traces.
```mermaid
flowchart TD
Env["Verifiers returns an empty successful outcome"] --> Dispatch["Prime-RL dispatcher"]
Dispatch --> Episode["No traces: inject EmptyEpisode"]
Dispatch --> Trace["Clean zero-turn trace: inject EmptyTrajectory"]
Episode --> Failed["Rewrite outcome as failed"]
Trace --> Failed
Failed --> Eval["Evaluation records a failure"]
Failed --> Training["Training and curriculum filter injected errors"]
```
## After
```mermaid
flowchart TD
Env["Verifiers environment returns an episode"] --> Dispatch["Prime-RL dispatcher preserves empty outcome verdicts"]
Dispatch --> Eval["Evaluation records and metrics"]
Dispatch --> Filter["Training trace eligibility"]
Filter --> Empty["Zero turns: no training sample"]
Filter --> Sample["Eligible trace with sampled tokens: training sample"]
Dispatch --> Curriculum["Curriculum ignores zero-turn traces and admits only trainable groups"]
```
Remove the synthetic `EmptyEpisode` and `EmptyTrajectory` errors.
`iter_trainable_traces()` filters empty traces alongside failed and
untrainable traces before advantages are assigned, so the advantage gate
needs no separate zero-turn check. Difficulty sampling also excludes
zero-turn traces. Empty groups finish without producing a trainer
payload, and mixed groups retain their eligible traces. Curriculum
admission also requires a trainable trace, so groups without training
samples cannot inflate admission metrics. Sampler observations of
completed turns are retained even when token metadata is unavailable.
Verifiers' no-agent validation and training timeout handling remain in
place.
[#3824](https://github.com/PrimeIntellect-ai/prime-rl/pull/3824) applies
the same ownership rule to partially failed episodes: preserve
environment results, then decide training eligibility explicitly.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes evaluation outcome recording and which rollouts feed
training/curriculum admission, which can shift eval metrics and training
batch composition without touching auth or data stores.
>
> **Overview**
> Stops the dispatcher from **injecting** `EmptyEpisode` /
`EmptyTrajectory` errors on successful trace-less or zero-turn outcomes,
so **evaluation keeps Verifiers’ success verdict** instead of recording
synthetic failures.
>
> Training and curriculum now **exclude zero-turn traces explicitly**:
`iter_trainable_traces()` skips `num_turns == 0`, difficulty-pool reward
updates require `num_turns > 0`, and curriculum admission requires
**both** passing gates **and** at least one trainable trace via
`iter_trainable_traces()`. Scored rollouts without token/advantage
metadata can still update sampler difficulty; groups with no trainable
samples no longer count as admitted.
>
> Tests cover mixed groups with non-trainable traces, empty-only groups,
and reward-only observations for the sampler.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8582fb8c18e7cb4aa0dc7af58c6e0a4474bd7b40. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
Raises the `prime-runs[train]` floor from `>=0.1.3` to `>=0.1.4` and
updates `uv.lock` to match.
## Why
`prime-runs` 0.1.4 lets a run opt out of Prime Traces and upload its
samples to the legacy sample tables instead
(PrimeIntellect-ai/prime#998):
- `PRIME_TRACES_OPT_OUT=true`
- `prime config set-traces-opt-out true`, which sets `traces_opt_out` in
`~/.prime/config.json`
- `prime_runs.init(traces_opt_out=True)`
`prime-runs` 0.1.3 doesn't know about any of these. With 0.1.3
installed, which is what `uv sync` gives today, a user who sets the
environment variable or the config key gets no error and no warning, and
their runs keep uploading to Prime Traces. Requiring 0.1.4 makes the
setting take effect.
Nothing changes for runs that don't opt out. The Prime monitor calls
`prime_runs.init()` without the new argument, so the default (upload to
Prime Traces) is unchanged.
A training run that opts out needs pyarrow for the legacy sample
encoder. prime-rl already depends on `prime-runs[train]`, which includes
it.
## Changes
- `pyproject.toml`: `prime-runs[train]>=0.1.3` →
`prime-runs[train]>=0.1.4`.
- `uv.lock`: `prime-runs` 0.1.3 → 0.1.4. No other package moves;
`prime-traces` stays at 0.0.7.
The `deps/verifiers` submodule is not changed. Its own floor is raised
separately in PrimeIntellect-ai/verifiers#2805, and this PR doesn't
depend on it.
`uv lock --check` passes. I did not run the test suite.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Dependency floor bump only; no application code changes and default
trace upload behavior stays the same.
>
> **Overview**
> Raises the **`prime-runs[train]`** minimum from **`>=0.1.3`** to
**`>=0.1.4`** in `pyproject.toml` and pins **`prime-runs` 0.1.4** in
`uv.lock`.
>
> This ensures installs pick up **Prime Traces opt-out** behavior
(`PRIME_TRACES_OPT_OUT`, `prime config set-traces-opt-out`, or
`prime_runs.init(traces_opt_out=True)`), which 0.1.3 silently ignored so
opted-out runs could still upload to Prime Traces. Default runs that do
not opt out are unchanged; `prime-rl` still depends on the **`[train]`**
extra for legacy sample encoding when opting out.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
06caa96109250b6b800d8e757de7133b4f152031. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
With `moe_router_dtype="float32"` (the RL default) and activation
checkpointing on, every MoE block ran eager under `torch.compile`. Two
things combine to cause it:
- The fp32 router is its own FSDP2 unit, and FSDP2 hooks are
dynamo-disabled, so the router always breaks the graph.
- Under `compile(AC(block))` the checkpoint compiles as a higher-order
op, which forbids breaks, so Dynamo ran the whole block eagerly.
This PR compiles inside the checkpoint instead: for any checkpointed
block that holds a nested FSDP unit (today, the fp32 router), an eager
checkpoint now wraps the compiled block (`AC(compile(block))`), so the
nested unit's break only splits the block into compiled graphs. To see
those units, compile now runs after FSDP. Compiling in place keeps the
same module object, so the order changes nothing at runtime.
The reorder is safe. The old `AC -> Compile -> FSDP` comment was ported
from TorchTitan in #923, when `apply_compile` still wrapped each block
with `torch.compile(block)`. #957 switched to in-place `.compile()` two
days later without revisiting it. With in-place compile, both orders
trace the same frames: graph breaks, loss and step time match on both
workloads, and `fullgraph=True` (with a bf16 router) still compiles with
zero graph breaks.
| Workload (8x H200, EP 8, full AC) | before (s/step) | after (s/step) |
MFU |
|---|---|---|---|
| GLM-4.5-Air, 16 layers, real data | 6.21, 6.17 | 5.22, 5.21 | 35% to
42% |
| Qwen3-30B-A3B, fake data | 5.96, 5.96 | 4.51, 4.51 | 32% to 42% |
Two runs per arm, each the median `time/step` over steps 5 to 20, no
offloading. Peak memory is unchanged, and loss and grad norm track the
baseline within run-to-run noise.

**Figure:** one MoE layer's forward on Qwen3-30B-A3B, before and after
this PR. The orange eager elementwise kernels collapse into a few pink
compiled Triton kernels, so the layer's forward drops from 16.4 to 11.3
ms.
<details><summary>Same view on GLM-4.5-Air</summary>

</details>
## Alternative considered
Keeping recompute inside the compiler: drop the block-level checkpoint
and instead checkpoint two compiled regions that exclude the router, the
attention module and the post-router MoE work. It beat the baseline but
was slower than this PR (Qwen3-30B 5.50 vs 4.51 s/step, GLM-4.5-Air 5.85
vs 5.22 s/step) and used more memory, because the norms and the router's
fp32 activations stay outside any checkpoint.
## North star: fullgraph fp32 router support
Fullgraph compile with an fp32 router stays unsupported, and
`model.compile.fullgraph=true` still raises for it. The blocker is the
router's FSDP unit itself: FSDP2 applies one mixed-precision policy per
unit, so the fp32 router cannot share the block's bf16 unit, and its
dynamo-disabled hooks are the graph break above. PyTorch
[#196626](https://github.com/pytorch/pytorch/pull/196626) adds
per-parameter mixed precision, which lets the router stay in the block's
unit. That removes the break, enables fullgraph, and makes this PR's
compile-inside-AC path unnecessary, so it should be reverted then.
#196626 is on PyTorch `main` but not yet in a release.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
## Summary
Add `iter_moe_blocks(model)` in `trainer/model.py`. It yields the `MoE`
MLP of each decoder layer. It replaces the five copies of the
decoder-layer MoE lookup in `freeze_moe_router`,
`apply_fp32_moe_router`, `get_full_offload_dtype_policy`,
`apply_force_balanced_routing` and `get_load_balance_stats`.
## What changed
- New `iter_moe_blocks` next to the helpers that use it. The helpers
stay in `model.py`, so no imports change.
- The four `layer.mlp if hasattr(...) else layer.feed_forward ...`
lookups and the `getattr(mlp)` + `hasattr(tokens_per_expert)` scan in
`get_load_balance_stats` now call `iter_moe_blocks`.
- Removed the stale "HF impl" comment in `get_expert_load_stats`. The HF
fallback was removed in #3773.
## Behavior change
None. The `feed_forward` fallback is gone. Every prime-rl decoder layer
uses `mlp`. `get_load_balance_stats` already looked only at `mlp`. Only
`MoE` registers `tokens_per_expert`, so it selects the same layers as
before.
## Checks
- CPU equivalence vs `main` (throwaway script, not in the repo). Tiny
Qwen3-MoE (`mlp_only_layers=[1]`) and GLM4-MoE
(`first_k_dense_replace=1`) models with fixed router-count buffers.
Compared `is_tt_moe_model`, `get_load_balance_stats`,
`get_global_moe_stats`, `compute_expert_load_stats`,
`get_expert_load_stats` and `get_full_offload_dtype_policy`, plus
parameter dtype and `requires_grad`, and router
`fp32_gate`/`force_balanced` after the three router helpers. All 16
outputs were bit-identical.
- `pytest tests/unit/train tests/unit/orchestrator
tests/unit/test_configs* -m "not gpu"`: 450 passed, 1 failed. The
failure is
`test_cpu_adam.py::test_native_cpu_adamw_matches_fused_torch_and_preserves_gradients`
(ninja build), which fails the same way on `main`.
- `ruff check` and `ruff format --check`.
- GPU: reverse-text MoE RL smoke vs `main` on one node, running.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Mechanical refactor of MoE traversal with no intended behavior change;
only risk is if a model relied on the removed feed_forward path (none in
this codebase).
>
> **Overview**
> Introduces **`iter_moe_blocks`**, a single iterator over decoder
layers whose `mlp` is a **`MoE`**, and rewires MoE
router/offload/metrics helpers to use it instead of repeated per-layer
`mlp` / `feed_forward` lookups.
>
> **`freeze_moe_router`**, **`apply_fp32_moe_router`**,
**`get_full_offload_dtype_policy`**, **`apply_force_balanced_routing`**,
and **`get_load_balance_stats`** now loop over that iterator; the unused
**`feed_forward`** fallback is removed. **`get_expert_load_stats`** only
drops an outdated comment on the empty tensor guard.
>
> Intended as a no-op for supported models: same router freezing, fp32
gates, FSDP dtype policy, debug balanced routing, and load-balance /
expert-load metrics.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2cf0399ca4e467c9ae028082c2a03f02604abbf8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Make `trainer.model.freeze_moe_router` default to on for RL.
## What changes
- `model.freeze_moe_router` is now `bool | "auto"`, default `"auto"`. It
resolves to `True` on the RL `TrainerConfig` and to `False` on
`SFTConfig`, following the per-trainer pattern of `moe_router_dtype`. An
explicit `true`/`false` still wins.
- `freeze_moe_router()` no longer raises on non-MoE models; it does
nothing, so dense RL runs keep working with the new default.
- `docs/training.md` knobs table lists the field.
## Why
In RL, router updates amplify the train/inference routing mismatch: the
trainer's expert choices drift away from the ones inference sampled. So
RL keeps the pretrained router by default. SFT is unchanged.
What gets frozen: the router gate parameters (`mlp.router.gate.weight`,
plus `gate.bias` on gpt-oss). The aux-loss-free `selection_bias` buffer
is not a parameter, and nothing on main updates it. Shared-expert gates
(Qwen3.5) and Nemotron-H latent projections are not touched. Frozen
routers get no optimizer state.
## Breaking changes
- RL runs on MoE models no longer train the router. All MoE RL examples
are affected (glm-5.3, glm-4.5-air, intellect-3.1, qwen3-30b-a3b,
minimax-m2.5, nemotron-3-super). Set `trainer.model.freeze_moe_router =
false` for the old behavior.
- An explicit `freeze_moe_router = true` on a non-MoE model is now a
no-op instead of an error.
- Resuming: a checkpoint saved before this change (trainable router)
loads into a frozen-router run; the extra router optimizer state is
ignored. The reverse, resuming a frozen-router checkpoint with
`freeze_moe_router = false`, fails on missing DCP keys (noted in the
field docstring).
- With LoRA, a router listed in `lora.modules_to_save` is frozen again
by the new default unless `freeze_moe_router = false` is set.
## GPU check
One node (8×H200), FSDP over 8 ranks, `samsja/mini-glm-moe` (23 MoE
layers), SFT with fake data, `freeze_moe_router = true`,
`moe_router_dtype = "float32"` (so each router is its own fp32 FSDP unit
whose params are all frozen), 5 steps with a checkpoint every step:
- Log: "Froze 23 MoE router parameters", "Running 23 MoE router gates in
fp32"; all 5 steps ran with finite loss and grad norm.
- DCP checkpoints step 1 vs step 5: all 23 fp32 router gate weights are
bitwise unchanged; expert weights changed; no optimizer state exists for
any router parameter.
#3753 let MoE blocks compile with `model.compile.fullgraph = true`, but
it was validated on B300 with FA4. On H200, where FA3 is the default,
fullgraph still failed at the first forward, because FA2's and FA3's
`flash_attn_varlen_func` are autograd.Functions and Dynamo rejects the
same `cu_seqlens` tensor passed as both `cu_seqlens_q` and
`cu_seqlens_k`. FA2 and FA3 now run through `prime_rl_attn` custom ops
like FA4 (#3754), so the checkpointed MoE blocks compile with fullgraph
and no graph breaks on H200 too.
- AFMoE, Ulysses CP and the Qwen3.5 vision encoder now call the op
wrappers; FA4's op takes optional `max_seqlen_q/k` for Ulysses.
- The ops match the library functions bitwise, except FA3's GQA
`dk`/`dv`, which the library itself doesn't reproduce run to run.
- `apply_compile` traces `max_seqlen` symbolically: as a constant, each
rank recompiled on its first new value and stalled every rank for ~6 s.
A
[benchmark](https://github.com/PrimeIntellect-ai/prime-rl/blob/9db5336241304a0263664c8408e03159cbb8767e/tools/benchmark_flash_attn_max_seqlen.py)
shows the symbolic int costs nothing measurable.
| GLM-4.5-Air, 24 layers, 2 x 8 H200, ep 8, bf16 router | s/step (lower
is better) | tok/s/GPU (higher is better) |
|---|---|---|
| main, FA3, fullgraph off (fullgraph fails) | 4.64 | 3533 |
| this PR, FA3, fullgraph on | 3.83 | 4282 |
That is 17.5% less time per step, or 21.2% more tokens per second per
GPU. Medians over steps 5 to 20; loss tracks main within 0.03 over 20
steps. The GPU is about 99% busy in both arms, so the gain is fusion:
per step, about 1030 ms of unfused aten kernels (MoE routing glue, RoPE)
become 262 ms of Inductor-fused Triton kernels.

**Figure:** one layer's forward, before (`main`, fullgraph off) and
after (this PR, fullgraph on). The strings of small yellow and
red-orange aten kernels on `main` become a few fused Triton kernels
(pink), and the layer finishes in 35.9 ms instead of 45.4 ms.

**Figure:** the same layer's recompute and backward, 106.7 ms after
versus 131.6 ms before. The bottom panel totals the whole step: about 1
s of unfused aten kernels became 262 ms of fused Triton kernels, while
FlashAttention and GEMM time barely changed.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
## Problem
`Integration tests (reverse_text_lora)` has failed since the vLLM 0.31
bump (#3888's own CI run, and main's GPU Tests at b9c0bfe87). The first
`POST /load_lora_adapter` returns `400 Bad Request` and the orchestrator
exits.
Root cause: vLLM 0.31 added a check to
`OpenAIServingModels._check_load_lora_adapter_request`. It rejects a
`lora_name` equal to a served base model name ("conflicts with a served
base model", 400). vLLM 0.30 had no such check. prime-rl registers its
adapter under the model name (`model.name`) on purpose, because every
client (rollouts, evals, the renderer client) sends that name. vLLM
serves the base model under the same name by default, so the two
collide.
## Change
No vLLM patch. With LoRA on, the inference server serves the base model
under a different name, and the adapter keeps the name clients already
send.
- `InferenceConfig.to_namespace` sets `served_model_name =
[f"{vllm.model}-base"]` when `vllm.enable_lora` is on, unless the user
sets `served_model_name` explicitly. Every launch path builds the vLLM
args here: local `rl`/`sft`, standalone `uv run inference`, SLURM
single/multi-node, and P/D prefill/decode ranks.
- `maybe_check_has_model` (startup readiness) also accepts the name as a
model's `root`. Before the first weight sync, a LoRA server lists only
`<model>-base`, whose `root` is the model path.
- The `load_lora_adapter` docstring, an orchestrator comment, and the
LoRA section of `docs/advanced.md` now describe the served name.
## Checks
- **Nothing on the policy server asks for the base model by name.**
Rollouts, evals, and the renderer/prefill scorer all send `model.name`,
which is now the adapter. OPD teachers and frozen reference models are
separate endpoints. A LoRA server also cannot serve a frozen reference
under `model.name`. Before this change that name would already have
resolved to the adapter, and the base model can now be reached as
`<model>-base`. Admin routes (`/pause`, `/update_weights`,
`/load_lora_adapter`, health, liveness) do not take a model name.
vllm-router and llm-d configs do not reference model names. Dynamo
workers are external, so this change does not affect them.
- **The v0 adapter is loaded before the first request.** The
orchestrator and online evals wait for the trainer's startup broadcast
(v0, or the resume step). They load it through `/load_lora_adapter`
before they dispatch any rollout or eval. Readiness is the only earlier
check that uses the model name, and the `root` match covers it.
- **`/metrics`:** vLLM's `model_name` label becomes `<model>-base`. The
inference-metrics collector and the concurrency controller group samples
by the `engine` label only, and the dashboard does not read vLLM's
`/metrics`.
## Tests
- `configs/ci/integration/reverse-text-lora/start.toml` on one H200 node
(vLLM 0.31.0, this commit, patch module absent): all 15 steps run and
16/16 `/load_lora_adapter` calls return 200. There are no 400s or 404s.
Reward goes from 0.145 to 0.798, matching the patched version (0.14 to
0.79). Before the first sync, `/v1/models` lists only
`...-Reverse-Text-SFT-base` (root `...-Reverse-Text-SFT`). After it, the
list also has the adapter `...-Reverse-Text-SFT` (parent
`...-SFT-base`).
- `reverse-text-sft-lora/start.toml` (5 steps) passes.
- `pytest tests/unit/orchestrator tests/unit/inference
tests/unit/test_configs.py tests/unit/test_parsers.py -m "not gpu"` (469
passed), `ruff check`, and `ruff format --check` all pass.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how LoRA vLLM instances advertise models at startup and during
readiness checks; client-facing model IDs stay the same, but anything
expecting the base under the policy name would need `<model>-base`.
>
> **Overview**
> Fixes LoRA inference startup on **vLLM 0.31**, which returns 400 when
an adapter is registered under the same name as a served base model.
>
> When `enable_lora` is on and `served_model_name` is not set
explicitly, **`InferenceConfig.to_namespace`** now serves the base
weights as ``<vllm.model>-base`` so the reloaded policy adapter can keep
**`model.name`** for all rollout/eval clients.
**`maybe_check_has_model`** treats a match on either the model **`id`**
or **`root`**, so readiness passes before the first `/load_lora_adapter`
when only the `-base` entry is listed. Docs and comments describe the
naming split.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
18064f3367009c265c11ffd58fb9d5b989ca7ec1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Turn off loguru's `diagnose` on every handler.
With loguru's default `diagnose=True`, every logged exception (including
the `Fatal error in …` that `clean_exit` logs) `repr()`s the variables
in each traceback frame. A `torch` storage repr walks the storage in
Python, element by element. When a frame holds a multi-GB tensor or
storage (a checkpoint state dict, a staging buffer, model shards),
formatting the traceback takes hours. The crashing trainer then looks
hung instead of exiting, and the real error never reaches the log.
Seen while debugging async DCP checkpoint saves: the trainer stopped at
`Saving checkpoint at step 2` with no error. A faulthandler dump showed
the main thread inside `loguru/_better_exceptions.py` →
`torch/storage.py __repr__`. The actual exception (a staging error) only
showed up through `traceback.print_exc`.
Repro on CPU (a frame whose failing line references an 8 MB
`UntypedStorage`):
- main: formatting took 19.1 s. It scales with size, so about 40 min per
GB.
- this PR: 0.0 s.
Tracebacks are still logged in full; only the per-variable value
annotations are dropped.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Logging-only change that reduces exception detail slightly; improves
reliability when failures involve large tensor locals.
>
> **Overview**
> Disables loguru’s **`diagnose`** mode on every handler installed in
`setup_logger` (JSON console, colorized stdout, and optional file sink).
>
> With the default **`diagnose=True`**, exception formatting
**`repr()`s** locals in each traceback frame. When those locals are
large PyTorch tensors or storages, that step can take minutes or hours,
so a fatal error during logging looks like a hang and the real exception
may never appear in logs. **Full tracebacks are still logged**; only the
per-variable value annotations are omitted.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
93a682f6fedf415561d4e5f31cbf0ee8b92a2a04. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Use Verifiers' client configuration and resolvers for Prime-RL
endpoints, credentials, headers, and timeouts. Standalone evaluation
honors an explicit URL, then `PRIME_INFERENCE_URL`, the Prime CLI
config, and the default Prime endpoint. Partial overrides retain the
correct defaults for each run type.
## Before
Prime-RL owned a separate client schema and credential/header resolvers.
Standalone eval supplied a hardcoded Prime endpoint, so changing
`PRIME_INFERENCE_URL` did not change that default. Client setup resolved
environment headers into static values, prefill scoring constructed its
own SDK client, and admin authentication reused the inference
configuration instead of resolving against the admin URL.
```mermaid
flowchart TD
Eval["Standalone eval hardcodes Prime URL and key defaults"] --> Config["Prime-RL ClientConfig"]
Config --> Local["Prime-RL credential and header resolvers"]
Local --> Inference["Construct Verifiers client with resolved static headers"]
Inference --> Prefill["Prefill builds its own OpenAI SDK client"]
Local --> Admin["Admin client resolves using inference config"]
AdminURL["Separate admin URL"] --> Admin
```
## After
```mermaid
flowchart TD
Eval["Standalone eval: Prime endpoint defaults"] --> Config["Verifiers BaseClientConfig"]
Train["Training and online eval: localhost vLLM defaults"] --> Config
Config --> Inference["Inference client configuration"]
Config --> Prefill["Shared SDK builder for prefill scoring"]
Config --> Admin["Admin configuration with its own URL"]
Inference --> Resolve["Resolve credentials and headers for actual destination"]
Prefill --> Resolve
Admin --> Resolve
Runtime["Environment values and Prime CLI config"] --> Resolve
Resolve --> Endpoint["Target endpoint"]
```
Training and online evaluation retain their vLLM defaults, including
when only part of the client config is overridden. Frozen models require
an explicit endpoint. Environment-backed headers remain references in
saved configs, and header overrides compare names case-insensitively.
Admin authentication uses the admin destination. Prefill scoring uses
the shared SDK builder's timeout and retry policy.
Depends on [Verifiers
#2766](https://github.com/PrimeIntellect-ai/verifiers/pull/2766). When
combining this with
[#3782](https://github.com/PrimeIntellect-ai/prime-rl/pull/3782) and
[#3808](https://github.com/PrimeIntellect-ai/prime-rl/pull/3808), pin a
Verifiers revision containing all three companion fixes.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how eval and inference clients pick URLs, API keys, and
headers at runtime; mis-resolution could break eval or admin traffic,
though behavior is covered by new default-preservation tests.
>
> **Overview**
> **Client configuration now delegates to Verifiers** instead of a
duplicate Prime-RL schema and local credential/header resolvers.
`ClientConfig` extends Verifiers' `BaseClientConfig`; training and
online eval use `VLLMClientConfig` (`localhost:8000` / `VLLM_API_KEY`).
Standalone `uv run eval` drops the hardcoded Prime URL and inherits
Prime Inference defaults from Verifiers (honoring `PRIME_INFERENCE_URL`,
Prime CLI, then the standard endpoint). Frozen external models require
an explicit `base_url`.
>
> **Runtime client setup** forwards unresolved config into Verifiers
train/eval clients (`setup_client` dumps `BaseClientConfig` fields),
resolves auth per destination in admin clients (including separate admin
URLs), and builds prefill scoring via `build_async_openai`. Docs
describe the eval endpoint precedence; tests assert partial `[client]`
overrides keep the right defaults per run type.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c643ef25637bfafb13af555d56167fdbd3525e57. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
`TokenChoiceTopKRouter` gets a `"sqrtsoftplus"` score function
(`sqrt(softplus(logits.float()))`, DeepSeek V4's). The copied
`DeepseekV4Router` (its whole `forward` was restated for that one
scoring line) is deleted. Standard V4 layers use `TokenChoiceTopKRouter`
directly, and `DeepseekV4HashRouter` subclasses it, forwarding the
router kwargs and only adding `tid2eid` and `selection_bias=False`. The
router signature uses `ScoreFuncType` instead of repeating the
`Literal`. The `DeepseekV4MoE` guard that rejected any `scoring_func`
other than `sqrtsoftplus` is removed, because the shared router
implements every score function.
Clamped activation: `GroupedExperts` and `FeedForward` now take either
an activation name or an `Activation` object. A new shared
`ClampedSilu(limit)` in `layers/activations.py` holds V4's clamp
(`silu(gate.clamp(max=limit)) * up.clamp(-limit, limit)`, limit from
`config.swiglu_limit`). V4's routed experts are a plain
`GroupedExperts(activation=ClampedSilu(...))` and its shared expert a
plain `FeedForward(activation=ClampedSilu(...))`. Deleted from
`deepseek_v4/moe.py`: `ClampedSwiglu`, `DeepseekV4Experts` and
`DeepseekV4MLP`. The one init difference (HF draws expert `up_proj` at
std 0.02, not `initializer_range`) is a 3-line
`DeepseekV4MoE.init_weights` override. The hash-routing table and
forward stay in the V4 file. gpt-oss's `clamped_swiglu` is different
math (`(up+1) * gate * sigmoid(1.702 * gate)`, limit fixed at 7), so it
is not merged with this. Sonic MoE rejects `ClampedSilu`, as it rejected
the old V4 experts.
## Behavior change
None for V4 checkpoints, which all ship `sqrtsoftplus`. A V4 config with
another `scoring_func` now builds with that score function instead of
raising. `sqrtsoftplus` takes the non-softmax confidence branch
(`top/sum(scores)`), the same as the deleted copy. State dict keys are
unchanged.
## Equivalence
- CPU: router and full `DeepseekV4MoE` (hash and standard layers, with
and without replay, fp32/bf16, active clamp) are bitwise identical to
main: forward, all grads, buffers and state-dict keys. Other MoE archs
(qwen3_moe, glm4_moe, minimax_m2, afmoe, laguna, gpt_oss) are unchanged.
- GPU (8×H200): qwen3_moe, glm4_moe, laguna and nemotron_h are bitwise
identical to main. deepseek_v4 is not deterministic on GPU even main vs
main; the branch is within that run-to-run spread.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches shared MoE routing and expert activation paths used beyond V4;
behavior change only for non-default V4 `scoring_func`, but incorrect
`sqrtsoftplus` parity would affect training/inference for V4
checkpoints.
>
> **Overview**
> **DeepSeek V4 MoE is refactored onto shared layer primitives** instead
of V4-only router, expert, and MLP subclasses.
>
> `TokenChoiceTopKRouter` now supports **`sqrtsoftplus`**
(`sqrt(softplus(logits))`), so the duplicated `DeepseekV4Router` is
removed and standard V4 layers use the shared router directly.
`DeepseekV4HashRouter` subclasses `TokenChoiceTopKRouter` and only adds
the `tid2eid` buffer. The config no longer documents `scoring_func` as
V4-only, and `DeepseekV4MoE` drops the guard that rejected
non-`sqrtsoftplus` values (other score functions now build through the
shared router).
>
> **Clamped SwiGLU** moves into shared `ClampedSilu(limit)`;
`FeedForward` and `GroupedExperts` accept either an activation name or
an `Activation` instance. V4 wires `GroupedExperts` and optional
`FeedForward` shared experts with `ClampedSilu(config.swiglu_limit)`;
`DeepseekV4Experts`, `DeepseekV4MLP`, and local `ClampedSwiglu` are
deleted. HF-style expert `up_proj` init (std 0.02) lives in a small
`DeepseekV4MoE.init_weights` override. Unit tests target
`GroupedExperts` + `ClampedSilu` instead of `DeepseekV4Experts`.
>
> Shipped V4 checkpoints (`sqrtsoftplus`) should behave the same;
configs with other `scoring_func` values now construct instead of
raising.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
019f42b643266b8be15ce15985b8a82034925d4b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
The dashboard smoke check at the end of the `alphabet_sort` integration
test flakes at `tests/integration/dashboard_smoke.py:164`. It asserts
that `#replay-top` is active after Home. It failed on #3767 and #3774,
which don't touch the dashboard.
**Root cause.** The smoke test presses `t` and then Home. When thinking
is hidden, a trace that overflowed the replay pane gets shorter and
fits. The browser then clamps `scrollTop` and queues a scroll event.
That event fires after Home. At that point the pane fits, so the scroll
handler sees the view as "at bottom", switches back to follow mode, and
clears `#replay-top`. The same thing happens when the pane overflows by
less than the 24px threshold, because top and bottom then count as the
same position.
**Fix.** When the replay output fits (overflow < 24px), the scroll
handler leaves the follow mode alone. Home and End decide it, and that
choice still applies if the output grows later. Scrolling a long trace
by hand still switches between the modes as before.
**Check.** I ran headless Chromium against a dashboard serving synthetic
runs, with the same steps as the smoke test (skip inference, `t`, Home,
End):
- trace that fits after hiding thinking: 4/4 failed before the fix, 4/4
passed after
- 14px overflow: 4/4 failed before the fix, 4/4 passed after
- short trace that always fits: passed before and after
- long scrollable trace: passed before and after
- long trace, scrolling up and back down by hand: still toggles follow
mode and the top/live buttons
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Small dashboard UI scroll-handler guard with no auth, data, or API
impact.
>
> **Overview**
> Fixes flaky replay **Home/End** behavior when the trace output
**fits** (or barely overflows) in the replay pane.
>
> The `#replay-output` scroll listener now **bails out** when
`scrollHeight - clientHeight < 24`, so clamped or near-no-op scroll
events (e.g. after hiding thinking shrinks the content) no longer force
**follow/live** mode and clear **`#replay-top`**. **Home/End** and
manual scrolling on long traces are unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
83d2f3f9b71e5b4309b98146eb1ffa944db08c23. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
- Bump vLLM 0.30.0 → 0.31.0 (exempt `flashinfer-python` 0.7.0.post1 from
the `exclude-newer` cooldown).
- Read `enable_return_routed_experts` from
`VllmConfig.aux_output_config` (moved in 0.31).
- Router replay now always uses the V2 runner; router replay with
disaggregated P/D is rejected at config time (0.31 has no NIXL
routed-expert capture).
- Resync the copied LoRA loader in `_patch_lora_key_prefix` with 0.31
(`modules_to_save`).
Removed patches:
- `monkey_patch_deepseek_v4_request_tools_placement`: fixed upstream
(vllm#51856).
- `monkey_patch_return_routed_experts_with_nixl_connector`: crashes the
engine on 0.31.
Tested end to end: multi-node RL on SLURM (1 trainer + 1 inference
node), Qwen3-0.6B reverse-text, 10 steps. Eval reward 0.08 → 0.81.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Deletes tests that are skipped unconditionally, plus the 777-line
vendored HF AFMoE model that only the skipped AFMoE test used (rev-infra
P4).
Deleted:
- `tests/unit/train/models/test_afmoe.py` (whole module skipped: "HF
afmoe model does not support flash attention 2") and
`tests/unit/train/models/afmoe_hf_modeling/` (vendored HF model;
transformers 5.6.2 ships `transformers.models.afmoe` anyway).
- `tests/unit/train/test_model.py::test_model_with_sequence_packing`
(skipped since 2025-05, "Sequence packing for Qwen not working") and
`::test_model_forward_custom_impl` (skipped, "need special token for
meta stuff in ci").
-
`tests/unit/train/rl/test_fused_lm_head.py::test_full_model_fused_vs_vanilla`
(skipped, "Produces NaNs in bf16 with FA3").
- `tests/unit/transports/test_nccl_broadcast.py` (skipped since 2025-12,
"fail only in ci").
- The `free_port` fixture in `tests/conftest.py`: only the NCCL test
used it (and it called the int as a function, so it was broken too).
No source changes. Behavior change: none. These tests never ran.
## Checks
- CI test selection: `pytest --collect-only -q tests/unit -m "not gpu"`
gives the same 673 ids before and after. `-m gpu` goes from 190 to 182
ids, and the diff is exactly the 8 skipped ids listed above. Nothing
that ran before is gone.
- `pytest -m "not gpu" tests/unit/orchestrator
tests/unit/test_configs.py tests/unit/train/rl/test_fused_lm_head.py`:
297 passed.
- `ruff check .`, `ruff format --check .`: clean.
- GPU: none needed (only skipped tests are removed).
## Conflicts
- #3833 (remove transformers modeling) edits `test_afmoe.py`,
`test_model.py::test_model_with_sequence_packing` and
`test_fused_lm_head.py::test_full_model_fused_vs_vanilla` to port them
to the new model API, but keeps them skipped. Text conflict only.
Whichever PR lands second resolves it by keeping the deletion.
- #3794 and #3698 edit the import block of `test_fused_lm_head.py`. This
PR drops `selective_log_softmax` from the same import line. Expect a
trivial text conflict.
- If an AFMoE parity check is still wanted, port it to upstream
`transformers.models.afmoe` with `sdpa` in a follow-up. That would need
a GPU run to validate.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Test-only deletions with no application code changes; CI coverage for
tests that actually ran is unchanged per PR checks.
>
> **Overview**
> **Removes dead test code** that never executed in CI: unconditionally
skipped GPU/unit tests and the vendored HuggingFace AFMoE copy they
depended on.
>
> Deleted the whole `tests/unit/train/models/afmoe_hf_modeling/` tree
(~777 lines) plus `test_afmoe.py`, since upstream `transformers` already
ships AFMoE and the module was skipped for flash-attention
incompatibility. Also drops skipped cases in `test_model.py` (sequence
packing, Meta Llama custom forward),
`test_fused_lm_head.py::test_full_model_fused_vs_vanilla`, and the
entire `test_nccl_broadcast.py` module.
>
> `tests/conftest.py` loses the unused `free_port` fixture and its
`socket` import (only the NCCL test used it, and incorrectly).
`test_fused_lm_head.py` no longer imports `selective_log_softmax` after
removing the skipped full-model test.
>
> **No production/runtime behavior change** — only fewer collected tests
(8 GPU-marked ids removed).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
61235f155a74f04ee3119deb9a4b557839313bec. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Moves every GPU Tests job that fits in 2 GPUs onto the `prime-rl-2xh200`
ARC scale set, so runs stop queueing behind the two `vm` runners.
Stacked on #3834.
**Assignment**
- `prime-rl-2xh200` (9): unit-tests, reverse_text, reverse_text_sft,
reverse_text_sft_lora, reverse_text_lora, reverse_text_moe,
reverse_text_rl_opd, reverse_text_rl_sft, alphabet_sort, gsm8k_eval
- `4xa6000` (1): benchmark_regression, unchanged
The `vm` runners are left registered and untouched - just no longer on
the GPU Tests path.
**Sizing checks**
- Integration configs put inference on GPU 0 and trainer on GPU 1, so 2
GPUs each.
- Unit tests peak at `world_size=2` (NCCL broadcast test); `gsm8k_eval`
needs no GPU.
- benchmark_regression stays put: baselines are A6000-pinned
(`benchmark-4xa6000-*.json`) and the 4-GPU case exceeds a job pod. Note
`4xa6000` has zero registered runners today, so it queues regardless of
this PR.
**Worth knowing:** 12 tests in `test_deepseek_v4_kernels.py` are gated
on `requires_datacenter_gpu` (compute capability 9/10). They skip on
A6000 and will begin running on H200 - new coverage, but they have not
run in CI before.
Runners use `containerMode: kubernetes`, so `container:` blocks work
unchanged - each job gets a fresh pod, no Docker daemon, no privileged
containers.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> CI-only runner reassignment can surface new failures when
datacenter-GPU-gated unit tests run on H200 for the first time;
production code paths are untouched.
>
> **Overview**
> **GPU Tests** CI now targets the `prime-rl-2xh200` Kubernetes runner
scale set instead of `vm` for every job that needs at most two GPUs.
>
> The **unit-tests** job and nine **integration-tests** matrix entries
(`reverse_text*`, `alphabet_sort`, `gsm8k_eval`, etc.) all use
`prime-rl-2xh200`. **`benchmark_regression`** is unchanged on `4xa6000`
because it needs four GPUs and A6000-pinned baselines.
>
> No test commands, containers, or matrix structure change—only
`runs-on` / `runner` labels. Unit tests on H200 may start executing
tests gated by `requires_datacenter_gpu` in
`test_deepseek_v4_kernels.py` that previously skipped on
`vm`/A6000-class hardware.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
579a43fe10fbd114a1bf935bd43917fc63873a18. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Hosted image `v0.9.1.dev200` fails when GLM-5 selects `model.dsa_backend
= "cudnn_flashmla"`: the forward path imports `flash_mla`, but Docker's
explicit sync extras omit `flash-mla`. The [dev200 build
log](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/37265534904)
confirms the missing extra; `nvidia-cudnn-frontend` is already
installed.
Add `--extra flash-mla` to the dependency-image sync and the
source-override entrypoint sync. Add an amd64 package-presence check
before publishing the dependency image. The existing Linux/x86_64 marker
excludes the wheel on arm64, and the Dockerfile change invalidates the
dependency-image fingerprint.
## Verification
- Compared locked requirement exports with the exact Docker extras
before and after the fix: amd64 adds only the pinned FlashMLA wheel;
arm64 requirements are unchanged. Neither platform loses dependencies,
and both include `nvidia-cudnn-frontend==1.30.0`.
- Confirmed Docker and source-override entrypoint extras match.
- Downloaded the pinned CPython 3.12/CUDA 13/PyTorch 2.13 wheel and
verified its lockfile SHA256. Confirmed it exports
`flash_mla_sparse_fwd` and includes the native extension.
- Docker Buildx Dockerfile checks: no warnings. Bash syntax and `git
diff --check`: passed.
GPU import and execution checks on a rebuilt image are still pending.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Build-time dependency and publish-time presence checks only; arm64 is
unchanged because the extra is x86_64-gated in the lockfile.
>
> **Overview**
> Adds the **`flash-mla`** optional dependency to CUDA image builds and
runtime source overlays so GLM-5 paths using `model.dsa_backend =
"cudnn_flashmla"` can import `flash_mla` in hosted images.
>
> **`Dockerfile.cuda`** includes `--extra flash-mla` in the builder `uv
sync` (alongside the other GPU extras) and, on **x86_64 only**, asserts
`flash-mla` is present in the published dependency image via
`importlib.metadata`. **`scripts/docker-entrypoint.sh`** adds the same
extra to `uv sync` when `PRIME_RL_REF` overlays a checkout, keeping the
entrypoint extras list aligned with the Dockerfile comment.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
12329d455836ab80ac581e18de7339718312e7a9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Removes legacy config options and their code paths. They have had no
changes of their own in 4+ months.
## Removed
- **SGD optimizer** (`optim.type = "sgd"`): `SGDConfig`, its union
member, and the `torch.optim.SGD` branch in `trainer/optim`. AdamW,
Muon, and SignSGD stay.
- **`ckpt.skip_progress`** (orchestrator and trainer ckpt configs):
resume now always restores progress. This affects the orchestrator ckpt
loading and SFT resume.
- **`Jackmin108/` model-name special case** in
`validate_shared_model_name`. Trainer and orchestrator model names now
must always match when no inference config is given.
## Kept
- **`orchestrator.collect_inference_metrics`** stays, unchanged from
main. Hosted training uses Grafana for inference metrics and sets it to
`false` to turn off W&B mirroring. The `/metrics` poll for the
concurrency controller always runs either way.
## Also included (#3774, merged into this branch)
- `RLConfig`: top-level shared fields (including `resume`) go through
`propagate_shared_fields` only. The old `validate_shared_*` helpers in
`validation.py` are replaced by inline cross-component checks in
`RLConfig.validate_shared_configs`.
## Breaking changes
TOMLs/CLI args that set any of these now fail validation:
- `trainer.optim.type = "sgd"` (and `optim.momentum`, `optim.nesterov`)
- `orchestrator.ckpt.skip_progress`, `trainer.ckpt.skip_progress` (SFT
`ckpt.skip_progress`)
No configs, examples, docs, or skills in the repo reference these
options.
## Validation
- `pytest tests/unit -m "not gpu"` (excluding
`tests/unit/train/test_cpu_adam.py`, which needs `ninja` to build a C++
extension on this machine): 651 passed
- `ruff check .` and `ruff format --check .` (only `docs/algorithms.md`
is flagged, same as on main)
- GPU/integration tests were not run (no GPU on this machine).
Rebased on main f42630873; resolved conflicts in `configs/rl.py` and
`utils/validation.py` (main's #3788 already removed
`validate_shared_weight_broadcast`; kept that and this PR's removal of
the other `validate_shared_*` helpers).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking config validation for old TOMLs/CLI flags and stricter
cross-component model/resume rules; resume behavior changes if anything
relied on skipping progress restore.
>
> **Overview**
> Removes **legacy config knobs** that are no longer supported:
**`optim.type = "sgd"`** (config type + `torch.optim.SGD` factory), and
**`ckpt.skip_progress`** on trainer/orchestrator checkpoints. Resume now
**always** restores orchestrator progress/curriculum state and SFT
training progress (step counter always advances after load).
>
> **RL config validation** is consolidated: shared-field helpers in
`validation.py` are deleted in favor of
**`RLConfig.validate_shared_configs`** using a generic `require_equal`
check (model name, chat template, `max_steps`, `resume`, ckpt/W&B
parity, seq_len bound). Top-level **`resume`** is propagated via
**`propagate_shared_fields`** instead of a separate `auto_setup_resume`
validator; the **`Jackmin108/`** trainer/orchestrator model-name
exemption is gone.
>
> CI slim-install smoke test imports **`propagate_shared_fields`** only.
Unit tests drop SGD from full-offload optimizer coverage.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1df3854c75fc652e2b0a5dbd7d019555e73736ba. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Two small cleanups in `orchestrator/algo/`. Item 4 of the orchestrator
review.
- `action_loss_type` is now declared once, on the algorithm config
classes. Before, it was declared on the config classes and again on the
runtime classes (`algo/base.py`, `sft.py`, `opd.py`, `opsd.py`), and
`build_algorithm` asserted that the two agreed. Now `Algorithm.__init__`
copies it from the config, so `train_sink`'s
`env.algorithm.action_loss_type` is unchanged.
- `Algorithm.finalize_group` is removed. It only called `score_group`,
and `train_sink` now calls `score_group` directly. `finalize_episode` is
kept: its "has sampled tokens" guard matters for `echo`, whose
`score_episode` does not filter on the mask.
- `docs/algorithms.md` is updated to match.
Behavior change: none. Every algorithm type gets the same loss routing
as before, because the old assert guaranteed that the config and runtime
values were equal.
## Checks
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 291 passed (`test_algorithms` covers the per-type
`action_loss_type`).
- `ruff check`, `ruff format --check`: clean.
GPU checks: none needed.
## Conflicts
`algo/base.py` and `algo/__init__.py`: #3802, #3803 (small). #3838 (fold
`GenerationSource`) also edits `algo/base.py` and `algo/__init__.py`
(`connect_frozen_client`), which needs a trivial rebase.
`train_sink.py:245`: #3652 rewrites `train_sink.py` (a one-line change
there).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Refactor-only: loss routing and group scoring call paths are unchanged
in effect; no auth, data, or trainer hot-path logic changes.
>
> **Overview**
> **Single source of truth for loss routing:** runtime `Algorithm`
instances now take `action_loss_type` from the algorithm config in
`__init__` instead of duplicating it on each subclass and asserting
agreement in `build_algorithm`. Per-algorithm class variables on `OPD`,
`OPSD`, and `SFT` are removed; `train_sink` still reads
`env.algorithm.action_loss_type` when stamping samples.
>
> **Thinner scoring API:** `Algorithm.finalize_group` is dropped and the
train sink calls `score_group` directly when a group has trainable
survivors. `finalize_episode` remains as the guarded entry point for
rollout-local `score_episode` (skips episodes with no trainable sampled
tokens).
>
> **Docs:** `algorithms.md` is updated to describe this pipeline wiring
and config-owned `action_loss_type`.
>
> No intended training behavior change—loss routing values are the same
as before when config and runtime matched.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1ebee7fec9fab8740b04de41e3aee9e89d4ca6d7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Moves `BatchPacker` (35 lines) from `orchestrator/packing.py` into
`orchestrator/batch.py` and deletes `packing.py`. The class only wraps
`build_bin_cost` and `prepare_batch`, which already live in `batch.py`.
Item 6 of the orchestrator review.
Behavior change: none (pure move; the import in `orchestrator.py` is
updated).
## Checks
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 291 passed
- `ruff check`, `ruff format --check`: clean
- `python -c "import prime_rl.orchestrator.orchestrator"` OK
- Equivalence: the class body is copied byte for byte (`git diff` shows
only the move and the import lines).
GPU checks: none needed.
## Conflicts
- #3840 (FLOP estimator): textual, in the `batch.py` imports only.
- #3652: its `Shipper` imports `BatchPacker` from `packing`, which
becomes a one-line change to `from prime_rl.orchestrator.batch import
BatchPacker`.
- #3819, #3836, #3794 touch other parts of `batch.py`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Pure file move and import path update with no logic changes to
training batch packing.
>
> **Overview**
> **Colocates batch packing with the bin-packing helpers it already
delegates to.**
>
> `BatchPacker` moves from `orchestrator/packing.py` into
`orchestrator/batch.py` next to `build_bin_cost` and `prepare_batch`;
`packing.py` is removed. The orchestrator now imports `BatchPacker` from
`batch` instead of `packing`. Class behavior and `pack()` semantics are
unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
986f5bf0f692cca69a2bf1d49bbec53b09ececef. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Removes duplicate and unused entries from `pyproject.toml` (rev-infra
P9). The set of installed packages does not change for any extra
combination (checked below).
| Removed | Reason |
|---|---|
| second `orjson>=3.10` in `dependencies` | Duplicate of
`orjson>=3.11.0` a few lines above. |
| `pandas>=2.0` | Nothing imports it: no `import pandas` / `pd.` in
`src/`, `tools/`, `scripts/`, `tests/`, `examples/`, `skills/`,
`packages/`. It was added for the nano bridge (7089ba1e4). It stays
installed because `datasets` depends on it. |
| `pyarrow>=21.0.0` | No direct use anywhere in those directories. The
one parquet writer, `tools/convert_traces_to_hf_dataset.py`, calls
`datasets.Dataset.to_parquet`, and `datasets` depends on `pyarrow`
itself. It stays installed. |
| `nixl-cu13==0.10.1` in the `disagg` extra | `disagg` already lists
`nixl`, and the `[[tool.uv.dependency-metadata]]` override for `nixl`
0.10.1 requires exactly `nixl-cu13==0.10.1`. The `gpu` extra keeps its
explicit pin, because `transports/weights/nixl/agent.py` imports
`nixl_cu13` directly. |
| `mamba-ssm` dependency group | Duplicate of the `gpu` extra entry,
which was added with the native Nemotron-H model (#3426). Every user of
the group also syncs `--extra gpu` or `--all-extras`, so I dropped
`--group mamba-ssm` from `Dockerfile.cuda` (2 places),
`scripts/docker-entrypoint.sh` and the `pre_run_command` in
`configs/advanced/nemotron-3-super/swe.toml`. The `[tool.uv.sources]`
git pin and the build dependencies for mamba-ssm stay. |
Behavior change:
- None for installs: same locked packages and versions.
- `uv sync --group mamba-ssm` no longer works; use `--extra gpu`, which
every repo caller already passes.
- `pandas` and `pyarrow` lose their direct lower bounds. They are still
pulled in by `datasets`.
## Checks
- `uv lock`: resolves 564 packages, the same set as before (568
`[[package]]` entries before and after). `uv lock --check` passes. The
`uv.lock` diff only touches prime-rl's own metadata. I reverted the
reordering of `[options.exclude-newer-package]` that my uv version
(0.12.10) introduced.
- I ran `uv export --frozen --all-packages` and compared the package
lists before and after, ignoring the `# via` comment lines. They are
identical for: no extras, `--extra disagg`, `--extra gpu`, `--extra
dashboard`, `--all-extras`, and `--all-extras --all-groups`. `--extra
disagg` still yields `nixl==0.10.1` and `nixl-cu13==0.10.1`, and
`--extra gpu` still yields `mamba-ssm` at the pinned rev.
- No Python changes, so no unit tests are affected. GPU: not needed. The
Docker image build in CI covers the Dockerfile and entrypoint edits.
## Conflicts
Text conflicts only in `pyproject.toml` / `uv.lock`, as with any
dependency PR. None of the open PRs that touch these files (e.g. #3829,
#3803, #3767, #3660) edit the lines removed here. A re-lock after rebase
is enough.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Metadata and sync-flag cleanup only; lockfile exports are unchanged
and runtime installs should match prior behavior.
>
> **Overview**
> Cleans up **duplicate and redundant dependency declarations** in
`pyproject.toml` and aligns `uv.lock`, Docker, and Slurm sync commands
with the slimmer manifest. **No intended change to installed packages**
for existing extra combinations (`gpu`, `disagg`, `--all-extras`, etc.).
>
> **Removed from core `dependencies`:** duplicate `orjson>=3.10`, unused
direct pins on `pandas` and `pyarrow` (they still come in via
`datasets`). **Removed from `disagg` extra:** explicit
`nixl-cu13==0.10.1` because `nixl` metadata already pulls that version;
the **`gpu` extra keeps** its explicit `nixl-cu13` pin for direct
imports. **Dropped the `mamba-ssm` dependency group** as a duplicate of
the `gpu` extra entry—`Dockerfile.cuda`, `scripts/docker-entrypoint.sh`,
and the Nemotron SWE `pre_run_command` no longer pass `--group
mamba-ssm`.
>
> **Workflow note:** `uv sync --group mamba-ssm` alone is no longer
supported; use `--extra gpu` (or `--all-extras`), which callers already
use.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f0f2ff6b6365165a92be511c8029a47080f748e0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Fixes two wrong statements in `docs/scaling.md` (from the whole-codebase
review, rev-infra P8 / rev-trainer §6). Docs only. No code or behavior
change.
- **`ep = "auto"`**: the doc said auto picks the largest divisor of
`num_experts` that divides the FSDP island, is a multiple of `cp`, and
is ≤ 8. The code (`trainer/parallel_dims.py:resolve_ep`) returns
`min(world_size // dp_replicate, 8)` for MoE models and 1 otherwise.
That matches the `ModelConfig.ep` docstring. The doc now describes what
the code does and says to set `ep` explicitly when the result does not
fit `cp` / `num_experts`.
- **NIXL wheel**: `scripts/install_nixl_from_source.sh` names the wheel
`nixl-cu13` (lines 85-88, 105). `docs/advanced.md:216` already says
`nixl_cu13-*.whl`, but `scaling.md` said `nixl_cu12-*.whl`, so that
install command did not match any file.
Checks: docs only. Compared against `resolve_ep` and the install script.
Conflicts with open PRs: none. No open PR touches `docs/scaling.md`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Documentation-only corrections to scaling and install instructions; no
runtime or training behavior changes.
>
> **Overview**
> Updates **`docs/scaling.md`** so it matches current behavior—no code
changes.
>
> **Expert parallelism (`ep = "auto"`)**: Replaces the old description
(largest valid divisor of `num_experts` subject to FSDP island, `cp`,
and cap 8) with what **`resolve_ep`** actually does: for MoE,
`min(world_size // dp_replicate, 8)`; for non-MoE, `1`. The doc now
notes that auto does not consider `num_experts` or `cp`, and that you
should set **`ep`** explicitly when the resolved value fails those
constraints.
>
> **NIXL install**: Changes the documented wheel from
`deps/nixl_cu12-*.whl` to **`deps/nixl_cu13-*.whl`**, consistent with
`scripts/install_nixl_from_source.sh` and other docs.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
778befd26ff787ee71cb7308071a26542c9cc470. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Removes the Kubernetes deployment path. The Helm chart has had no
functional change since its initial additions (last own change
2026-08-12 was a docs fix), and supported multi-node deployment is SLURM
(see docs/scaling.md). The trainer `metrics_server` (Prometheus
`/metrics` + `/health`) only existed to serve the chart's
liveness/readiness probes.
## Removed
- `k8s/` Helm chart (and `COPY k8s` from `Dockerfile.cuda`)
- `src/prime_rl/utils/metrics_server.py` (`MetricsServer`,
`HealthServer`) and its unit test
- `MetricsServerConfig` (configs/shared.py), trainer `metrics_server`
field, and its setup/update/teardown in `trainer/rl/train.py`
- Kubernetes sections/mentions in README,
`examples/basic/reverse-text/README.md`, `docs/training.md`; `k8s/`
TOMLs dropped from `test_configs.py`
- Inference `liveness_timeout_seconds` docstring reworded neutrally; the
`/liveness` endpoint stays (used by SLURM/router health checks)
`prometheus-client` stays in `pyproject.toml`:
`orchestrator/inference_metrics.py` still uses its parser.
## Breaking changes
- Trainer configs that set `metrics_server` now fail validation.
- The Helm chart and `/app/k8s` in the image are gone.
## Validation
- `pytest tests/unit/test_configs.py -m "not gpu"` (205 passed)
- `ruff check .` and `ruff format --check .`
- No GPU on the machine used; GPU/integration tests not run.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking for anyone using the Helm chart or trainer `metrics_server`
config; training/runtime core paths are unchanged but deployment and
observability options shrink.
>
> **Overview**
> **Removes the Kubernetes/Helm deployment path** and related trainer
observability that existed mainly for chart probes.
>
> The entire `k8s/` Helm chart (StatefulSets, services, PVC,
reverse-text example values/TOMLs, and `k8s/README.md`) is deleted.
**`Dockerfile.cuda`** no longer copies `k8s/` into the image, and
docs/README/example copy now describe **Slurm-only** multi-node
deployment (K8s sections dropped from `reverse-text` README).
>
> **Trainer Prometheus/health HTTP server is removed:**
`MetricsServerConfig`, the `metrics_server` trainer config field,
`src/prime_rl/utils/metrics_server.py`, RL trainer
startup/update/shutdown hooks, and unit tests. Configs that still set
`metrics_server` will fail validation.
>
> **Minor doc tweaks:** inference `liveness_timeout_seconds` help text
is generic (not K8s-specific); `env-server` docs refer to externally
managed hosts instead of pods. Config validation tests only scan
`configs/` and `examples/` TOMLs, not `k8s/`.
>
> Inference `/liveness` and `prometheus-client` elsewhere (e.g.
orchestrator) are unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
42e89b437dc19ae11abd0172672b89b9f03e6c30. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Removes legacy leftovers that were last touched 2025-11 to 2026-02 or
were orphaned by features that are already gone. Behavior does not
change.
- **`orchestrator/patches.py`**: deletes the OpenAI chat-type
monkeypatches, which were written for verifiers 0.1.8. The orchestrator
and eval processes no longer parse `ChatCompletion` or message objects
in-process. Rollouts run in separate env-server processes, which never
applied the patch, and `prefill_logprobs` reads the raw
`httpx.Response`.
- **`FileSystemWeightUpdateWorker.init_broadcaster`**: deletes this
no-op stub. `/init_broadcaster` is only called by the NCCL and NIXL
transports, whose workers define their own method. The stub took no
arguments, so the route could never have dispatched to it anyway.
- **`prime_rl.utils.utils` pathing re-export**: deletes the shim (its
TODO asked for this) and points the remaining imports at
`prime_rl.utils.pathing`. The shim's file-wide `noqa: F401` was hiding
three unused imports in `utils.py`; they are removed too.
- **`tests/unit/inference/test_serving_chat_with_tokens.py`**: deletes
this empty file.
- **`ConcurrencyController.record_episode`**: now takes only `tokens`.
`env_name`, `kind` and `duration` are left over from the removed per-env
cost model and were ignored. The dispatcher's `on_episode_complete`
callback type now matches, and the `ConcurrencyConfig` docstring no
longer mentions "learned per-env episode costs".
- **`@deprecate_kwarg("past_key_value", ...)`**: removed from the llama,
glm4_moe and glm_moe_dsa decoder layers. These layers never accepted
`past_key_value(s)`, and transformers is pinned to 5.6.2. The signatures
still accept everything their callers pass.
## Breaking changes
- `from prime_rl.utils.utils import get_ckpt_dir` (and the other pathing
helpers) no longer works. Import them from `prime_rl.utils.pathing`.
- `ConcurrencyController.record_episode(tokens)` and the
`Dispatcher(on_episode_complete=...)` callback now take one argument.
- `prime_rl.orchestrator.patches` no longer exists.
## Validation
- `ruff check .` and `ruff format --check .`
- `pytest tests/unit/orchestrator tests/unit/eval tests/unit/inference
tests/unit/train/models tests/unit/utils tests/unit/test_configs.py -m
"not gpu"`: 417 passed, 154 deselected
- Import check of every modified module.
- GPU and integration tests were not run: this machine has no GPU.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Mostly deletions and import-path changes with documented API breaks;
adaptive concurrency still uses token counts for growth gating.
>
> **Overview**
> This PR deletes unused orchestration and compatibility shims and
tightens a few callback signatures. Runtime behavior for supported
entrypoints is intended to stay the same.
>
> **Removed OpenAI monkey-patches** — `orchestrator/patches.py` and
startup calls in the orchestrator and eval runner are gone. Rollouts no
longer parse `ChatCompletion` in those processes.
>
> **Concurrency hooks** — `ConcurrencyController.record_episode` and the
dispatcher `on_episode_complete` callback now only receive **token
count**; leftover per-env cost-model args were unused.
`ConcurrencyConfig` docs now describe KV-pressure sizing only.
>
> **Misc cleanup** — Drops
`FileSystemWeightUpdateWorker.init_broadcaster`, the
`prime_rl.utils.utils` re-export of pathing helpers (call sites import
`prime_rl.utils.pathing` directly), `@deprecate_kwarg` on custom decoder
layers, and an empty inference unit test file.
>
> **Breaking for downstream imports** — `prime_rl.orchestrator.patches`
is removed; pathing helpers must be imported from
`prime_rl.utils.pathing`; `record_episode` / `on_episode_complete` take
a single `int` argument.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
079daae952aeae8c1e6dd1a009ec3d950d0f4767. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Platform is adding a reverse proxy for the dashboard (platform#5719)
that forwards the bare path upstream with no prefix, so every
browser-side reference needs to be relative, not absolute.
- `index.html`: dropped the leading `/` from the icon, stylesheet, brand
image, and script `src`/`href` paths.
- `app.js`: the `api()` fetch helper now strips a leading `/` before
calling `fetch`, and the `EventSource("/api/view/events")` call is
relative too.
- `style.css` already only used `data:` URIs, no change needed.
Verification: served the static files through a throwaway reverse proxy
mounted under a sub-path prefix (mirroring the proxy's bare-path
forwarding), confirmed the HTML/JS no longer contain absolute `/static`
or `/api` references, and confirmed requests like
`.../prefix/static/app.js` and `.../prefix/api/runs` correctly resolve
relative to the page and reach the upstream dashboard.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> URL resolution-only changes for static assets and API/SSE calls; no
server or auth logic touched.
>
> **Overview**
> Makes the dashboard work when it is served behind a reverse proxy that
mounts it under a sub-path and forwards **bare** paths upstream (no
`/prefix` on upstream requests).
>
> **`index.html`** switches icon, CSS, images, and script tags from
root-absolute (`/static/...`) to **relative** (`static/...`) so assets
resolve against the current page URL.
>
> **`app.js`** strips a leading `/` in the shared `api()` `fetch` helper
so existing `api("/api/...")` callers emit relative `api/...` URLs, and
changes the live view **`EventSource`** from `/api/view/events` to
`api/view/events`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9efe2aa17fc084cf71491dabd88e9b039ff40555. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Removes the orchestrator `token_batch_size` option (token-budget batch
cutting). Batches are now always cut by sample count (`batch_size`).
**Why:** the train sink had two parallel batch-cut paths. Sample-count
batching is the one every shipped config uses, including GLM-5.3.
Removing the token path drops the `pending_tokens` / `payload_tokens`
accounting and the token branches in `process_batch`, `_drop_stale`,
`_maybe_batch` and `_record_zero_output`.
**Changes**
- `OrchestratorConfig.batch_size` is now a plain `int = 128` field.
Before, it was `int | None` and the validator set the 128 default.
- Removed `token_batch_size` and the "set exactly one of batch_size or
token_batch_size" check. The `batch_size` divisibility check by group
size stays.
- `TrainSink` takes `batch_size: int` only. `batch_progress()` now
returns `(count, target)` without the unit string. Its only caller is
the orchestrator status log.
- `constant_trainer_batch_size` is unchanged. No metric keys changed.
**Breaking:** configs that set `orchestrator.token_batch_size` now fail
validation. Use `batch_size` instead. No config, example, doc or skill
in the repo set it.
## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 300 passed
- `ruff check .` and `ruff format --check .`: clean
- GPU and integration tests were not run (no GPU on this machine).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how train batches are formed at the orchestrator; configs
using token batching break, but sample-count batching behavior for
existing runs should be unchanged.
>
> **Overview**
> Removes **token-budget batching** from the orchestrator so training
batches are always cut by **sample count** (`batch_size`).
>
> `OrchestratorConfig` drops `token_batch_size` and the mutual-exclusion
validator; `batch_size` is now a required `int` defaulting to **128**
(no longer optional with a validator fallback). `TrainSink` only tracks
trace count for readiness, staleness drops, zero-output warnings, and
`process_batch`—`pending_tokens`, `payload_tokens`, and token-based
partial cuts are gone. `batch_progress()` returns `(count, target)`
only; pipeline status logs no longer show a traces/tokens unit.
>
> **Breaking:** configs that set `orchestrator.token_batch_size` fail
validation; use `batch_size` instead.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
be797adb554eb5ba99aeb0cd3c3c210eac6e2e0d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Adds `GRPOAlgoConfig.loss_aggregation: Literal["token", "prompt"] =
"token"`. `echo` gets it too because it subclasses GRPO.
**Why:** the trainer averages the `rl` loss over every loss token in the
batch. Prompts whose groups produce long trajectories therefore dominate
the gradient. SWE groups can differ by about 10x in total tokens.
`"prompt"` implements MiMo-V2.6's prompt-mean aggregation exactly (Eq.
1, p8): `L = mean_q (1/T_q) Σ_{i,t ∈ q} ℓ_{i,t}`. MiMo uses it to keep
response length from growing too fast.
**How:**
- **Trainer:** the `rl` component now divides by the global sum of its
per-token weights, not by the count of nonzero-weight tokens. Every `rl`
weight set in prime-rl today is 0/1, so the sum equals the old count,
and the default path is bit-identical to main. `ce` and `ref_kl` still
divide by their token counts. This is on purpose: echo's fractional `ce`
weight (`alpha`) must keep scaling the loss instead of cancelling out.
- **Orchestrator:** with `"prompt"`, `GRPOAlgorithm.score_group` gives
each trainable token of group q the `rl` weight `1/T_q`. `T_q` is the
group's trainable tokens, the same tokens the advantage is assigned to.
Each group's weights sum to 1, so the `rl` denominator becomes the
number of groups in the step, all-reduced across ranks like before.
There is no extra state.
- **Config:** a validator rejects runs that mix `"token"` and `"prompt"`
across envs with an `rl` loss. In a mixed batch, a whole prompt-mean
group would weigh as much as one token of a token-mean env.
- **Known difference from MiMo:** zero-advantage pruning still drops
zero-advantage tokens from `rl`. A group with a zero-advantage rollout
therefore keeps less than its full weight of 1. MiMo divides by all of
the group's tokens.
- **#3789 (length-weighted baseline):** compatible. Within a group the
weights are uniform, so a length-weighted baseline still keeps the
per-token advantage zero-mean.
**Breaking changes:** none for the default. One behavior change: an `rl`
weight stream with fractional weights would now be normalized by its
sum. Nothing in the repo produces such a stream today.
## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 301 passed. This includes an updated test in `test_advantage.py`:
each group's `rl` weights are exactly `1/T_q` and sum to 1, for two
groups of different length.
- Manual check that the config validator rejects mixed
`loss_aggregation` across envs.
- `ruff check .` and `ruff format --check .`: clean.
- Not run, because this machine has no GPU:
- `tests/unit/train/rl/test_loss.py`, which needs CUDA and also fails
here on main.
- The trainer denominator change in `train.py`.
- GPU and integration tests.
- A training run.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how the RL loss denominator is computed globally; default
token aggregation should be numerically equivalent, but prompt-mean
alters gradient weighting for long trajectories and mixed configs are
blocked at validation time.
>
> **Overview**
> Adds **opt-in prompt-mean RL loss aggregation** for GRPO and echo via
`loss_aggregation = "prompt"` (default `"token"` stays unchanged).
>
> When enabled, **`GRPOAlgorithm.score_group`** stamps each trainable
token with `rl` weight `1/T_q` so each prompt group’s weights sum to 1
(MiMo-style prompt mean). The **trainer** now normalizes the `rl`
component by the **global sum of `rl_weights`** (not nonzero-token
count); with the default 0/1 weights this matches prior behavior. **`ce`
/ `ref_kl`** still divide by token counts so fractional echo `ce`
weights behave correctly.
>
> **Orchestrator config** rejects mixing `"token"` and `"prompt"` across
envs that use an `rl` loss. **Docs** describe the knob; a **unit test**
checks per-group `rl` weights sum to 1.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
91cf0629f13c3fa39d7c78f476e549b097efa025. 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 Hugging Face model-implementation fallback (`model.impl =
"hf"`). The trainer now only builds PrimeRL model implementations
(`src/prime_rl/trainer/models/`). An unsupported architecture fails at
setup with `'<model_type>' has no PrimeRL model implementation`.
- `model.impl` is removed. With `"hf"` gone, `"auto"` and `"custom"`
resolved to the same thing.
- `trainer/model.py`: removed impl resolution, `AutoModelForCausalLM` /
`AutoModelForImageTextToText` loading, the CPU-load fallback
(`can_reinit_empty_buffers`, `fix_model_post_empty`), HF weight
re-tying, the HF router-freeze branch, and the HF output handling in
`forward`.
- Removed `lm_head_gemma.py` and its hook in `inject_prime_lm_head`. It
only served HF-impl models with final-logit softcapping.
- Removed the HF CP patches (`substitute_hf_flash_attn`,
`substitute_hf_ulysses_attn`). The config already rejected CP for the HF
impl.
- Removed the `qwen3_vl`, `qwen3_vl_moe` and `gemma4` entries from the
trainer VLM registry. They could only be loaded through the HF path.
Orchestrator and inference multimodal adapters are unchanged.
- Removed the config validators that only checked `impl` (EP, CP, FA4,
quantization, router replay, VLM, trust_remote_code).
- `hendrycks-sanity` (`examples/basic`, `configs/basic`,
`configs/ci/nightly-fft`) used
`deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` (Qwen2 architecture, which
has no PrimeRL implementation). It now uses `Qwen/Qwen3-1.7B`. No other
settings changed.
- Dropped `impl = ...` from all configs/examples/docs, and updated
README, docs, and tests.
- `test_fused_lm_head.py`: the HF-model tests now use a tiny PrimeRL
Qwen3 (same config as #3768, which removes PrimeRL Llama), built in bf16
because the PrimeRL attention is FlashAttention-only (the fp32 build
failed CI with `FlashAttention only supports fp16, bf16, and fp8_e4m3`).
## Why
The HF fallback is an aging path: added 2025-09, last changed on its own
on 2026-07-17. It keeps a second loading, buffer-reinit, LM-head and CP
code path alive next to the custom implementations. After the
hendrycks-sanity switch, custom implementations cover every shipped
example and config.
## Breaking changes
- `model.impl` / `--trainer.model.impl` is no longer accepted. Configs
that set it fail validation (`extra_forbidden`), so delete the line.
- Architectures without a PrimeRL implementation (for example Qwen2,
Gemma, Qwen3-VL, Mistral) can no longer be trained.
- hendrycks-sanity now trains `Qwen3-1.7B`. Its dataset
(`mikasenghaas/Sanity-Test-R1D-1.5B`) was filtered to problems that
R1-Distill-Qwen-1.5B solves 20-80% of the time, and that band was not
measured for Qwen3-1.7B. **The expected reward, curves, and the nightly
thresholds (`MIN_TRAIN_REWARD = 0.75`, the mismatch-KL band in
`tests/nightly/test_hendrycks_sanity.py`) need GPU re-validation.**
## Validation
- `pytest tests/unit/test_configs.py tests/unit/train -m "not gpu"`: 356
passed, 2 failed. The 2 failures are in `test_cpu_adam.py` (ninja is
missing on this machine). They fail the same way on `origin/main`.
- `ruff check .` and `ruff format --check .`: clean.
- `test_fused_lm_head.py` inject tests: checked on CPU that the tiny
Qwen3 resolves to `flash_attention_3` / `FlashAttention`; the GPU run is
left to CI.
- Manual CPU check: `get_model` builds `Qwen/Qwen3-1.7B` on the meta
device, and a Qwen2 config raises the new setup error.
- Not run: GPU unit tests (including the edited `test_fused_lm_head.py`,
`test_model.py`, `qwen3_5/test_vlm.py`), integration tests, and nightly
runs. There is no GPU on this machine.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> This is a breaking API and behavior change: unsupported architectures
hard-fail, and the hendrycks-sanity model swap can invalidate nightly
reward/KL gates until re-validated on GPU.
>
> **Overview**
> **Removes the Hugging Face training path** by deleting `model.impl`
(`hf` / `custom` / `auto`). The trainer always loads PrimeRL classes
from `src/prime_rl/trainer/models/`; unknown `model_type` values fail at
setup with a clear error.
>
> **Trainer/runtime cleanup:** `get_model` no longer branches to
`AutoModelForCausalLM` or HF VLMs, drops the CPU/meta fallback
(`can_reinit_empty_buffers`, `fix_model_post_empty`), and always uses
PrimeRL weight conversion and `init_buffers_post_meta`. **Removed**
Gemma softcapped LM head (`lm_head_gemma.py`), HF context-parallel
patches, and HF-specific MoE router freeze / forward handling.
>
> **Config & docs:** `impl = "custom"` (and related validators tying EP,
CP, VLM, etc. to `impl`) are stripped from Pydantic configs, examples,
and docs. VLM registry narrows to Qwen3.5 families (drops `qwen3_vl`,
`gemma4` trainer paths). Sampling-replay docs no longer mention Gemma
rejection.
>
> **Hendrycks sanity** now trains **`Qwen/Qwen3-1.7B`** instead of
`DeepSeek-R1-Distill-Qwen-1.5B` (no PrimeRL Qwen2 impl); dataset
filtering is still keyed to the distill model’s 20–80% band.
>
> **Breaking:** configs with `model.impl` fail validation;
Qwen2/Gemma/Qwen3-VL and other unregistered archs cannot be trained.
Nightly sanity thresholds may need re-baselining on GPU.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3524e2eeabd2642b1e607a0b59ff0af6489ad3a8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
rebased on main 243cfba0f; resolved conflicts in
src/prime_rl/trainer/model.py (kept main's parallelize_module import),
src/prime_rl/utils/vlm.py (kept native qwen4_exp from #3434), and
dropped configs/basic/hendrycks-sanity + configs/debug/concurrency.toml
(deleted on main by #3777).
## Summary
`optim.weight_decay` defaults to `"auto"` and resolves per trainer at
config-construction time: **`0.0` for RL**, **`0.01` for SFT** (the
historical default). Explicit values are untouched.
Follow-up to #2422, which flipped the shared default to `0.0` for both
trainers. Resolving per trainer keeps the RL motivation (no silent L2
decay of the policy during reward optimization) without changing SFT
behavior.
## How it works
Same pattern as `model.moe_router_dtype = "auto"`:
- `BaseOptimizerConfig.weight_decay` is now `Annotated[float,
Field(ge=0)] | Literal["auto"] = "auto"`.
- A `resolve_weight_decay_auto` model validator on `TrainerConfig` (RL)
resolves to `0.0`, and one on `SFTConfig` resolves to `0.01`.
- Because resolution happens at model construction, dumped configs
(`trainer.json` / `sft.json`) and `--help` always show the concrete
float — a resumed or reparsed run never sees `"auto"`.
- TOML / JSON / CLI overrides all keep working, including `weight_decay
= "auto"` explicitly.
| Trainer | `weight_decay` default |
| ------- | ---------------------- |
| RL (`rl`, `trainer`) | `0.0` |
| SFT (`sft`) | `0.01` (unchanged) |
## Notes
- Example configs that already set `weight_decay` explicitly are left
as-is; `examples/basic/wiki-search/rl.toml` and
`examples/advanced/glm-5.3/swe.toml` (`0.0`) now match the default and
could be simplified in a follow-up.
- LoRA runs resolve the same way (the optimizer is built from the same
`config.optim`).
## Testing
-
`tests/unit/test_configs.py::test_weight_decay_auto_resolves_per_trainer`
covers defaults, explicit floats, and the explicit `"auto"` string.
- Verified end-to-end locally: defaults, `RLConfig` sub-config,
`dump_resolved_config` output, TOML round-trip through `cli()`, and the
param group the optimizer receives.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Config-default change only at construction time; RL gets no weight
decay by default while SFT behavior stays at 0.01 unless users override.
>
> **Overview**
> **`optim.weight_decay` now defaults to `"auto"`** on shared optimizer
config instead of a fixed `0.01`. At config construction, each trainer
resolves it to a concrete float—the same pattern as
`model.moe_router_dtype`.
>
> RL **`TrainerConfig`** maps `"auto"` → **`0.0`** so policy training
does not apply L2 decay toward zero by default. SFT **`SFTConfig`** maps
`"auto"` → **`0.01`**, preserving the historical supervised default.
Explicit numeric values (and leaving `"auto"` in user input until
validation) behave as before; resolved dumps should show floats, not
`"auto"`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5219af74484473a3b4d884ec0569530e3521fa93. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## What
Adds step-level MoE expert-load metrics to the RL and SFT trainers,
logged as mean and max over MoE layers:
- `expert_load/cv/{mean,max}`: std/mean of the per-expert token counts
in a layer.
- `expert_load/max_mean/{mean,max}`: the busiest expert's count divided
by the mean count.
- `expert_load/cold_frac/{mean,max}`: the fraction of experts that
receive under 0.1x the mean count. This is the MiMo-V2.6 §5.4
definition, so values compare directly with the paper.
## Why
MiMo-V2.6 §5.4 uses these three numbers to show that a trainable router
collapses expert load during RL (CV 0.78→2.0, cold experts 0.5%→22%
within 20 steps) and that freezing the router prevents it. We need the
same evidence to validate #3797 (freeze the router by default for RL) on
our models. The metrics also help catch EP load imbalance.
## How
- The MoE layers already add routed-token counts into the
`tokens_per_expert` buffer inside the forward pass. This uses the
existing `record_moe_routing_statistics` custom op, so it works with
compile without graph breaks. It covers both the torch and DeepEP
dispatch paths because the counts come from the router. **No model or
compiled code changes.**
- `get_global_moe_stats` now also returns this rank's raw per-layer
counts for the micro-step, captured before the existing EP reduction and
reset. The train loop sums them over the step. At step end, one
`all_reduce(SUM)` over `dp_cp` (which includes the EP ranks) produces
global counts, and the stats are computed from them. Extra cost: one
`[num_moe_layers, num_experts]` add per micro-step and one all-reduce
per step.
- Only aggregates over layers are logged, with no per-layer keys. This
follows the existing `max_vio`/`routing_confidence` convention, which
also reduces over layers. It also keeps the key count fixed for 75-layer
models. The max over layers catches a single collapsing layer, like
MiMo's layer 9.
- `max_vio` and `routing_confidence` are unchanged: they are still
per-micro-step.
- `docs/training.md` describes the new metrics.
No breaking changes. Existing metric keys are unchanged;
`get_global_moe_stats` now returns `(stats, tokens_per_expert)`
(internal function).
## Validation
- `pytest
tests/unit/train/models/{test_moe,test_checkpointing,test_qwen3_moe,test_glm4_moe,test_gpt_oss,test_deepseek_v4_cpu}.py
tests/unit/train/test_model.py tests/unit/test_configs.py -m "not gpu"`:
243 passed. This includes one new CPU test of the metric computation.
- `ruff check .` and `ruff format --check .`
Not run: there is no GPU on this machine. GPU checks still needed:
- [ ] EP>1 run (torch and DeepEP dispatch): `expert_load/*` values are
identical across ranks and plausible.
- [ ] Compiled run: no new recompiles or graph breaks
(`TORCH_LOGS=recompiles`).
- [ ] A short RL run with a frozen router vs a trainable router: the
trainable run should show `cv`/`cold_frac` rising.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Logging-only path using existing routing counters plus one optional
all_reduce per MoE step; no changes to loss, routing, or model forward
behavior.
>
> **Overview**
> Adds **step-level MoE expert-load observability** aligned with
MiMo-V2.6 §5.4: trainers now log
`expert_load/{cv,max_mean,cold_frac}/{mean,max}` (coefficient of
variation, hottest-expert/mean ratio, and fraction of “cold” experts
under 0.1× mean load), aggregated as mean and max over MoE layers.
>
> **Implementation:** `get_load_balance_stats` captures each rank’s
per-layer `tokens_per_expert` before EP reduction; micro-steps
accumulate counts across the step; `get_expert_load_stats` sums globally
over `dp_cp` and computes the three stats. Existing per-microstep
`max_vio` and `routing_confidence` logging is unchanged. RL and SFT
training loops wire the new metrics into step logs; `docs/training.md`
documents how to read them (e.g. rising `cv`/`cold_frac` when a
trainable router drifts).
>
> A CPU unit test covers `compute_expert_load_stats`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9dde6e6ac625b4469c67ad2d20350d1bfbde9311. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
The weight-broadcast config (filesystem | nccl | nixl) was declared four
times: the inference `WeightBroadcastConfig`, the trainer
`*WeightBroadcastConfig`, the orchestrator `*WeightBroadcastConfig`, and
the rl.py `Shared*WeightBroadcastConfig`.
`RLConfig.auto_setup_weight_broadcast` then copied each field between
them by hand. Every new transport field had to be added in four places
and in the copy code.
Design: one discriminated union `WeightBroadcastConfig` (`FileSystem` /
`NCCL` / `NIXL` variants) in `configs/shared.py`. The trainer,
orchestrator, inference, RLConfig, SFTConfig and the online eval config
all use it.
- `auto_setup_weight_broadcast` now does `model_copy()` of
`[weight_broadcast]` into the trainer and orchestrator, and sets
`inference_world_size` for in-memory transports. Inference gets a plain
copy. The inference server still reads only `type`.
- `validate_shared_weight_broadcast` is deleted. All three sub-configs
are now copies of the same object, so their types can't differ.
- SFT assigns the whole object to inference instead of mutating
`inference.weight_broadcast.type`.
- All three transports are kept.
Net: 82 lines added, 223 removed. Three class hierarchies, the
field-copy mapping and one validator are gone. No new abstractions.
## Breaking changes (all minor)
- `[weight_broadcast]` in `rl` now accepts `inference_world_size`. Like
before, the value is ignored: rl computes it.
- `[inference.weight_broadcast]` now accepts the transport fields
(`host`, `port`, `timeout`, ...). The inference server ignores them. The
resolved `inference.json` now contains them.
- Standalone `trainer.weight_broadcast.inference_world_size` must now be
`>= 1`. This matches the orchestrator, which already enforced it.
Before, `0` was accepted.
- Import paths: the classes now live in `prime_rl.configs.shared`. They
are no longer in `prime_rl.configs.trainer`, `.orchestrator` or
`.inference`.
## Validation
- Throwaway script (not committed): for every TOML in `configs/` and
`examples/`, parse it with every config class, plus sibling-base
overlays such as `glm-5.3/swe.toml @ swe-llmd.toml`. Dump the resolved
config on base and on this branch, then diff. Also covered: CLI cases
for rl/trainer/orchestrator/inference/sft with nccl/nixl/filesystem and
custom host/port/timeout/session_id. The only differences are the
additive or tightened cases listed under breaking changes. The trainer
and orchestrator `weight_broadcast` values are identical everywhere,
including glm-5.3 `swe.toml`, `swe.toml@swe-llmd.toml` and
nemotron-3-super.
- `rl --dry-run` / `sft --dry-run` on base vs branch for glm-5.3 swe,
glm-5.3 swe+llmd, nemotron-3-super swe, minimax-m2.5 swe, glm-4.5-air
swe+2-node, reverse-text (nccl and nixl), reverse-text sft and dynamo.
After normalizing paths, `trainer.json`, `orchestrator.json`, env
configs and `rl.sbatch` are byte-identical. `inference.json` only gains
the extra `weight_broadcast` fields.
- `pytest tests/unit -m "not gpu"`: 683 passed. 1 failure
(`test_cpu_adam`) also fails on main.
- `ruff check` and `ruff format --check` pass.
- No GPU on this machine, so GPU and integration tests (actual NCCL/NIXL
transfers) were not run.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches how RL/SFT wire trainer–orchestrator–inference weight transfer
(NCCL/NIXL sizing and config propagation); behavior is intended to match
prior dry-runs but import-path and validation changes could break custom
configs.
>
> **Overview**
> **Consolidates trainer-to-inference weight broadcast settings** into a
single discriminated union (`filesystem` / `nccl` / `nixl`) in
`prime_rl.configs.shared`, removing parallel class hierarchies that
lived under trainer, orchestrator, RL `Shared*`, and manual per-field
copying.
>
> `RLConfig.auto_setup_weight_broadcast` now **`model_copy()`**s the
shared `[weight_broadcast]` onto trainer and orchestrator (auto-filling
`inference_world_size` for in-memory transports) and sets inference to a
type-only config. **SFT** does the same for inference instead of
mutating `.type` alone. **`validate_shared_weight_broadcast`** is
dropped because all components share one schema.
>
> Weight transport code (`transports/weights/*`, online eval) **imports
the shared types** instead of `configs.trainer`. Minor behavior/doc
shifts: RL rejects user-set `inference_world_size`, standalone trainer
enforces `inference_world_size >= 1`, and resolved `inference.json` may
include full broadcast fields the server ignores.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
937fc8a870e5559f40bc390653dd6c45dbd912d5. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Adds `length_weighted_baseline: bool = False` to `GRPOAlgoConfig`.
When enabled, the GRPO group baseline is the token-length-weighted mean
reward `b = sum_i(L_i * r_i) / sum_i(L_i)` instead of the plain mean.
`L_i` is the number of trainable (mask-True, policy-sampled) tokens of
rollout `i`, summed across all turns. Advantage is `r_i - b`. The
baseline is applied after the length penalty, same as the plain mean.
There is no fallback for a group with zero trainable tokens: then every
trace has `L_i = 0`, so `assign_advantages` writes no tokens, and no
metric, annotation or sample reads the (NaN) baseline.
Why: with token-level loss normalization, long rollouts carry more
gradient weight. A length-weighted baseline makes the per-token
advantage zero-mean across the group's tokens instead of across
rollouts.
- `routing.py`: pulls the trainable-node selection out of
`assign_advantages` into `trainable_nodes(trace)`, so `L_i` counts
exactly the tokens that receive the advantage.
- `echo` inherits the option because it subclasses GRPO.
- With the flag off, results are bit-identical to today: same `rewards -
rewards.mean()` computation.
- No breaking changes.
## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 301 passed. Includes the new
`test_grpo_length_weighted_baseline`, which covers the flag alone and
the flag combined with the length penalty (ordering).
- `ruff check .` and `ruff format --check .`: clean.
- GPU and integration tests were not run (no GPU on this machine).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Opt-in GRPO baseline change with default off; touches advantage math
only on the orchestrator scoring path, with targeted unit tests.
>
> **Overview**
> Adds an opt-in **`length_weighted_baseline`** flag on GRPO-family
config (`GRPOAlgoConfig`, inherited by `echo`). When enabled, the group
baseline becomes the trainable-token-weighted mean of
(length-penalty-)shaped rewards instead of a plain rollout mean, so
advantages are **zero-mean per token** rather than per rollout—aligned
with token-normalized RL loss when long completions dominate gradient
mass.
>
> **`GRPOAlgorithm.score_group`** now computes `shaped_rewards` first,
then either `mean(shaped_rewards)` or `sum(L_i * r_i) / sum(L_i)` with
`L_i` counting mask-True policy tokens across turns.
**`routing.trainable_nodes`** is extracted so `L_i` matches the tokens
that receive broadcast advantages via `assign_advantages`. Default
`false` preserves the existing centered-mean behavior.
>
> Docs describe the math and ordering (after length penalty). Unit tests
cover the flag alone and combined with linear length penalty.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8f8d988d4957d02e61f28dfe0e46b1af3fefab7d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Unifies the local launch-and-monitor code in `rl_local` and `sft_local`.
Before this PR, both repeated the same machinery: Popen → log file →
monitor thread → error queue → SIGTERM/Ctrl-C/exception cleanup, GPU
partitioning from `CUDA_VISIBLE_DEVICES`, and the trainer torchrun
command. Each copy had small differences, which made the two launchers
drift.
## Design
`utils/process.py` already holds the launcher primitives
(`monitor_process`, `cleanup_processes`, env defaults). This PR adds
three small pieces there:
- `ProcessGroup`: a context manager. `start(name, cmd, env, log_path)`
starts a process with its log file and monitor thread. `wait(*names)`
blocks until the named processes exit and fails fast (exit 1) on the
first error from any process. SIGTERM, Ctrl-C, exceptions and normal
exit all clean up every process. The messages and ordering are the same
as the old inline code.
- `partition_gpus(num_infer, num_train)`: splits the physical GPUs into
inference GPUs followed by trainer GPUs, and raises the same
`ValueError` as before.
- `torchrun_cmd(module, config_path, nproc, log_dir, ranks_filter)`: the
shared single-node trainer command.
`rl_local` and `sft_local` keep their own commands and env dicts
unchanged. Only the plumbing moves. Net: −126 lines.
`inference.py` is not changed. Its only subprocess is the vllm-router.
The router inherits stdout (no log file), and its watcher SIGTERMs the
inference process itself. That does not fit the start/monitor/fail-fast
pattern, and forcing it in would change behavior. `eval.py` env servers
are also unmonitored on purpose, so they stay as they are. SLURM
rendering is not touched.
## Behavior
Behavior is the same: commands, env vars (including key order), log
paths, start order, kill order, exit codes and info/warning/error logs.
Two small differences:
- rl `--log-level debug` "command" lines now read `Inference command:
...` / `Train env server <name> command: ...` / `Trainer command: ...`
instead of `... start command: ...`.
- The rl wait loop is now the sft one: it checks errors before it checks
completion. Before, if the trainer failed *after* the orchestrator had
already exited, rl logged `Trainer failed with exit code N` from a
post-loop check. Now it logs `Error: Trainer failed with exit code N` /
`Terminating all processes...`. The exit code (1) and cleanup are the
same. The post-loop returncode checks could no longer be reached, so
they are removed. Side effect: if inference or an env server crashes in
the last ~1s, when the trainer and orchestrator also finish, the run now
fails instead of being ignored.
No config, metric, or checkpoint changes. No breaking changes.
## Validation
- I ran a throwaway (uncommitted) script against `rl_local`/`sft_local`,
once on `origin/main` and once on this branch, and diffed the results.
It fakes `subprocess.Popen` and `cleanup_process`, pins the free port,
uuid and `CUDA_VISIBLE_DEVICES=3,5,6,7`, and records each launch's exact
cmd, env delta, log path, kill sequence, exit code and logs. Configs:
reverse-text `rl.toml`, `configs/debug/multi-env/rl.toml`, reverse-text
`sft.toml` (online eval + inference), `configs/debug/fake/sft.toml`.
Scenarios: success;
trainer/orchestrator/inference/env-server/online-eval failure; trainer
failing after the orchestrator exits; SIGTERM; SIGINT; too many GPUs
requested. All records and exit codes were identical. The only log
differences are the two listed above.
- `pytest tests/unit -m "not gpu"`: 683 passed, 1 failed. The failure is
`test_cpu_adam.py::test_native_cpu_adamw_matches_fused_torch_and_preserves_gradients`,
which also fails on `origin/main` on this machine.
- `ruff check .` and `ruff format --check .` pass.
- No GPU on this machine, so I did not run any real launch or
integration test.
## Reviewer GPU checks (not run here)
- rl reverse-text e2e exits 0, and inference/env servers have no late
non-zero exits.
- SIGTERM and Ctrl-C mid-run leave no vLLM or torchrun workers.
- Trainer and inference logs are unchanged.
- sft with online eval waits for the eval to drain before it exits.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches core multi-process launcher lifecycle (spawn, monitor,
teardown) for training runs; behavior is mostly preserved but wait/error
ordering changes can alter exit outcomes at run end.
>
> **Overview**
> **Refactors local RL and SFT launchers** so they no longer duplicate
subprocess orchestration; shared behavior lives in
`prime_rl.utils.process`.
>
> Adds **`ProcessGroup`** (context manager with `start` / `wait`),
**`partition_gpus`**, and **`torchrun_cmd`**. Both `rl` and `sft`
entrypoints now start inference, env servers, orchestrator/online-eval,
and trainer through `ProcessGroup` instead of inline `Popen`, monitor
threads, error queues, and hand-rolled SIGTERM/Ctrl-C cleanup.
>
> Commands, env vars, log paths, and start order are intended to stay
the same. **Minor differences:** debug log lines drop the `"start"`
prefix on command logs; RL’s wait loop now checks the error queue before
completion (aligned with SFT), so late failures from non-terminal
processes (e.g. inference/env server in the last second) can fail the
run where RL previously might have exited successfully.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fb27b22cf76aa28b094caedb07a646b7d5db7c7e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Pure moves + import updates. No logic change.
**Design / target structure**
- `trainer/batch.py` -> `orchestrator/batch.py`. Only
`orchestrator/packing.py` uses it. Nothing in `trainer/` imports it. Its
test already lives at `tests/unit/orchestrator/test_batch.py`.
- `trainer/models/deepseek_v4/eager_reference.py` ->
`tests/unit/train/models/deepseek_v4_eager_reference.py`. Only the DSv4
tests import it. Its docstring says nothing in production calls it.
- `trainer/conversion_utils.py` (one 10-line function) is inlined into
`transports/weights/nccl.py`, its only user.
**Left as is (not equivalent)**
- FLOPs models: `orchestrator/batch.py` (forward-cost coefficients for
bin balancing) and `trainer/perf.py` `_get_num_flop_per_token` (train
FLOPs for MFU, LoRA-aware) give different numbers. For example, o_proj
is `2*h*h` vs `h*heads*head_dim`, router params are counted only in
perf, and attention uses `head_dim` vs `h/heads`. On Qwen3-0.6B/1.7B,
Qwen3-VL-4B, Qwen3.5-2B and debug-moe they differ by 4-11%, so merging
them would change either the packing or the MFU metric.
- `list_shards` duplicate in `tools/convert_fp8_to_bf16.py` and
`tools/convert_bf16_to_fp8.py`: kept so `convert_fp8_to_bf16.py` stays
standalone (torch + safetensors only, no `prime_rl` import).
- Blockwise FP8 dequant: the tools version takes the block size from
`quantization_config` and handles shapes that are not multiples of the
block (via ceil + slice). The DSv4 version infers the block size from
the shape ratio, needs exact divisibility, and also handles MXFP4. They
are not interchangeable.
- `tools/convert_dcp_to_fp8.py` sibling imports: these already work from
the repo root and from any cwd. Python puts the script's directory on
`sys.path`, and the same holds under `torchrun`. I checked `--help` from
the repo root and from `/tmp`. No change needed.
**Breaking changes**
- Import paths: `prime_rl.trainer.batch` ->
`prime_rl.orchestrator.batch`. `prime_rl.trainer.conversion_utils` and
`prime_rl.trainer.models.deepseek_v4.eager_reference` are removed from
the package.
**Validation**
- `pytest tests/unit/orchestrator/test_batch.py
tests/unit/train/models/test_deepseek_v4_cpu.py
tests/unit/train/models/test_deepseek_v4.py
tests/unit/train/models/test_deepseek_v4_kernels.py
tests/unit/transports tests/unit/train/test_perf.py -m "not gpu"`: 31
passed, 97 deselected. Both DSv4 test modules import fine. No GPU on
this machine, so the GPU DSv4 tests and integration tests were not run.
- `ruff check .` and `ruff format --check .` both pass.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Import-path-only refactor with inlined helper code; no training,
packing, or NCCL broadcast logic changes, aside from downstream breakage
if anything still imports the removed modules.
>
> **Overview**
> This PR reorganizes modules so orchestrator-only, test-only, and
single-use code no longer lives under `trainer/`. **Batch packing**
moves from `prime_rl.trainer.batch` to `prime_rl.orchestrator.batch`,
with `packing.py` and orchestrator unit tests updated to the new import
path.
>
> **DeepSeek V4 eager reference** implementations move out of the
production package into
`tests/unit/train/models/deepseek_v4_eager_reference.py`; DSv4 GPU tests
import from there instead of
`prime_rl.trainer.models.deepseek_v4.eager_reference`.
>
> **Layer counting for NCCL weight broadcast** drops the standalone
`trainer/conversion_utils.py` module: `get_max_layer_num` is defined
inline in `transports/weights/nccl.py`, its only caller. Behavior is
unchanged; callers must switch imports for batch and remove use of the
deleted trainer modules.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9287ae8ce22ba8731b80ebc1634ee0d5bbb25ea3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 13:42:11 -07:00
217 changed files with 3745 additions and 6358 deletions
RUN /app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'\
@@ -35,8 +35,8 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
2. Performant: built to train 1T+ MoE models on 1000+ GPUs with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) for training and [vLLM](https://github.com/vllm-project/vllm) for inference, with FP8 inference, PD disaggregation, EP and CP parallelism, and more.
3. Native integration with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments through the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars), including built-in support for SWE and agentic environments.
4. End-to-end post-training: SFT, RL training, and evals.
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
5. Multi-node deployment with Slurm support.
6. Multimodal support for VLMs such as Qwen3.5.
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.3/).
@@ -44,16 +44,14 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
## Models support
The trainer works with both Hugging Face and Prime custom `ModelForCausalLM` out of the box. For selected families (especially large MoE) we also ship highly optimized training code under `src/prime_rl/trainer/models/`, including expert parallelism (EP) for MoE layers and context parallelism (CP) for long sequences (see the table), and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels).
With `[model] impl = "auto"` (the default), the trainer selects that custom stack when the Hugging Face config type is registered.
The trainer runs the PrimeRL model implementations under `src/prime_rl/trainer/models/`: dense Llama, Qwen3 and Qwen3.5, plus the families in the table below, with expert parallelism (EP) for MoE layers, context parallelism (CP) for long sequences, and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels). Other architectures fail at trainer setup.
@@ -178,12 +176,12 @@ Follow this guide to learn the basics of prime-rl. You can train your own models
2. [**Wordle**](examples/basic/wordle/README.md): Train `Qwen3-1.7B` to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
3. [**Alphabet Sort**](examples/basic/alphabet-sort/README.md): Train `Qwen3-4B-Instruct-2507` to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
4. [**Wiki Search**](examples/basic/wiki-search/README.md): Train `Qwen3-4B-Instruct-2507` to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
5. [**Hendrycks Sanity**](examples/basic/hendrycks-sanity/README.md): Run a sanity check experiment on `DeepSeek-R1-Distill-Qwen-1.5B` using a filtered subset of MATH where the model already partially solves 20-80% of problems. Useful for algorithm ablations.
5. [**Hendrycks Sanity**](examples/basic/hendrycks-sanity/README.md): Run a sanity check experiment on `Qwen3-1.7B` using a subset of MATH filtered to problems that `DeepSeek-R1-Distill-Qwen-1.5B` partially solves (20-80%). Useful for algorithm ablations.
### Advanced Training: 32 - 2048 GPUs:
Follow this guide to train large models on hard reasoning and agentic tasks.
These guides are designed to be run from a Slurm cluster but can also be adapted to k8s deployments.
These guides are designed to be run from a Slurm cluster.
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.
@@ -16,19 +16,14 @@ This page covers the specialized features layered on top of the core training st
## Custom Modeling
`prime-rl` ships custom optimized model implementations for several MoE families. With `model.impl = "auto"` (default) the trainer picks the custom path when the HF config type is registered, falling back to plain HF otherwise. To force one:
```toml
[trainer.model]
impl="custom"# or "hf" to force the HF path
```
The trainer only runs `prime-rl`'s own model implementations, selected from the HF config type. Besides dense Llama, Qwen3 and Qwen3.5, these cover the families below. Other architectures fail at trainer setup.
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.
@@ -107,7 +100,7 @@ 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`).
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.
### Expert Parallelism Backends
@@ -161,7 +154,6 @@ Add `[model.vlm]` and bfloat16 dtypes:
```toml
[model]
name="Qwen/Qwen3.5-4B"
impl="custom"
optimization_dtype="bfloat16"
reduce_dtype="bfloat16"
@@ -195,7 +187,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. 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`).
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`). With LoRA on, the inference server registers the adapter under the model name and serves the base model as `<model>-base`.
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
At runtime, each env's `TrainEnv` (`prime_rl.orchestrator.envs`) resolves the `sampling.source` model into the inference pool used for train episodes, and its resolved config builds one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
@@ -157,9 +157,9 @@ Algorithms operate on native verifier artifacts and annotate their message graph
-`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 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.
The pipeline calls `score_group` directly and `score_episode` through `finalize_episode`, which skips episodes with no trainable sampled tokens. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.train.algo.advantage`.
The algorithm config states which loss component its action tokens feed (`action_loss_type`, a class variable on each config class). 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). Writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.train.algo.advantage`.
## Async / Off-Policy Training
@@ -188,11 +188,11 @@ $$
-`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.
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 — for `rl`, the sum of its weights, which is the same count while weights are 0/1 — 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.
### IPO Loss
The default RL loss is Importance Policy Optimization (IPO). It is an importance-weighted policy-gradient term. A symmetric trust region removes tokens whose absolute probability change exceeds $\epsilon$:
The default RL loss is INTELLECT Policy Optimization (IPO). It is an importance-weighted policy-gradient term. A symmetric trust region removes tokens whose absolute probability change exceeds $\epsilon$:
$$
\mathcal{L}(\theta) = -\frac{1}{N}\sum_t
@@ -211,6 +211,8 @@ The knobs under `[trainer.loss]` are:
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]`.
See [IPO](ipo.md) for why IPO masks by probability instead of ratio, and the GLM-4.5-Air ablation against IcePop behind `eps = 0.3`.
### IcePop Loss
IcePop is an opt-in RL loss that drops tokens whose trainer-to-inference
@@ -325,6 +327,16 @@ type = "grpo"
type="linear"
```
A **length-weighted baseline** (`length_weighted_baseline = true` on the `grpo`-family algorithms) replaces the plain group mean with $b = \sum_i L_i s_i / \sum_i L_i$, where $L_i$ is the number of trainable (policy-sampled, loss-masked) tokens of rollout $i$, summed across all its turns; it applies after the length penalty. With token-level loss normalization, long rollouts carry more gradient weight, so this baseline makes the per-token advantage zero-mean across the group's tokens rather than across rollouts.
**Prompt-mean loss aggregation** (`loss_aggregation = "prompt"` on `grpo` and `echo`; default `"token"`). By default every `rl` token in the batch weighs the same, so prompts whose groups produce long trajectories dominate the gradient. With `"prompt"`, the loss is MiMo-V2.6's prompt-mean (Eq. 1): the mean over prompt groups $q$ of $\frac{1}{T_q}\sum_{t \in q} \mathcal{L}_{rl,t}$, where $T_q$ is the group's total trainable tokens. MiMo uses it to keep response length from growing too fast. `score_group` gives each trainable token of the group the `rl` weight $1/T_q$, so each group's weights sum to 1 and $N_{rl}$ (the summed weights) is the number of groups in the step. Zero-advantage tokens are still dropped from the `rl` component, so a group with a zero-advantage rollout keeps less than its full weight of 1. All envs with an `rl` loss in a run must use the same `loss_aggregation`.
```toml
[orchestrator.train.algo]
type="grpo"
loss_aggregation="prompt"
```
### 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.
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — holds defaults for its sources. Every field that a group and its sources both have is a default: `env`, `sampling`, `select` and `group_size`, plus `algo` on the train group and `interval` on the eval groups of a training run. Each source inherits the fields that its group sets. One rule applies to all of them: nested blocks merge key by key, a source's own values win, and a block whose `type` (e.g. of `algo`) differs from the group's is the source's alone.
Sampling parameters use Verifiers' shared normalization: `max_tokens` and `max_completion_tokens` name the same limit, and `extra_body` parameters merge like top-level parameters. Agent overrides apply after source defaults; an explicit null clears an inherited parameter. Resolved sampling is recorded on each trace.
For live-policy training, set distribution parameters (`temperature`, `top_p`, `top_k`) on the source's `sampling` block. Every agent in that source, including non-trainable roles, may override only `max_tokens`, `reasoning_effort`, and `chat_template_kwargs`. These rules are checked when loading the config; evaluation and frozen-model sources allow general agent sampling overrides.
```toml
[orchestrator.train]
group_size=16
@@ -246,7 +250,7 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
- [**Alphabet Sort**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/alphabet-sort) — `Qwen3-4B-Instruct-2507` sorting names alphabetically. Multi-turn LoRA RL without SFT warmup; one H100.
- [**Wiki Search**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/wiki-search) — `Qwen3-4B-Instruct-2507` answering trivia by searching a Wikipedia corpus. Multi-turn with tool use.
- [**Hendrycks Sanity**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/hendrycks-sanity) — `DeepSeek-R1-Distill-Qwen-1.5B` on a filtered MATH subset. Useful for algorithm ablations.
- [**Hendrycks Sanity**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/hendrycks-sanity) — `Qwen3-1.7B` on a filtered MATH subset. Useful for algorithm ablations.
@@ -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_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) | relevant changes in non-draft PRs; full suite on push to `main` or manual dispatch | `pytest tests/unit -m gpu`, plus RL/SFT integration scenarios (`reverse_text`, `reverse_text_sft`,`reverse_text_sft_lora`,`reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `alphabet_sort`) with `max-parallel: 5`; separate hosted `gsm8k_eval` job | self-hosted `prime-rl-2xh200` k8s scale set (2xH200); `ubuntu-latest` for test selection and hosted eval |
| [`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.
@@ -117,7 +117,6 @@ Then run the full RL stack on reverse-text:
```bash
uv run rl @ configs/ci/integration/reverse-text-moe/start.toml \
@@ -25,6 +25,8 @@ uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Infe
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
```
The default endpoint comes from `PRIME_INFERENCE_URL`, then the Prime CLI's `inference_url`, then the standard Prime Inference URL. An explicit `client.base_url` wins. API keys and environment-backed headers are resolved when clients are built; Prime CLI credential and team fallbacks apply only to Prime Inference hosts, including for a separate admin URL.
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
```bash
@@ -80,7 +82,7 @@ Every source's env server is spawned by the eval process unless the source sets
## 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.
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: saved episodes with `episode.ok` 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. Failed episodes and the ones the interruption cut off run again. Saved records that fail schema validation stop the resume before the current stream is archived.
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`select` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
A landed episode counts toward a selected task in the same source when their content hashes (`task.hash`) match. A task whose content changes runs again even if its public `task.key` stays the same.`select` and `group_size` may change between launches: each selected occurrence keeps up to `group_size` matching episodes, and only its missing rollouts run. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Each selected occurrence owns a separate group containing its restored and new rollouts, even when the same task is selected more than once, so pass@k and the dashboard see one group per selected occurrence. Use `--clean` to start over instead.
@@ -287,7 +287,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Standard deployments use the V2 model runner. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Capture runs on vLLM's V2 model runner (forced automatically). Router replay is not supported with disaggregated P/D: vLLM does not capture routedexperts across NIXL KV transfer.
```toml
[trainer]
@@ -311,8 +311,8 @@ 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.
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`. 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.
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run together with router replay. 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`.
IPO (INTELLECT Policy Optimization) is the default RL loss in prime-rl. This page explains why it masks tokens by probability instead of ratio, and shows the ablation behind the default `eps = 0.3`. The loss definition and its knobs are in [Algorithms § IPO Loss](algorithms.md#ipo-loss).
## Table of Contents
- [Masking by Probability, Not Ratio](#masking-by-probability-not-ratio)
- [Ablation: IPO vs IcePop](#ablation-ipo-vs-icepop)
- [Choosing `eps`](#choosing-eps)
- [Reproducing](#reproducing)
## Masking by Probability, Not Ratio
In async RL, the trainer and the inference engine never agree exactly on a token's probability. The usual fix keeps importance sampling but drops the tokens where the two disagree too much. [IcePop](algorithms.md#icepop-loss) measures disagreement as a ratio and masks a token when $\pi_{\text{train}}/\pi_{\text{infer}}$ falls outside a fixed band $[\alpha, \beta]$. IPO masks a token when its absolute probability moved too much:
is_masked=probs_diff.abs()>eps# double-sided, independent of the advantage sign
```
A ratio treats every token the same regardless of its probability, which behaves badly at both ends:
- A rare token going from 0.01 to 0.06 has a ratio of 6×, so IcePop masks it, although it moved only 0.05 of probability mass.
- A likely token going from 0.90 to 0.20 has a ratio of 0.22, so IcePop keeps it, although it moved 0.70 of probability mass.
Treat the vocabulary as two outcomes, *this token* and *everything else*. Then $|\pi_{\text{train}} - \pi_{\text{infer}}|$ is the total-variation distance between the two engines on that split. The mask is double-sided and has one knob. [KPop](https://ringtech.notion.site/kpop) reached the same diagnosis independently and uses a binary KL instead.
## Ablation: IPO vs IcePop
GLM-4.5-Air on agentic SWE RL, with every arm on the same recipe and only `[trainer.loss]` changing:
| | |
|---|---|
| Model | `zai-org/GLM-4.5-Air` (100B MoE), BF16 training and inference |
| Task | `scaleswe` with the `bash` harness, taskset reward; eval on SWE-Bench Verified |
| Batch | 256 rollouts (16 groups of 16) at 131k context |
| Off-policy | up to 64 steps (`max_off_policy_steps = 64`), no router replay |
| Algorithm | GRPO with a linear length penalty (output tokens, input tokens, and turns at 0.1) |
| Arms | IcePop with $[\alpha, \beta] = [0.2, 5]$; IPO with `eps = 0.2` and `eps = 0.3` |

For the first 1k steps the arms are indistinguishable. IcePop's trainer–inference KL then creeps up and explodes around step 1.2k, more than 20× its baseline, and the solve rate falls from about 0.8 to about 0.3. Both IPO arms keep the mismatch low through the same window and keep training.
IcePop masks very little before it breaks: at steps 678–679 it masked 72 of 2.16M tokens (0.003%). Under a ratio band, the masked fraction stays tiny while the gap widens, so nothing pushes back once drift starts.
## Choosing `eps`
The first IPO default was `eps = 0.1`. On the run above it masked about 2% of tokens, and by step 1k its entropy had collapsed. To pick a new value without a sweep of full runs, we replayed the trainer and inference probabilities of 1.8M sampled tokens and measured what each `eps` would have masked:

The IPO band has the same width in probability everywhere. The IcePop cone is very narrow near zero, where it masks rare tokens that barely moved, and very wide near one, where it keeps likely tokens that lost most of their mass. `eps = 0.3` masks only the tail and targets the tokens IcePop lets through. Both 0.2 and 0.3 were stable in full runs; 0.3 kept the highest entropy with the lowest mismatch KL, so it is the default.
## Reproducing
The configs are in [`examples/advanced/glm-4.5-air/ipo-ablation/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air/ipo-ablation): a shared `base.toml` and one overlay per loss. See the [GLM-4.5-Air README](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) for cluster setup.
```bash
uv run rl @ examples/advanced/glm-4.5-air/ipo-ablation/base.toml @ examples/advanced/glm-4.5-air/ipo-ablation/ipo.toml
uv run rl @ examples/advanced/glm-4.5-air/ipo-ablation/base.toml @ examples/advanced/glm-4.5-air/ipo-ablation/ipo.toml --trainer.loss.eps 0.2
uv run rl @ examples/advanced/glm-4.5-air/ipo-ablation/base.toml @ examples/advanced/glm-4.5-air/ipo-ablation/icepop.toml
```
Compare `mismatch_kl/all/mean` and the training solve rate across arms.
@@ -86,19 +87,16 @@ 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 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. |
| `trainer.model.offload` | CPU offloading: `optimizer` (default) offloads optimizer state between steps; `full` offloads gradients, FP32 masters, and optimizer state and runs the optimizer (AdamW or SignSGD) on CPU during backward; `none` disables offloading. |
### Expert Parallelism
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput.
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is at most 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
`ep` defaults to `"auto"`. At startup it loads the model config to check whether the model is MoE. For MoE models it resolves to `min(world_size // dp_replicate, 8)`: the FSDP island size, capped at 8. For non-MoE models it resolves to 1 (no-op).`"auto"` does not look at `num_experts` or `cp`; the resolved degree must still be a multiple of `cp` and divide `num_experts`, so set it explicitly when it does not. Set `ep` to an explicit integer to override:
```toml
[trainer.model]
impl="custom"
ep=8# explicit EP degree; must divide num_experts
[trainer.model.moe.dispatch]
@@ -116,7 +114,6 @@ CP shards a single sequence across multiple GPUs along the token dimension — f
```toml
[trainer.model]
impl="custom"
attn="auto"# auto = FA3 on Hopper, FA4 on datacenter Blackwell, FA2 otherwise; or flash_attention_2/3/4
cp=2# CP degree
cp_style="ulysses"# "ring"
@@ -145,19 +142,19 @@ Activation offloading still applies to tensors saved by autograd, but tensors re
### Optimizer Offloading
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).
State-only optimizer offload is enabled by default (`model.offload = "optimizer"`). For full offload, set `model.offload = "full"`; 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
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization. It defaults to `1024` for RL training:
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization. It defaults to `8192` for RL training:
```toml
[trainer.model]
fused_lm_head_token_chunk_size=1024# default
fused_lm_head_token_chunk_size=8192# default
# fused_lm_head_token_chunk_size = "disabled" # vanilla LM head
```
Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. SFT training silently disables this (not supported yet). Only available with `model.impl = "custom"`.
Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. SFT training silently disables this (not supported yet).
## Memory-Tight Recipe
@@ -165,7 +162,6 @@ The kitchen-sink config for fitting large MoE on limited GPUs at acceptable thro
```toml
[trainer.model]
impl="custom"
ep=8
cp=2
@@ -176,7 +172,28 @@ freq = 1
max_inflight_activations=1
```
The defaults already cover: fused LM head chunking (`1024`), `torch.compile` (fullgraph=False), AC (full mode), AC offloading (`max_inflight_activations=5`), and optimizer CPU offload. Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
The defaults already cover: fused LM head chunking (`8192`), `torch.compile` (fullgraph=False), AC (full mode), AC offloading (`max_inflight_activations=5`), and optimizer CPU offload. Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
## Max Trainer Throughput Recipe
The trainer defaults are tuned for memory, not speed: optimizer CPU offload, AC offloading, and `torch.compile` without `fullgraph` let large models fit on few GPUs, at a throughput cost. When you have enough GPUs to keep the model state and activations on GPU, turn them off:
```toml
[model]
offload="none"# optimizer states stay on GPU
ac_offloading="None"# activations stay on GPU
moe_router_dtype="bfloat16"# fullgraph needs the router inside the block's FSDP unit; an fp32 router is not
[model.compile]
fullgraph=true# compile each block as a single graph
```
Then add nodes instead of CP (`cp = 1`) and run one full-length sequence per GPU (`micro_batch_size = 1`). Keep full AC unless selective AC fits. The SFT default router dtype is already `bfloat16`. RL defaults to an fp32 router, so check that bf16 routing is acceptable for your model before using `fullgraph` in RL.
Examples:
- [`examples/advanced/qwen3-235b-a22b/sft-max-perf.toml`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-235b-a22b): Qwen3-235B-A22B SFT on 4 x 8 B300 at 16k, around 46% MFU.
- [`examples/advanced/glm-5.3/sft/h200/16k-12-node.toml`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3/sft/h200): the same recipe as an overlay for GLM-5.3 SFT on 12 H200 nodes.
## SLURM
@@ -184,6 +201,8 @@ The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras --all-packages` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
Compile and JIT caches are node-local by default: the launcher sets `TRITON_CACHE_DIR=/tmp/triton-<uid>` for every component, and `VLLM_CACHE_ROOT=/tmp/.vllm-cache-<uid>` and `FLASHINFER_WORKSPACE_BASE=/tmp/.flashinfer-cache-<uid>` for inference. Ranks writing one cache on a shared filesystem can crash or hang. Override them in `[env_vars]` or a component's `env_vars`.
### Activation
A SLURM config is usually a thin overlay that adds `[slurm]` (and `[deployment]` for multi-node) on top of a base config. Configs are composed left-to-right via the `@` CLI syntax — see [Configuration § TOML Composition](configuration.md#toml-composition):
@@ -244,7 +263,7 @@ Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transf
@@ -37,7 +37,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-server` per source. |
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
| `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. on their own host) and the launcher expects the server to already run there. |
## RL Trainer
@@ -62,6 +62,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| `orchestrator.train.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.train.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `trainer.model.freeze_moe_router` | Freeze MoE router gates (default `true` for RL, `false` for SFT). Router updates in RL shift the trainer's expert choices away from the ones inference sampled, amplifying the train-inference mismatch, so RL keeps the pretrained router. Set `false` to train it. |
| `[[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). |
@@ -158,6 +159,10 @@ messages = "conversation"
tools="schemas"
```
**Per-message loss selection.** An optional `message_loss_mask` column contains one boolean or integer 0/1 per message. For example, `[0, 0, 0, 1]` on a user/assistant/user/assistant conversation trains only the final assistant turn while retaining the full context. For prompt-completion rows, the mask covers the concatenated prompt and completion messages. Zero excludes a message; one preserves the normal role and renderer loss settings. A missing or null mask leaves those settings unchanged. The renderer applies selection without changing token IDs, including ownership of assistant closing tokens. Invalid mask lengths or entries raise an error.
To read a differently named column, set `data.columns.message_loss_mask = "selection"`.
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column in OpenAI function-calling format. Each row's value can be either a list of dicts or a JSON-encoded string of a list.
Renderer-backed SFT reads template controls from the typed `[renderer]` config in the SFT TOML. For example:
@@ -191,7 +196,7 @@ The same config selects the renderer for RL under `[orchestrator.renderer]`. The
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5.
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) requires `model.impl = "custom"` and only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectories) for the full picture.
@@ -280,6 +285,7 @@ Pulled from the console log and mirrored to W&B.
-`optim/grad_norm` — spikes precede divergence.
-`optim/lr` — LR schedule.
- For MoE: `max_vio/mean`, `max_vio/max` — mean and max over the step's microsteps of the largest load-balancing violation across layers and EP groups, computed from expert token counts summed across each EP group. `routing_confidence/mean` — mean routing confidence.
- For MoE: `expert_load/{cv,max_mean,cold_frac}/{mean,max}` — expert load per layer over the whole step, from token counts summed across all ranks, as the mean and max over MoE layers. `cv` is std/mean of the per-expert token counts, `max_mean` the busiest expert's count over the mean, and `cold_frac` the fraction of experts receiving under 0.1x the mean. A trainable router that drifts shows up as a rising `cv`/`cold_frac` (MiMo-V2.6 §5.4).
@@ -12,6 +12,7 @@ Larger runs on frontier models, one folder per model, each with a launch README
- [`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.
- [`qwen3-235b-a22b/`](advanced/qwen3-235b-a22b/README.md) — SFT max trainer perf: `Qwen3-235B-A22B` on 4 trainer nodes at 16k context, a throughput reference using the max trainer throughput recipe.
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.
The `ipo-ablation/` configs reproduce the IPO vs IcePop loss ablation in [docs/ipo.md](../../../docs/ipo.md).
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`).
@@ -113,5 +113,17 @@ This will start a SFT run with the following configuration:
- The model is `zai-org/GLM-5.3-BF16`
- The data is `PrimeIntellect/INTELLECT-3-SFT-10K` (math split)
- 8 nodes at 131k context: CP 8, EP 8, full activation checkpointing with activation offloading, optimizer state offloaded to CPU
- DSA attention runs on the FlashMLA sparse forward and the cuDNN sparse backward (`model.dsa_backend = "cudnn_flashmla"`)
For a fake-data dry run, append [`fake.toml`](sft/h200/fake.toml) instead. You can use the same dashboard to monitor the SFT run.
### 12 nodes at 16k
For 16k-token samples, append [`16k-12-node.toml`](sft/h200/16k-12-node.toml) after the data overlay:
```bash
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml @ examples/advanced/glm-5.3/sft/h200/16k-12-node.toml
```
On 12 nodes the sharded model state fits in GPU memory without CP or any offloading. Each GPU runs one 16k sequence per step (batch 96), and transformer blocks compile with `fullgraph = true`. Full activation checkpointing stays on; peak memory is about 115 GiB per GPU.
A throughput reference for the SFT trainer on a large MoE: `Qwen/Qwen3-235B-A22B-Thinking-2507` on 4 nodes x 8 B300 at 16k context. It applies the [Max Trainer Throughput Recipe](../../../docs/scaling.md#max-trainer-throughput-recipe): everything on GPU, no offloading, `fullgraph` compile. It runs 20 steps on balanced routing and writes no checkpoint. Use it to check a cluster or a trainer change against a known number, around 46% MFU.
- A Slurm cluster with 4 nodes x 8 B300 and a shared filesystem.
-`HF_TOKEN` exported in the launch shell. The first run downloads the checkpoint and builds the HF -> prime-rl conversion cache, which `dist_timeout_seconds = 14400` covers.
## Launch
```bash
uv run sft @ examples/advanced/qwen3-235b-a22b/sft-max-perf.toml
```
Read `time/step`, `perf/mfu`, `perf/throughput_per_gpu`, and `perf/peak_memory` from `outputs/<run>/monitors/file/metrics.jsonl`, skipping the first few warmup steps.
Variants:
- Real routing: remove `[model.debug]`. Expect it to be noticeably slower, since routing imbalance dominates at this size.
- Other clusters: set `[slurm] partition` and point `HF_HOME` at a shared cache via `[env_vars]`.
This example runs the Hendrycks Sanity Check experiment proposed in [Defeating the Training-Inference Mismatch](https://arxiv.org/abs/2510.26788). The sanity check tests whether an RL algorithm can reliably improve a model on problems it can *already partially solve*. The dataset is filtered from MATH to only include problems where the base model (`DeepSeek-R1-Distill-Qwen-1.5B`) solves 20-80% of the time across 40 rollouts. A reliable algorithm should push training accuracy on this "perfectible" subset above 95%.
This example runs the Hendrycks Sanity Check experiment proposed in [Defeating the Training-Inference Mismatch](https://arxiv.org/abs/2510.26788). The sanity check tests whether an RL algorithm can reliably improve a model on problems it can *already partially solve*. The dataset is filtered from MATH to only include problems that `DeepSeek-R1-Distill-Qwen-1.5B` solves 20-80% of the time across 40 rollouts. A reliable algorithm should push training accuracy on this "perfectible" subset above 95%. This example trains `Qwen3-1.7B` on that subset; the 20-80% band was measured for the distill model, not for `Qwen3-1.7B`.
Because our trainer is asynchronous, we perform only one gradient step per batch (the inference engine generates the next batch while the trainer processes the current one).
Way better! Now we get an **average reward of ~0.8**.
## Kubernetes Deployment
If you're running on Kubernetes, you can deploy this example using the provided Helm chart. The Helm chart automatically configures all components with proper networking and shared storage.
### Step 1: Deploy for SFT Training
The reverse-text example is configured with `autoStart: true` for RL training, but we need to run SFT first. Deploy with autoStart disabled:
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training requires a custom PrimeRL implementation (`impl = "custom"`, `[model.vlm]` set — see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training (`[model.vlm]` set) requires a PrimeRL VLM implementation (see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
@@ -208,6 +201,12 @@ class GRPOAlgoConfig(BaseAlgoConfig):
length_penalty:LengthPenaltyConfig|None=None
"""Linear length penalty subtracted from each reward before the GRPO baseline (see ``LinearLengthPenaltyConfig``): a ``pass_rate``-scaled sum of output-token, input-token, and turns terms, each normalized by the group's own max for that quantity. None disables it."""
length_weighted_baseline:bool=False
"""Use the token-length-weighted group mean reward ``sum_i(L_i * r_i) / sum_i(L_i)`` as the baseline instead of the plain mean, where ``L_i`` is the number of trainable (mask-True, policy-sampled) tokens of rollout ``i`` summed across all its turns."""
"""How the rl loss weights tokens across prompt groups. ``token``: every loss token in the batch weighs the same, so groups with more total tokens dominate the gradient. ``prompt``: prompt-mean (MiMo-V2.6 Eq. 1) — each trainable token of group ``q`` gets rl weight ``1 / T_q`` (``T_q`` = the group's trainable tokens), and the trainer divides the rl loss by the summed weights, i.e. the number of groups. All rl envs of a run must use the same value."""
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. With Kubernetes liveness probes, keep the probe ``timeoutSeconds`` at least this high."""
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. Health checks polling this endpoint should use a timeout at least this high."""
# Valid vLLM max_lora_rank values (`vllm.config.lora.MaxLoRARanks`), excluding 1 so
@@ -29,15 +29,6 @@ class ServerConfig(BaseConfig):
# not depend on vLLM, and importing it costs seconds in every config-parsing process.
"""Wait up to this many seconds for the startup weight directory to appear (the trainer broadcasts the incoming policy — v0 from scratch, the resumed step's version on resume — before the first step). If None, fall back to a default timeout. Raise this for large models on slow shared filesystems."""
keep_last:int|None=Field(None,ge=1)
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
keep_interval:int|None=Field(None,ge=1)
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
"""Optional initial in-flight episodes to start from. Set it when a good value is known to skip the initial ramp; otherwise auto-derive a pessimistic bound at runtime."""
@@ -593,10 +495,10 @@ class OrchestratorConfig(BaseConfig):
"""Role for each policy admin client when collecting P/D inference metrics."""
ckpt:CheckpointConfig|None=None
"""Checkpoint configuration."""
resume:ResumeConfig|None=None
"""Resume the orchestrator from a checkpoint. None starts from scratch; an empty block resumes from the latest checkpoint, ``resume.step`` from that step, ``resume.dir`` from an external checkpoint step directory. Without ``ckpt`` the run loads but saves no new checkpoints."""
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
tasks_per_minute:int|None=Field(None,ge=1)
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
dispatch_per_minute:int|None=Field(None,ge=1)
"""Rate limit on episode dispatch, shared by train and eval: at most this many episodes start per minute. Each episode counts once, so a group of ``group_size`` episodes counts ``group_size`` times. Recommended for sandbox-backed environments to pace provisioning during autoscaling. None disables it."""
batch_size:int|None=Field(None,ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
batch_size:int=Field(128,ge=1)
"""Samples to train on per step."""
constant_trainer_batch_size:bool=True
"""Require each batch to reach its effective sample target."""
token_batch_size:int|None=Field(None,ge=1)
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
concurrency:ConcurrencyConfig=ConcurrencyConfig()
"""Adaptive in-flight concurrency control (``[orchestrator.concurrency]``)."""
@@ -665,6 +564,19 @@ class OrchestratorConfig(BaseConfig):
env_cfg.algo.validate_env(env_cfg.env)
returnself
@model_validator(mode="after")
defvalidate_loss_aggregation(self):
"""The trainer divides the rl loss by the batch's summed rl weights, so token-mean (weight
1pertoken)andprompt-mean(weight1pergroup)envscan't share a batch."""
"""Shared sequence length. Propagates to ``trainer.model.seq_len`` and ``orchestrator.seq_len`` only when those values were not explicitly set; explicit per-component values always win."""
@@ -100,6 +101,9 @@ class SFTColumnsConfig(BaseConfig):
tools:str="tools"
"""Column with the tool schemas in OpenAI function-calling format."""
message_loss_mask:str="message_loss_mask"
"""Optional column of booleans or integer 0/1 flags, one per resolved message (prompt + completion for split rows). Zero excludes a message from loss; one preserves its normal supervision. Missing or null masks leave supervision unchanged."""
"""Per-sample renderer arguments as ``renderer field = dataset column``, e.g. ``reasoning_effort = "effort"``. A row's non-null value overrides the ``[renderer]`` setting; rows and datasets without the column use it unchanged."""
@@ -275,6 +279,20 @@ class SFTConfig(BaseConfig):
self.model.moe_router_dtype="bfloat16"
returnself
@model_validator(mode="after")
defresolve_weight_decay_auto(self):
"""Resolve ``optim.weight_decay='auto'``: SFT keeps the historical 0.01 default — standard L2 regularization for supervised training."""
ifself.optim.weight_decay=="auto":
self.optim.weight_decay=0.01
returnself
@model_validator(mode="after")
defresolve_freeze_moe_router_auto(self):
"""Resolve ``model.freeze_moe_router='auto'``: SFT trains the router."""
ifself.model.freeze_moe_router=="auto":
self.model.freeze_moe_router=False
returnself
@model_validator(mode="after")
defauto_setup_run_identity(self):
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
@@ -308,8 +326,8 @@ class SFTConfig(BaseConfig):
trace_path:Path|None=None
"""Path to write the PyTorch profiler trace to."""
dist_timeout_seconds:int=3600
"""Timeout in seconds for torch distributed ops."""
dist_timeout_seconds:int=900
"""Timeout in seconds for torch distributed ops: a hung collective (e.g. a dead rank) fails the run after this long."""
heartbeat:HeartbeatConfig|None=None
"""BetterStack heartbeat configuration for monitoring training progress."""
@@ -370,13 +388,13 @@ class SFTConfig(BaseConfig):
"""Weight transfer from trainer to inference. ``rl`` copies its ``[weight_broadcast]`` to the trainer and orchestrator."""
classRunConfig(BaseConfig):
@@ -79,8 +123,8 @@ class ResumeConfig(BaseConfig):
classSlurmConfig(BaseConfig):
job_name:str="prime-rl"
"""SLURM job name."""
job_name:str|None=None
"""SLURM job name. Defaults to ``run.name`` for ``rl`` and ``sft``, and to ``inference`` for ``inference``."""
project_dir:Path=Path(".")
"""Path to the project root, used to source .env, activate .venv, and run uv sync."""
@@ -88,8 +132,8 @@ class SlurmConfig(BaseConfig):
template_path:Path|None=None
"""SLURM template file. If None, uses the bundled single-node or multi-node template."""
partition:str="cluster"
"""SLURM partition (#SBATCH --partition)."""
partition:str|None=None
"""SLURM partition (#SBATCH --partition). If None, the job goes to the cluster's default partition."""
nodelist:str|None=None
"""Comma-separated list of specific nodes to run on (#SBATCH --nodelist)."""
@@ -110,7 +154,7 @@ class SlurmConfig(BaseConfig):
"""Start a job-scoped ModelExpress service for NIXL weight transfer."""
cleanup_grace_period:int=Field(3600,ge=0)
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
"""Maximum seconds a multi-node RL job that hit a non-zero exit waits for an in-flight trainer checkpoint to finish before tearing down. Without an in-flight checkpoint (or without ``[ckpt]``) it tears down immediately. Set to 0 to never wait."""
shared_fs:bool=True
"""Whether the project filesystem (including the venv) is shared across nodes (e.g. NFS). When True, a single ``uv sync`` on the batch node suffices. Set to False when the venv is node-local (e.g. ``UV_PROJECT_ENVIRONMENT`` on ``/tmp``) so ``uv sync`` runs on every node via srun."""
@@ -170,28 +214,27 @@ class DynamoConfig(BaseConfig):
"""Dynamo frontend URL used to discover inference workers for RL control."""
classClientConfig(BaseConfig):
classClientConfig(BaseClientConfig):
wait_for_ready_timeout:int=3600
"""Seconds to wait at startup for the inference pool to become ready."""
base_url:str="http://localhost:8000/v1"
"""Base URL for the OpenAI API. For multi-replica deployments, point this at a router in front of the replicas."""
api_key_var:str="VLLM_API_KEY"
"""Environment variable name containing the API key, resolved via ``os.getenv``. Can be any string when the server is not protected by an API key; the same key is used for every URL."""
headers:dict[str,str]={}
"""Static headers sent with every request."""
headers_from_env:dict[str,str]={}
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
skip_model_check:bool=False
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
admin_base_url:list[str]|None=None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in multi-replica or disaggregated P/D deployments where the router must not handle admin traffic."""
classVLLMClientConfig(ClientConfig):
"""Client defaults for the live inference deployment managed by training."""
base_url:str="http://localhost:8000/v1"
api_key_var:str="VLLM_API_KEY"
classPolicyClientConfig(VLLMClientConfig):
"""Client of the policy deployment the orchestrator drives (weight updates, admin plane)."""
dynamo:DynamoConfig|None=None
"""Dynamo RL worker-discovery configuration."""
@@ -228,14 +271,6 @@ class HeartbeatConfig(BaseConfig):
ratelimit.Sizeitwellunderthemonitor's period."""
classMetricsServerConfig(BaseConfig):
port:int=Field(8000,ge=1,le=65535)
"""Port to expose metrics and health endpoints on."""
@@ -41,41 +42,13 @@ class ActivationCheckpointConfig(BaseConfig):
classActivationOffloadingConfig(BaseConfig):
pin_memory:bool=True
"""Pin offloaded activations to CPU memory."""
"""Offload tensors saved for backward to pinned CPU memory during the forward pass."""
max_inflight_activations:int=Field(5,ge=1)
"""Max activations kept in flight while offloading. More activations smooth overlap at the cost of GPU memory."""
"""Max activations kept on GPU while their offload copies are in flight on the side stream. Higher values give more copy/compute overlap at the cost of GPU memory."""
@@ -94,14 +67,6 @@ class FusionsConfig(BaseConfig):
"""Experimental. Shard fused 2-D weights along dim 1 under FSDP so that weight loading and checkpointing are zero-copy: the checkpoint reads and writes the fused weights and their optimizer state in place, instead of assembling a full copy of every fused weight on each rank first. Requires the hidden size to be divisible by the FSDP shard mesh size."""
classIndexCacheConfig(BaseConfig):
topk_freq:int=Field(1,ge=1)
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
topk_pattern:str|None=None
"""Optional per-layer schedule that overrides ``topk_freq``. ``'F'`` computes fresh indices for that layer; ``'S'`` reuses the previously cached indices. Length should match the number of decoder layers."""
classLoRAConfig(BaseConfig):
rank:int=Field(16,ge=1)
"""Rank of the low-rank decomposition matrices."""
@@ -287,14 +252,8 @@ class ModelConfig(BaseModelConfig):
"""Activation offloading configuration. If None, activation offloading is disabled."""
fsdp_cpu_offload:bool=False
"""Enable FSDP CPU offloading for parameters, gradients, and optimizer states. Uses pinned memory for efficient CPU↔GPU transfers."""
optim_cpu_offload:bool=True
"""Offload only optimizer states (momentum, variance) to CPU, keeping weights on GPU. Avoids the H2D all-gather overhead of FSDP CPU offload while still saving GPU memory."""
full_offload:OptimizerInBackwardOffload=None
"""Full CPU optimizer offload: FP32 masters, moments, and gradients live in CPU RAM and the optimizer runs on CPU, overlapped with backward. Enable with ``true`` or a ``[model.full_offload]`` section; disabled by default."""
offload:OffloadMode="optimizer"
"""CPU offloading. ``optimizer`` keeps optimizer states (momentum, variance) in CPU RAM and weights on GPU. ``full`` keeps FP32 masters, optimizer states, and accumulated gradients in CPU RAM and runs each optimizer chunk on CPU as soon as its last gradient arrives, overlapped with backward; it supports AdamW and SignSGD only, disables gradient clipping, and rounds each gradient to BF16 once before the FP32 CPU update. ``none`` keeps everything on GPU."""
reshard_after_forward:bool=True
"""Reshard the model after each forward pass."""
@@ -314,9 +273,6 @@ class ModelConfig(BaseModelConfig):
cp_style:Literal["ring","ulysses"]="ring"
"""CP communication style. ``ring`` uses ring-attention all-gather/reduce-scatter (requires custom kernels per attention type). ``ulysses`` uses all-to-all to redistribute Q/K/V from sequence-sharded to head-sharded, runs vanilla attention locally on the full sequence, then all-to-all back — works out-of-the-box with any attention kernel (softmax FA, linear attention, mamba, etc.)."""
impl:Literal["hf","custom","auto"]="auto"
"""Model implementation. ``auto`` selects ``custom`` if supported by the model, otherwise ``hf``."""
"""Compute dtype for MoE router gates. ``float32`` keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. ``auto`` (default) resolves to ``float32`` for RL and ``bfloat16`` for SFT. Router score functions (sigmoid/softmax) run in fp32 regardless. Only affects the custom MoE implementation; a no-op for non-MoE and HF-impl models."""
"""Compute dtype for MoE router gates. ``float32`` keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. ``auto`` (default) resolves to ``float32`` for RL and ``bfloat16`` for SFT. Router score functions (sigmoid/softmax) run in fp32 regardless. A no-op for non-MoE models."""
"""Maximum number of FSDP gradient reduce-scatter input buffers kept in flight. Raising it trades memory (about one layer's gradients per extra buffer) for overlap when reduce-scatters are exposed, e.g. MoE without EP or full activation checkpointing."""
quantization:QuantizationConfig|None=None
index_cache:IndexCacheConfig|None=None
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
dsa_backend:DSABackend="tilelang"
"""Kernels for the DSA sparse MLA attention (``glm_moe_dsa``, e.g. GLM-5). ``tilelang`` runs the TileLang forward and backward. ``cudnn_flashmla`` runs the FlashMLA sparse prefill forward with the cuDNN frontend CuTe-DSL backward; it needs the ``flash-mla`` extra and an SM90 GPU (SM100/SM103 are wired up but untested)."""
freeze_moe_router:bool=False
"""Freeze MoE router parameters during training."""
freeze_moe_router:bool|Literal["auto"]="auto"
"""Freeze MoE router gate parameters. ``auto`` (default): ``True`` for RL, ``False`` for SFT; a no-op on non-MoE models. Frozen routers get no optimizer state, so resuming a checkpoint saved with a frozen router with ``freeze_moe_router=false`` fails on missing DCP keys."""
lora:LoRAConfig|None=None
"""LoRA configuration. If None, LoRA is disabled."""
@@ -343,20 +302,6 @@ class ModelConfig(BaseModelConfig):
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. In SFT the fused head computes the summed cross-entropy and its gradients chunk by chunk, holding one chunk's full-vocab logits at a time."""
@model_validator(mode="after")
deftrust_remote_code_only_with_hf(self):
"""Trust remote code only if the model is from HF."""
ifself.trust_remote_code:
ifself.implnotin("hf","auto"):
raiseValueError("Trust remote code is only supported with the HF implementation or auto mode.")
returnself
@model_validator(mode="after")
defvlm_only_with_custom_impl(self):
ifself.vlmisnotNoneandself.impl!="custom":
raiseValueError("VLM training requires model.impl='custom'")
"""Number of background threads that prepare micro batches ahead of the training loop, analogous to torch DataLoader's ``num_workers`` but with threads instead of processes. 0 prepares them on the main thread."""
classTrainerConfig(BaseConfig):
@@ -753,15 +615,12 @@ class TrainerConfig(BaseConfig):
trace_path:Path|None=None
"""Path to write the PyTorch profiler trace to."""
dist_timeout_seconds:int=3600
"""Timeout in seconds for torch distributed ops."""
dist_timeout_seconds:int=900
"""Timeout in seconds for torch distributed ops: a hung collective (e.g. a dead rank) fails the run after this long."""
heartbeat:HeartbeatConfig|None=None
"""BetterStack heartbeat configuration for monitoring training progress."""
metrics_server:MetricsServerConfig|None=None
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
env_vars:EnvVars={}
"""Extra environment variables for the trainer process(es). Merged on top of the launcher defaults."""
@@ -772,6 +631,20 @@ class TrainerConfig(BaseConfig):
self.model.moe_router_dtype="float32"
returnself
@model_validator(mode="after")
defresolve_weight_decay_auto(self):
"""Resolve ``optim.weight_decay='auto'``: RL optimizes the reward objective, not a fixed dataset — L2 decay toward zero fights it, so default to no weight decay."""
ifself.optim.weight_decay=="auto":
self.optim.weight_decay=0.0
returnself
@model_validator(mode="after")
defresolve_freeze_moe_router_auto(self):
"""Resolve ``model.freeze_moe_router='auto'``: RL keeps the pretrained router."""
"Trainer checkpoint config is specified, but orchestrator checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
)
iforchestrator.ckptandnottrainer.ckpt:
raiseValueError(
"Orchestrator checkpoint config is specified, but trainer checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
f"Trainer checkpoint interval ({trainer.ckpt.interval}) and orchestrator checkpoint interval ({orchestrator.ckpt.interval}) are not the same. Please specify the same checkpoint interval for both."
)
iftrainer.resume!=orchestrator.resume:
raiseValueError(
f"Trainer resume ({trainer.resume}) and orchestrator resume ({orchestrator.resume}) are not the same. Please specify the same resume config for both."
)
defvalidate_shared_model_name(
trainer:TrainerConfig,
orchestrator:OrchestratorConfig,
inference:Optional[InferenceConfig]=None,
)->None:
# Orchestrator must match inference (it queries the inference server)
ifinferenceisnotNone:
ifinference.vllm.model!=orchestrator.model.name:
raiseValueError(
f"Inference model name ({inference.vllm.model}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
"The orchestrator queries the inference server and must use the same model name."
)
return
iftrainer.model.name.startswith("Jackmin108/"):# The TT MoE models will have a different name on the orchestrator
return
iftrainer.model.name!=orchestrator.model.name:
raiseValueError(
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
f"Trainer W&B project ({trainer.monitors.wandb.project}) and orchestrator W&B project ({orchestrator.monitors.wandb.project}) are not the same. Please specify the same W&B project for both."
)
defvalidate_shared_max_steps(
trainer:TrainerConfig,
orchestrator:OrchestratorConfig,
)->None:
iftrainer.max_steps!=orchestrator.max_steps:
raiseValueError(
f"Trainer max steps ({trainer.max_steps}) and orchestrator max steps ({orchestrator.max_steps}) are not the same. Please specify the same max steps for both."
)
defvalidate_shared_seq_len(
trainer:TrainerConfig,
orchestrator:OrchestratorConfig,
)->None:
iftrainer.model.seq_len<orchestrator.seq_len:
raiseValueError(
f"Trainer model seq_len ({trainer.model.seq_len}) must be >= orchestrator seq_len ({orchestrator.seq_len}). "
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
)
defvalidate_shared_tokenizer(
trainer:TrainerConfig,
orchestrator:OrchestratorConfig,
inference:Optional[InferenceConfig]=None,
)->None:
# Validate chat_template is consistent across all components.
# We only check chat_template (not name/trust_remote_code) because those
# are auto-derived from model names which may legitimately differ (e.g.
# when inference uses an FP8 quantized variant of the same model).
f"Trainer weight broadcast type ({trainer.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and trainer/orchestrator weight broadcast type ({trainer.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for all components."
@@ -42,7 +42,7 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
**Sources are one block** — inside a `[[...source]]` entry, write nested sub-configs as dotted keys in the same block (`env.taskset.id = "..."`, `env.agent.harness.id = "..."`), not one subsection header per nested config. Nested arrays of tables (e.g. `[[orchestrator.train.source.env.taskset.task.judges]]`) keep full-path headers — they attach to the preceding `[[...source]]` entry.
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enable_prefix_caching = true`).
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--vllm.max-model-len None`.
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.