## What
`[inference.vllm] quantization` is typed as `Literal["fp8_per_block"]`,
so it is currently impossible to serve with MXFP8. This PR adds
`"mxfp8"`.
## Why
vLLM supports `--quantization mxfp8` as an online shorthand: a BF16/FP16
checkpoint's weights are quantized to MXFP8 at load (E4M3 values with
block-32 E8M0 scales) and activations are quantized dynamically per
forward, for both dense linears and MoE experts. On Blackwell
(SM100/SM103) vLLM auto-selects native W8A8 block-scaled GEMMs
(FlashInfer CuTe-DSL); older GPUs fall back to W8A16 (Marlin). This is
useful for serving BF16 SFT exports on B200/B300 without building an FP8
checkpoint.
## How
The value already passes through verbatim to vLLM's `--quantization`;
the pydantic `Literal` was the only gate. vLLM validates the shorthand
and picks the kernel at startup (`Using <kernel> for MXFP8 GEMM`), so no
further wiring is needed. Unknown shorthands (e.g. `mxfp4`) stay
rejected.
Verified locally: `InferenceConfig(vllm={"quantization": "mxfp8"})`
validates, `ruff check`/`format` pass, and `tests/unit/test_configs.py`
shows no new failures (20 pre-existing failures reproduce on pristine
`origin/main` with this checkout's venv).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Single-type widening in config validation with no runtime wiring
changes; vLLM still validates quantization at server startup.
>
> **Overview**
> Extends **`inference.vllm.quantization`** so configs can set
**`mxfp8`** alongside the existing **`fp8_per_block`** option. That
value already forwards to vLLM’s `--quantization`; the only change is
lifting the Pydantic **`Literal`** gate that previously rejected MXFP8
at parse time.
>
> This enables online MXFP8 serving (quantize BF16/FP16 weights at load,
dynamic activation quant) on supported hardware without a separate FP8
checkpoint—useful for BF16 SFT exports on Blackwell-class GPUs.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
777ad501a85ced1985b1b735b4d633ff2ec2d71d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
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 -->
2026-10-10 18:38:11 +01:00
82 changed files with 770 additions and 490 deletions
@@ -100,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.
@@ -192,7 +192,7 @@ The orchestrator stamps each sample's component membership as per-token weight s
### 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
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,9 +87,7 @@ 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
@@ -143,15 +142,15 @@ 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
```
@@ -173,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
@@ -181,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):
@@ -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`).
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]`.
"""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."""
classConcurrencyConfig(BaseConfig):
"""Adaptive in-flight concurrency control. The orchestrator sizes the
@@ -515,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."""
@@ -122,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."""
@@ -131,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)."""
@@ -153,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."""
@@ -223,9 +224,6 @@ class ClientConfig(BaseClientConfig):
admin_base_url:list[str]|None=None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in multi-replica or disaggregated P/D deployments where the router must not handle admin traffic."""
dynamo:DynamoConfig|None=None
"""Dynamo RL worker-discovery configuration."""
classVLLMClientConfig(ClientConfig):
"""Client defaults for the live inference deployment managed by training."""
@@ -234,6 +232,13 @@ class VLLMClientConfig(ClientConfig):
api_key_var:str="VLLM_API_KEY"
classPolicyClientConfig(VLLMClientConfig):
"""Client of the policy deployment the orchestrator drives (weight updates, admin plane)."""
@@ -42,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."""
@@ -95,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."""
@@ -288,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."""
@@ -324,14 +282,14 @@ class ModelConfig(BaseModelConfig):
"""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
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)."""
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."""
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."""
@@ -358,20 +316,9 @@ class ModelConfig(BaseModelConfig):
@model_validator(mode="after")
defac_offloading_requires_ac(self):
"""Automatically enable activation checkpointing when activation offloading is enabled."""
@@ -612,7 +559,7 @@ class DataLoaderConfig(BaseConfig):
fake:FakeDataLoaderConfig|None=None
"""Use a fake data loader sampling random micro-batches (for debugging)."""
num_workers:int=Field(0,ge=0)
num_workers:int=Field(1,ge=0)
"""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."""
@@ -668,8 +615,8 @@ 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."""
@@ -711,13 +658,13 @@ class TrainerConfig(BaseConfig):
@@ -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`.
# Cross-node teardown is driven by `srun --kill-on-bad-exit=1`, which reaps peer
# tasks only once a task *exits* non-zero. So on a non-zero exit (crash, SIGTERM,
# wall-time) we stay alive for the grace period and signal nothing: this lets an
# in-flight trainer checkpoint on this node finish, and — because the task has
# not exited yet — keeps --kill-on-bad-exit from reaping checkpointing trainers
# on peer nodes. We then propagate the exit code so the allocation tears down. A
# clean (zero) exit cannot trip --kill-on-bad-exit, so we tear down immediately.
# wall-time) we stay alive and signal nothing while the newest trainer checkpoint
# is still being written (no DCP `.metadata` yet), up to the grace period: this lets
# it finish on this node, and — because the task has not exited yet — keeps
# --kill-on-bad-exit from reaping checkpointing trainers on peer nodes. We then
# propagate the exit code so the allocation tears down. A clean (zero) exit cannot
# trip --kill-on-bad-exit, so we tear down immediately.
if [ "$EXIT_CODE" -ne 0 ]; then
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for in-flight checkpoints to flush before teardown"
sleep {{ cleanup_grace_period }}
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for an in-flight trainer checkpoint to finish before teardown"
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.