Compare commits

...
Author SHA1 Message Date
HubertandGitHub 7a630865ca fix(inference): backport vLLM SHM buffer ownership fix (#4031)
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 -->
2026-10-14 02:04:48 +02:00
bbbe9cb1bf fix: release the allocator cache after every checkpoint load (#4053)
Tag and Release / auto-tag-on-main (push) Canceled after 0s
Tag and Release / release-from-auto-tag (push) Canceled after 0s
Tag and Release / resolve-release (push) Canceled after 0s
Tag and Release / publish-release (push) Canceled after 0s
## 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>
2026-10-13 15:49:01 -07:00
6afa65111a chore: release v0.10.0 (#4079)
## 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>
2026-10-13 15:19:05 -07:00
dd72f0f97c fix(sft): FakeDataset variable-length random samples have mismatched lengths (#4048)
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>
2026-10-13 13:01:10 -07:00
4487ef3d7d perf(trainer): make the FSDP reduce-scatter buffer cap configurable and default it to 1 (#3912)
#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.

![per layer, production
shape](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/494252e3020765397c17c29792af76f6e3ca317a/figures/pr-ep8-16k-ac.png)

**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.

![per layer, exposed
shape](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/84c856df0c94b618c35fd10e7238a775a95d8a59/figures/pr-ep2-2k-noac-cap1-vs-cap2.png)

**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>
2026-10-13 11:32:56 -04:00
4b3319f3a0 docs: IPO stands for INTELLECT Policy Optimization (#4052)
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>
2026-10-12 19:41:49 -07:00
82fb5e1943 docs: IPO page with the GLM-4.5-Air ablation against IcePop (#4049)
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>
2026-10-12 19:28:21 -07:00
40e0fcea90 docs(scaling): max-throughput recipe + Qwen3-235B-A22B SFT max trainer perf example (#4046)
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>
2026-10-12 17:19:46 -07:00
7c9d4744cd fix(inference): DeepSeek V4 C128 compressor and attn_sink loading patches (#4040)
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>
2026-10-12 15:02:32 -04:00
faresobeidandGitHub 52455b41fc chore(trainer)!: remove ac_offloading.pin_memory (#3972) 2026-10-12 17:17:53 +01:00
4f4d7e4402 revert(trainer): compile around the checkpoint again for MoE blocks with an fp32 router (#4037)
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>
2026-10-12 09:56:19 -04:00
faresobeidandGitHub 1e5318108d feat(trainer): 900 s collective timeout, flight recorder dumps, master-only waits off NCCL (#4019)
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`.
2026-10-11 20:07:56 +01:00
faresobeidandGitHub 3309613436 fix(orchestrator): no checkpoint and a non-zero exit after a crash (#4018)
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 -->
2026-10-11 19:20:22 +01:00
faresobeidandGitHub 8793c37118 perf(trainer): default RL data.num_workers to 1 (#3976)
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 -->
2026-10-11 18:57:20 +01:00
faresobeidandGitHub ae28fb70c5 fix(slurm): portable defaults for partition and job_name (#3973) 2026-10-11 17:21:58 +01:00
faresobeidandGitHub 2ff7f53d47 fix(trainer): log the RL loss correctly under context parallelism (#4005) 2026-10-11 17:21:38 +01:00
faresobeidandGitHub c13a7ec75b fix(trainer): model.ac = None disables activation checkpointing (#3975) 2026-10-11 17:18:59 +01:00
faresobeidandGitHub ee058677f2 fix(launch): node-local vLLM and FlashInfer caches by default (#3981)
## 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 -->
2026-10-11 13:31:16 +01:00
53 changed files with 601 additions and 100 deletions
@@ -6,9 +6,6 @@
#
# Note: on 4 8xH200 nodes, this config is near the memory limit, using ~94%+ GPU memory.
#
# `dist_timeout_seconds = 14400` is needed on any run that has to build the HF -> prime-rl
# conversion cache, which takes far longer than the 3600s default.
#
# To buy memory back for quicker testing on fewer nodes, set `offload = "full"` under `[model]`,
# which keeps the fp32 masters, moments and gradients in CPU RAM and disables gradient clipping;
# the lighter `offload = "optimizer"` is already the default here.
@@ -17,7 +14,6 @@
# checkpoint (fp32 master weights plus two fp32 AdamW moments) is ~3 TiB. Add one with
# `ckpt.output_dir` pointed at a volume that can hold it if you need the trained weights.
dist_timeout_seconds = 14400
max_steps = 20
[model]
+1
View File
@@ -13,6 +13,7 @@ num_infer_nodes = 12
[slurm]
job_name = "swe-minimax"
partition = "all"
[ckpt]
interval = 100
+3 -1
View File
@@ -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
Binary file not shown.

After

Width:  |  Height:  |  Size: 228 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 357 KiB

+74
View File
@@ -0,0 +1,74 @@
# IPO
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:
$$
\left|\pi_{\text{train}}(y_t) - \pi_{\text{infer}}(y_t)\right| > \epsilon
$$
```python
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
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 |
| Topology | 2 trainer nodes (Muon, CP 4 ulysses), 4 single-node TP=8 inference replicas with expert parallelism |
| 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` |
![IPO vs IcePop on GLM-4.5-Air SWE RL: solve rate (top) and trainer–inference KL (bottom)](assets/ipo/ipo-vs-icepop.png)
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:
![Left: sampled tokens by inference and trainer probability, with the IPO eps = 0.3 band and the IcePop ratio bounds. Right: fraction of tokens masked as a function of eps.](assets/ipo/eps-choice.png)
| `eps` | 0.1 | 0.2 | **0.3** | 0.5 | IcePop [0.2, 5] |
|---|---|---|---|---|---|
| tokens masked | 1.98% | 0.64% | **0.25%** | 0.047% | 0.06% |
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.
+1
View File
@@ -11,6 +11,7 @@
"inference",
"scaling",
"algorithms",
"ipo",
"advanced",
"development"
]
+24
View File
@@ -17,6 +17,7 @@ This page covers how to scale `prime-rl` from a single GPU to a 1000-GPU cluster
- [Optimizer Offloading](#optimizer-offloading)
- [LM Head Chunking](#lm-head-chunking)
- [Memory-Tight Recipe](#memory-tight-recipe)
- [Max Trainer Throughput Recipe](#max-trainer-throughput-recipe)
- [SLURM](#slurm)
- [Activation](#activation)
- [`[deployment]` Block](#deployment-block)
@@ -173,12 +174,35 @@ max_inflight_activations = 1
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
The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]` table is present — there's no separate entrypoint.
> **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):
+1
View File
@@ -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.
+3
View File
@@ -9,6 +9,9 @@ RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a
| [`swe-budget.toml`](swe-budget.toml) + [`swe-4-node.toml`](swe-4-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
| [`swe-budget.toml`](swe-budget.toml) + [`swe-2-node.toml`](swe-2-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 1 infer node |
| [`terminal.toml`](terminal.toml) | `tmax` (per-task Docker image, `rlm` ipython harness) | `swebench-verified` + `terminal-bench-2` (avg@4) | 2 train + 4 infer nodes |
| [`ipo-ablation/`](ipo-ablation) `base.toml` + `ipo.toml` / `icepop.toml` | `scaleswe` (`bash` harness), no router replay, 64 steps off-policy | `swebench-verified` | 2 train + 4 infer nodes |
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`).
@@ -0,0 +1,96 @@
# IPO vs IcePop ablation on GLM-4.5-Air agentic SWE RL (see docs/ipo.md). Shared base: compose with one
# loss overlay from this folder, e.g.
#
# uv run rl @ examples/advanced/glm-4.5-air/ipo-ablation/base.toml @ examples/advanced/glm-4.5-air/ipo-ablation/icepop.toml
#
# The arms differ only in [trainer.loss]. Same recipe as ../swe.toml with three changes that make the
# trainer-inference mismatch harder to handle: router replay off, up to 64 steps off-policy, and an
# output-token term in the length penalty. 2 trainer nodes (Muon, CP 4 ulysses) and 4 single-node
# TP=8 BF16 inference replicas, batch 256 x group 16 at 131k context.
max_steps = 1000
seq_len = 131072
[slurm]
partition = "all"
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 1
num_infer_replicas = 4
[monitors.wandb]
project = "ipo-ablation"
[ckpt]
interval = 50
keep_last = 1
[resume]
# --- Trainer ---
[trainer]
enable_router_replay = false
[model]
name = "zai-org/GLM-4.5-Air"
[trainer.model]
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.optim]
type = "muon"
# --- Orchestrator ---
[orchestrator]
batch_size = 256
max_off_policy_steps = 64
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
type = "grpo"
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.1
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
group_size = 1
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
# --- Inference ---
[inference]
[inference.vllm]
gpu_memory_utilization = 0.85
max_model_len = 131072
tensor_parallel_size = 8
enable_expert_parallel = true
@@ -0,0 +1,12 @@
# IcePop arm: mask a token when p_train / p_infer falls outside [ratio_low, ratio_high].
[slurm]
job_name = "ipo-ablation-icepop"
[monitors.wandb]
name = "icepop"
[trainer.loss]
type = "icepop"
ratio_low = 0.2
ratio_high = 5.0
@@ -0,0 +1,12 @@
# IPO arm: mask a token when |p_train - p_infer| > eps. eps = 0.3 is the default; the ablation also ran
# eps = 0.2 (`--trainer.loss.eps 0.2`).
[slurm]
job_name = "ipo-ablation-ipo"
[monitors.wandb]
name = "ipo-eps-0.3"
[trainer.loss]
type = "ipo"
eps = 0.3
@@ -159,11 +159,6 @@ env.taskset.task.judge.model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
[inference]
# vLLM + FlashInfer caches on node-local /tmp.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
@@ -90,11 +90,6 @@ thinking_retention = "all"
[inference]
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
-5
View File
@@ -108,11 +108,6 @@ env.agent.timeout.rollout = 3600
[inference]
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
gpu_memory_utilization = 0.85
max_model_len = 131072
@@ -154,11 +154,6 @@ env.taskset.id = "terminal-bench-2"
[inference]
# vLLM + FlashInfer caches on node-local /tmp.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
+1
View File
@@ -13,6 +13,7 @@ num_infer_nodes = 12
[slurm]
job_name = "swe-qwen30b"
partition = "all"
[ckpt]
interval = 100
@@ -0,0 +1,25 @@
# Qwen3-235B-A22B: SFT max trainer perf
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.
| Config | What it runs | Topology |
|---|---|---|
| [`sft-max-perf.toml`](sft-max-perf.toml) | 20 SFT steps, seq 16384, EP 8, full AC, fp32 AdamW, balanced routing | 4 train nodes |
## Requirements
- 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]`.
@@ -0,0 +1,61 @@
# SFT max trainer perf: Qwen3-235B-A22B on 4 nodes x 8 B300 at seq 16k.
#
# FSDP over 32 GPUs with EP 8, one packed 16384-token sample per GPU per step (32 x 16384 tokens),
# full activation checkpointing, AdamW with fp32 master weights and fp32 optimizer states, bf16
# compute, fp32 gradient reduce, FA4 varlen attention, torch.compile with fullgraph per block,
# everything on GPU (no CPU offloading), 20 steps. Routing is forced round-robin balanced so the
# step time does not depend on the data; drop [model.debug] for the checkpoint's real routing.
# See docs/scaling.md#max-trainer-throughput-recipe. Around 46% MFU on 4 x 8 B300.
#
# uv run sft @ examples/advanced/qwen3-235b-a22b/sft-max-perf.toml
#
# There is no [ckpt] block: this run measures step time, it does not produce a usable checkpoint.
# `dist_timeout_seconds` covers the first run, which builds the HF -> prime-rl conversion cache.
dist_timeout_seconds = 14400
max_steps = 20
# The renderer registry lists Qwen/Qwen3-235B-A22B but not the 2507 Thinking variant, which uses
# the same Qwen3 chat template.
[renderer]
name = "qwen3"
[model]
name = "Qwen/Qwen3-235B-A22B-Thinking-2507"
seq_len = 16384
ep = 8
offload = "none"
ac_offloading = "None"
# fullgraph needs the router inside the block's FSDP unit, which the fp32 router is not.
moe_router_dtype = "bfloat16"
# Selective AC does not fit at seq 16384 on 4 nodes with fp32 AdamW states and the torch dispatch.
[model.ac]
mode = "full"
freq = 1
[model.compile]
fullgraph = true
[model.moe.dispatch]
type = "torch"
[model.debug]
force_balanced_routing = true
[data]
name = "PrimeIntellect/Reverse-Text-SFT"
seq_len = 16384
batch_size = 32
micro_batch_size = 1
[optim]
type = "adamw"
lr = 1e-5
[deployment]
type = "multi_node"
num_train_nodes = 4
[slurm]
job_name = "qwen3-235b-sft-max-perf"
@@ -13,6 +13,7 @@ num_infer_nodes = 2
[slurm]
job_name = "math-qwen30b"
partition = "all"
[ckpt]
interval = 100
+1
View File
@@ -13,6 +13,7 @@ num_infer_nodes = 2
[slurm]
job_name = "swe-qwen30b"
partition = "all"
[ckpt]
interval = 100
@@ -3,6 +3,7 @@ seq_len = 32768
[slurm]
job_name = "general-agent-qwen3-30b-a3b-rlm"
partition = "all"
[deployment]
type = "multi_node"
@@ -534,6 +534,8 @@ class InferenceConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_slurm_template(self):
if self.slurm is not None and self.slurm.job_name is None:
self.slurm.job_name = "inference"
if self.slurm is not None and self.slurm.template_path is None:
templates_dir = find_package_resource("templates")
if templates_dir is not None:
@@ -781,6 +781,8 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_slurm_template(self):
"""Auto-setup the default single-node/multi-node SLURM template if no custom template is provided."""
if self.slurm is not None and self.slurm.job_name is None:
self.slurm.job_name = self.run.name
if self.slurm is not None and self.slurm.template_path is None:
templates_dir = find_package_resource("templates")
if templates_dir is not None:
@@ -326,8 +326,8 @@ class SFTConfig(BaseConfig):
trace_path: Path | None = None
"""Path to write the PyTorch profiler trace to."""
dist_timeout_seconds: int = 3600
"""Timeout in seconds for torch distributed ops."""
dist_timeout_seconds: int = 900
"""Timeout in seconds for torch distributed ops: a hung collective (e.g. a dead rank) fails the run after this long."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
@@ -643,6 +643,8 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_slurm_template(self):
if self.slurm is not None and self.slurm.job_name is None:
self.slurm.job_name = self.run.name
if self.slurm is not None and self.slurm.template_path is None:
templates_dir = find_package_resource("templates")
if templates_dir is not None:
@@ -123,8 +123,8 @@ class ResumeConfig(BaseConfig):
class SlurmConfig(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."""
@@ -132,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)."""
@@ -42,11 +42,10 @@ class ActivationCheckpointConfig(BaseConfig):
class ActivationOffloadingConfig(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."""
OffloadMode: TypeAlias = Literal["none", "optimizer", "full"]
@@ -283,6 +282,9 @@ class ModelConfig(BaseModelConfig):
moe_router_dtype: Literal["bfloat16", "float32", "auto"] = "auto"
"""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."""
reduce_scatter_max_input_buffers: int = Field(1, ge=1)
"""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"
@@ -314,9 +316,9 @@ class ModelConfig(BaseModelConfig):
@model_validator(mode="after")
def ac_offloading_requires_ac(self):
"""Automatically enable activation checkpointing when activation offloading is enabled."""
if self.ac_offloading is not None and self.ac is None:
self.ac = ActivationCheckpointConfig()
"""Activation offloading requires activation checkpointing, so ``ac = None`` disables both."""
if self.ac is None:
self.ac_offloading = None
return self
@model_validator(mode="after")
@@ -557,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."""
@@ -613,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."""
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "prime-rl"
version = "0.9.0"
version = "0.10.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
+143
View File
@@ -14,6 +14,7 @@ def apply_shared_vllm_patches():
patch_gpt_oss_weight_loading()
patch_qwen38_weight_loading()
monkey_patch_shm_buffer_ownership()
_patch_lora_key_prefix()
_patch_qwen35_moe_lora_format()
monkey_patch_nano_v3_reasoning_parser()
@@ -28,6 +29,67 @@ def apply_shared_vllm_patches():
# Set by `server()` when the LoRA target modules include no expert layers.
if os.environ.get("PRIME_NO_MOE_LORA") == "1":
monkey_patch_no_moe_lora()
monkey_patch_deepseek_v4_c128_boundary()
monkey_patch_deepseek_v4_attn_sink_loading()
def monkey_patch_shm_buffer_ownership():
"""Own out-of-band buffers before releasing a reusable vLLM SHM slot."""
import pickle
import zmq
from vllm.distributed.device_communicators import shm_broadcast
# Backport https://github.com/vllm-project/vllm/pull/61000; remove when our
# minimum vLLM version includes it. Retained routed-expert arrays otherwise
# alias ring slots that subsequent messages can overwrite.
MessageQueue = shm_broadcast.MessageQueue
if getattr(MessageQueue.dequeue, "_prime_rl_owns_shm_buffers", False):
return
def dequeue(self, timeout: float | None = None, indefinite: bool = False):
if self._is_local_reader:
with self.acquire_read(timeout, indefinite) as buf:
overflow = buf[0] == 1
if not overflow:
offset = 3
buf_count = shm_broadcast.from_bytes_big(buf[1:offset])
all_buffers = []
for i in range(buf_count):
buf_offset = offset + 4
buf_len = shm_broadcast.from_bytes_big(buf[offset:buf_offset])
offset = buf_offset + buf_len
buffer = buf[buf_offset:offset]
all_buffers.append(buffer if i == 0 else bytearray(buffer))
obj = pickle.loads(all_buffers[0], buffers=all_buffers[1:])
if overflow:
obj = MessageQueue.recv(self.local_socket, timeout)
elif self._is_remote_reader:
obj = MessageQueue.recv(self.remote_socket, timeout)
else:
raise RuntimeError("Only readers can dequeue")
return obj
def _rebuild_tensor(buf, shape: tuple[int, ...], dtype_str: str) -> torch.Tensor:
dtype = getattr(torch, dtype_str)
assert isinstance(dtype, torch.dtype)
if isinstance(buf, zmq.Frame):
try:
return torch.frombuffer(buf, dtype=torch.uint8).view(dtype).view(shape)
except ValueError:
pass
raw = buf if isinstance(buf, bytearray) else bytearray(buf)
if not raw:
assert 0 in shape
return torch.empty(shape, dtype=dtype)
return torch.frombuffer(raw, dtype=torch.uint8).view(dtype).view(shape)
# Pickle resolves this reducer by its module and name in receiving processes.
_rebuild_tensor.__module__ = shm_broadcast.__name__
_rebuild_tensor.__qualname__ = "_rebuild_tensor"
dequeue._prime_rl_owns_shm_buffers = True
shm_broadcast._rebuild_tensor = _rebuild_tensor
MessageQueue.dequeue = dequeue
def monkey_patch_deepseek_v4_allowed_layer_types():
@@ -47,6 +109,87 @@ def monkey_patch_deepseek_v4_allowed_layer_types():
allow_deepseek_v4_layer_types()
def monkey_patch_deepseek_v4_c128_boundary():
"""Fix DeepSeek V4 long-context KV corruption under piecewise CUDA graphs.
On vLLM 0.30+, including the pinned 0.31.0, the piecewise CUDA graphs are captured on a step
that skips writing C128 compressed KV, so every replay skips it too. Mixed batches of up to
512 tokens never store their C128 entries, later queries attend over stale compressed KV, and
long-context rollouts drift from the trainer, inflating mismatch KL.
The skip is an optimization: ``DeepseekCompressor.forward`` returns early when
``_get_c128_boundary`` reports that no request completes a 128-token block this step.
vllm-project/vllm#55353 made that helper return a bool under Model Runner V2, so capture on
dummy batches records the early return. Returning None instead disables the skip, which is
the path vLLM already takes under async speculative decoding and the one 0.29 always took.
The upstream fix, vllm-project/vllm#59709, keeps the skip on eager steps and only stops it
from being captured. That change sits inline in ``forward``, so matching it here would mean
copying the whole method. Patching the helper costs one extra compress kernel launch on eager
steps that complete no block, and the kernel already skips those tokens on the GPU.
Remove this patch once vllm-project/vllm#59709 lands in the pinned vLLM version.
"""
from vllm.logger import init_logger
from vllm.models.deepseek_v4 import compressor
if getattr(compressor._get_c128_boundary, "_prime_rl_always_compresses", False):
return
def _get_c128_boundary(metadata):
return None
_get_c128_boundary._prime_rl_always_compresses = True
compressor._get_c128_boundary = _get_c128_boundary
init_logger("vllm.prime_rl.deepseek_v4").info("DeepSeek V4 C128 compressor store runs on every step.")
def monkey_patch_deepseek_v4_attn_sink_loading():
"""Fix DeepSeek V4 weight updates silently keeping the boot-time attention sinks.
``DeepseekV4Model.load_weights`` writes the sinks with a bare slice copy instead of
``param.weight_loader``. Layerwise reload moves parameters to meta and only buffers writes
that go through a loader, so the copy is silently dropped. This pads this rank's heads back
to the full parameter with ``-inf`` (no sink) and loads that through ``param.weight_loader``.
Remove this patch once vllm-project/vllm#57797 lands in the pinned vLLM version. Only
``nvidia/model.py`` is covered, not the MTP, DSpark or non-NVIDIA variants.
"""
from vllm.logger import init_logger
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.models.deepseek_v4.nvidia import model as dsv4_model
original_load_weights = dsv4_model.DeepseekV4Model.load_weights
if getattr(original_load_weights, "_prime_rl_uses_weight_loaders", False):
return
def load_weights(self, weights):
params = dict(self.named_parameters())
tp_size = dsv4_model.get_tensor_model_parallel_world_size()
heads_per_rank = self.config.num_attention_heads // tp_size
head_start = heads_per_rank * dsv4_model.get_tensor_model_parallel_rank()
loaded_params: set[str] = set()
def remaining_weights():
for name, weight in weights:
if "attn_sink" not in name or dsv4_model.is_pp_missing_parameter(name, self):
yield name, weight
continue
param = params[name]
sink = weight.new_full(tuple(param.shape), -float("inf"))
sink[:heads_per_rank] = weight[head_start : head_start + heads_per_rank]
weight_loader = getattr(param, "weight_loader", default_weight_loader)
weight_loader(param, sink)
loaded_params.add(name)
loaded_params.update(original_load_weights(self, remaining_weights()))
return loaded_params
load_weights._prime_rl_uses_weight_loaders = True
dsv4_model.DeepseekV4Model.load_weights = load_weights
init_logger("vllm.prime_rl.deepseek_v4").info("DeepSeek V4 attn_sink loads through param.weight_loader.")
def monkey_patch_online_fp8_parameter_cast():
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
+9 -5
View File
@@ -404,16 +404,20 @@ class Orchestrator:
# CancelledError, KeyboardInterrupt, or a real error), so the teardown
# logs a forced-cleanup warning instead of a clean-exit success.
clean_exit = False
loop_done = False
try:
await self.main_loop()
loop_done = True
await self.wait_for_final_broadcast()
clean_exit = True
finally:
elapsed = format_time(time.perf_counter() - start_time)
# ``progress.step`` points at the next (unshipped) step; the last finished step is
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
# first ship). Saved before finalize, which tells the launcher the run is done.
if self.config.ckpt is not None and self.progress.step > 1:
# first ship). Saved before finalize, which tells the launcher the run is done. Only once the
# step loop finished (the last step is fully shipped); a crash mid-loop leaves no consistent
# state for that step, and the trainer has no checkpoint for it.
if loop_done and self.config.ckpt is not None and self.progress.step > 1:
self.progress.step -= 1
get_logger().info(f"Saving final checkpoint at step {self.progress.step}")
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
@@ -430,7 +434,7 @@ class Orchestrator:
await monitors.finalize()
else:
get_logger().warning(f"Orchestrator interrupted after {elapsed} — forcing cleanup (not a clean exit)")
await self.stop()
await self.stop(clean_exit)
if clean_exit:
get_logger().success("Orchestrator finished")
else:
@@ -983,7 +987,7 @@ class Orchestrator:
self.update_dispatch_gate()
self.version_advanced.set()
async def stop(self) -> None:
async def stop(self, clean_exit: bool) -> None:
"""Bounded best-effort teardown of all components. Has a global
timeout so a wedged peer can't keep the process alive forever —
training artifacts are already persisted before this is reached."""
@@ -1026,7 +1030,7 @@ class Orchestrator:
f"Orchestrator shutdown did not complete within {SHUTDOWN_TIMEOUT_S}s; "
"forcing process exit. Training artifacts are already persisted."
)
os._exit(0)
os._exit(0 if clean_exit else 1)
await task
get_logger().debug(f"Stopped orchestrator components in {format_time(time.perf_counter() - t0)}")
@@ -4,7 +4,9 @@
#SBATCH --nodes={{ num_nodes }}
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
{%- if partition %}
#SBATCH --partition={{ partition }}
{%- endif %}
{%- if account %}
#SBATCH --account={{ account }}
{%- endif %}
@@ -4,7 +4,9 @@
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
{%- if partition %}
#SBATCH --partition={{ partition }}
{%- endif %}
{%- if account %}
#SBATCH --account={{ account }}
{%- endif %}
@@ -4,7 +4,9 @@
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
{%- if partition %}
#SBATCH --partition={{ partition }}
{%- endif %}
{%- if account %}
#SBATCH --account={{ account }}
{%- endif %}
@@ -5,7 +5,9 @@
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --exclusive
{%- if partition %}
#SBATCH --partition={{ partition }}
{%- endif %}
{%- if account %}
#SBATCH --account={{ account }}
{%- endif %}
@@ -5,7 +5,9 @@
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --exclusive
{%- if partition %}
#SBATCH --partition={{ partition }}
{%- endif %}
{%- if account %}
#SBATCH --account={{ account }}
{%- endif %}
+10 -12
View File
@@ -25,6 +25,7 @@ from prime_rl.trainer.models.fusions import (
write_back_loaded_packed_optimizer_state,
)
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
from prime_rl.trainer.utils import get_dcp_group
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_ckpt_dir, get_step_path
@@ -151,14 +152,6 @@ class AppState(Stateful):
for key, value in state_dict["progress"].items():
setattr(self.progress, key, value)
# state_dict is the same dict object that dcp_load held internally; clearing
# it drops the last references to the loaded tensor wrappers so the cuda
# allocator can release whatever blocks it cached during the read.
if has_cpu_offload:
state_dict.clear()
gc.collect()
torch.cuda.empty_cache()
class CheckpointManager:
"""Utility class to save and load trainer checkpoints to resume SFT and RL training."""
@@ -204,11 +197,11 @@ class CheckpointManager:
# FileExistsError (EEXIST + stale is_dir() metadata).
if self.world.is_master:
dataloader_dir.mkdir(parents=True, exist_ok=True)
torch.distributed.barrier()
torch.distributed.barrier(group=get_dcp_group())
torch.save(dataloader.state_dict(), dataloader_dir / f"rank_{self.world.rank}.pt")
# Save sharded state
dcp_save(state_dict, checkpoint_id=path)
dcp_save(state_dict, checkpoint_id=path, process_group=get_dcp_group())
self.logger.debug(f"Saved training checkpoint in {format_time(time.perf_counter() - start_time)}")
@@ -228,7 +221,12 @@ class CheckpointManager:
# Load sharded state
app_state = AppState(model, optimizers if not self.skip_optimizer else [], scheduler, progress)
state_dict = {"app": app_state}
dcp_load(state_dict=state_dict, checkpoint_id=path)
dcp_load(state_dict=state_dict, checkpoint_id=path, process_group=get_dcp_group())
# DCP materializes the optimizer state with a zero-grad step, which allocates a full set of
# gradients. Left in the allocator cache, those blocks fragment the pool and the first step
# reserves on top of them instead of reusing them.
gc.collect()
torch.cuda.empty_cache()
if self.skip_optimizer:
for optimizer in optimizers:
if isinstance(optimizer, OffloadOptimizer):
@@ -282,7 +280,7 @@ class CheckpointManager:
# re-raise FileExistsError on a parallel FS (see save_to_path).
if self.world.is_master:
ckpt_path.parent.mkdir(parents=True, exist_ok=True)
torch.distributed.barrier()
torch.distributed.barrier(group=get_dcp_group())
self.save_to_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
bisect.insort(self.ckpt_steps, step)
+12 -18
View File
@@ -16,7 +16,6 @@ import torch.nn as nn
from huggingface_hub import snapshot_download
from jaxtyping import Int
from torch import Tensor
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointWrapper
from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
from torch.distributed.fsdp import FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
@@ -63,7 +62,8 @@ from prime_rl.trainer.models.qwen3_8_flash_next.indexer import SparseAttentionIn
from prime_rl.trainer.models.qwen3_8_flash_next.ngram_embedding import NGramEmbedding
from prime_rl.trainer.moe_runtime import configure_moe_runtime
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.world import get_world
from prime_rl.trainer.utils import get_dcp_group
from prime_rl.trainer.world import get_world, wait_for_master
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import format_time
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
@@ -108,6 +108,9 @@ DTYPE_MAP = {
"float32": torch.float32,
}
# The one-time HF <-> PrimeRL conversion runs on the master alone and can take hours for large models.
CONVERSION_TIMEOUT_S = 4 * 3600
# We increase the torch.compile recompile limit and cache size as we found this
# necessary for training INTELLECT-3 with Muon.
torch._dynamo.config.recompile_limit = 16 # default: 8
@@ -586,8 +589,6 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
reshard_after_forward=config.reshard_after_forward,
shard_placement_fn=shard_placement_fn,
)
# Keep the router reduction from waiting for the expert reduction's input buffer.
block_mlp.router.set_reduce_scatter_max_input_buffers(2)
fully_shard(
transformer_block,
@@ -633,6 +634,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
reshard_after_forward=config.reshard_after_forward,
shard_placement_fn=shard_placement_fn,
)
model.set_reduce_scatter_max_input_buffers(config.reduce_scatter_max_input_buffers)
if not parallel_dims.ep_enabled:
return
@@ -752,7 +754,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
del snapshot_state_dict
# All ranks wait for master rank to finish conversion
torch.distributed.barrier()
wait_for_master(f"model_conversion:{config.name}", timeout=CONVERSION_TIMEOUT_S)
if snapshot_path.name == "prime" and not (snapshot_path / ".prime-v1").is_file():
raise RuntimeError(f"PrimeRL conversion cache {snapshot_path} is missing the required .prime-v1 marker")
@@ -765,6 +767,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
dcp_load(
state_dict,
storage_reader=HuggingFaceStorageReader(path=snapshot_path.as_posix()),
process_group=get_dcp_group(),
)
write_back_loaded_packed_parameters(model, state_dict)
@@ -832,16 +835,8 @@ def apply_compile(model: nn.Module, compile_config: CompileConfig):
mark_dynamic_int_args()
language_model = get_language_model(model)
for layer_id in range(len(language_model.layers)):
layer = language_model.layers[layer_id]
if isinstance(layer, CheckpointWrapper) and any(
isinstance(module, FSDPModule) for module in layer._checkpoint_wrapped_module.modules()
):
# A nested FSDP unit's hooks always break the graph, and a break inside a compiled checkpoint
# sends the block to eager, so keep AC eager around the compiled block. pytorch/pytorch#196626
# removes the fp32 router's nested unit by letting it join the block's FSDP unit.
layer = layer._checkpoint_wrapped_module
# Doing it in-place avoids mangled fqn which can break checkpoint loading
layer.compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
language_model.layers[layer_id].compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
get_logger().info(
f"Compiled {len(language_model.layers)} layers (fullgraph={compile_config.fullgraph}, mode={compile_config.mode})"
)
@@ -993,15 +988,14 @@ def setup_model(
override_attr=config.vlm.vision_encoder_attr if config.vlm is not None else None,
)
# the right order is AC -> FSDP -> Compile: compile needs to see which blocks hold nested FSDP units
# the right order is AC -> Compile -> FSDP
if config.ac is not None:
apply_ac(model, config.ac)
setup_fsdp(model, config, parallel_dims)
if config.compile is not None:
apply_compile(model, config.compile)
setup_fsdp(model, config, parallel_dims)
if loading_from_checkpoint_later:
logger.warning(
"Skipping loading weights. Initializing an empty model on device, loading from checkpoint later."
+3 -1
View File
@@ -507,7 +507,9 @@ def train(config: TrainerConfig):
# Add relevant tensors to tensor dict for logging purposes
entropy = out["entropy"][loss_mask].detach().to("cpu")
tensors["entropy/all"].append(entropy)
tensors["loss"].append(loss.detach().to("cpu").unsqueeze(0))
# Every CP rank computes the whole sequence's loss, and the global normalizers count each
# sequence once per CP rank (gradients still sum correctly), so undo that for the logged value.
tensors["loss"].append((loss.detach() * cp_size).to("cpu").unsqueeze(0))
env_names = micro_batch["env_names"]
masked_env_names = [env_name for env_name, keep in zip(env_names, loss_mask.flatten().tolist()) if keep]
+2 -2
View File
@@ -105,7 +105,7 @@ class FakeDataset(StatefulIterableDataset):
else self.seq_len
)
random_input_ids = (
torch.randint(0, self.vocab_size, (self.seq_len + 1,), generator=generator).long().tolist()
torch.randint(0, self.vocab_size, (seq_len + 1,), generator=generator).long().tolist()
if self.input_ids == "random"
else None
)
@@ -144,7 +144,7 @@ class FakeDataset(StatefulIterableDataset):
"mm_token_type_ids": None,
}
self.num_samples["fake"] += 1
self.num_tokens["fake"] += len(input_ids)
self.num_tokens["fake"] += seq_len
yield fake_sample
+11
View File
@@ -5,6 +5,7 @@ import shutil
import time
from collections import defaultdict
from datetime import timedelta
from functools import cache
from pathlib import Path
from typing import TYPE_CHECKING
@@ -24,6 +25,7 @@ if TYPE_CHECKING:
from prime_rl.trainer.optim import GradientOffloadManager
DEFAULT_TIMEOUT = timedelta(seconds=600)
DCP_TIMEOUT = timedelta(hours=4)
class GarbageCollection:
@@ -203,6 +205,15 @@ def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: b
get_logger().debug(f"Initialized torch distributed in {format_time(time.perf_counter() - t0)}")
@cache
def get_dcp_group() -> dist.ProcessGroup:
"""A gloo group for DCP checkpoint save/load. DCP's collectives wait for the slowest rank's
writes or reads (and, on the first HF load, its download), which can outlast
``dist_timeout_seconds``; on this group they wait up to ``DCP_TIMEOUT`` instead. Every rank must
make its first call at the same point."""
return dist.new_group(backend="gloo", timeout=DCP_TIMEOUT)
def print_sample(input_ids: list[int], loss_mask: list[bool], tokenizer: PreTrainedTokenizer):
"""
Visualize the loss mask of a tokenized sample using rich.
+15
View File
@@ -1,4 +1,7 @@
import os
from datetime import timedelta
import torch.distributed as dist
class World:
@@ -42,3 +45,15 @@ def get_world() -> World:
def reset_world():
global _WORLD
_WORLD = None
def wait_for_master(key: str, timeout: float) -> None:
"""A barrier for work only the master does, which can outlast ``dist_timeout_seconds`` (a model
conversion, waiting for a weight broadcast's receiver). The other ranks wait on the c10d store,
not in an NCCL collective, whose watchdog kills them after ``dist_timeout_seconds``. The master
calls it with the same ``key`` when it is done."""
store = dist.distributed_c10d._get_default_store()
if get_world().is_master:
store.set(key, "done")
else:
store.wait([key], timedelta(seconds=timeout))
+4 -4
View File
@@ -10,7 +10,7 @@ import torch.nn as nn
from prime_rl.configs.shared import WeightBroadcastConfig
from prime_rl.orchestrator.clients import AdminPlane
from prime_rl.trainer.world import get_world
from prime_rl.trainer.world import get_world, wait_for_master
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_broadcast_dir, get_step_path
@@ -63,6 +63,7 @@ class WeightSender(ABC):
(step_dir / SENDER_READY_MARKER).touch()
self._wait_for_receiver_ready(step_dir)
(step_dir / STARTED_MARKER).touch()
wait_for_master(f"weight_broadcast/{step}", self.timeout)
self._broadcast(model, step, step_dir)
if self.world.is_master:
(step_dir / FINISHED_MARKER).touch()
@@ -94,9 +95,8 @@ class WeightSender(ABC):
@abstractmethod
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
"""Move v{step}'s weights to the consumer. Rank synchronization is the
transport's own job — non-master ranks must be held back until the
master finished the handshake (see ``NCCLWeightSender._broadcast``)."""
"""Move v{step}'s weights to the consumer. All ranks enter only after
the master finished the handshake."""
def _clean(self, step: int) -> None:
"""Remove old broadcast dirs, keeping ``step`` and ``step - 1`` (a
@@ -1,6 +1,5 @@
from pathlib import Path
import torch.distributed as dist
import torch.nn as nn
from torch.distributed.tensor import DTensor
@@ -52,7 +51,6 @@ class FileSystemWeightSender(WeightSender):
dropout=self.lora_config.dropout,
)
else:
dist.barrier()
state_dict = gather_weights_parallel(model)
state_dict = convert_state_dict_to_hf(model, state_dict)
self.logger.debug(f"Saving weights to {step_dir}")
-8
View File
@@ -3,7 +3,6 @@ from pathlib import Path
from typing import Callable, Generator
import torch
import torch.distributed as dist
import torch.nn as nn
from torch import Tensor
from torch.distributed.tensor import DTensor
@@ -189,13 +188,6 @@ class NCCLWeightSender(WeightSender):
@torch.no_grad()
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
# The master enters only after the receiver acknowledged the handshake,
# but all ranks must be held back until then: the broadcast preparation
# (DTensor resolution, checkpoint conversion) enqueues collectives on non-master
# ranks, and if those start before the receiver has paused inference,
# the collectives sit unmatched until NCCL's watchdog kills the process.
if self.world.world_size > 1:
dist.barrier()
self.nccl_broadcast_sender.send(model)
@@ -23,6 +23,7 @@ from prime_rl.configs.shared import NIXLWeightBroadcastConfig
from prime_rl.orchestrator.clients import init_nixl_broadcast
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.world import wait_for_master
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
from prime_rl.transports.weights.nixl.agent import (
NixlAgent,
@@ -394,6 +395,8 @@ class NIXLWeightSender(WeightSender):
inference_metadata = None
if startup:
# The master's ModelExpress discovery can outlast the NCCL timeout; hold the others on the store.
wait_for_master(f"weight_broadcast/nixl_discovery/{step}", self.config.timeout)
objects = [inference_metadata]
dist.broadcast_object_list(objects, src=0)
if self.is_serving_rank:
@@ -442,6 +445,7 @@ class NIXLWeightSender(WeightSender):
policy_notification(step, "complete"),
timeout=self.config.timeout,
)
wait_for_master(f"weight_broadcast/nixl_complete/{step}", self.config.timeout)
dist.barrier()
self.broadcast_count += 1
self.logger.info(f"NIXL+ModelExpress policy v{step} synchronized in {time.perf_counter() - start:.2f}s")
+1 -4
View File
@@ -324,7 +324,4 @@ def maybe_activation_offloading(config: ActivationOffloadingConfig | None) -> Of
if config is None:
return nullcontext()
return OffloadActivations(
use_pin_memory=config.pin_memory,
max_fwd_stash_size=config.max_inflight_activations,
)
return OffloadActivations(max_fwd_stash_size=config.max_inflight_activations)
+9
View File
@@ -28,6 +28,11 @@ DEFAULT_COMMON_ENV_VARS: dict[str, str] = {
DEFAULT_TRAINER_ENV_VARS: dict[str, str] = {
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
# NCCL flight recorder: on a collective timeout every rank dumps its last 2000 collectives
# to /tmp/nccl_trace_<uid>_rank_<rank> (read with `torchfrtrace`), showing which rank hung where.
"TORCH_FR_BUFFER_SIZE": "2000",
"TORCH_NCCL_DUMP_ON_TIMEOUT": "1",
"TORCH_FR_DUMP_TEMP_FILE": f"/tmp/nccl_trace_{os.getuid()}_rank_",
}
DEFAULT_INFERENCE_ENV_VARS: dict[str, str] = {
@@ -35,6 +40,10 @@ DEFAULT_INFERENCE_ENV_VARS: dict[str, str] = {
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:False",
"VLLM_ENGINE_READY_TIMEOUT_S": "4200",
"UCX_TLS": "all",
# vLLM's AOT compile cache and FlashInfer's JIT cache default to $HOME; a partial cache shared across
# nodes makes TP ranks load different compiled artifacts and hang.
"VLLM_CACHE_ROOT": f"/tmp/.vllm-cache-{os.getuid()}",
"FLASHINFER_WORKSPACE_BASE": f"/tmp/.flashinfer-cache-{os.getuid()}",
}
+6
View File
@@ -778,6 +778,12 @@ def test_trainer_rejects_vlm_cp_with_ring():
TrainerConfig.model_validate(config)
def test_ac_none_disables_ac_offloading():
config = TrainerModelConfig.model_validate({"ac": None})
assert config.ac is None
assert config.ac_offloading is None
def test_shared_model_name_propagates_to_subconfigs():
model_name = "PrimeIntellect/test-model"
config = RLConfig.model_validate(
+3 -1
View File
@@ -325,13 +325,15 @@ def test_deepseek_v4_hash_table_survives_the_load_path(tmp_path, monkeypatch):
meta_model = DeepseekV4ForCausalLM(MODEL_CONFIG)
expected = tables[0]
def fake_dcp_load(state_dict, storage_reader=None):
def fake_dcp_load(state_dict, storage_reader=None, process_group=None):
buffer = state_dict["model.layers.0.mlp.router.tid2eid"]
buffer.copy_(expected.to(device=buffer.device))
monkeypatch.setattr("prime_rl.trainer.model.dcp_load", fake_dcp_load)
monkeypatch.setattr("prime_rl.trainer.model.load_state_dict_keys", lambda path: meta_model.state_dict().keys())
monkeypatch.setattr("torch.distributed.barrier", lambda *args, **kwargs: None)
monkeypatch.setattr("prime_rl.trainer.model.wait_for_master", lambda *args, **kwargs: None)
monkeypatch.setattr("prime_rl.trainer.model.get_dcp_group", lambda: None)
load_dcp_from_hf(meta_model, ModelConfig(name=str(tmp_path)), parallel_dims=MagicMock())
@@ -35,13 +35,15 @@ def test_load_dcp_from_hf_keeps_checkpoint_selection_bias(model, tmp_path, monke
"""Checkpoint values for the persistent selection bias must survive loading."""
expected = torch.tensor([0.1, 0.2, 0.3, 0.4])
def fake_dcp_load(state_dict, storage_reader=None):
def fake_dcp_load(state_dict, storage_reader=None, process_group=None):
buffer = state_dict["model.layers.1.mlp.router.selection_bias"]
buffer.copy_(expected.to(device=buffer.device, dtype=buffer.dtype))
monkeypatch.setattr("prime_rl.trainer.model.dcp_load", fake_dcp_load)
monkeypatch.setattr("prime_rl.trainer.model.load_state_dict_keys", lambda path: model.state_dict().keys())
monkeypatch.setattr("torch.distributed.barrier", lambda *args, **kwargs: None)
monkeypatch.setattr("prime_rl.trainer.model.wait_for_master", lambda *args, **kwargs: None)
monkeypatch.setattr("prime_rl.trainer.model.get_dcp_group", lambda: None)
load_dcp_from_hf(model, ModelConfig(name=str(tmp_path)), parallel_dims=MagicMock())
+14
View File
@@ -26,6 +26,20 @@ def test_fake_dataset_state():
assert dataset.state_dict() == {"step": 4, "epoch": 0}
@pytest.mark.parametrize("length", ["fixed", "variable"])
@pytest.mark.parametrize("input_ids", ["increasing", "random"])
def test_fake_dataset_sample_lengths(length: str, input_ids: str):
dataset = FakeDataset(vocab_size=10000, seq_len=128, length=length, input_ids=input_ids)
dataiter = iter(dataset)
for _ in range(20):
sample = next(dataiter)
seq_len = len(sample["input_ids"])
assert len(sample["target_ids"]) == seq_len
assert len(sample["position_ids"]) == seq_len
assert len(sample["loss_mask"]) == seq_len
assert sum(sample["seq_lens"]) == seq_len
@pytest.mark.parametrize("length", ["fixed", "variable"])
@pytest.mark.parametrize("data_world_size", [1, 2, 3])
def test_fake_dataset_random_resume(length: str, data_world_size: int):
Generated
+1 -1
View File
@@ -4999,7 +4999,7 @@ dev = [
[[package]]
name = "prime-rl"
version = "0.9.0"
version = "0.10.0"
source = { editable = "." }
dependencies = [
{ name = "aiolimiter" },