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
9fff742eae Allow eval.retrigger_on_resume with an in-memory weight broadcast (#4007)
## Problem

`eval.retrigger_on_resume` is rejected at config-validation time unless
`weight_broadcast.type == "filesystem"`:

```python
if self.eval.retrigger_on_resume:
    raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
```

With the default `nccl` transport the flag is therefore unusable, and
resuming an SFT run at an interval-aligned step silently skips that
step's evals: the trainer broadcasts the resume checkpoint at startup
and the evals process loads it, but nothing re-fires, so the next eval
is a full interval away and the step resumed from is never evaluated.

## Why the gate isn't needed

The in-memory path already meets the precondition the gate was
protecting. `OnlineEval.watch()` rendezvouses with the trainer's startup
broadcast before the re-fire, for every transport:

```python
startup_step = config.resume_step or 0
await self.receiver.sync_startup(startup_step, timeout=STARTUP_BROADCAST_TIMEOUT_S)
```

and `sync_startup` is transport-agnostic in
`transports/weights/base.py`:

```python
async def sync_startup(self, step: int, timeout: float) -> None:
    await asyncio.wait_for(self.wait_published(step), timeout=timeout)
    await self.receive(step)
```

So by the time `maybe_run_eval(step=config.resume_step)` runs, the
served weights are already the resume checkpoint's — and that call
passes `reload_weights=False`, so it never needs to re-read them from
disk, which is the only thing a filesystem broadcast would have added.

Cancellation is unchanged: the re-fired epoch gets the usual
`superseding_step` callback, so a newer broadcast supersedes it exactly
as for any other eval epoch.

NIXL remains rejected by the check immediately above. The RL
orchestrator already honours `retrigger_on_resume` with no transport
restriction, so this also removes an SFT/RL inconsistency.

## Change

Two-line deletion. No tests assert the removed error.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Config-validation-only change; removes an overly strict guard with no
runtime logic changes.
> 
> **Overview**
> **Allows `eval.retrigger_on_resume` with NCCL (in-memory) weight
broadcast for SFT online evals.**
> 
> SFT config validation no longer raises when `retrigger_on_resume` is
set alongside non-filesystem `weight_broadcast` (e.g. default `nccl`).
Resuming at an interval-aligned step can re-fire that step’s evals
without forcing `weight_broadcast.type = 'filesystem'`. **LoRA +
in-memory broadcast** and **NIXL** restrictions in the same block are
unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
acf86f21d9345e3677852baaefe690f73b938026. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-11 13:30:16 +01:00
HubertandGitHub 73140dec35 fix(trainer): keep Qwen3.5 CP context setup eager (#4011)
Qwen3.5 training with context parallelism can fail on the first forward
after #3925 places compilation inside activation checkpointing. FLA's CP
setup reads tensor-valued sequence boundaries and calls
`torch.searchsorted`; Inductor fails to specialize the resulting scalar:

```
GuardOnDataDependentSymNode:
Could not extract specialized integer from data-dependent expression (u0//4)
```

Wrap `build_cp_context` with `torch.compiler.disable`, alongside the
existing eager CP convolution wrapper. CP setup runs eagerly while the
surrounding block remains eligible for compilation. CP calculations,
model parameters and checkpointing settings are unchanged.

Validation ran on an allocated India H200 compute node with PyTorch
2.13.0+cu130 and FLA 0.5.2. A bounded CUDA/FSDP/checkpoint reproducer
used two sequence-boundary fixtures and logical CP size 4:

| Layout | Result | Maximum absolute
output/input-gradient/parameter-gradient difference vs eager |
| --- | --- | --- |
| Earlier outer compilation | Pass | 0 |
| Inner compilation introduced by #3925 | Same `(u0//4)` compiler
failure | — |
| Inner compilation with eager FLA CP metadata | Pass |
1.9073486328125e-6 |

This reproducer uses one CUDA/FSDP rank; it does not exercise real
four-rank CP collectives or a full Qwen training step. Full distributed
training validation remains outstanding. Ruff and `git diff --check`
passed for the patch. No test or experiment files are included in this
diff.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Narrow trainer workaround for a known torch.compile + FLA CP setup
issue; behavior matches eager CP setup with negligible numeric drift in
repro.
> 
> **Overview**
> Fixes Qwen3.5 **context-parallel (CP)** training failures when the
block is compiled inside activation checkpointing (#3925). Inductor
cannot specialize scalars from FLA’s `build_cp_context`
(`torch.searchsorted` on tensor sequence boundaries), which triggers
`GuardOnDataDependentSymNode`.
> 
> The change wraps **`build_cp_context`** with
**`torch.compiler.disable`** (same pattern as the existing eager CP
**`causal_conv1d`** wrapper) and calls **`build_cp_context_eager`** in
the forward path when CP is enabled. CP math, parameters, and
checkpointing are unchanged; only CP metadata setup runs outside the
compiled graph.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c192fc98cedc342e16af9307577f38fa77213b4e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 16:05:14 -07:00
0936378085 refactor(configs)!: one model.offload field for CPU offloading (#3988)
Replaces the three switches `model.fsdp_cpu_offload`,
`model.optim_cpu_offload` and `model.full_offload` with one field:

```toml
[model]
offload = "optimizer"   # default; also "full", "none"
```

This applies to both the RL trainer and SFT. The `fsdp` switch is not
migrated: the mode is removed outright (rationale below). The
`[model.full_offload] numa_bind` knob is dropped: no recipe, deployment,
template or doc sets it. Full offload now always pins each rank's CPUs
to its GPU's NUMA node. That was already the default. Ranks whose GPU
reports no NUMA node still skip binding with a warning. On hosts without
GPU sysfs topology (`/sys/bus/pci/devices/<bus>/numa_node`), binding is
no longer optional: full offload fails there instead of being switched
off.

Why: the three switches could only be used one at a time, enforced by
`cpu_offload_mutual_exclusion`. Because `optim_cpu_offload` defaulted to
`true`, enabling full offload also meant writing `optim_cpu_offload =
false`, otherwise validation failed (see the old
`configs/advanced/deepseek-v4-flash/sft.toml` comment). With one value
the conflicting combinations cannot be expressed, so that validator is
deleted. The default behaviour does not change: optimizer-state offload
stays on.

Why drop `fsdp`: the mode was the stock torch FSDP2 `CPUOffloadPolicy`
with no in-tree config, example, or test user; Muon rejected it and it
broke NCCL weight broadcast. It was kept only for long-context runs
whose fp32 masters/moments no longer fit on GPU (the reason it was
restored in #3052); the `full` mode added in #3234 keeps FP32 masters,
moments, and gradients in host RAM, covering that memory pressure
instead. Gone with it: the `CPUOffloadPolicy` selection in `setup_fsdp`,
CPU-side model init in `setup_model`/`load_dcp_from_hf`,
`_move_buffers_to_cuda`, and the fsdp leg of the Gloo special case.

Changes:
- `ModelConfig.offload: Literal["none", "optimizer", "full"] =
"optimizer"` replaces the three fields.
`OptimizerInBackwardOffloadConfig` (and with it `numa_bind`) and its
bool-normalizing `BeforeValidator` are gone.
- Validators in `TrainerConfig` and `SFTConfig`:
- full offload accepts only AdamW or SignSGD and disables clipping, now
reading `offload == "full"`;
- the `Muon optimizer does not support FSDP CPU offload` validators are
deleted with the mode.
- Runtime:
- `setup_optimizer(..., offload=...)` replaces `cpu_offload` +
`full_offload_config`, and its "both enabled" check is gone.
- `FullCPUOffloadOptimizer` drops its unused `offload_config` argument.
- `setup_full_cpu_optimizer_offload()` takes no arguments and always
binds.
- `model.py`: FSDP always uses the default `OffloadPolicy()`; CPU-side
model init in `setup_model`/`load_dcp_from_hf` and
`_move_buffers_to_cuda` are gone.
- Tomls: `glm-4.5-air/swe-budget.toml` and
`ci/integration/reverse-text-sft/full-offload-resume.toml` → `offload =
"full"`; `glm-5.3/sft/h200/16k-12-node.toml` → `offload = "none"`;
`glm-5.3/sft/h200/base.toml` → `offload = "optimizer"`. Also updated
`docs/scaling.md`, the `deepseek-v4-flash/sft.toml` comment, and
`skills/training/start-run/SKILL.md`, which documented the removed
fields.

Breaking: the old keys now fail with `extra_forbidden`, and `offload =
"fsdp"` fails the `Literal`. There is no shim.

Interaction with #3849 (one trainer-common config base): #3849 moves the
full-offload and Muon/FSDP validators from `TrainerConfig`/`SFTConfig`
onto `BaseTrainerConfig`. This PR edits the full-offload validator's
condition and deletes the Muon/FSDP one, so the conflict is textual
only: keep #3849's single copy of the full-offload validators with
`self.model.offload == "full"` and drop its Muon/FSDP copy. Whichever
lands second takes a small rebase.

Other open PRs that set or read the old keys need a rebase:
- tomls: #3883, #3879, #3766, #3765, #3729, #3629, #3627, #3616, #3544
- code: #3885 (`optim_cpu_offload`), #3739 (`full_offload` validators),
#3724, #3719, #3699, #3610, #3487 (`fsdp_cpu_offload` / `enable_gloo`)

Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/train/test_cpu_adam.py tests/unit/train/test_state_offload.py
-m "not gpu"`: 336 passed, 1 skipped (Qwen3-VL snapshot not cached on
this host), 4 deselected (GPU; this host has no GPU). The existing
offload config tests are updated to the new field. `test_load_configs`
covers the 4 edited tomls.
- `cli(TrainerConfig|SFTConfig, ...)`: `--model.offload full|none` and
the default (`optimizer`) resolve as expected; `optim_cpu_offload` and
`offload = "fsdp"` are rejected.
- `import prime_rl.trainer.rl.train, prime_rl.trainer.sft.train` works.
- `ruff check` and `ruff format --check` on the changed Python files:
clean.
- Not run: GPU or multi-node training with `offload = "full"`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking TOML/API surface touches distributed training memory paths
(FSDP offload, optimizer-in-backward, Gloo); behavior should match prior
modes when mapped correctly, but mis-migrated configs will fail at parse
time.
> 
> **Overview**
> **Breaking config change:** `model.fsdp_cpu_offload`,
`model.optim_cpu_offload`, and `model.full_offload` are replaced by a
single **`model.offload`** setting (`"optimizer"` default, or `"full"`,
`"fsdp"`, `"none"`). RL and SFT share the same field; example TOMLs and
scaling docs are updated accordingly.
> 
> The mutual-exclusion validator between the old flags is removed
because only one mode can be expressed. **`[model.full_offload]` /
`numa_bind` is dropped** — `"full"` always runs NUMA binding and CPU
optimizer thread setup via parameterless
`setup_full_cpu_optimizer_offload()`. Runtime paths (`setup_optimizer`,
FSDP CPU offload in `model.py`, Gloo when offload is `"full"` or
`"fsdp"`) key off the new enum; `FullCPUOffloadOptimizer` no longer
takes an offload config object.
> 
> Default training behavior is unchanged: optimizer-state CPU offload
remains the default (`"optimizer"`). Old TOML keys are not aliased and
should fail validation.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
35da73ad2f1a73533595a979a971b0cdd8d6e63f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: sami jaghouar <sami.jaghouar@gmail.com>
2026-10-10 15:39:30 -07:00
faresobeidandGitHub 41a8ed0190 feat(configs): one weight wait timeout, default 3600 s (#3980)
## What
- `weight_broadcast.timeout` default goes from 1200 s to 3600 s
(`configs/shared.py`).
- It now also bounds the orchestrator's wait for the trainer's startup
broadcast. `orchestrator.ckpt.wait_for_weights_timeout` and the
hardcoded `STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200` fallback are removed.
Configs that set the old field fail validation (`extra="forbid"`); no
in-repo config sets it.
- The `[weight_broadcast]` blocks in five recipes only repeated `type =
"nccl"` (already the `rl` default when inference is managed and LoRA is
off) and `timeout = 3600`. They are removed: glm-4.5-air
swe/swe-budget/search/terminal and nemotron-3-super swe. glm-5.3 keeps
its `timeout = 12000`.
- Orchestrator `ckpt` and `resume` docstrings: `resume` had two
docstrings and `ckpt` had none. The stray one now documents `ckpt`.

## Why
- Every large multi-node recipe raises the timeout: 3600 s in five
recipes, 12000 s in glm-5.3.
- Measured startups come close to 1200 s or pass it. GLM-4.5-Air TP8
cold start takes 465-623 s. GLM-5.3 and DeepSeek-V4 inference startup
with cudagraph capture took about 16 min.
- vLLM's own engine-ready timeout is already 4200 s
(`VLLM_ENGINE_READY_TIMEOUT_S`).
- The startup wait and the per-step waits had two knobs with the same
1200 s default. The startup one was under `ckpt`, but it applies without
`ckpt` too.
- Trade-off: a consumer that dies is detected after 60 min instead of
20.

## Overlap
- #3652 (mikasenghaas, draft) reformats the `wait_timeout = ...` line
that this PR removes. Whichever lands second has a one-line conflict.
- Rebased over #3983, which removed the neighbouring orchestrator
`ckpt.keep_last`/`keep_interval` fields. The orchestrator
`CheckpointConfig` now has only `interval`.

## Test plan
- Rebased onto origin/main 32c48f5d9. `pytest tests/unit/orchestrator
tests/unit/test_configs.py -m "not gpu"`: 335 passed. `test_configs`
validates every TOML under `configs/` and `examples/`.
- `ruff check` and `ruff format --check` on the changed files: clean.
- Resolved `RLConfig` of the 5 edited recipes, main vs this branch:
identical (apart from the checkout path in `template_path`).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes orchestrator startup behavior and timeout defaults for
trainer–inference weight sync; mis-tuned timeouts could delay failure
detection (up to 60 min) or still timeout on very slow large-model
startups.
> 
> **Overview**
> **Unifies weight-broadcast timing** so one knob
(`weight_broadcast.timeout`) covers both the trainer handshake and the
orchestrator’s wait for the trainer’s **startup** broadcast. The default
rises from **1200 s to 3600 s**, and docs note raising it for large
models on slow filesystems.
> 
> **Removes** `orchestrator.ckpt.wait_for_weights_timeout` and the
orchestrator’s `STARTUP_WEIGHT_WAIT_TIMEOUT_S` fallback; startup sync
now uses `config.weight_broadcast.timeout` in `sync_startup`.
**Orchestrator config** docstrings are fixed so `ckpt` is documented on
the right field.
> 
> **Five example/advanced recipes** drop redundant `[weight_broadcast]`
blocks that only repeated NCCL type and `timeout = 3600` (now defaults).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e318f1cb0b10a8a5507520f2c6b1176f9fbd0813. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:34:47 +01:00
faresobeidandGitHub 9cde4d74f5 fix(slurm): stop crashed multi-node RL jobs idling for an hour (#3979)
Multi-node RL jobs that crash currently sit idle for an hour.

On any non-zero exit (crash, OOM, SIGTERM, wall-time),
`multi_node_rl.sbatch.j2` ran an unconditional `sleep {{
cleanup_grace_period }}` (default 3600 s, #2670) before tearing down.
The sleep keeps the task alive so `--kill-on-bad-exit` does not reap
trainers that are mid-checkpoint. But it waits the full hour even when
no checkpoint is being written, so a crashed N-node job idles for 1 h.

Now the node waits only while the newest `checkpoints/step_*/trainer`
has no DCP `.metadata` yet, i.e. a trainer save is still in flight. It
polls every 10 s, with `cleanup_grace_period` as the cap, and tears down
as soon as that save finishes or there is none. Runs without `[ckpt]`
tear down immediately. The checkpoint dir follows `ckpt.output_dir` when
it is set. The default stays 3600 s; it is now only an upper bound.

Limitation: if the crash happens right before a save starts (step dir
not created yet), we no longer wait for that save. Only that save is
lost; the previous checkpoint is intact.

**Interaction with #3875 (requeue + step watchdog):** before this
change, every requeue of a crashed multi-node RL job first waited the
full grace period. Now it waits only for an in-flight checkpoint.
`.metadata` is the same completeness marker that #3906 uses for "latest
complete checkpoint". The SFT and inference templates do not use
`cleanup_grace_period` and are unchanged.

Test plan (all run):
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed.
- `rl @ examples/advanced/glm-4.5-air/swe.toml --dry-run`: the rendered
sbatch has the wait loop with the run's `checkpoints/` path and passes
`bash -n`. With `--no-ckpt` the loop is not rendered.
- Ran the rendered teardown snippet in bash against a temp checkpoint
dir:
  - empty dir: no wait;
  - newest step complete: no wait;
  - newest step in flight: waits until the cap;
  - older incomplete step but newest complete: no wait;
  - in-flight save that completes after 1 s: waits ~1 s.
- `ruff check` and `ruff format --check` on the changed Python files.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes multi-node job teardown timing and checkpoint detection logic;
incorrect polling could tear down early or delay allocation release, but
scope is limited to SLURM RL launcher scripts.
> 
> **Overview**
> Multi-node SLURM RL jobs no longer **sleep the full
`cleanup_grace_period` (default 1h) on every failure**. Teardown after a
non-zero exit now waits only while an **in-flight trainer checkpoint**
is detected.
> 
> The `multi_node_rl.sbatch.j2` teardown block is gated on both
`cleanup_grace_period` and a rendered **`ckpt_dir`** (from
`get_ckpt_dir` when `[ckpt]` is enabled). Instead of a fixed `sleep`, it
polls every 10s: if the newest `step_*/trainer` directory lacks DCP
**`.metadata`**, it keeps the task alive (preserving
`--kill-on-bad-exit` behavior for peer trainers); otherwise it tears
down immediately. **`cleanup_grace_period` is documented as an upper
bound**; runs without checkpoints skip the wait entirely.
> 
> `write_slurm_script` in `rl.py` passes `ckpt_dir` into the multi-node
template renders.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8168264718f38f6e2e9636ea7bc7098e91743ba3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:31:54 +01:00
faresobeidandGitHub 32c48f5d9a chore(configs)!: rename tasks_per_minute to dispatch_per_minute (#3991)
## What

Renames `tasks_per_minute` to `dispatch_per_minute` on `orchestrator`,
the `eval` entrypoint and the SFT online `[eval]` block. This uses the
same name and wording as #3652.

The old name was wrong. The dispatcher takes one rate-limiter token per
**episode** it starts (`Dispatcher.acquire`, called once per scheduled
episode), not one per task. With `group_size = 8`, `tasks_per_minute =
80` started only 10 tasks per minute. The docstrings now say what is
counted: at most N episodes start per minute, and a group counts
`group_size` times.

Breaking: configs that set `tasks_per_minute` now fail validation
(`extra="forbid"`). No shipped config, doc, test or skill sets it or
mentions it.

## Overlap
#3652 (draft, orchestrator as hook-wired components) makes the same
rename. This PR lands it on its own and does not depend on that
refactor.

## Test plan
- `pytest tests/unit/orchestrator tests/unit/eval
tests/unit/test_configs.py -m "not gpu"`: 357 passed.
- `ruff check` and `ruff format --check` on the changed files.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Breaking config field rename only; runtime rate limiting behavior is
unchanged aside from clearer documentation.
> 
> **Overview**
> **Breaking rename:** `tasks_per_minute` → `dispatch_per_minute` on
orchestrator config, eval/SFT online eval config (`ServedEvalConfig`),
and everywhere it is passed into `Dispatcher` (orchestrator + eval
runner).
> 
> The limit semantics are unchanged in code (still `AsyncLimiter` with
one token per scheduled episode in `Dispatcher.acquire`), but the name
and docstrings now match behavior: the cap is **episodes started per
minute**, and a rollout group with `group_size` N consumes N tokens.
Configs that still use `tasks_per_minute` will fail validation under
`extra="forbid"`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0436304d5e40baed76abfadaa5b989048e818b6a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:29:40 +01:00
faresobeidandGitHub 8b2eb329e1 chore(trainer)!: remove the model.index_cache override (#3984)
Removes `model.index_cache` (`IndexCacheConfig.topk_freq` and
`.topk_pattern`). The trainer still turns on IndexShare from the model's
own `indexer_types` schedule (`src/prime_rl/trainer/model.py`), as
before.

Why: the override changes the trainer only. No inference-side config
matches it, so setting it makes the trainer pick different top-k indices
than vLLM unless the user also passes the same vLLM `hf_overrides` by
hand. The setting appears in no config, example or test. The HF-level
`use_index_cache` / `index_topk_freq` / `index_topk_pattern` attributes
on `GlmMoeDsaConfig` stay, so a checkpoint's own `config.json` still
drives them.

Breaking: `[trainer.model.index_cache]` / `[model.index_cache]` now
fails validation.

Overlap with open PRs:
- #3833 rewrites the same `index_cache` lines in `model.py`
(`set_model_options(model_config, "index_cache", ...)`). Whichever lands
second drops or rebases that block; the conflict is small.
- #3879 is based on that code too.
- #3616 already leaves `trainer.model.index_cache` unset for the reason
above: a trainer frequency override replaces the checkpoint schedule and
requests weights the checkpoint does not have.

Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed.
- `pytest tests/unit/utils/test_weights.py` (includes
`GlmMoeDsaForCausalLM`): 7 passed.
- `ruff check` and `ruff format --check` on the changed Python files:
clean.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking config validation for anyone using `index_cache`, and it
changes sparse-attention index scheduling to follow the checkpoint
only—important for trainer/inference logprob alignment on DSA models.
> 
> **Overview**
> **Removes the trainer-only `[trainer.model.index_cache]` override**
(`topk_freq` / `topk_pattern`). Configs that still set it will fail
validation.
> 
> IndexShare for GLM-5.2-style DSA models is unchanged in behavior: when
the checkpoint’s `indexer_types` includes `"shared"` layers, the trainer
still sets `use_index_cache` on the HF config and logs the full/shared
layer counts. It no longer applies manual `index_topk_freq` /
`index_topk_pattern` or clears `indexer_types`, which could diverge from
vLLM rollouts.
> 
> Docs no longer mention manually overriding the schedule via
`[trainer.model.index_cache]`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bf75c92edd9982a776bff29601c1e8c4519aebeb. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:22:14 +01:00
faresobeidandGitHub be89bbdaa1 fix(inference): keep the routed-experts dtype vLLM picks from the model config (#3965)
vLLM 0.31's routed-experts capturer already returns uint8 or uint16,
chosen from the model's expert count (`uint8 if num_experts <= 256 else
uint16`). `serialize_routed_experts` cast every request back to uint8
whenever its ids happened to be below 256. On a >256-expert model
(NemotronH Super/Ultra: 512 experts), a request whose ids all fall below
256 therefore came out uint8 while the others were uint16. Packing two
such samples into one micro batch trips `assert routed_experts.dtype ==
sample.routed_experts.dtype` in `orchestrator/batch.py`. Multi-turn
traces hit the same mix: verifiers concatenates the per-turn arrays, and
NumPy widens the result.

`serialize_routed_experts` now keeps the capturer's dtype and asserts
that it is uint8 or uint16. Every request of a model then has the same
dtype. Models with 256 or fewer experts are unchanged (uint8).

Tests: the existing serialize test now passes a uint16 array with ids
below 256 and checks that it stays uint16. `tests/unit/orchestrator`,
`tests/unit/inference`, `tests/unit/utils`, `tests/unit/test_configs.py`
pass with `-m "not gpu"`; `ruff check` and `ruff format --check` are
clean.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Narrow inference serialization fix; ≤256-expert models stay uint8, and
behavior only changes where mixed dtypes previously caused orchestrator
batch asserts.
> 
> **Overview**
> **Fixes inconsistent routed-experts dtypes** that broke micro-batch
packing on models with more than 256 experts (e.g. NemotronH 512).
> 
> `serialize_routed_experts` no longer re-encodes expert indices to the
smallest integer width based on per-request max values. It keeps the
array dtype from vLLM’s capturer (`uint8` or `uint16` from model expert
count), with assertions that the input is 3-D and one of those two
types. The serialized payload’s `"dtype"` field reflects that array
unchanged.
> 
> Unit tests now decode using `encoded["dtype"]` and assert a `uint16`
capture with all ids &lt; 256 stays `uint16` through serialize/decode.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e4a8e9ea05cb4e960192cdb7929e2c2566ca9734. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:18:00 +01:00
faresobeidandGitHub a1e0edbb4f fix(rl): inherit inference.deployment.gpus_per_node from deployment (#3978)
Under `rl`, `inference.deployment.gpus_per_node` was never set from
`deployment.gpus_per_node`. `InferenceConfig.auto_setup_disaggregated`
sizes `data_parallel_size_local`, `data_parallel_size` and
`api_server_count` from the nested copy, which defaults to 8. The
launcher, sbatch `dp_per_node` and weight-broadcast world size use the
top-level copy. So a P/D run on nodes that do not have 8 GPUs got
mismatched engine counts.

Example: `examples/advanced/glm-5.3/swe.toml` with
`deployment.gpus_per_node = 4` resolved to `data_parallel_size_local =
8` and `api_server_count = 8`, while the template launched 4 engines per
node.

Changes:
- `propagate_shared_fields` now fills
`inference.deployment.gpus_per_node` from `deployment.gpus_per_node`. As
with the other shared fields, setting both to different values raises.
- `RLConfig.validate_shared_configs` requires the two to be equal. This
catches a nested-only override that leaves the top-level value at its
default.

## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 335 passed (includes the new
`test_disaggregated_inference_inherits_deployment_gpus_per_node`)
- Parsed all 78 tomls under `configs/` and `examples/` with every config
class on main and on this branch: same results, none fail
- glm-5.3 `swe.toml` with `deployment.gpus_per_node = 4` now resolves
`inference.deployment.gpus_per_node = 4`, `dp_local = 4`,
`api_server_count = 4`
- `ruff check` / `ruff format --check` on the changed files

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Mis-sized inference parallelism and launcher/engine counts on
multi-node disaggregated runs; the change is narrow config propagation
plus validation with low blast radius beyond P/D sizing.
> 
> **Overview**
> Fixes a config bug where **`deployment.gpus_per_node`** at the RL top
level did not flow into **`inference.deployment.gpus_per_node`**, so
disaggregated P/D runs could size **`data_parallel_size_local`**,
**`api_server_count`**, and related fields from the nested default (8)
while SLURM/launchers used the top-level value (e.g. 4).
> 
> **`propagate_shared_fields`** now copies top-level
**`deployment.gpus_per_node`** into
**`inference.deployment.gpus_per_node`** (with the same
shared-vs-sub-config conflict rules as other shared fields).
**`RLConfig.validate_shared_configs`** additionally requires the two
values to match when inference is enabled, catching nested-only
overrides that disagree with the top-level deployment.
> 
> A unit test asserts inheritance and that mismatched nested/top-level
**`gpus_per_node`** fails validation.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
863bbf67298b456c48418c7326c820cc930ca203. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:14:07 +01:00
faresobeidandGitHub 8493109b7d chore(inference): drop typed vLLM fields that only repeat vLLM defaults (#3986)
Drops seven typed `[inference.vllm]` fields: `seed`, `enforce_eager`,
`dtype`, `trust_remote_code`, `enable_dbo`, `max_loras`,
`all2all_backend`, and the `All2AllBackend` alias. Each one only
repeated vLLM 0.31's own default, and nothing in prime-rl reads it.
`VllmConfig` is `extra="allow"`, so all seven keys still pass through to
vLLM unchanged. The `VllmConfig` docstring says to type only fields that
prime-rl types, defaults or reads back; these were none of those.

`all2all_backend` also suggested control it doesn't have for P/D: the
sbatch templates set the per-role backend in `ROLE_EXTRA`
(`inference.sbatch.j2:261,276`, `multi_node_rl.sbatch.j2:405,419`). That
stays as is.

Behavior: I resolved the vLLM serve args (`to_namespace` →
`make_arg_parser().parse_args`) on main and on this branch for the
default config and for `--vllm.enforce-eager`, `--vllm.enforce-eager
true`, `--vllm.max-loras 2`, `--vllm.dtype bfloat16`, `--vllm.seed 7`,
`--vllm.all2all-backend deepep_low_latency`, `--vllm.enable-dbo true`,
`--vllm.trust-remote-code true`, `@
examples/advanced/glm-5.3/infer/pd.toml`. All seven values are
identical. The nested rl form `--inference.vllm.enforce-eager
--inference.vllm.max-loras 2` also resolves to `True, 2`. `"enable_dbo"
= true` in `examples/advanced/glm-5.3/swe.toml` sits under
`prefill_vllm_overrides` and is unaffected.

Differences:
- `--no-vllm.enforce-eager` (the negated bool flag) only exists for
typed fields. Use `--vllm.enforce-eager false`. All four removed bools
default to False, so this only matters when undoing a toml that set one
to true.
- `dtype` now accepts every value vLLM accepts (for example `half`)
instead of prime-rl's narrower Literal.

`skills/configs/SKILL.md` used `enforce_eager = true` as its TOML
boolean example. It now uses `enable_prefix_caching = true`, which is
still typed, so `--no-flag` applies to it.

## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/test_parsers.py -m "not gpu"`: 489 passed
- Parsed all 78 tomls under `configs/` and `examples/` with every config
class on main and on this branch: same results
- The resolved-args comparison above
- `ruff check` / `ruff format --check` on the changed file
2026-10-10 19:07:27 +01:00
faresobeidandGitHub c9ce5f3d30 chore(configs): drop dead orchestrator fields (#3983) 2026-10-10 19:04:40 +01:00
faresobeidandGitHub 9570bccc28 chore(configs): drop recipe lines that repeat defaults (#3982)
## What
Drop recipe lines that only repeat what the config already resolves to.
The resolved configs do not change, except for `skip_optimizer` (see
below).
- `[weight_broadcast] type = "nccl"`: `rl` already picks NCCL when
inference is managed and LoRA is off. Removed from minimax-m2.5 swe,
intellect-3.1 rl, and qwen3-30b-a3b swe/math. The block stays in
examples/extra/dynamo/rl.toml (no managed inference, so the default
there is filesystem) and in glm-5.3 (it also sets port and timeout).
- `ac.freq = 1` (the default) is removed from 8 recipes. The
`[*.model.ac]` table header stays, matching the GLM-4.5-Air recipes.
- `trainer.dist_timeout_seconds = 3600` / `dist_timeout_seconds = 3600`
(the default) is removed from 5 RL recipes and vlm/sft-moe.
- `inference.vllm.enable_return_routed_experts = true` is removed where
`trainer.enable_router_replay = true` already sets it (glm-4.5-air ×4,
nemotron-3-super).
- `[trainer.ckpt] skip_optimizer = true` is removed from glm-4.5-air
swe-budget/search/terminal and nemotron-3-super swe.
  - It only affects loading: on resume, it drops the AdamW/Muon state.
- It came from the #2862/#2915 ablation configs. None of these recipes
warm-starts from another run's checkpoint. They train from the HF model
and resume their own checkpoints, which include optimizer state.
- configs/ci/integration/reverse-text-sft/full-offload-resume.toml keeps
it on purpose: it tests that path.
- docs/scaling.md: the `fused_lm_head_token_chunk_size` default is 8192
(since #3302), not 1024.

## Not touched
- `fused_lm_head_token_chunk_size = 1024` pins (7 recipes) and `attn =
"flash_attention_3"` pins (10). Should they stay as memory/hardware
choices?
- `[ac_offloading] max_inflight_activations` lines (a separate PR
removes the field).
- The `[weight_broadcast]` blocks of the GLM-4.5-Air and nemotron
recipes (handled in the weight_broadcast.timeout PR, to avoid a
conflict).

## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed (validates every TOML under configs/ and examples/).
- Resolved configs of all 14 edited recipes, main vs this branch
(RLConfig/SFTConfig `model_dump`):
- identical, except `trainer.ckpt.skip_optimizer` True → False in the 4
recipes above;
- the checkout path in `template_path` also differs (main checkout vs
this worktree), which is not a recipe change.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Mostly documentation and deduplication; the only resolved-config
change is `skip_optimizer` false on four recipes that resume with full
optimizer state, which matches their intended training flow.
> 
> **Overview**
> Trims RL/SFT example and advanced recipe TOMLs by deleting settings
that already match framework defaults, so recipes only spell out
non-default choices.
> 
> Removed redundant **`[weight_broadcast] type = "nccl"`**,
**`trainer.model.ac` `freq = 1`**, **`dist_timeout_seconds = 3600`**,
and **`inference.vllm.enable_return_routed_experts`** where NCCL
broadcast, AC frequency, dist timeout, and routed-expert return are
implied (e.g. managed inference + **`enable_router_replay`**). Dropped
**`[trainer.ckpt] skip_optimizer = true`** from four GLM-4.5-Air and
Nemotron SWE/search/terminal recipes so resume loads optimizer state
from their own checkpoints instead of discarding it.
> 
> **`docs/scaling.md`** now documents
**`fused_lm_head_token_chunk_size`** default **8192** (was incorrectly
**1024**). Explicit pins like **`fused_lm_head_token_chunk_size =
1024`** in memory-tight recipes are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c87c43defc655e83c39559736ca874740327d266. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 18:38:11 +01:00
faresobeidandGitHub c5406f8d09 perf(examples): use cudnn_flashmla DSA backend in GLM-5.3 RL example (#3968)
Sets `dsa_backend = "cudnn_flashmla"` for the trainer in the GLM-5.3 RL
example (`examples/advanced/glm-5.3/swe.toml`). The SFT example already
uses it (#3829); the RL example still ran the TileLang forward and
backward.

Measured on 1x8 H200 with the trainer settings of `swe.toml` (131k seq,
cp 4, ep 8, fp8 + `deepgemm_fp8`, full AC + offload, compile). Random
init, 8 layers (3 dense + 5 MoE), fake data, 2 micro-batches per dp
rank, balanced routing:

| `dsa_backend` | step 2 / 3 | sparse attn fwd per call | sparse attn
bwd per call |
|---|---|---|---|
| `tilelang` | 16.6 s / 15.5 s | 35 ms | 190 ms |
| `cudnn_flashmla` | 12.8 s / 12.1 s | 12 ms | 53 ms |

- Entropy and mismatch KL are identical to 4 decimals.
- With a 4-layer run (5.7 s), one MoE layer costs 1.6 s instead of 2.07
s. Extrapolated to 78 layers at this shape: ~124 s vs ~160 s per step
(-22%).
- Kernel check at the CP shape (8k local queries vs 32k keys, cp rank 0
and 3, top-k 2048, sentinel slots): out / dq / dkv relative error vs
TileLang 5e-4 to 9e-4, LSE 7e-8.
- Needs the `flash-mla` extra, which the README's `uv sync --all-extras`
installs.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single example TOML knob with no production code changes; requires the
optional flash-mla dependency for the new backend.
> 
> **Overview**
> Aligns the GLM-5.3 RL example trainer config with the SFT example by
setting **`dsa_backend = "cudnn_flashmla"`** in
`examples/advanced/glm-5.3/swe.toml`, so sparse DSA attention uses the
cuDNN/FlashMLA path instead of the default TileLang forward/backward.
> 
> This is a **performance-only** example change for long-context RL
training (131k seq, CP/EP, fp8 MoE); behavior should match TileLang
within measured numerical tolerance when the `flash-mla` extra is
installed.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e2135c38262af40b51d866026cdfa3a83fb7c7b4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 18:29:07 +01:00
Florian BrandandGitHub 9b39a10949 refactor(sampling): share parameter resolution across eval and training (#3782)
Use Verifiers' shared sampling config and resolution path for evaluation
and rollout dispatch. Parameter names, provider options, source
defaults, and agent overrides follow the same rules in native Verifiers
and Prime-RL. Training retains its strict config for the distribution
the trainer replays.

## Sampling flow

```mermaid
flowchart TD
    T["Train source and agent config<br/>TrainSamplingConfig and replay bounds"] --> V["Validate live-policy sampling<br/>Source owns the distribution"]
    V --> S["Shared Verifiers SamplingConfig<br/>Normalize aliases and extra_body"]
    V --> A["AgentConfig.sampling<br/>Sparse overrides across config transport"]
    E["Eval source and agent config"] --> S
    E --> A
    S --> R["RunRequest to env server"]
    A --> M["Verifiers resolve_agent<br/>Shared merge_defaults"]
    R --> M
    M --> P["Provider request<br/>Non-null resolved parameters"]
    M --> C["Trace<br/>Complete resolved sampling"]
```

## Shared parameters

Verifiers normalizes `max_tokens` / `max_completion_tokens` and flattens
`extra_body` before merging each override layer. Source values replace
group defaults; agent values replace inherited sampling. An explicit
null clears an inherited parameter.

Within one sampling block, top-level values take precedence over
`extra_body`. A typed training `top_k=20`, or the automatic replay bound
of `512`, therefore takes precedence over `extra_body.top_k=-1`. With no
typed `top_k`, the disabled sentinel remains effective.

Prime-RL carries `vf.SamplingConfig` through dispatch and converts
`TrainSamplingConfig` once. Source defaults and agent overrides use
Verifiers' `merge_defaults`; duplicate eval schemas and
sampling-dictionary converters are removed. Request-specific cache salts
are copied onto the shared config.

Unresolved agent overrides remain sparse across env-server config
boundaries. `resolve_agent` materializes the sampling used for
generation, and traces record the complete resolved config. Provider
dialects and the renderer client omit nulls when constructing requests.

## Training ownership

Live-policy sources validate their sampling when the config loads.
Unsupported source parameters, including `frequency_penalty`, are
rejected before generation.

The source owns the distribution replayed by the trainer. Every agent in
a live-policy source, including non-trainable roles, may override only
`max_tokens`, `reasoning_effort`, and `chat_template_kwargs`.
Distribution parameters belong on the source, even when an agent would
repeat the same value. Policy logprobs remain enabled. Evaluation and
frozen-model sources retain general agent overrides.

This removes the post-rollout sampling comparison from `TrainSink`.

## Dependency

Pins Verifiers `2cb0a6d`, the merged commit for [Verifiers
#2762](https://github.com/PrimeIntellect-ai/verifiers/pull/2762), for
shared sampling normalization and resolution. This includes merging
per-call judge sampling overrides before constructing SDK requests,
preserving unrelated configured provider parameters. The lockfile
updates `prime-tunnel` to `0.1.14` to meet the merged dependency's
minimum.

Before publishing packages outside this source checkout, release that
Verifiers change and raise the `verifiers` minimum in both `prime-rl`
and `prime-rl-configs`. The current `>=0.3.2.dev158` package constraints
do not guarantee these semantics.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how sampling is resolved and validated for all rollouts;
mis-merged configs or rejected agent overrides could break existing
TOMLs, though unit tests cover the main inheritance and policy rules.
> 
> **Overview**
> **Unifies rollout sampling** on Verifiers' shared `SamplingConfig` and
merge rules instead of Prime-RL–specific eval schemas and
`to_sampling_args()` dict builders.
> 
> Eval sources and group defaults now use `vf.SamplingConfig`;
train/eval env wrappers carry a typed `SamplingConfig` through to the
env server (including per-request `cache_salt` via `model_copy`). Policy
train sources get **load-time validation**: the source owns distribution
parameters (`temperature`, `top_p`, etc.), while agents may only
override `max_tokens`, `reasoning_effort`, and
`chat_template_kwargs`—frozen-model and eval paths stay permissive.
`TrainSink` reads temperature from `env.config.sampling` instead of a
resolved args dict.
> 
> **Docs** describe alias normalization (`max_tokens` /
`max_completion_tokens`), `extra_body` merging, and live-policy override
limits. **Tests** cover inherited sampling merges and policy sampling
rejection cases. Lockfile bumps `prime-tunnel` to `0.1.14`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
671a5aa9857a39a4d44fa7902f1c89021b8fd380. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 00:30:12 -07:00
Florian BrandandGitHub f7e8ab6456 fix(eval): resume rollouts by task content and selected occurrence (#3808) 2026-10-09 15:47:46 -07:00
84e94bf05c perf(orchestrator): poll for new weight versions every 0.1s instead of 1s (#3952)
## Summary
- `WeightWatcher.poll_interval` default: 1.0s → 0.1s
- `WeightReceiver.wait_published` sleep: 0.2s → 0.1s

## Why
The trainer blocks in `WeightSender._wait_for_receiver_ready` until the
orchestrator notices `.sender_ready`. With a 1s poll, that adds 0–1s
(~0.5s avg) of idle trainer time on every step. NVIDIA flagged this
while benchmarking the ModelExpress broadcast (#3890).

A poll is one `glob("step_*")` on the broadcast dir (≤2 entries thanks
to `_clean`) plus a few `exists()` calls, so 10Hz is negligible.
Correctness relies on the marker handshake + `update_lock`, not on the
poll timing.

Caveat: these are sync FS calls on the orchestrator event loop. On a
very slow shared FS, that might show up in `EventLoopLagMonitor`. If it
does, we can move them to `asyncio.to_thread`.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Timing-only tuning on poll loops; no change to weight handshake logic,
though more frequent sync FS calls could add event-loop lag on very slow
filesystems.
> 
> **Overview**
> **Faster weight-version discovery** so the trainer spends less time
blocked waiting for the orchestrator to see `.sender_ready`.
> 
> The orchestrator `WeightWatcher` default `poll_interval` drops from
**1.0s to 0.1s**, cutting typical idle wait on each broadcast handshake
from ~0.5s toward ~0.05s. `WeightReceiver.wait_published` uses the same
**0.1s** sleep (was 0.2s) while waiting for the sender marker.
> 
> Handshake correctness is unchanged (markers + `update_lock`); cost is
slightly more frequent lightweight FS checks on the orchestrator event
loop.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5c825d0f126e16885eae77f4f6ebc2ddf306de59. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:25:55 -07:00
IanandGitHub 37b48a996e security(ci): pin BuildKit builder to v0.33.1 and rotate registry buildcache (CVE-2026-93318) (#3889)
## security(ci): pin BuildKit builder to v0.33.1 and rotate the GHCR
registry buildcache (CVE-2026-93318)

### What changed (rebased onto current main)
`.github/workflows/build_image.yaml`:
1. **Builder pin** — `docker/setup-buildx-action@v4` now sets
`driver-opts: image=moby/buildkit:v0.33.1`. Without it the job starts
the rolling `moby/buildkit:buildx-stable-1` tag, and because these are
persistent self-hosted runners (`image-builder`,
`image-builder-arm-2204`), the builder version is not even guaranteed to
follow the tag — a stale local image can keep a pre-patch builder alive
indefinitely. The pin makes the builder version deterministic.
2. **Registry cache rotation** — both shared cache refs rotated:
- `:dependency-buildcache-<suffix>` ->
`:dependency-buildcache-v2-<suffix>`
- `:application-buildcache-<suffix>` ->
`:application-buildcache-v2-<suffix>`

### Why rotation (evidence)
- The registry-backed cache was introduced in d8f3d0101 (2026-08-16,
#3279) and has been written on nearly every run since — including all
runs before the patch was published.
- BuildKit v0.33.1 (the CVE fix) was released **2026-09-30T17:08Z**; the
rolling `moby/buildkit:buildx-stable-1` tag only moved to that digest at
**2026-09-30T17:32Z**. Every cache write before that timestamp came from
a builder older than v0.33.1, on runners that may also hold stale local
images.
- Per the CVE-2026-93318 playbook: stop importing a shared cache that
pre-fix builders wrote, rebuild from trusted inputs, and pin the patched
builder so every future write is attributable to a fixed version.

### Expected cost
The first run per platform suffix after merge does a cold build of the
dependency layer + application layer (no cache import). The old
`*-buildcache-*` tags can be deleted from the `prime-rl` GHCR package as
cleanup — they are cache-only refs, never deployed.

### Out of scope / notes
- `docker-push.yaml` (old Docker Hub publisher) no longer exists on main
— nothing to pin there.
- No GHA-scope (`type=gha`) caches exist in this repo's workflows
(verified by grep), so no Actions-cache cleanup applies.
- Build image runs are frequent and mostly manual dispatch; this PR
should merge before the next `main` image build.

### Security review requested
- Cache invalidation: confirm the `*-v2-*` refs fully replace the old
buildcache lineage.
- Published-image provenance: GHCR `prime-rl` images built before
2026-09-30T17:32Z were produced by a pre-patch builder; assess whether a
clean rebuild of the current release tags is warranted.
- No applicable CODEOWNERS entry exists in this repo; CI/build owner
please review.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> CI-only security remediation with intentional cache busting (slower
first builds); no application runtime code changes, but GHCR images
built before the fix may need a separate provenance/rebuild decision.
> 
> **Overview**
> Remediates **CVE-2026-93318** in the GHCR image build workflow by
making the BuildKit builder version fixed and breaking reuse of
artifacts produced before the patch.
> 
> **BuildKit pin:** `docker/setup-buildx-action` now sets `driver-opts`
to `moby/buildkit:v0.33.1` (digest-pinned) so self-hosted
`image-builder` runners do not keep serving a stale local
`buildx-stable-1` builder.
> 
> **Cache and deps lineage:** Shared registry cache refs move to
`dependency-buildcache-v2-*` and `application-buildcache-v2-*` so layers
written by pre-v0.33.1 builders are not imported. Dependency base tags
gain a `-v2-` epoch (`deps-${key}-v2-${suffix}`) so existing
`deps-${key}` images are not reused as the runtime base when only
Dockerfile/lock inputs are unchanged.
> 
> The first build per platform after merge is expected to be cold (no
old cache import); published runtime tags are unchanged—only CI
remediation naming and builder configuration.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0310e6d89608d9d34fd0c1a4c0e9a5c6ba5261bf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-09 08:22:03 -07:00
Konstantin DunasandGitHub 88faa6dc22 feat(sft): warn when renderer is not prefix stable (#3953)
Warn when SFT constructs a renderer that does not guarantee prefix
stability. The warning explains that each conversation is rendered once
into one training sample, that N assistant turns are not expanded into N
samples, and that earlier reasoning may be omitted by the template.
Cached renderers warn only on construction; stable renderers stay quiet.
Custom renderers without the capability are conservatively treated as
unknown.

Pin `deps/renderers` to merged main revision `41f9290`, which includes
https://github.com/PrimeIntellect-ai/renderers/pull/184. It provides the
resolved capability and the manual, opt-in witness audit. Sample
construction is unchanged.

Validation: all **73 SFT dataset tests passed**, including
stable/unstable renderer selection and cache-warning behavior. Prime-rl
unit-test CI passed on the preceding revision; this update changes only
the renderer gitlink to the merged revision. Dependency requirements are
unchanged apart from renderer Python >=3.11, compatible with prime-rl
Python 3.12. The manually invoked renderer audit passes **59 tests** and
is excluded from normal CI discovery.
2026-10-09 11:53:24 +02:00
Florian BrandandGitHub 083b8fe9ec ci: reduce GPU usage and parallelize test setup (#3944)
Reduce CI time and GPU usage by selecting the relevant test suites for
each PR, moving hosted eval to CPU, and running independent setup steps
in parallel.

- Select GPU unit tests, SFT, RL, and hosted eval from changed paths
before allocating runners. Shared runtime and dependency changes retain
broad coverage; pushes to `main` and manual runs execute the full suite.
- Keep RL/SFT coverage for checkpoint converters, dashboard code, and
the shared dashboard smoke helper.
- Run `gsm8k_eval` on `ubuntu-latest` because it uses hosted inference.
- Run public submodule initialization and `uv` setup concurrently, then
wait for both before installing dependencies. Keep dependency caching
keyed on `uv.lock` and the five-job limit on GPU integration tests.
- Cancel superseded CPU and style runs on the same PR.
- Give the GPU workflow read-only contents access and the test selector
PR read access.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Path-based GPU job gating can skip integration coverage on PRs if
filters miss a dependency; full suite still runs on main and manual
dispatch.
> 
> **Overview**
> **GPU CI now picks which jobs to run from the PR diff**, instead of
always running the full GPU unit + integration matrix on every non-draft
PR. A new **Select tests** job uses path filters for unit, SFT, RL, and
eval; pushes to `main` and `workflow_dispatch` still run everything.
RL/SFT integration scenarios are built dynamically (still capped at
`max-parallel: 5` on `prime-rl-2xh200`).
> 
> **`gsm8k_eval` is split out** into a dedicated job on `ubuntu-latest`
(hosted inference), so it no longer consumes GPU runners. Integration
pytest invocations use `tests/integration/test_${{ matrix.test }}.py`
from the dynamic matrix rather than per-row `pytest_args`.
> 
> **Setup and queueing tweaks:** submodule init and `setup-uv` run in
parallel in CPU/GPU jobs; CPU and style workflows cancel in-progress
runs per PR; GPU workflow gets `workflow_dispatch`, read-only
`contents`, and PR-scoped concurrency cancel. `docs/development.md`
documents the new triggers and runner split.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
20da35f30de85b2b18cf82e29598846a1228ca12. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 17:17:55 -07:00
853208336e feat(sft): pad to a multiple of cp and remove fp8 indexer dynamism (#3948)
SFT now pads packed rows only to a multiple of cp, as RL does, instead
of to `seq_len`. The fp8 indexer drops its autotuning, which
re-benchmarked configs on every new row length and made unpadded rows
slower than padded ones on DeepSeek-V4 (#3726).

- The indexer pads keys to a multiple of 16 and runs one fixed config,
within 1.05x of the best.
- Every rank, including RL on DeepSeek-V4 and GLM-5, runs that config
with bitwise-identical top-k.
- SFT and RL throughput count trained tokens, not `seq_len` × rows or
the first row × count.
- The SFT `seq_len % (2 * cp)` check is gone: CP only needs `seq_len %
cp`, which configs enforce.

Same samples per arm, time summed over steps 5 to 20, one H200 node:

| Workload | Padding on main | main | This PR | Speedup |
|---|---|---|---|---|
| DeepSeek-V4-Flash 6L, scaleswe, 256K rows, cp 8 | 19.8% | 61.2 s |
38.2 s | 1.60x |
| GLM-4.5-Air 8L, math, 131K rows, dp 4 cp 2 | 7.3% | 223.8 s | 200.1 s
| 1.12x |
| GLM-4.5-Air 8L, scaleswe, 131K rows, dp 4 cp 2 | 19.7% | 701.0 s |
623.0 s | 1.13x |

On DeepSeek-V4, the 1.60x exceeds the 1.25x that removing 19.8% of
tokens predicts because two effects multiply: main's token-0 pads crowd
onto the same experts, and the padding itself costs compute. The
DeepSeek-V4 ablation section below separates the two.

On GLM with scaleswe, removing 19.7% of the tokens would predict about
1.25x, but it measured 1.13x. Its 4 data-parallel ranks now get rows of
different lengths, and each step likely waits for the rank with the
longest rows.

Loss matches main to within 1e-3 per step. This overlaps
https://github.com/PrimeIntellect-ai/prime-rl/pull/3932 in
`CatDataset._finalize_pack`. Harness:
[`benchmarks/scripts/sft_pad_to_cp/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/0ed0e78b33e8533d7fd1e0d603759dc2ab50e5dd/benchmarks/scripts/sft_pad_to_cp)
(removed before merge).

## DeepSeek-V4 ablation

Each row changes one thing on the DeepSeek-V4 workload above, to
separate the cost of the padding length, of token-0 pads crowding onto
the same experts, and of indexer re-tuning:

| Arm | Time | Speedup vs main |
|---|---|---|
| main: pads every row to `seq_len` with token 0 | 61.2 s | 1.00x |
| main, but pads with the row's own tokens (#3932) | 49.6 s | 1.23x |
| pads only to a multiple of cp, indexer still autotuned | 73.6 s |
0.83x |
| pads only to a multiple of cp, fixed-config indexer (this PR) | 38.2 s
| **1.60x** |

## Alternatives considered

- Bucketing the autotune key on `next_power_of_2(S_q)` reached 1.47x on
DeepSeek-V4. Each bucket kept its first row's config (up to 1.44x slower
later), short rows paid extra tunes, and each rank still tuned on its
own rows, so ranks could run different kernels.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 19:13:22 -04:00
Konstantin DunasandGitHub 31281d88f9 feat(sft): pass per-message loss selection to renderers (#3950)
SFT samples can contain prefilled assistant turns that must remain in
context without becoming training targets. Read an optional
`message_loss_mask` dataset column and pass it directly to
`renderers.build_training_sample`; for a user/assistant/user/assistant
conversation, `[0, 0, 0, 1]` trains only the final assistant turn.

The renderer owns token attribution and mask validation, including GLM's
assistant-generated closing markers. prime-rl performs no owner walking
or template-specific mask reconstruction. Selection only removes
existing loss targets and preserves input/target token IDs. Missing or
null masks preserve normal supervision; fully masked samples follow the
existing skip behavior.

`data.columns.message_loss_mask` supports renamed columns. For
prompt/completion rows, the mask covers their concatenated message list.
This API reads a separate column; datasets with inline
`messages[].trainable_mask` need conversion before use.

Pins `deps/renderers` to upstream main commit
`e3ace557545274385abb30435975c134c7c2429d`, which merges
https://github.com/PrimeIntellect-ai/renderers/pull/181. The renderer
dependency is now merged.

Validation:
- Signed pin update `838828713` points to the merged renderer commit.
Its Git tree is identical to the previously tested renderer head; no
source changes accompany the pin update.
- The following tests and checks passed on signed implementation commit
`7e0800051`:
- 73 SFT dataset tests passed, including real GLM-5 and Qwen3
tokenizers, both dataset layouts, custom column names,
missing/null/all-enabled masks, excluded initial/final turns, fully
masked samples, and invalid values/lengths.
- Ruff 0.13.0 lint and formatting checks passed for the changed Python
files; `git diff --check` passed.
- CPU tests ran in an isolated Python 3.12 environment with Transformers
5.6.2 and PyTorch 2.14.1. No GPU training run performed.
- Commit signature verified locally.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes which tokens receive loss during SFT when datasets supply
masks; incorrect masks could silently train the wrong turns, though
behavior is opt-in and heavily tested against real renderers.
> 
> **Overview**
> Adds **optional per-message SFT loss selection** via a dataset
`message_loss_mask` column (0/1 or booleans, one entry per resolved
message—including prompt+completion rows). The trainer forwards the
column to `build_training_sample` so renderers drop supervision on
excluded turns **without changing token IDs** (e.g. `[0, 0, 0, 1]` keeps
context but trains only the last assistant reply). Missing/null masks
behave as today; all-zero masks still skip the sample.
> 
> **Config and docs:** `SFTColumnsConfig.message_loss_mask` defaults to
`"message_loss_mask"` and can be remapped (e.g. `"selection"`); dataset
init errors if a remap points at a missing column. `docs/training.md`
documents the format and semantics.
> 
> **Tests:** Coverage for GLM-5 and Qwen3, both dataset layouts, custom
column names, partial masks, fully masked rows, and invalid mask
values/lengths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
838828713529afa49a57cf441071f946ec195cdf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-09 00:36:22 +02:00
samsjaandGitHub bc250759bf fix(ci): uv cache on h200 runners, drop phantom 4xa6000 job, cap fan-out (#3909)
## Why

Since **Sep 2** the `4xa6000` runner has been offline. Since then,
`benchmark_regression` has queued on a dead label on **every single GPU
Tests run**, hit GitHub's 24h self-hosted queue timeout, and failed the
workflow. There has not been one green GPU Tests run in over a month, so
the per-PR GPU check is permanently red and real regressions hide in the
noise. Measured over Sep 29-Oct 6: all 28 completed runs failed at
exactly 1440 +/- 1 min, and 20+ phantom `benchmark_regression` jobs were
sitting in the queue at any time.

## What changes

1. **uv cache on the GPU jobs** (`enable-cache: true`, keyed on
`uv.lock`, mirroring `cpu_tests.yaml`) — each h200 pod currently
re-resolves and re-downloads the full dependency set from PyPI on every
job.
2. **`benchmark_regression` removed from the PR matrix.** It cannot
simply move to `prime-rl-2xh200`: the test unconditionally runs a 1-GPU
**and** a 4-GPU benchmark (a 2-GPU pod cannot host the latter), and it
asserts against A6000-captured baselines with a 15% tolerance (H200
results would blow through it). It belongs on benchmark hardware
(`benchmarks.yaml`) or behind a 4-GPU scale set when one exists — happy
to re-add once either exists.
3. **`max-parallel: 5` on the integration matrix** — a concrete per-PR
ceiling:
- 9 integration jobs + unit-tests = **6 h200 pods peak per PR**, 2 waves
- at current job durations (~10-15 min each) a PR finishes in ~25-35 min
- with 2-3 PRs in flight: <= ~18 pods steady-state; the ARC scale set
`maxRunners` (suggest 16-20) is the complementary global cap
4. `docs/development.md` CI table updated to match (also adds
`gsm8k_eval`, which was missing, and the current runner).

## Result

GPU Tests runs **only** on the `prime-rl-2xh200` scale set, and every PR
gets a real green or red within ~30-60 min instead of a guaranteed 24h
failure.

## Not in this PR (follow-ups)

- Bake git/uv into the CI image to kill the per-job `apt-get install
git`
- PVC-backed `~/.cache/uv` mount to avoid per-pod cache archive
downloads
- Nightly Tests still target a `research-cluster` runner that does not
exist — needs the same treatment or a cron disable

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> CI workflow and documentation only; no runtime or auth changes.
Benchmark regression no longer runs on every PR until re-homed to
suitable hardware.
> 
> **Overview**
> **GPU Tests** is adjusted so PR runs can finish on live hardware
instead of timing out on a dead runner label.
> 
> Both GPU jobs now enable **uv dependency caching** keyed on `uv.lock`
(same pattern as `cpu_tests.yaml`), cutting repeated PyPI
resolves/downloads on each H200 pod. The integration matrix **drops
`benchmark_regression`** (it targeted offline `4xa6000` hardware and
cannot run meaningfully on 2×H200), and adds **`max-parallel: 5`** so at
most five integration jobs run at once per PR. **`docs/development.md`**
updates the CI table to list the current integration scenarios
(`gsm8k_eval` included), `max-parallel`, and **`prime-rl-2xh200`** as
the runner.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8207cc05d9a731a4c5d7c561354284f1a79792d4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 15:18:58 -07:00
1983d8dfed chore: bump verifiers to main (#3934)
## Summary

- Bump `deps/verifiers` from `1fa2bbc42` to main `da75527ca`. This pulls
in the Harbor adapter changes from PrimeIntellect-ai/verifiers#2808:
  - Honor reward-file precedence and select named rewards explicitly.
  - Resolve separate verifier definitions by Harbor image precedence.
  - Align the adapter with Harbor 0.24.0 and reject multi-step tasks.
- Move the `harbor` upload cutoff in `[tool.uv.exclude-newer-package]`
from 2026-08-11 to 2026-10-08, which matches `deps/verifiers`. verifiers
now pins `harbor==0.24.0`, which the old cutoff excluded.
- Relock: `harbor` 0.21.0 → 0.24.0, and `semver` 3.1.0 is new.

`deps/prime-envs` is already at its main head (`89dcc7ffc`). The current
verifiers pin already has the network notice
(PrimeIntellect-ai/verifiers#2769), so this bump supersedes #3734.

## Verification

- `uv sync --all-extras --all-packages --locked` succeeds.
- `uv run pytest -m "not gpu" tests/unit`: 663 passed.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Lockfile and uv policy changes only; risk is mainly behavioral shifts
from Harbor 0.24.0 and updated verifiers Harbor adapter usage in
eval/training paths.
> 
> **Overview**
> Updates dependency resolution so **`harbor` 0.24.0** (via the
`verifiers[harbor]` pin) can install under uv’s rolling
**exclude-newer** policy by moving the bounded **`harbor` cutoff** from
`2026-08-11` to **`2026-10-08`** in `pyproject.toml`, mirrored in
`uv.lock`.
> 
> The lockfile refresh bumps **`harbor` 0.21.0 → 0.24.0**, records new
transitive deps **`jsonschema`** and **`semver`**, and aligns the
verifiers harbor extra specifier to **`==0.24.0`**. This pairs with the
verifiers main bump described in the PR (Harbor adapter alignment and
reward/verifier precedence behavior), even though those code changes
live outside this diff.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
69e62c1fc116896ce99c79dbfc454959c748cb47. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:18:33 -07:00
26681fc6c7 fix(models): pass contiguous router-replay experts to compiled layers (#3947)
On torch 2.13.0 with compile and router replay, some MoE layers silently
replay layer 0's routing instead of their own from the second training
step on. This PR calls `.contiguous()` on each layer's routed-experts
slice, which removes the bug.

Each decoder layer `l` receives `routed_experts[:, :, l]`, a view into
one shared int32 tensor with axes (batch, sequence, layer, expert slot).
When `top_k` is not a multiple of 4, that view starts at a byte offset
that is not 16-byte aligned for some layers (odd layers on DeepSeek V4,
`top_k = 6`).

Inductor copies a misaligned input into a fresh aligned buffer, which
starts at offset 0. Once automatic dynamic shapes recompile the layer,
AOTAutograd mistakenly applies that offset 0 to the original shared
tensor when it rebuilds the layer's routed-experts output. Offset 0 of
the shared tensor holds layer 0's experts. A contiguous slice is its own
aligned tensor, so Inductor never makes the copy.

- Applied to the eight models that passed the raw view. `glm4_moe`
already called `.contiguous()`.
- Fixed upstream in pytorch/pytorch#191002 (torch 2.14.0 and 2.14.1, no
2.13.x release). The copy is cheap, so it can stay after an upgrade.
- Models with `top_k = 8` (Qwen3-30B-A3B, Trinity-Mini, GLM-4.5-Air)
were unaffected.

DeepSeek V4 Flash RL probe (compile on, router replay on, lr 0),
mismatch KL mean, lower is better:

| trainer | step 1 | steps 2-10 |
|---|---|---|
| compiled, strided slice (main) | 0.0008 | 0.022-0.11 |
| compiled, contiguous slice (this PR) | 0.0009 | 0.0007-0.0025 |

With compile off, the same probe spans 0.0008-0.0032 over steps 1-10.

## Verification

A standalone torch reproducer was added in
66641b0b0b31da76082edaadd70b4f601b13a53a and removed again at the end of
this branch, so main never carries it. Run it on one CUDA device from
that commit with `TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 uv run python
tools/repro_misaligned_replay_alias.py`. In earlier runs it printed `BUG
REPRODUCED` on torch 2.13.0 and was clean on the 2.14.0.dev20260809 and
2.16.0.dev20261008 nightlies.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 17:03:55 -04:00
Florian BrandandGitHub 6b0906c900 fix(eval): preserve sibling trace verdicts when an episode fails (#3824) 2026-10-08 12:12:16 -07:00
JannikStandGitHub 5e963f027a fix(monitors): send online-eval metrics to the parent training run (#3941)
Hosted runs with online evals score real rewards but the run dashboard
shows no `eval` metric group (ENG-6573).

The dashboard's `eval` group is built from the run's own metric keys
(`eval/{env}/...`). The orchestrator's in-process evals reach it through
the train monitor, but when evals run in a process of their own (SFT
online evals) the metrics are dropped: `PrimeEvalMonitor.log_metrics`
was a deliberate no-op.

- `PrimeEvalMonitor` now attaches to the parent training run via
`$RUN_ID` and forwards each epoch's `eval/...` metrics there.
- The eval process never reports the parent run's status: the SDK's
atexit crash hook is unregistered and `finalize()` only drains the
queue. Without that, an eval process exiting while the trainer is still
going would mark the whole run failed.
- No parent attached without `$RUN_ID`, so a standalone `prime eval` is
unchanged.

Note the ticket proposes exposing `environmentshub/resolve` on the
platform's internal API instead. That's a separate gap: it silences the
`EnvironmentResolutionError` warning and would create per-epoch
Evaluation records, but it does not produce the `eval` metric group, and
it needs four more `/evaluations` routes that the internal surface also
lacks.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how eval processes interact with the parent platform run
(metrics + SDK lifecycle hooks); mistakes could misreport run status or
drop metrics, but behavior is gated on $RUN_ID and explicitly avoids
finishing the parent.
> 
> **Overview**
> Fixes hosted runs where **SFT online evals** compute rewards but the
run dashboard never shows the **`eval`** metric group (keys like
`eval/{env}/...`).
> 
> **`PrimeEvalMonitor`** now attaches a metrics-only handle to the
parent training run when **`$RUN_ID`** is set, and **`log_metrics`**
forwards sanitized epoch aggregates there instead of being a no-op.
Standalone **`prime eval`** (no **`$RUN_ID`**) is unchanged.
> 
> Lifecycle is guarded so the eval subprocess cannot poison the parent
run: the SDK **atexit** hook on the attached parent is **unregistered**,
and **`finalize()`** only **`flush`**es the upload queue—never finishes
or reports status on the trainer’s run.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
892035628173119b14a591b2975a5b6176f4c357. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 19:44:51 +02:00
72834b3b52 feat(trainer): prepare RL micro batches on a background thread pool (#3917)
This is an alternative to #3907. The RL trainer decoded and preprocessed
each micro batch's images on the main thread right before its forward
pass, leaving the GPU idle. `WorkerPool`, a small ordered thread pool
configured by `data.num_workers` like torch's DataLoader, now prepares
micro batches ahead of the loop through a single `prepare_micro_batch`
hook.

- `num_workers` defaults to 0, which prepares on the main thread as
before, and one thread gives the full speedup. Here it counts threads,
unlike SFT's DataLoader processes.
- An earlier version used forked worker processes. They pickle data
through `/dev/shm`, risk copy-on-write memory, and were 0.6 s/step
slower than a thread.
- Pinned memory and `non_blocking` copies are left to a follow-up that
first removes the per-micro-step CUDA syncs.

Qwen3.5-9B trainer-only on 4 H200s, mock micro batches of 1024 px JPEGs
(about 1 s of CPU decoding each), median s/step, lower is better
(benchmark code added in
[`331fc83fe`](https://github.com/PrimeIntellect-ai/prime-rl/commit/331fc83fed9ff8b6fb435df5207a07e37b08c0e5)
and removed in the next commit):

| Arm | main thread | prepared ahead | time saved |
|---|---|---|---|
| this PR, 1 thread | 24.98 | 18.86 | 24.5% |
| this PR, 1 thread, optimizer CPU offload | 26.56 | 20.24 | 23.8% |
| earlier process version, 2 workers | 24.79 | 19.02 | 23.3% |
| #3907 (thread with pinned memory) | 24.98 | 18.63 | 25.4% |

Every arm matches the main-thread baseline bit for bit in loss and grad
norm. Host memory stays flat over 30 steps, 0.3 GiB above the baseline
for the prefetched images.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 12:15:19 -04:00
faresobeidandGitHub 0bcb868e91 fix(configs): size the single-node NCCL transfer group after the DP fill (#3841)
## Summary
Two bugs in how `rl` sets `weight_broadcast.inference_world_size` on
main:

1. **World size computed before the DP fill.**
`auto_setup_weight_broadcast` set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
before `auto_setup_deployment` fills the single-node inference GPUs with
DP ranks. With `num_infer_gpus = 4` and `data_parallel_size` unset, the
NCCL group was sized for 1 inference worker while vLLM started 4, so the
first weight update cannot form the group.
2. **A single-node SLURM job cannot re-parse its `rl.json`** (since
#3788). The resolved `rl.json` always contains
`weight_broadcast.inference_world_size` (default 1), and #3788's guard
rejects any config that sets it. So `rl @ rl.json` in the single-node
sbatch fails validation for every NCCL config.

## Fix
- Single-node: set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
right after the DP fill in `auto_setup_deployment` (non-filesystem
only). Multi-node already sets it there.
- `auto_setup_weight_broadcast` copies `weight_broadcast` to the trainer
and orchestrator without touching the world size, and the guard is
removed. The top-level value is now only passed through: `rl` overwrites
it whenever it knows the inference size.

This also fixes what #3924 fixes.

## Behavior change
Yes (bug fixes).
- Resolved configs for every TOML in `configs/`, `examples/`, `k8s/`
that parses as `RLConfig` (41 of 78) are identical before and after,
except `trainer`/`orchestrator.weight_broadcast.inference_world_size`
goes from 1 to 4 in `examples/basic/hendrycks-sanity/rl.toml` and
`configs/ci/nightly/multimodal_color_codeword.toml` (4 infer GPUs, DP
unset).
- Re-parsing the dumped config (as the single-node sbatch does) fails on
main for all 18 single-node NCCL configs and passes for all of them
here.
- With `inference = None` and NCCL against external servers, a user-set
`weight_broadcast.inference_world_size` is now passed through instead of
rejected.

## Checks
- `pytest tests/unit/test_configs.py tests/unit/orchestrator -m "not
gpu"`: 298 passed
- `ruff check`, `ruff format --check`: clean
- New test `test_single_node_nccl_resolved_json_roundtrips`: dumps a
single-node NCCL config like `rl`'s `write_config`, re-parses it, and
checks it is equal. It fails on main with the guard error.
- `rl @ examples/basic/reverse-text/rl.toml --deployment.num-infer-gpus
2 --slurm.partition all --dry-run`, then re-parse the written `rl.json`:
fails on main, passes here (world size 2).
- GPU (one node): running: `rl @ examples/basic/hendrycks-sanity/rl.toml
--max-steps 3` on main and on this branch, plus the rendered single-node
sbatch for reverse-text (2 infer GPUs) run end to end.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes when NCCL weight broadcast groups are sized for single-node
runs; mis-sizing previously caused deadlocks or init failures during
weight updates.
> 
> **Overview**
> Fixes incorrect **NCCL/NIXL** `inference_world_size` on single-node RL
runs when vLLM **data parallel size** is inferred from `num_infer_gpus`
rather than set explicitly.
> 
> **`auto_setup_weight_broadcast`** no longer derives
`trainer`/`orchestrator.weight_broadcast.inference_world_size` from
`data_parallel_size × tensor_parallel_size` (which ran before DP was
filled) and no longer rejects a user-set `inference_world_size`.
**`auto_setup_deployment`** (single-node) now sets
`inference_world_size` to `dp × tensor_parallel_size` immediately after
the DP/`api_server_count` fill, so the in-memory transfer group matches
every inference GPU that joins NCCL.
> 
> Unit tests assert the resolved world size (2 infer GPUs → size 2) and
that a dumped `rl.json` round-trips unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f5553f5c5dd2f91aa11003338ef13e285a6c9ee6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 12:56:47 +01:00
faresobeidandGitHub 746d8a96d0 chore(models): drop rms_norm re-export, move fp8 quantizer into its tool (#3858)
## Summary
- Delete `trainer/models/layers/rms_norm.py`. It only re-exported
`RMSNorm`/`RMSNormConfig` from `layers/norms.py`, and nothing imported
it.
- Move `quantize_to_fp8_blockwise` from `trainer/models/fp8.py` into
`tools/convert_bf16_to_fp8.py`, its only user.
`tools/convert_dcp_to_fp8.py` still imports it through
`convert_bf16_to_fp8`. While moving it, the 9-line zero-pad block
becomes `F.pad(weight, (0, pad_cols, 0, pad_rows)).contiguous()`; the
output is bitwise identical to the old function (bf16/fp16/fp32, padded
and unpadded shapes, contiguous and transposed inputs).

## Behavior change
None.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dead-code removal and relocating a tool-only quantizer; no trainer
inference or training path changes.
> 
> **Overview**
> Removes dead trainer surface area and keeps FP8 checkpoint conversion
self-contained in the tooling layer.
> 
> **`trainer/models/layers/rms_norm.py`** is deleted (it only
re-exported `RMSNorm` / `RMSNormConfig` with no importers).
**`trainer/models/fp8.py`** is removed and
**`quantize_to_fp8_blockwise`** now lives in
**`tools/convert_bf16_to_fp8.py`**, which was its only consumer;
**`convert_dcp_to_fp8.py`** continues to pull quantization helpers from
that script. Padding inside the moved helper uses **`F.pad`** instead of
manual zero-fill, with the same blockwise e4m3 logic otherwise
unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c35ca75057037c6d98f0080bdffae8efd24e2f85. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 12:46:12 +01:00
faresobeidandGitHub 765bbeba7b fix(launch): default TRITON_CACHE_DIR to a node-local path (#3877)
Processes that share `~/.triton` on a shared filesystem can hang or
crash (seen with Nemotron-H, where many ranks compile the Mamba Triton
kernels at once; reproduced below with Qwen3.5 and GLM-4.5-Air).

This PR adds `TRITON_CACHE_DIR = /tmp/triton-<uid>` to
`DEFAULT_COMMON_ENV_VARS`. It is per-user because `/tmp` is shared by
all users on a node. Like the other launcher defaults, it reaches every
launched component: the local `rl`/`sft`/`inference` launchers (also
used by the single-node sbatch scripts) and the trainer, orchestrator,
inference (incl. prefill/decode), and online-eval env blocks of the
multi-node and inference sbatch scripts. `[env_vars]` (or a component's
`env_vars`) overrides it; a value exported in the shell or `.env` does
not. It also removes the `TRITON_CACHE_DIR` overrides from six example
configs (glm-4.5-air swe/swe-budget/search/terminal, glm-5.3 and
qwen3-30b-a3b sft h200 base): they pointed every user at the same `/tmp`
dir and are now covered by the default. `docs/scaling.md` says so in one
paragraph.

vLLM 0.31's own default: when `TRITON_CACHE_DIR` is unset, its Inductor
adaptor points it at
`$VLLM_CACHE_ROOT/torch_compile_cache/<hash>/rank_<i>_<j>/triton_cache`
(`~/.cache/vllm` by default, so usually on the shared home). That only
covers Triton kernels compiled after torch.compile initializes, and it
is still on the shared filesystem. vLLM keeps a `TRITON_CACHE_DIR` that
is already set, so with this PR vLLM uses `/tmp/triton-<uid>` too.

### Measured cost (one H200 node, vLLM 0.31 venv, Triton 3.7.1)

Each run starts from a fresh process with the same config. "Ready" is
launch → first trainer step logged (Qwen) or launch → `/health` OK
(GLM). For GLM, the first generated token came 1.3–2 s after ready in
every run that came up. Inductor's cache dir was emptied before each run
except the warm node-local one.

| Triton cache | Qwen3.5-4B SFT, 8 GPUs, compiled blocks (step 1 time) |
GLM-4.5-Air vLLM TP8 |
|---|---|---|
| shared, cold (today on a new cluster / after a Triton or torch update)
| **failed 2/2**: `FileNotFoundError` on a cache file that another rank
was writing (`causal_conv1d_fwd_kernel.llir`, `l2norm_fwd_kernel.ptx`) |
**failed 2/2**: 4 of 8 ranks hit `FileNotFoundError` in the cache during
Inductor autotune, the other 4 hung in a collective until killed (1st
run). The 2nd run crashed instead of hanging. |
| shared, warm | not measured cleanly (see below) | 344 s |
| node-local, cold (this PR, first job on a node) | 233 s (step 1: 91
s), 164 kernels compiled | 375 s with vLLM's compile cache warm (106
kernels); 465 s if vLLM's cache is also cold (87 kernels) |
| node-local, warm (this PR, later jobs on the same node) | 138 s (step
1: 8.3 s) | 344 s |

- A cold node-local cache costs about **95 s per node for Qwen3.5** (FLA
+ Inductor kernels) and about **31 s for GLM-4.5-Air inference** when
vLLM's own compile cache is warm. Warm node-local and warm shared take
the same time.
- The rest of the GLM startup does not depend on the Triton cache: about
3.5 min of Python imports and process spawn from the shared venv, 13 s
to load weights.
- vLLM: `VLLM_CACHE_ROOT` (`~/.cache/vllm`, shared home) holds vLLM's
AOT/Inductor artifacts. With this PR it stays shared. On a new node,
vLLM loads those artifacts (`torch.compile` 0.6 s instead of 30 s), and
the Triton binaries are compiled into `/tmp/triton-<uid>` (106 kernels,
+31 s). `TORCHINDUCTOR_CACHE_DIR` (default `/tmp/torchinductor_<user>`,
already node-local) stayed empty in these runs. Inductor's Triton
kernels go to `TRITON_CACHE_DIR`.
- A crash on the shared cache can also break later starts. After the
first failed GLM run, the shared vLLM cache only had AOT artifacts from
the 4 ranks that got through. On the next start, those 4 ranks loaded
the artifacts and the other 4 recompiled, so the ranks diverged and hung
(Triton cache warm-ish, 60 kernels). For the same reason the Qwen
"shared, warm" run started from a partial cache and failed again. The
warm-shared GLM number comes from a shared dir seeded with a complete
cache.

### Possible middle ground (not implemented)

Because the cold cost is above 1 min per node for FLA-heavy models, a
run could seed the node-local cache from a shared read-only copy at job
start. For example, on each node before the components start:
`[ -n "$TRITON_CACHE_SEED" ] && cp -rn "$TRITON_CACHE_SEED"/.
"$TRITON_CACHE_DIR"/`
The seed would be a warm `/tmp/triton-<uid>` copied once to the shared
FS. Triton keys entries by source, compiler, and GPU, so stale entries
are never reused, only skipped. Only reads hit the shared FS, so the
concurrent-write race does not occur. I left it out to keep this PR
minimal.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Launch-time env default only; behavior is overridable via config and
fixes known multi-rank Triton cache races, with a one-time cold-compile
cost on each node.
> 
> **Overview**
> **Sets a global launcher default** so every trainer, orchestrator, and
inference process gets `TRITON_CACHE_DIR=/tmp/triton-<uid>` via
`DEFAULT_COMMON_ENV_VARS`, avoiding concurrent Triton kernel writes
under `~/.triton` on a shared filesystem (hangs / `FileNotFoundError`
under multi-rank compile).
> 
> **Removes redundant `[env_vars]` overrides** from six GLM-4.5-Air RL
and GLM-5.3 / Qwen3-30B SFT example configs that previously pinned
Triton cache paths under `/tmp`; those runs now inherit the per-user
node-local default (still overridable through config `env_vars`).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f21642046ea59cab0b9460863560b4df825f29c0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
2026-10-08 11:59:17 +01:00
faresobeidandGitHub fec3acd8e7 chore(orchestrator): fold GenerationSource into TrainEnv (#3838)
## Summary
Fold `GenerationSource` into `TrainEnv`, its only owner. Move
`connect_frozen_client` from `algo/base.py` to `clients.py`, so `algo`
no longer imports `clients` lazily. Give `TrainEnv` `setup()`/`aclose()`
so orchestrator setup and teardown no longer reach into its parts.

## What changed
- `orchestrator/generation_source.py` is deleted. `TrainEnv` (`envs.py`)
now holds `clients`, `renderer_config`, `connected` (the frozen source
clients it connected) and `uses_live_policy`. Dropping `logprobs` for
frozen sources happens in `TrainEnv.__init__`.
- `TrainEnv.setup()` connects the frozen generation source and runs
`algorithm.setup()` concurrently. `TrainEnv.aclose()` closes `connected`
and `algorithm.connected`, never the shared policy clients.
- `connect_frozen_client` is a plain function in `clients.py`, next to
`check_inference_ready`. `algo/base.py` imports it at module level. It
is no longer re-exported from `prime_rl.orchestrator.algo`.
- `dispatcher.py` reads the `TrainEnv` directly at the four former
`generation_source` call sites. `orchestrator.py` calls `env.setup()`
and `env.aclose()`.
- `docs/algorithms.md` and the `algo/__init__.py` docstrings refer to
`TrainEnv`.

## Behavior change
None.

## Checks run
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 297 passed.
- `ruff check`, `ruff format --check`: clean.
- Equivalence script, old `GenerationSource` (`origin/main`) vs new
`TrainEnv`, on 4 configs: policy, policy with `top_p=0.9`, sft with a
frozen `sampling.source`, opd with a frozen teacher. Identical
`sampling_args`, `requires_sampling_masks` and `uses_live_policy`. After
`setup()`, the same generation clients (policy object, or the frozen
endpoint with the same train client config) and the same algorithm
clients. Teardown closes the same clients.
- GPU smoke on one node (vLLM 0.31): reverse-text RL (15 steps), sft
with a frozen `sampling.source` (5 steps), opd with a frozen teacher (5
steps). All three ran to "Training finished" and exited 0.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Internal orchestrator refactor with stated behavioral equivalence and
no changes to training algorithms or dispatch semantics beyond
indirection.
> 
> **Overview**
> **Refactors train rollout sourcing** by deleting `GenerationSource`
and moving its responsibilities onto `TrainEnv`: inference `clients`,
live-vs-frozen policy detection (`uses_live_policy`), sampling-arg
tweaks (e.g. dropping `logprobs` for frozen endpoints), and frozen-pool
connection in `setup()`.
> 
> `TrainEnv.setup()` now connects frozen `sampling.source` endpoints and
runs `algorithm.setup()` together; `TrainEnv.aclose()` closes only
env-owned clients (`connected` + algorithm pools), not the shared policy
pool. The orchestrator and dispatcher call these surfaces instead of
reaching into a nested `generation_source`.
> 
> `connect_frozen_client` moves from `algo/base.py` to `clients.py`
(next to `check_inference_ready`); it is no longer re-exported from
`prime_rl.orchestrator.algo`. Docs and package docstrings now describe
`TrainEnv` as owning the sampling half of the algorithm config.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e89ca1a663ae6ae808b05ff3326ce9ed63c9b467. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 11:52:10 +01:00
Florian BrandandGitHub adda4731fe fix(eval): salt inference caches only when policy weights change (#3825)
Apply a policy-version cache salt only when inference weights can change
during a run. Standalone evaluations and frozen-model requests omit the
training salt; live RL rollouts and online evaluation retain it so
caches distinguish policy versions.

## Before

The dispatcher added the policy version as `cache_salt` to every request
using the live policy source. Standalone evaluation used that same
source path, so fixed-weight evaluations received a training cache salt
even though no weight updates occurred. Frozen-model requests already
omitted it.

```mermaid
flowchart TD
    Standalone["Standalone evaluation with fixed weights"] --> Live["Live policy source"]
    Training["RL or online evaluation with changing weights"] --> Live
    Live --> Salt["Always add policy-version cache_salt"]
    Salt --> Request["Verifiers provider request"]
    Frozen["Frozen model source"] --> Plain["Omit training cache_salt"]
    Plain --> Request
```

## After

```mermaid
flowchart TD
    Request["Prime-RL dispatcher builds request sampling"] --> Mode{"Live policy source with changing weights?"}
    Mode -->|"Yes: RL or online evaluation"| Salt["Set cache_salt to policy version"]
    Mode -->|"No: standalone evaluation or frozen model"| Plain["Omit training cache_salt"]
    Salt --> Client["Verifiers client builds provider request"]
    Plain --> Client
    Client --> Provider["Inference provider"]
```

The dispatcher records whether policy weights can change. The standalone
evaluator disables version salting, SFT online evaluation enables it,
and RL orchestration keeps it enabled. The request decision also checks
whether the source uses the live policy.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Narrow behavior change to cache salting on eval paths; RL and online
eval keep prior salting via the default flag.
> 
> **Overview**
> Adds a **`policy_weights_change`** flag on `Dispatcher` so inference
**`cache_salt`** (policy version) is only attached when weights can
actually change during the run.
> 
> **Standalone eval** (`EvalConfig`) sets the flag to **false**, so
fixed-weight evaluation no longer invalidates prefix caches on every
training policy version. **SFT online eval** and **RL orchestration**
(default **true**) still salt live-sourced requests so caches stay
correct across weight updates.
> 
> The cache decision is now **`live_sourced and policy_weights_change`**
instead of salting all live policy paths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5a2d7d9652740106e63fee31a6e79da13816dae7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 01:52:39 -07:00
Florian BrandandGitHub a3f1f892c5 fix(eval): preserve empty outcomes and exclude zero-turn traces from training (#3809)
Keep successful empty environment outcomes in evaluation results. A
trace-less episode or clean zero-turn trace retains the verdict returned
by Verifiers, while training and curriculum logic exclude zero-turn
traces.

## Before

The dispatcher changed successful trace-less episodes into
`EmptyEpisode` failures. Clean, non-timeout zero-turn traces became
`EmptyTrajectory` failures, marking both the trace and episode
unsuccessful. Evaluation therefore recorded a failure even when the
environment had returned success, while training and curriculum filters
relied on those injected errors to exclude empty traces.

```mermaid
flowchart TD
    Env["Verifiers returns an empty successful outcome"] --> Dispatch["Prime-RL dispatcher"]
    Dispatch --> Episode["No traces: inject EmptyEpisode"]
    Dispatch --> Trace["Clean zero-turn trace: inject EmptyTrajectory"]
    Episode --> Failed["Rewrite outcome as failed"]
    Trace --> Failed
    Failed --> Eval["Evaluation records a failure"]
    Failed --> Training["Training and curriculum filter injected errors"]
```

## After

```mermaid
flowchart TD
    Env["Verifiers environment returns an episode"] --> Dispatch["Prime-RL dispatcher preserves empty outcome verdicts"]
    Dispatch --> Eval["Evaluation records and metrics"]
    Dispatch --> Filter["Training trace eligibility"]
    Filter --> Empty["Zero turns: no training sample"]
    Filter --> Sample["Eligible trace with sampled tokens: training sample"]
    Dispatch --> Curriculum["Curriculum ignores zero-turn traces and admits only trainable groups"]
```

Remove the synthetic `EmptyEpisode` and `EmptyTrajectory` errors.
`iter_trainable_traces()` filters empty traces alongside failed and
untrainable traces before advantages are assigned, so the advantage gate
needs no separate zero-turn check. Difficulty sampling also excludes
zero-turn traces. Empty groups finish without producing a trainer
payload, and mixed groups retain their eligible traces. Curriculum
admission also requires a trainable trace, so groups without training
samples cannot inflate admission metrics. Sampler observations of
completed turns are retained even when token metadata is unavailable.
Verifiers' no-agent validation and training timeout handling remain in
place.

[#3824](https://github.com/PrimeIntellect-ai/prime-rl/pull/3824) applies
the same ownership rule to partially failed episodes: preserve
environment results, then decide training eligibility explicitly.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes evaluation outcome recording and which rollouts feed
training/curriculum admission, which can shift eval metrics and training
batch composition without touching auth or data stores.
> 
> **Overview**
> Stops the dispatcher from **injecting** `EmptyEpisode` /
`EmptyTrajectory` errors on successful trace-less or zero-turn outcomes,
so **evaluation keeps Verifiers’ success verdict** instead of recording
synthetic failures.
> 
> Training and curriculum now **exclude zero-turn traces explicitly**:
`iter_trainable_traces()` skips `num_turns == 0`, difficulty-pool reward
updates require `num_turns > 0`, and curriculum admission requires
**both** passing gates **and** at least one trainable trace via
`iter_trainable_traces()`. Scored rollouts without token/advantage
metadata can still update sampler difficulty; groups with no trainable
samples no longer count as admitted.
> 
> Tests cover mixed groups with non-trainable traces, empty-only groups,
and reward-only observations for the sampler.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8582fb8c18e7cb4aa0dc7af58c6e0a4474bd7b40. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 01:51:52 -07:00
Florian BrandandGitHub e6acff78aa chore: align network prompt dependency pins (#3929) 2026-10-07 19:45:14 -07:00
131 changed files with 1825 additions and 1088 deletions
+20 -5
View File
@@ -192,6 +192,12 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
with:
# CVE-2026-93318: pin the BuildKit builder to the patched release so
# the version is deterministic on the self-hosted runners (otherwise
# the rolling moby/buildkit:buildx-stable-1 tag is used, and a
# persistent runner may keep a stale local copy of it).
driver-opts: image=moby/buildkit:v0.33.1@sha256:cec9f139f45e93c5c69c60f8b07cfad9f43f4ef6b6a6cd917527fea5ff2e3dea
- name: Set up uv
uses: astral-sh/setup-uv@v7
@@ -207,7 +213,12 @@ jobs:
run: |
set -euo pipefail
key=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py fingerprint .)
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-${SUFFIX}"
# deps-v2: remediation epoch for CVE-2026-93318 — the fingerprint
# hashes only Dockerfile/lock inputs, not the workflow or BuildKit
# version, so pre-fix deps-${key} images would otherwise be reused
# as the runtime base instead of being rebuilt by the pinned v0.33.1
# builder.
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-v2-${SUFFIX}"
digest=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py resolve "$image")
echo "image=${image}" >> "$GITHUB_OUTPUT"
echo "digest=${digest}" >> "$GITHUB_OUTPUT"
@@ -222,8 +233,10 @@ jobs:
file: ./Dockerfile.cuda
target: dependencies
outputs: type=image,push=true,compression=zstd,compression-level=3
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
# builders (cache writers since 2026-08-16) must not be re-imported.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: ${{ steps.dependency.outputs.image }}
@@ -240,8 +253,10 @@ jobs:
RENDERERS_PRETEND_VERSION=${{ steps.dependency.outputs.renderers }}
PYDANTIC_CONFIG_PRETEND_VERSION=${{ steps.dependency.outputs.pydantic_config }}
outputs: type=image,push=true,compression=zstd,compression-level=3
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
# builders (cache writers since 2026-08-16) must not be re-imported.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
+14 -9
View File
@@ -6,6 +6,10 @@ on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
unit-tests:
name: Unit tests
@@ -15,15 +19,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run tests
+156 -47
View File
@@ -5,20 +5,103 @@ on:
branches: [main]
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
changes:
name: Select tests
runs-on: ubuntu-latest
if: github.event_name != 'pull_request' || github.event.pull_request.draft == false
permissions:
pull-requests: read
outputs:
unit: ${{ github.event_name != 'pull_request' || steps.filter.outputs.unit == 'true' }}
integration: ${{ steps.matrix.outputs.tests }}
eval: ${{ github.event_name != 'pull_request' || steps.filter.outputs.eval == 'true' }}
steps:
- uses: dorny/paths-filter@v4
id: filter
if: github.event_name == 'pull_request'
with:
filters: |
unit:
- &runtime
- '.github/workflows/gpu_tests.yaml'
- '{pyproject.toml,uv.lock,.python-version,.gitmodules}'
- 'deps/**'
- 'packages/**/pyproject.toml'
- 'packages/prime-rl-configs/src/prime_rl/configs/{trainer,shared,__init__}.py'
- 'packages/prime-rl-configs/src/prime_rl/utils/**'
- 'src/prime_rl/*.py'
- 'src/prime_rl/{trainer,multimodal,transports,utils}/**'
- 'tests/{__init__.py,conftest.py,utils.py}'
- 'tests/integration/{__init__.py,conftest.py}'
- 'tests/unit/{train,inference}/**'
- 'src/prime_rl/inference/**'
sft:
- *runtime
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
- 'src/prime_rl/dashboard/**'
- 'tests/integration/dashboard_smoke.py'
- 'packages/prime-rl-configs/src/prime_rl/configs/{sft,eval,monitors}.py'
- 'src/prime_rl/entrypoints/{sft,dashboard}.py'
- 'src/prime_rl/monitors/**'
- 'src/prime_rl/eval/{online,runner}.py'
- 'tests/integration/test_reverse_text_sft{,_lora}.py'
- 'configs/ci/integration/reverse-text-sft{,-lora}/**'
rl:
- *runtime
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
- 'src/prime_rl/dashboard/**'
- 'tests/integration/dashboard_smoke.py'
- 'packages/prime-rl-configs/src/prime_rl/configs/{rl,orchestrator,inference,env_server,algorithm,eval,monitors}.py'
- 'src/prime_rl/entrypoints/{rl,trainer,inference,orchestrator,env_server,dashboard}.py'
- 'src/prime_rl/{inference,orchestrator,monitors}/**'
- 'src/prime_rl/eval/{online,runner}.py'
- 'tests/integration/test_reverse_text{,_lora,_moe,_rl_opd,_rl_sft}.py'
- 'tests/integration/test_alphabet_sort.py'
- 'configs/ci/integration/reverse-text{,-lora,-moe,-rl-opd,-rl-sft}/**'
- 'configs/ci/integration/alphabet_sort.toml'
eval:
- *runtime
- 'packages/prime-rl-configs/src/prime_rl/configs/{eval,orchestrator,inference,env_server,algorithm,monitors}.py'
- 'src/prime_rl/{eval,orchestrator,monitors}/**'
- 'src/prime_rl/entrypoints/{eval,env_server}.py'
- 'tests/integration/test_gsm8k_eval.py'
- 'configs/ci/integration/gsm8k-eval.toml'
- name: Build integration matrix
id: matrix
env:
# Main and manual runs retain the full suite.
RUN_ALL: ${{ github.event_name != 'pull_request' }}
SFT: ${{ steps.filter.outputs.sft || 'false' }}
RL: ${{ steps.filter.outputs.rl || 'false' }}
run: |
tests=$(jq -cn --argjson all "$RUN_ALL" --argjson sft "$SFT" --argjson rl "$RL" '[
if $all or $sft then "reverse_text_sft", "reverse_text_sft_lora" else empty end,
if $all or $rl then
"reverse_text", "reverse_text_rl_opd", "reverse_text_rl_sft",
"alphabet_sort", "reverse_text_lora", "reverse_text_moe"
else empty end
]')
echo "tests=$tests" >> "$GITHUB_OUTPUT"
unit-tests:
name: Unit tests
needs: changes
runs-on: prime-rl-2xh200
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
timeout-minutes: 45
if: github.event_name == 'push' || github.event.pull_request.draft == false
if: needs.changes.outputs.unit == 'true'
steps:
- name: Install Git
run: |
@@ -29,12 +112,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run unit tests
@@ -50,46 +137,20 @@ jobs:
integration-tests:
name: Integration tests (${{ matrix.test }})
runs-on: ${{ matrix.runner }}
needs: changes
runs-on: prime-rl-2xh200
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
timeout-minutes: 60
if: github.event_name == 'push' || github.event.pull_request.draft == false
if: needs.changes.outputs.integration != '[]'
strategy:
fail-fast: false
# Bound per-PR fan-out: at most 5 integration jobs at a time (plus unit-tests),
# i.e. 6 h200 pods per PR. Tune together with the ARC scale set maxRunners.
max-parallel: 5
matrix:
include:
- test: reverse_text_sft
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_sft.py"
- test: reverse_text_sft_lora
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
- test: reverse_text
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text.py"
- test: reverse_text_rl_opd
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
- test: reverse_text_rl_sft
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
- test: alphabet_sort
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_alphabet_sort.py"
- test: reverse_text_lora
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_lora.py"
- test: reverse_text_moe
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py"
- test: gsm8k_eval
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_gsm8k_eval.py"
test: ${{ fromJSON(needs.changes.outputs.integration) }}
steps:
- name: Install Git
run: |
@@ -100,12 +161,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run integration tests
@@ -120,7 +185,7 @@ jobs:
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
VLLM_WORKER_MULTIPROC_METHOD: spawn
run: uv run pytest -vvs ${{ matrix.pytest_args }}
run: uv run pytest -vvs tests/integration/test_${{ matrix.test }}.py
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v7
@@ -129,3 +194,47 @@ jobs:
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
eval-tests:
name: Integration tests (gsm8k_eval)
needs: changes
if: needs.changes.outputs.eval == 'true'
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
submodules: false
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run eval tests
env:
USERNAME_CI: CI_RUNNER
WANDB_MODE: offline
HF_TOKEN: ${{ secrets.HF_TOKEN }}
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
GITHUB_REF_NAME: ${{ github.ref_name }}
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
run: uv run pytest -vvs tests/integration/test_gsm8k_eval.py
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: gsm8k_eval-logs
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
+4
View File
@@ -9,6 +9,10 @@ on:
# This will trigger the workflow for pull requests to any branch
types: [opened, synchronize, reopened]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
ruff:
name: Ruff
+3 -8
View File
@@ -6,19 +6,14 @@
#
# 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 `full_offload = true` under `[model]`,
# which keeps the fp32 masters, moments and gradients in CPU RAM and needs `optim_cpu_offload =
# false` and `optim.max_norm = "None"` set alongside it; the lighter `optim_cpu_offload = true` is
# already the default here.
# 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.
#
# There is no `[ckpt]` block. The trainer saves unconditionally at the last step, and a 43-layer
# 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 -4
View File
@@ -6,9 +6,6 @@ level = "debug"
[model]
name = "PrimeIntellect/MiniMax-M2.5-bf16"
[weight_broadcast]
type = "nccl"
[deployment]
type = "multi_node"
num_train_nodes = 4
@@ -16,6 +13,7 @@ num_infer_nodes = 12
[slurm]
job_name = "swe-minimax"
partition = "all"
[ckpt]
interval = 100
@@ -35,7 +33,6 @@ fused_lm_head_token_chunk_size = 1024
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[trainer.optim]
type = "adamw"
@@ -22,10 +22,6 @@ num_infer_replicas = 4
project = "nemotron-3-super"
name = "nemotron-3-super-swe"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
@@ -36,7 +32,6 @@ keep_last = 1
name = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
@@ -54,9 +49,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "adamw"
@@ -110,4 +102,3 @@ max_model_len = 131072
tensor_parallel_size = 8
enable_prefix_caching = true
enable_expert_parallel = true
enable_return_routed_experts = true
@@ -24,8 +24,6 @@ group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.model.lora]
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -21,8 +21,6 @@ group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.model.lora]
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -9,8 +9,7 @@ step = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
optim_cpu_offload = false
full_offload = true
offload = "full"
[optim]
lr = 0.0
+1 -1
+1 -1
+1 -1
View File
@@ -100,7 +100,7 @@ Backend shape checks and token alignment apply only to the selected compute path
In RL runs, configure the same precision selection for rollouts. Inference module names can differ from the trainer's names, and inference precision is configured explicitly, not inferred from `apply_to`. Check the selected modules on both sides before comparing trainer and rollout logprobs.
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed.
### Expert Parallelism Backends
+4 -2
View File
@@ -139,7 +139,7 @@ algo.type = "echo"
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
At runtime, each env's `TrainEnv` (`prime_rl.orchestrator.envs`) resolves the `sampling.source` model into the inference pool used for train episodes, and its resolved config builds one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
@@ -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

+4
View File
@@ -173,6 +173,10 @@ env.agent.runtime.type = "subprocess"
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — holds defaults for its sources. Every field that a group and its sources both have is a default: `env`, `sampling`, `select` and `group_size`, plus `algo` on the train group and `interval` on the eval groups of a training run. Each source inherits the fields that its group sets. One rule applies to all of them: nested blocks merge key by key, a source's own values win, and a block whose `type` (e.g. of `algo`) differs from the group's is the source's alone.
Sampling parameters use Verifiers' shared normalization: `max_tokens` and `max_completion_tokens` name the same limit, and `extra_body` parameters merge like top-level parameters. Agent overrides apply after source defaults; an explicit null clears an inherited parameter. Resolved sampling is recorded on each trace.
For live-policy training, set distribution parameters (`temperature`, `top_p`, `top_k`) on the source's `sampling` block. Every agent in that source, including non-trainable roles, may override only `max_tokens`, `reasoning_effort`, and `chat_template_kwargs`. These rules are checked when loading the config; evaluation and frozen-model sources allow general agent sampling overrides.
```toml
[orchestrator.train]
group_size = 16
+1 -1
View File
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
| Workflow | Trigger | What runs | Where |
|---|---|---|---|
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | relevant changes in non-draft PRs; full suite on push to `main` or manual dispatch | `pytest tests/unit -m gpu`, plus RL/SFT integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_sft_lora`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `alphabet_sort`) with `max-parallel: 5`; separate hosted `gsm8k_eval` job | self-hosted `prime-rl-2xh200` k8s scale set (2xH200); `ubuntu-latest` for test selection and hosted eval |
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
+2 -2
View File
@@ -82,7 +82,7 @@ Every source's env server is spawned by the eval process unless the source sets
## Resume
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: the episodes that landed rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch) and only the rollouts still owed run. Errored episodes and the ones the interruption cut off run again.
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: saved episodes with `episode.ok` rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch), and only the rollouts still owed run. Failed episodes and the ones the interruption cut off run again. Saved records that fail schema validation stop the resume before the current stream is archived.
```bash
uv run eval @ eval.toml --run.name my-eval
@@ -92,7 +92,7 @@ uv run eval @ eval.toml --run.name my-eval --resume
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
A landed episode counts toward the task with its `task.key`, so `select` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
A landed episode counts toward a selected task in the same source when their content hashes (`task.hash`) match. A task whose content changes runs again even if its public `task.key` stays the same. `select` and `group_size` may change between launches: each selected occurrence keeps up to `group_size` matching episodes, and only its missing rollouts run. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Each selected occurrence owns a separate group containing its restored and new rollouts, even when the same task is selected more than once, so pass@k and the dashboard see one group per selected occurrence. Use `--clean` to start over instead.
## Monitors
+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"
]
+29 -7
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)
@@ -86,9 +87,7 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
|---|---|
| `trainer.model.dp_replicate` | Number of dimensions to **replicate** instead of shard. Set to 2 to run 2-way DP replication × FSDP sharding within each replica — useful for very large clusters where pure FSDP communication dominates. |
| `trainer.model.reshard_after_forward` | If `true` (default), parameters are resharded after the forward pass to free memory; the backward pass re-gathers. Set `false` to keep params resident — faster but more memory. |
| `trainer.model.fsdp_cpu_offload` | Offload params + grads + optimizer state to CPU. Big memory win, large throughput hit. |
| `trainer.model.optim_cpu_offload` | Offload optimizer state to CPU between steps. Enabled by default. |
| `trainer.model.full_offload` | Offload gradients, FP32 masters, and optimizer state and run the optimizer (AdamW or SignSGD) on CPU during backward. Disabled by default. |
| `trainer.model.offload` | CPU offloading: `optimizer` (default) offloads optimizer state between steps; `full` offloads gradients, FP32 masters, and optimizer state and runs the optimizer (AdamW or SignSGD) on CPU during backward; `none` disables offloading. |
### Expert Parallelism
@@ -143,15 +142,15 @@ Activation offloading still applies to tensors saved by autograd, but tensors re
### Optimizer Offloading
State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`. For full offload, set `model.optim_cpu_offload = false` and `model.full_offload = true`; this keeps BF16 compute weights on GPU and runs CPU optimizer chunks as gradients become ready during backward. Full offload only supports AdamW and SignSGD (`optim.type = "sign_sgd"`) and disables gradient clipping. SignSGD is stateless, so it halves the host RAM footprint versus AdamW (8 instead of 16 bytes per parameter: FP32 master + FP32 accumulated gradient, no moments).
State-only optimizer offload is enabled by default (`model.offload = "optimizer"`). For full offload, set `model.offload = "full"`; this keeps BF16 compute weights on GPU and runs CPU optimizer chunks as gradients become ready during backward. Full offload only supports AdamW and SignSGD (`optim.type = "sign_sgd"`) and disables gradient clipping. SignSGD is stateless, so it halves the host RAM footprint versus AdamW (8 instead of 16 bytes per parameter: FP32 master + FP32 accumulated gradient, no moments).
### LM Head Chunking
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization. It defaults to `1024` for RL training:
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization. It defaults to `8192` for RL training:
```toml
[trainer.model]
fused_lm_head_token_chunk_size = 1024 # default
fused_lm_head_token_chunk_size = 8192 # default
# fused_lm_head_token_chunk_size = "disabled" # vanilla LM head
```
@@ -173,7 +172,28 @@ freq = 1
max_inflight_activations = 1
```
The defaults already cover: fused LM head chunking (`1024`), `torch.compile` (fullgraph=False), AC (full mode), AC offloading (`max_inflight_activations=5`), and optimizer CPU offload. Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
The defaults already cover: fused LM head chunking (`8192`), `torch.compile` (fullgraph=False), AC (full mode), AC offloading (`max_inflight_activations=5`), and optimizer CPU offload. Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
## Max Trainer Throughput Recipe
The trainer defaults are tuned for memory, not speed: optimizer CPU offload, AC offloading, and `torch.compile` without `fullgraph` let large models fit on few GPUs, at a throughput cost. When you have enough GPUs to keep the model state and activations on GPU, turn them off:
```toml
[model]
offload = "none" # optimizer states stay on GPU
ac_offloading = "None" # activations stay on GPU
moe_router_dtype = "bfloat16" # fullgraph needs the router inside the block's FSDP unit; an fp32 router is not
[model.compile]
fullgraph = true # compile each block as a single graph
```
Then add nodes instead of CP (`cp = 1`) and run one full-length sequence per GPU (`micro_batch_size = 1`). Keep full AC unless selective AC fits. The SFT default router dtype is already `bfloat16`. RL defaults to an fp32 router, so check that bf16 routing is acceptable for your model before using `fullgraph` in RL.
Examples:
- [`examples/advanced/qwen3-235b-a22b/sft-max-perf.toml`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-235b-a22b): Qwen3-235B-A22B SFT on 4 x 8 B300 at 16k, around 46% MFU.
- [`examples/advanced/glm-5.3/sft/h200/16k-12-node.toml`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3/sft/h200): the same recipe as an overlay for GLM-5.3 SFT on 12 H200 nodes.
## SLURM
@@ -181,6 +201,8 @@ The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras --all-packages` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
Compile and JIT caches are node-local by default: the launcher sets `TRITON_CACHE_DIR=/tmp/triton-<uid>` for every component, and `VLLM_CACHE_ROOT=/tmp/.vllm-cache-<uid>` and `FLASHINFER_WORKSPACE_BASE=/tmp/.flashinfer-cache-<uid>` for inference. Ranks writing one cache on a shared filesystem can crash or hang. Override them in `[env_vars]` or a component's `env_vars`.
### Activation
A SLURM config is usually a thin overlay that adds `[slurm]` (and `[deployment]` for multi-node) on top of a base config. Configs are composed left-to-right via the `@` CLI syntax — see [Configuration § TOML Composition](configuration.md#toml-composition):
+4
View File
@@ -159,6 +159,10 @@ messages = "conversation"
tools = "schemas"
```
**Per-message loss selection.** An optional `message_loss_mask` column contains one boolean or integer 0/1 per message. For example, `[0, 0, 0, 1]` on a user/assistant/user/assistant conversation trains only the final assistant turn while retaining the full context. For prompt-completion rows, the mask covers the concatenated prompt and completion messages. Zero excludes a message; one preserves the normal role and renderer loss settings. A missing or null mask leaves those settings unchanged. The renderer applies selection without changing token IDs, including ownership of assistant closing tokens. Invalid mask lengths or entries raise an error.
To read a differently named column, set `data.columns.message_loss_mask = "selection"`.
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column in OpenAI function-calling format. Each row's value can be either a list of dicts or a JSON-encoded string of a list.
Renderer-backed SFT reads template controls from the typed `[renderer]` config in the SFT TOML. For example:
+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
-18
View File
@@ -5,10 +5,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-search"
partition = "all"
@@ -25,10 +21,6 @@ num_infer_replicas = 4
project = "search-ablations"
name = "glm45air-search"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
@@ -41,7 +33,6 @@ name = "zai-org/GLM-4.5-Air"
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
@@ -57,9 +48,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "muon"
@@ -171,12 +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
enable_return_routed_experts = true
+1 -21
View File
@@ -23,11 +23,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
partition = "all"
@@ -39,10 +34,6 @@ num_infer_nodes = 1
[monitors.wandb]
project = "swe-ablations"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
@@ -52,7 +43,6 @@ keep_last = 1
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
@@ -62,8 +52,7 @@ name = "zai-org/GLM-4.5-Air"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
optim_cpu_offload = false
full_offload = true
offload = "full"
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
@@ -73,9 +62,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "sign_sgd"
@@ -104,12 +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
enable_return_routed_experts = true
-16
View File
@@ -19,11 +19,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-swe"
partition = "all"
@@ -40,10 +35,6 @@ num_infer_replicas = 4
project = "swe-ablations"
name = "glm45air-scaleswe"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
@@ -53,7 +44,6 @@ keep_last = 1
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
@@ -118,14 +108,8 @@ 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
tensor_parallel_size = 8
enable_expert_parallel = true
enable_return_routed_experts = true
@@ -6,10 +6,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-terminal"
partition = "all"
@@ -26,10 +22,6 @@ num_infer_replicas = 4
project = "terminal-ablations"
name = "glm45air-terminal"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
@@ -42,7 +34,6 @@ name = "zai-org/GLM-4.5-Air"
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
@@ -58,9 +49,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "muon"
@@ -166,12 +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
enable_return_routed_experts = true
@@ -4,7 +4,7 @@
[model]
cp = 1
optim_cpu_offload = false
offload = "none"
ac_offloading = "None"
[model.compile]
+1 -2
View File
@@ -2,14 +2,13 @@ clean = true
[env_vars]
HF_HOME = "/home/huggingface"
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "zai-org/GLM-5.3-BF16"
attn = "flash_attention_2"
cp = 8
ep = 8
optim_cpu_offload = true
offload = "optimizer"
dsa_backend = "cudnn_flashmla"
[model.ac]
+1 -1
View File
@@ -89,6 +89,7 @@ attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
ep = 8
dsa_backend = "cudnn_flashmla"
[trainer.model.quantization]
type = "fp8"
@@ -97,7 +98,6 @@ type = "fp8"
type = "deepgemm_fp8"
[trainer.model.ac]
freq = 1
[trainer.model.compile]
+1 -4
View File
@@ -6,9 +6,6 @@ level = "debug"
[model]
name = "PrimeIntellect/INTELLECT-3-Base"
[weight_broadcast]
type = "nccl"
[deployment]
type = "multi_node"
num_train_nodes = 4
@@ -16,6 +13,7 @@ num_infer_nodes = 12
[slurm]
job_name = "swe-qwen30b"
partition = "all"
[ckpt]
interval = 100
@@ -35,7 +33,6 @@ fused_lm_head_token_chunk_size = 1024
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[trainer.optim]
type = "muon"
@@ -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"
+1 -4
View File
@@ -6,9 +6,6 @@ level = "debug"
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
[weight_broadcast]
type = "nccl"
[deployment]
type = "multi_node"
num_train_nodes = 2
@@ -16,6 +13,7 @@ num_infer_nodes = 2
[slurm]
job_name = "math-qwen30b"
partition = "all"
[ckpt]
interval = 100
@@ -33,7 +31,6 @@ ep = 8
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[trainer.optim]
type = "adamw"
@@ -2,7 +2,6 @@ clean = true
[env_vars]
HF_HOME = "/home/huggingface"
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
+1 -4
View File
@@ -6,9 +6,6 @@ level = "debug"
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
[weight_broadcast]
type = "nccl"
[deployment]
type = "multi_node"
num_train_nodes = 2
@@ -16,6 +13,7 @@ num_infer_nodes = 2
[slurm]
job_name = "swe-qwen30b"
partition = "all"
[ckpt]
interval = 100
@@ -34,7 +32,6 @@ cp = 2
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[trainer.optim]
type = "adamw"
+1 -1
View File
@@ -3,6 +3,7 @@ seq_len = 32768
[slurm]
job_name = "general-agent-qwen3-30b-a3b-rlm"
partition = "all"
[deployment]
type = "multi_node"
@@ -26,7 +27,6 @@ name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
cp = 2
[trainer.model.ac]
freq = 1
[trainer.model.compile]
-1
View File
@@ -12,7 +12,6 @@ project = "alphabet-sort"
name = "alphabet-sort"
[trainer.model.ac]
freq = 1
[trainer.model.lora]
rank = 32
-2
View File
@@ -38,8 +38,6 @@ group_size = 16
[orchestrator.concurrency]
initial_inflight = 1024
[orchestrator.model.lora]
[orchestrator.train.sampling]
max_completion_tokens = 512
-1
View File
@@ -1,6 +1,5 @@
# Multimodal (VLM) SFT on a Mixture-of-Experts model — single 8xH200 node.
max_steps = 1000
dist_timeout_seconds = 3600
[model]
name = "Qwen/Qwen3.6-35B-A3B"
-1
View File
@@ -19,7 +19,6 @@ freeze_vision_encoder = true
rank = 16
[model.ac]
freq = 1
[data]
type = "sft"
@@ -28,10 +28,11 @@ class ServedEvalConfig(EvalSourcesConfig):
"""Adaptive in-flight episode concurrency, sized by the same controller as
``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on episode dispatch, in tasks per minute. Use it for
sandbox-backed environments to pace provisioning during autoscaling. None disables
rate limiting."""
dispatch_per_minute: int | None = Field(None, ge=1)
"""Rate limit on episode dispatch: at most this many episodes start per minute. Each
episode counts once, so a group of ``group_size`` episodes counts ``group_size``
times. Use it for sandbox-backed environments to pace provisioning during
autoscaling. None disables it."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat for the run: pinged by landed episodes — the first
@@ -29,15 +29,6 @@ class ServerConfig(BaseConfig):
# not depend on vLLM, and importing it costs seconds in every config-parsing process.
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
# vLLM all2all backend options for expert-parallel deployments.
All2AllBackend = Literal[
"allgather_reducescatter",
"deepep_high_throughput",
"deepep_low_latency",
"flashinfer_nvlink_one_sided",
"flashinfer_nvlink_two_sided",
]
QuantizationType = Literal["fp8_per_block"]
@@ -59,18 +50,9 @@ class VllmConfig(BaseConfig):
model: str = "Qwen/Qwen3-0.6B"
"""HF model name or local path."""
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models."""
max_model_len: int | None = None
"""Maximum model context length. If None, uses the model config's value."""
enforce_eager: bool = False
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance."""
trust_remote_code: bool = False
"""Trust remote code when loading the model."""
chat_template: str | None = None
"""Chat template — a Jinja2 template string or path to a template file. If None, uses the model's default."""
@@ -98,9 +80,6 @@ class VllmConfig(BaseConfig):
api_server_count: int = Field(1, ge=0)
"""API servers to run. Set to 0 for headless mode."""
seed: int = 0
"""Seed the inference components."""
gpu_memory_utilization: float = 0.9
"""GPU memory utilization."""
@@ -113,10 +92,6 @@ class VllmConfig(BaseConfig):
enable_lora: bool = False
"""Enable LoRA."""
max_loras: int = 1
"""Maximum number of concurrently served LoRAs. prime-rl serves one adapter and reloads
it in place every policy version (same name, same lora_int_id), so one slot suffices."""
max_lora_rank: int | None = None
"""Maximum LoRA rank. Rounded up to the nearest value vLLM accepts."""
@@ -126,9 +101,6 @@ class VllmConfig(BaseConfig):
enable_expert_parallel: bool = False
"""Enable expert parallelism for MoE models."""
all2all_backend: All2AllBackend = "allgather_reducescatter"
"""All-to-all backend for expert-parallel communication."""
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB)."""
@@ -138,9 +110,6 @@ class VllmConfig(BaseConfig):
expert parallelism is disabled, or under EPLB (redundant expert slots need all
logical expert weights)."""
enable_dbo: bool = False
"""Enable dual batch overlap (DBO)."""
enable_return_routed_experts: bool = False
"""Return routed experts in responses."""
@@ -565,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:
@@ -6,6 +6,7 @@ import verifiers.v1 as vf
from pydantic import AliasChoices, BaseModel, Field, SerializeAsAny, TypeAdapter, ValidationError, model_validator
from pydantic.fields import FieldInfo
from renderers import AutoRendererConfig, RendererConfig
from verifiers.v1.configs.agent import agent_config_fields
from prime_rl.configs.algorithm import (
AlgoConfig,
@@ -18,9 +19,9 @@ from prime_rl.configs.shared import (
FileSystemWeightBroadcastConfig,
HeartbeatConfig,
LogConfig,
PolicyClientConfig,
ResumeConfig,
TransportConfig,
VLLMClientConfig,
WeightBroadcastConfig,
ZMQTransportConfig,
)
@@ -28,19 +29,8 @@ from prime_rl.configs.trainer import TokenizerConfig
from prime_rl.utils.config import BaseConfig, default_output_dir
class LoRAConfig(BaseConfig):
rank: int | None = Field(None, ge=1)
"""LoRA rank for this run. Must be ≤ trainer's max rank. If None, uses the trainer's rank."""
alpha: float | None = Field(None, ge=0)
"""LoRA alpha for this run. If None, uses the trainer's alpha."""
class ModelConfig(BaseModelConfig):
lora: LoRAConfig | None = None
"""Per-run LoRA configuration. If None, LoRA is disabled."""
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
client: PolicyClientConfig = Field(default_factory=PolicyClientConfig)
"""Client of the live deployment (``[orchestrator.model.client]``)."""
@@ -90,70 +80,6 @@ class TrainSamplingConfig(BaseConfig):
)
return self
def to_sampling_args(self) -> dict[str, Any]:
"""Convert to OAI-compatible sampling args dict, omitting None values."""
args: dict[str, Any] = {
"temperature": self.temperature,
"top_p": self.top_p,
"logprobs": True,
}
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens
# top_k rides extra_body (like EvalSamplingConfig), overriding the sentinel.
extra_body = dict(self.extra_body)
if self.top_k is not None:
extra_body["top_k"] = self.top_k
if extra_body:
args["extra_body"] = extra_body
return args
class EvalSamplingConfig(BaseConfig):
temperature: float | None = Field(None, ge=0, le=2.0)
"""Sampling temperature. None defers to the inference server default."""
top_p: float | None = None
"""Nucleus sampling threshold. None defers to the inference server default."""
top_k: int | None = None
"""Top-k sampling. None defers to the inference server default."""
min_p: float | None = Field(None, ge=0)
"""Min-p sampling threshold. None defers to the inference server default."""
max_completion_tokens: int | None = None
"""Maximum output tokens per turn. None defers to the inference server default."""
reasoning_effort: Literal["minimal", "low", "medium", "high"] | None = None
"""Reasoning effort constraint for reasoning models."""
extra_body: dict[str, Any] = {}
"""Extra body parameters forwarded to the inference server."""
def to_sampling_args(self) -> dict[str, Any]:
"""Convert to OAI-compatible sampling args dict. Only includes non-None fields."""
args: dict[str, Any] = {}
if self.temperature is not None:
args["temperature"] = self.temperature
if self.top_p is not None:
args["top_p"] = self.top_p
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens
if self.reasoning_effort is not None:
args["reasoning_effort"] = self.reasoning_effort
extra_body = dict(self.extra_body)
if self.top_k is not None:
extra_body["top_k"] = self.top_k
if self.min_p is not None:
extra_body["min_p"] = self.min_p
if extra_body:
args["extra_body"] = extra_body
return args
class EnvConfig(BaseConfig):
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
@@ -316,9 +242,37 @@ class TrainSourceConfig(EnvConfig):
"""User-authored task sampler and admission gates. The default cycles
through the taskset and admits every finalized group."""
@model_validator(mode="after")
def validate_policy_sampling(self):
if self.algo.sampling.source != "policy":
return self
# The source owns the distribution replayed by the trainer; agents may
# change generation limits and rendering without changing that distribution.
agent_options = {"max_tokens", "reasoning_effort", "chat_template_kwargs"}
supported = (
agent_options
| TrainSamplingConfig.model_fields.keys()
| {"min_p", "logprobs", "return_token_ids", "cache_salt"}
)
sampling = vf.SamplingConfig(**self.sampling.model_dump(exclude_none=True))
if unsupported := sampling.model_dump(exclude_none=True).keys() - supported:
raise ValueError(
f"Policy source '{self.resolved_name}' has unsupported sampling parameters: {sorted(unsupported)}"
)
for name, agent in agent_config_fields(self.env).items():
if agent.sampling is None:
continue
if unsupported := agent.sampling.model_dump(exclude_unset=True).keys() - agent_options:
raise ValueError(
f"Agent '{name}' in policy source '{self.resolved_name}' sets sampling {sorted(unsupported)}. "
"Set distribution parameters on the source's sampling config; agent sampling only supports "
f"{sorted(agent_options)}."
)
return self
class EvalSourceConfig(EnvConfig):
sampling: EvalSamplingConfig = EvalSamplingConfig()
sampling: vf.SamplingConfig = vf.SamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
group_size: int = Field(1, ge=1)
@@ -409,7 +363,7 @@ class EvalSourcesConfig(SourceGroupConfig):
source: list[EvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources."""
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
sampling: vf.SamplingConfig = Field(default_factory=vf.SamplingConfig)
"""Sampling that every eval source inherits; can differ from training sampling."""
select: vf.SelectConfig = vf.SelectConfig()
@@ -472,15 +426,6 @@ class CheckpointConfig(BaseConfig):
interval: int | None = Field(None, ge=1)
"""Step interval at which to save the orchestrator checkpoint."""
wait_for_weights_timeout: int | None = Field(None, ge=1)
"""Wait up to this many seconds for the startup weight directory to appear (the trainer broadcasts the incoming policy — v0 from scratch, the resumed step's version on resume — before the first step). If None, fall back to a default timeout. Raise this for large models on slow shared filesystems."""
keep_last: int | None = Field(None, ge=1)
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
keep_interval: int | None = Field(None, ge=1)
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
class ConcurrencyConfig(BaseConfig):
"""Adaptive in-flight concurrency control. The orchestrator sizes the
@@ -550,10 +495,10 @@ class OrchestratorConfig(BaseConfig):
"""Role for each policy admin client when collecting P/D inference metrics."""
ckpt: CheckpointConfig | None = None
"""Checkpoint configuration."""
resume: ResumeConfig | None = None
"""Resume the orchestrator from a checkpoint. None starts from scratch; an empty block resumes from the latest checkpoint, ``resume.step`` from that step, ``resume.dir`` from an external checkpoint step directory. Without ``ckpt`` the run loads but saves no new checkpoints."""
"""Checkpoint configuration."""
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
"""Transport used to receive updated weights from the trainer."""
@@ -564,8 +509,8 @@ class OrchestratorConfig(BaseConfig):
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
dispatch_per_minute: int | None = Field(None, ge=1)
"""Rate limit on episode dispatch, shared by train and eval: at most this many episodes start per minute. Each episode counts once, so a group of ``group_size`` episodes counts ``group_size`` times. Recommended for sandbox-backed environments to pace provisioning during autoscaling. None disables it."""
batch_size: int = Field(128, ge=1)
"""Samples to train on per step."""
@@ -360,6 +360,13 @@ class RLConfig(BaseConfig):
# The orchestrator queries the inference server it is paired with; without one, it
# must match the trainer whose weights the external server receives.
if inference is not None:
require_equal(
"deployment.gpus_per_node",
{
"deployment.gpus_per_node": self.deployment.gpus_per_node,
"inference.deployment.gpus_per_node": inference.deployment.gpus_per_node,
},
)
require_equal(
"model.name",
{"inference.vllm.model": inference.vllm.model, "orchestrator.model.name": orchestrator.model.name},
@@ -433,17 +440,8 @@ class RLConfig(BaseConfig):
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
"have no disk artifact to load from."
)
if "inference_world_size" in self.weight_broadcast.model_fields_set:
raise ValueError("weight_broadcast.inference_world_size is set automatically by rl; remove it.")
update = {}
if self.weight_broadcast.type != "filesystem":
update["inference_world_size"] = (
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
if self.inference
else 1
)
self.trainer.weight_broadcast = self.weight_broadcast.model_copy(update=update)
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy(update=update)
self.trainer.weight_broadcast = self.weight_broadcast.model_copy()
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy()
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
return self
@@ -479,37 +477,6 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_lora(self):
if self.trainer.model.lora is not None:
if self.orchestrator.model.lora is None:
from prime_rl.configs.orchestrator import LoRAConfig
self.orchestrator.model.lora = LoRAConfig()
if (
self.orchestrator.model.lora.rank is not None
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
):
raise ValueError(
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
)
if (
self.orchestrator.model.lora.alpha is not None
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
):
raise ValueError(
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
)
if self.orchestrator.model.lora.rank is None:
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.model.lora.alpha is None:
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
if self.inference is not None:
self.inference.vllm.enable_lora = True
self.inference.vllm.max_lora_rank = self.trainer.model.lora.rank
@@ -659,6 +626,11 @@ class RLConfig(BaseConfig):
dp = self.inference.vllm.data_parallel_size
if self.inference.vllm.api_server_count < dp and not self.inference.vllm.enable_lora:
self.inference.vllm.api_server_count = dp
if self.weight_broadcast.type != "filesystem":
# Every inference GPU joins the in-memory transfer group, so size it after the DP fill.
world_size = dp * self.inference.vllm.tensor_parallel_size
self.trainer.weight_broadcast.inference_world_size = world_size
self.orchestrator.weight_broadcast.inference_world_size = world_size
elif self.deployment.type == "multi_node": # multi-node
self.orchestrator.num_train_workers = (
@@ -809,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:
@@ -101,6 +101,9 @@ class SFTColumnsConfig(BaseConfig):
tools: str = "tools"
"""Column with the tool schemas in OpenAI function-calling format."""
message_loss_mask: str = "message_loss_mask"
"""Optional column of booleans or integer 0/1 flags, one per resolved message (prompt + completion for split rows). Zero excludes a message from loss; one preserves its normal supervision. Missing or null masks leave supervision unchanged."""
renderer: dict[str, str] = {"reasoning_effort": "reasoning_effort"}
"""Per-sample renderer arguments as ``renderer field = dataset column``, e.g. ``reasoning_effort = "effort"``. A row's non-null value overrides the ``[renderer]`` setting; rows and datasets without the column use it unchanged."""
@@ -323,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."""
@@ -385,13 +388,13 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def full_optimizer_offload_requires_supported_optimizer(self):
if self.model.full_offload and self.optim.type not in ("adamw", "sign_sgd"):
if self.model.offload == "full" and self.optim.type not in ("adamw", "sign_sgd"):
raise ValueError("Full optimizer offload only supports AdamW and SignSGD")
return self
@model_validator(mode="after")
def full_optimizer_offload_disables_grad_clipping(self):
if self.model.full_offload and self.optim.max_norm is not None:
if self.model.offload == "full" and self.optim.max_norm is not None:
warnings.warn(
"Gradient clipping prevents optimizer-in-backward overlap with CPU optimizer offload. "
"Automatically setting optim.max_norm to None (disabled).",
@@ -439,8 +442,6 @@ class SFTConfig(BaseConfig):
"LoRA training is not yet supported with in-memory weight broadcast. "
"Set weight_broadcast.type = 'filesystem'."
)
if self.eval.retrigger_on_resume:
raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
if self.deployment.type == "multi_node":
# Dedicated nodes in the SFT allocation run the inference pool, router,
@@ -618,12 +619,6 @@ class SFTConfig(BaseConfig):
validate_scheduler(self.scheduler, self.max_steps)
return self
@model_validator(mode="after")
def validate_opt_and_fsdp_offload(self):
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
### Auto-setup and validate shared configs
@model_validator(mode="after")
@@ -648,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:
@@ -39,9 +39,10 @@ EnvVars: TypeAlias = Annotated[dict[str, str], AfterValidator(reject_protected_e
class BaseWeightBroadcastConfig(BaseConfig):
timeout: int = 1200
"""Timeout in seconds for the broadcast handshake and transfer. The trainer
fails the run when no consumer acknowledges an offered version in time."""
timeout: int = 3600
"""Timeout in seconds for the broadcast handshake and transfer, including the orchestrator's wait
for the trainer's startup broadcast. The trainer fails the run when no consumer acknowledges an
offered version in time. Raise it for large models on slow shared filesystems."""
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
@@ -122,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."""
@@ -131,8 +132,8 @@ class SlurmConfig(BaseConfig):
template_path: Path | None = None
"""SLURM template file. If None, uses the bundled single-node or multi-node template."""
partition: str = "cluster"
"""SLURM partition (#SBATCH --partition)."""
partition: str | None = None
"""SLURM partition (#SBATCH --partition). If None, the job goes to the cluster's default partition."""
nodelist: str | None = None
"""Comma-separated list of specific nodes to run on (#SBATCH --nodelist)."""
@@ -153,7 +154,7 @@ class SlurmConfig(BaseConfig):
"""Start a job-scoped ModelExpress service for NIXL weight transfer."""
cleanup_grace_period: int = Field(3600, ge=0)
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
"""Maximum seconds a multi-node RL job that hit a non-zero exit waits for an in-flight trainer checkpoint to finish before tearing down. Without an in-flight checkpoint (or without ``[ckpt]``) it tears down immediately. Set to 0 to never wait."""
shared_fs: bool = True
"""Whether the project filesystem (including the venv) is shared across nodes (e.g. NFS). When True, a single ``uv sync`` on the batch node suffices. Set to False when the venv is node-local (e.g. ``UV_PROJECT_ENVIRONMENT`` on ``/tmp``) so ``uv sync`` runs on every node via srun."""
@@ -223,9 +224,6 @@ class ClientConfig(BaseClientConfig):
admin_base_url: list[str] | None = None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in multi-replica or disaggregated P/D deployments where the router must not handle admin traffic."""
dynamo: DynamoConfig | None = None
"""Dynamo RL worker-discovery configuration."""
class VLLMClientConfig(ClientConfig):
"""Client defaults for the live inference deployment managed by training."""
@@ -234,6 +232,13 @@ class VLLMClientConfig(ClientConfig):
api_key_var: str = "VLLM_API_KEY"
class PolicyClientConfig(VLLMClientConfig):
"""Client of the policy deployment the orchestrator drives (weight updates, admin plane)."""
dynamo: DynamoConfig | None = None
"""Dynamo RL worker-discovery configuration."""
class LogConfig(BaseConfig):
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
"""Log level for the process. Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``."""
@@ -3,7 +3,7 @@ import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import BeforeValidator, Field, field_validator, model_validator
from pydantic import Field, field_validator, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
@@ -42,41 +42,13 @@ 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."""
class OptimizerInBackwardOffloadConfig(BaseConfig):
"""Full CPU optimizer offload: FP32 masters, optimizer state (AdamW moments; SignSGD is
stateless), and accumulated gradients live in CPU RAM, each optimizer chunk runs on CPU as
soon as its last gradient arrives, and the refreshed BF16 weights stream back while backward
is still executing.
Gradient numerics: gradients are reduced across ranks in FP32 (``reduce_dtype``) but FSDP2
materializes them in the sharded parameter's dtype, which is BF16 for the offload compute
model — so each gradient is rounded to BF16 once before the FP32 CPU update. Masters,
moments, accumulation, and optimizer arithmetic remain FP32. For gradient numerics
bit-faithful to that path, disable offloading.
"""
numa_bind: bool = True
"""Pin each rank's CPUs to its GPU's NUMA node. Disable when the launcher already manages CPU affinity or GPU sysfs topology is unavailable."""
def _normalize_optimizer_in_backward_offload(value: Any) -> Any:
if value is True:
return {}
if value is False:
return None
return value
OptimizerInBackwardOffload = Annotated[
OptimizerInBackwardOffloadConfig | None, BeforeValidator(_normalize_optimizer_in_backward_offload)
]
OffloadMode: TypeAlias = Literal["none", "optimizer", "full"]
class CompileConfig(BaseConfig):
@@ -95,14 +67,6 @@ class FusionsConfig(BaseConfig):
"""Experimental. Shard fused 2-D weights along dim 1 under FSDP so that weight loading and checkpointing are zero-copy: the checkpoint reads and writes the fused weights and their optimizer state in place, instead of assembling a full copy of every fused weight on each rank first. Requires the hidden size to be divisible by the FSDP shard mesh size."""
class IndexCacheConfig(BaseConfig):
topk_freq: int = Field(1, ge=1)
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
topk_pattern: str | None = None
"""Optional per-layer schedule that overrides ``topk_freq``. ``'F'`` computes fresh indices for that layer; ``'S'`` reuses the previously cached indices. Length should match the number of decoder layers."""
class LoRAConfig(BaseConfig):
rank: int = Field(16, ge=1)
"""Rank of the low-rank decomposition matrices."""
@@ -288,14 +252,8 @@ class ModelConfig(BaseModelConfig):
ac_offloading: ActivationOffloadingConfig | None = ActivationOffloadingConfig()
"""Activation offloading configuration. If None, activation offloading is disabled."""
fsdp_cpu_offload: bool = False
"""Enable FSDP CPU offloading for parameters, gradients, and optimizer states. Uses pinned memory for efficient CPU↔GPU transfers."""
optim_cpu_offload: bool = True
"""Offload only optimizer states (momentum, variance) to CPU, keeping weights on GPU. Avoids the H2D all-gather overhead of FSDP CPU offload while still saving GPU memory."""
full_offload: OptimizerInBackwardOffload = None
"""Full CPU optimizer offload: FP32 masters, moments, and gradients live in CPU RAM and the optimizer runs on CPU, overlapped with backward. Enable with ``true`` or a ``[model.full_offload]`` section; disabled by default."""
offload: OffloadMode = "optimizer"
"""CPU offloading. ``optimizer`` keeps optimizer states (momentum, variance) in CPU RAM and weights on GPU. ``full`` keeps FP32 masters, optimizer states, and accumulated gradients in CPU RAM and runs each optimizer chunk on CPU as soon as its last gradient arrives, overlapped with backward; it supports AdamW and SignSGD only, disables gradient clipping, and rounds each gradient to BF16 once before the FP32 CPU update. ``none`` keeps everything on GPU."""
reshard_after_forward: bool = True
"""Reshard the model after each forward pass."""
@@ -324,14 +282,14 @@ class ModelConfig(BaseModelConfig):
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"
"""Kernels for the DSA sparse MLA attention (``glm_moe_dsa``, e.g. GLM-5). ``tilelang`` runs the TileLang forward and backward. ``cudnn_flashmla`` runs the FlashMLA sparse prefill forward with the cuDNN frontend CuTe-DSL backward; it needs the ``flash-mla`` extra and an SM90 GPU (SM100/SM103 are wired up but untested)."""
index_cache: IndexCacheConfig | None = None
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
freeze_moe_router: bool | Literal["auto"] = "auto"
"""Freeze MoE router gate parameters. ``auto`` (default): ``True`` for RL, ``False`` for SFT; a no-op on non-MoE models. Frozen routers get no optimizer state, so resuming a checkpoint saved with a frozen router with ``freeze_moe_router=false`` fails on missing DCP keys."""
@@ -358,20 +316,9 @@ class ModelConfig(BaseModelConfig):
@model_validator(mode="after")
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()
return self
@model_validator(mode="after")
def cpu_offload_mutual_exclusion(self):
if self.fsdp_cpu_offload and (self.optim_cpu_offload or self.full_offload):
raise ValueError("Cannot combine fsdp_cpu_offload with optimizer CPU offloading.")
if self.optim_cpu_offload and self.full_offload:
raise ValueError(
"Cannot enable both optim_cpu_offload and full_offload. "
"Set optim_cpu_offload=false when enabling full optimizer offload."
)
"""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")
@@ -612,6 +559,9 @@ class DataLoaderConfig(BaseConfig):
fake: FakeDataLoaderConfig | None = None
"""Use a fake data loader sampling random micro-batches (for debugging)."""
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."""
class TrainerConfig(BaseConfig):
model: ModelConfig = ModelConfig()
@@ -665,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."""
@@ -708,13 +658,13 @@ class TrainerConfig(BaseConfig):
@model_validator(mode="after")
def full_optimizer_offload_requires_supported_optimizer(self):
if self.model.full_offload and self.optim.type not in ("adamw", "sign_sgd"):
if self.model.offload == "full" and self.optim.type not in ("adamw", "sign_sgd"):
raise ValueError("Full optimizer offload only supports AdamW and SignSGD")
return self
@model_validator(mode="after")
def full_optimizer_offload_disables_grad_clipping(self):
if self.model.full_offload and self.optim.max_norm is not None:
if self.model.offload == "full" and self.optim.max_norm is not None:
warnings.warn(
"Gradient clipping prevents optimizer-in-backward overlap with CPU optimizer offload. "
"Automatically setting optim.max_norm to None (disabled).",
@@ -748,12 +698,6 @@ class TrainerConfig(BaseConfig):
validate_scheduler(self.scheduler, self.max_steps)
return self
@model_validator(mode="after")
def validate_opt_and_fsdp_offload(self):
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
@model_validator(mode="after")
def validate_lora_broadcast(self):
if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "nixl"):
@@ -86,8 +86,8 @@ def propagate_shared_fields(data: Any) -> Any:
# ``orchestrator.ckpt`` has no ``output_dir`` field — trainer-only.
propagate("ckpt.output_dir", "trainer.ckpt.output_dir")
propagate("ckpt.interval", "trainer.ckpt.interval", "orchestrator.ckpt.interval")
propagate("ckpt.keep_last", "trainer.ckpt.keep_last", "orchestrator.ckpt.keep_last")
propagate("ckpt.keep_interval", "trainer.ckpt.keep_interval", "orchestrator.ckpt.keep_interval")
propagate("ckpt.keep_last", "trainer.ckpt.keep_last")
propagate("ckpt.keep_interval", "trainer.ckpt.keep_interval")
# [monitors.wandb] leaves. (Bare empty ``[monitors.wandb]`` block enablement is at the end.)
# ``monitors.wandb.name`` flows verbatim to both sub-configs — shared W&B mode is
@@ -133,6 +133,10 @@ def propagate_shared_fields(data: Any) -> Any:
propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps")
propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len")
# [deployment] gpus_per_node → inference: the nested inference deployment sizes its
# engines per node from its own copy.
propagate("deployment.gpus_per_node", "inference.deployment.gpus_per_node")
# [slurm] → inference: a multi-node RL run drives its inference deployment under
# the same SLURM allocation, so the nested inference inherits [slurm]. This is
# what lets the nested InferenceConfig's multi-node / disaggregated SLURM check
+3 -3
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"
@@ -225,9 +225,9 @@ requires-dist = [
]
[tool.uv.exclude-newer-package]
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
# verifiers pins harbor==0.24.0, published inside the rolling window;
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
harbor = "2026-08-11T00:00:00Z"
harbor = "2026-10-08T00:00:00Z"
tokenspeed-mla = false
# vLLM 0.31.0 pins flashinfer-python 0.7.0.post1, published inside the rolling window
flashinfer-python = false
+1 -1
View File
@@ -42,7 +42,7 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
**Sources are one block** — inside a `[[...source]]` entry, write nested sub-configs as dotted keys in the same block (`env.taskset.id = "..."`, `env.agent.harness.id = "..."`), not one subsection header per nested config. Nested arrays of tables (e.g. `[[orchestrator.train.source.env.taskset.task.judges]]`) keep full-path headers — they attach to the preceding `[[...source]]` entry.
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enable_prefix_caching = true`).
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--vllm.max-model-len None`.
+4 -5
View File
@@ -26,12 +26,11 @@ SLURM launches write generated scripts and coordination files under `<run_dir>/l
- Validation aliases let renamed fields keep working; legacy keys can be remapped in a `model_validator(mode="before")`.
- Auto-generated `--help` panels from `Field(description=...)` or PEP 224 docstrings.
- Friendly errors: required-field boxes, validator errors point at the offending flag, unknown flags get a "did you mean" hint.
- State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`.
- State-only optimizer offload is enabled by default (`model.offload = "optimizer"`).
- For gradients, FP32 masters, optimizer state, and optimizer-in-backward CPU execution, set
`model.optim_cpu_offload = false` and `model.full_offload = true`. This mode uses the native
CPU optimizer kernel, only supports AdamW and SignSGD (SignSGD is stateless and
halves the host RAM footprint), and disables gradient clipping. Use a
`[model.full_offload]` table only to disable NUMA binding.
`model.offload = "full"`. This mode uses the native CPU optimizer kernel, only supports
AdamW and SignSGD (SignSGD is stateless and halves the host RAM footprint), disables
gradient clipping, and pins each rank's CPUs to its GPU's NUMA node.
## `rl` — RL training
+4
View File
@@ -320,6 +320,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
"modelexpress_redis_port": 6380 if nixl_broadcast is not None and nixl_broadcast.port == 6379 else 6379,
}
ckpt_dir = get_ckpt_dir(config.trainer.ckpt.output_dir or config.run_dir) if config.trainer.ckpt else None
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
@@ -342,6 +344,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
config_dir=config_dir,
log_dir=log_dir,
output_dir=config.run_dir,
ckpt_dir=ckpt_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
num_train_nodes=config.deployment.num_train_nodes,
@@ -387,6 +390,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
config_dir=config_dir, # TODO: should prob have each subconfig path separately
log_dir=log_dir,
output_dir=config.run_dir,
ckpt_dir=ckpt_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
num_train_nodes=config.deployment.num_train_nodes,
+5 -6
View File
@@ -8,6 +8,8 @@ rollouts still owed run (``prime_rl.eval.resume``)."""
from __future__ import annotations
import verifiers.v1 as vf
from prime_rl import monitors
from prime_rl.configs.eval import EvalConfig
from prime_rl.eval import resume
@@ -24,7 +26,7 @@ class Eval:
async def run(self) -> None:
config = self.config
landed: list[dict] = []
landed: list[vf.WireEpisode] = []
if config.resume:
# read and set aside before the monitors start: the resumed attempt writes a fresh stream
landed = resume.take_landed(config.run_dir)
@@ -41,17 +43,14 @@ class Eval:
)
resume.stamp_config(config.run_dir, dump_resolved_config(config))
await self.runner.setup()
restored: list = []
fired, restored = self.runner.eval_source.trigger(0, completed=landed)
if config.resume:
restored, owed, groups = resume.plan(landed, self.runner.eval_envs)
self.runner.eval_source.restore(owed, groups)
get_logger().info(
f"Resuming from the trace stream: {len(restored)} episodes restored, "
f"{sum(sum(counts.values()) for counts in owed.values())} rollouts owed"
f"{sum(request.rollouts or 0 for request in self.runner.eval_source.queue)} rollouts owed"
)
await self.runner.start()
fired = self.runner.eval_source.trigger(0)
await self.runner.run_epoch(fired, 0, restored=restored)
await self.runner.drain()
+1 -1
View File
@@ -178,7 +178,7 @@ class OnlineEval:
# Trigger before the reload: the dispatcher only schedules eval in PREFER_EVAL,
# so nothing dispatches until ``run_epoch`` switches modes below.
fired = runner.eval_source.trigger(step, force=force)
fired, _ = runner.eval_source.trigger(step, force=force)
self.last_step = max(self.last_step, step)
if reload_weights:
+14 -50
View File
@@ -1,20 +1,18 @@
"""Resume an interrupted eval from its trace stream.
The stream records what landed, so it is what a resume continues from. The run's ok
episodes are read back and rejoin the epoch as if they had just arrived - through the
monitors, so the rebuilt stream, the epoch's metrics and the platform upload cover the
whole epoch - and only the rollouts still owed run. Errored episodes and the in-flight
The stream records what landed, so it is what a resume continues from. Successful
episodes rejoin the epoch through the monitors as if they had just arrived,
so the rebuilt stream, the epoch's metrics and the platform upload cover the
whole epoch - and only the rollouts still owed run. Failed episodes and the in-flight
ones the interruption cut off are owed again.
A landed episode counts toward the task with its ``task.key``, so a resumed run may
select more or fewer examples or rollouts per example than the interrupted one: the
kept episodes are matched to the new selection and the rest is owed. The resumed
config is not checked against the interrupted one: any of it may be overridden.
The shared Verifiers rollout planner matches these episodes to the current tasks
by content hash. The resumed config is not checked against the interrupted one:
any of it may be overridden.
"""
from __future__ import annotations
from collections import Counter, defaultdict
from collections.abc import Iterator
from pathlib import Path
@@ -23,7 +21,6 @@ import verifiers.v1 as vf
from prime_rl.monitors.file.traces import get_trace_stream
from prime_rl.monitors.file.traces.chunks import chunk_numbers, open_chunk
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.utils.pathing import get_file_monitor_dir
CONFIG_NAME = "eval.json"
@@ -57,52 +54,19 @@ def archives(run_dir: Path) -> list[Path]:
return sorted(monitors.glob("file.attempt_*"), key=lambda path: int(path.name.rsplit("_", 1)[1]))
def take_landed(run_dir: Path) -> list[dict]:
"""The ok eval episodes the run has landed, each once, from every attempt's stream.
def take_landed(run_dir: Path) -> list[vf.WireEpisode]:
"""Successful episodes from every attempt; the planner deduplicates them.
The current file monitor directory joins the archives so the resumed attempt writes a
fresh stream, plan and metrics; nothing is deleted."""
current = get_file_monitor_dir(run_dir)
stream = get_trace_stream(run_dir).relative_to(current)
landed: dict[str, dict] = {}
landed: list[vf.WireEpisode] = []
for directory in [*archives(run_dir), current]:
if (directory / stream).is_dir():
for record in read_records(directory / stream):
if record.get("ok"):
landed.setdefault(record["id"], record)
episode = vf.WireEpisode.model_validate(record)
if episode.ok and "traces" in record:
landed.append(episode)
if current.is_dir():
current.rename(current.with_name(f"file.attempt_{len(archives(run_dir)) + 1}"))
return list(landed.values())
def plan(
landed: list[dict], eval_envs: EvalEnvs
) -> tuple[list[vf.WireEpisode], dict[str, dict[str, int]], dict[str, dict[str, str]]]:
"""Match the landed episodes to the run's tasks: the episodes to keep, in stream
order, the rollouts still owed per env and task key, and the group id a task's kept
episodes carry, so the owed ones complete that group rather than open another."""
targets: dict[str, Counter[str]] = {}
for env in eval_envs:
targets[env.name] = Counter(task.key for task in env.examples)
for key in targets[env.name]:
targets[env.name][key] *= env.config.group_size
kept: list[vf.WireEpisode] = []
counts: dict[str, Counter[str]] = defaultdict(Counter)
groups: dict[str, dict[str, str]] = defaultdict(dict)
for record in landed:
env_name = record["env"].get("name") or record["env"]["id"]
key = record["task"]["key"]
if counts[env_name][key] >= targets.get(env_name, Counter())[key]:
continue
kept.append(vf.WireEpisode.model_validate(record))
counts[env_name][key] += 1
if (group := record.get("group") or {}).get("id"):
groups[env_name].setdefault(key, group["id"])
owed = {
env_name: {
key: target - counts[env_name][key]
for key, target in target_counts.items()
if target > counts[env_name][key]
}
for env_name, target_counts in targets.items()
}
return kept, owed, dict(groups)
return landed
+3 -2
View File
@@ -105,7 +105,7 @@ class EvalRunner:
# Pessimistic per-episode token cost for the controller's starting cap,
# only used when the engine doesn't report its max context length.
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.source) or 8192
fallback_cost = max((source.sampling.max_tokens or 0) for source in config.source) or 8192
self.concurrency = ConcurrencyController(config.concurrency, fallback_cost=fallback_cost)
self.dispatcher = Dispatcher(
train_envs=None,
@@ -114,10 +114,11 @@ class EvalRunner:
eval_source=self.eval_source,
policy_clients=self.clients,
policy=self.policy,
policy_weights_change=isinstance(config, SFTOnlineEvalConfig),
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
tasks_per_minute=config.tasks_per_minute,
dispatch_per_minute=config.dispatch_per_minute,
max_off_policy_steps=0,
run_id=self.run_id,
run_name=self.run_name,
+3 -3
View File
@@ -10,7 +10,7 @@ from typing import Literal
import httpx
from pydantic import BaseModel, Field
from prime_rl.configs.shared import ClientConfig
from prime_rl.configs.shared import ClientConfig, PolicyClientConfig
from prime_rl.orchestrator.clients import (
ADMIN_TIMEOUT_S,
UPDATE_WEIGHTS_TIMEOUT_S,
@@ -100,7 +100,7 @@ def _discovery_headers(client_config: ClientConfig) -> dict[str, str]:
return headers
def resolve_dynamo_discovery_url(client_config: ClientConfig) -> str:
def resolve_dynamo_discovery_url(client_config: PolicyClientConfig) -> str:
dynamo = client_config.dynamo
if dynamo is None or not dynamo.enabled:
raise ValueError("Dynamo discovery is not enabled")
@@ -156,7 +156,7 @@ class DynamoAdminPlane(AdminPlane):
def __init__(
self,
client_config: ClientConfig,
client_config: PolicyClientConfig,
model_name: str,
*,
poll_interval: float = 1.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.
+6 -14
View File
@@ -12,24 +12,16 @@ def serialize_routed_experts(routed_experts: Any, start: int = 0) -> dict[str, A
if routed_experts is None:
return None
array = np.asarray(routed_experts)
assert array.ndim == 3
assert np.issubdtype(array.dtype, np.integer)
dtype = np.uint8
if array.size:
assert array.min() >= 0
if array.max() > np.iinfo(np.uint8).max:
# Models with >256 experts (e.g. NemotronH Super/Ultra: 512) need wider
# indices. The payload self-describes via "dtype" so consumers pick it up.
assert array.max() <= np.iinfo(np.uint16).max
dtype = np.uint16
compact = np.ascontiguousarray(array.astype(dtype, copy=False))
# vLLM's capturer picks uint8 or uint16 from the model's expert count, so every request of a
# model has the same dtype and the orchestrator can pack them into one micro batch.
compact = np.ascontiguousarray(routed_experts)
assert compact.ndim == 3
assert compact.dtype in (np.uint8, np.uint16), compact.dtype
return {
"data": pybase64.b64encode(memoryview(compact)).decode("ascii"),
"shape": list(compact.shape),
"start": start,
"dtype": np.dtype(dtype).name,
"dtype": compact.dtype.name,
}
+45 -2
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
import atexit
import fcntl
import os
import time
@@ -251,7 +252,12 @@ class PrimeEvalMonitor(Monitor):
evaluation per env and step, opened when the epoch starts (``log_eval_plan``), fed
every episode as it lands (``log_episodes``) and finished with the epoch's aggregates
(``log_eval_epoch``), so the platform page follows the run from its first episode.
Metrics are not forwarded; the evaluation is the epoch."""
Under a managed launch ($RUN_ID) the epoch's ``eval/{env}/...`` metrics ALSO go to
the parent training run, which is what the run dashboard groups into its `eval`
section. The orchestrator's in-process evals reach it through the train monitor, but
an eval process of its own (SFT online evals) has no other way there, so without
this the run shows every metric group except the one its evals produced."""
config: PrimeEvalMonitorConfig
@@ -268,6 +274,7 @@ class PrimeEvalMonitor(Monitor):
# (env, step) -> its open evaluation; None once opening it failed, so the epoch's
# episodes do not retry the platform on every arrival
self.runs: dict[tuple[str, int], pr.Run | None] = {}
self.parent: pr.Run | None = None
self._lock = asyncio.Lock()
self.evaluation_id = os.getenv(EVAL_ID_VAR)
if self.evaluation_id and len(self.sources) != 1:
@@ -277,6 +284,7 @@ class PrimeEvalMonitor(Monitor):
)
if self.mode == "online":
self.logger.info("Streaming eval epochs to the Prime platform")
self.parent = await asyncio.to_thread(self._attach_parent)
if output_dir is not None:
# Merge, not overwrite: when the eval process shares the
# trainer's run dir (SFT online evals), the train record's
@@ -294,8 +302,39 @@ class PrimeEvalMonitor(Monitor):
else:
self.logger.info(f"Platform evaluations disabled ({pr.MODE_ENV}=disabled)")
def _attach_parent(self) -> pr.Run | None:
"""The parent training run this eval process belongs to, for metrics only.
Blocking: runs in a worker thread.
Attaching is a local handle, not a request, so a run that turns out to be
unreachable costs the eval nothing. The caller owns the run's lifecycle: we
drop the SDK's atexit crash hook, because an eval process that exits while the
trainer is still going would otherwise report the WHOLE run failed."""
run_id = os.getenv("RUN_ID")
if not run_id:
return None
run = pr.init(
kind="train",
mode=self.mode,
base_url=_base_url(),
id=run_id,
finish_timeout=FINISH_TIMEOUT,
)
atexit.unregister(run._atexit_hook) # the SDK's own unregister handle
self.logger.info(f"Logging eval metrics to parent training run {run.id}")
return run
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
pass
"""An epoch's aggregates (``eval/{env}/...``) onto the parent training run.
Only there: a standalone eval has no parent, and the per-epoch evaluation
carries its own aggregates through ``log_eval_epoch``."""
if self.parent is None:
return
metrics, dropped = sanitize(metrics)
if dropped:
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
# A queue put that can block briefly under backpressure - off the loop.
await asyncio.to_thread(self.parent.log_metrics, metrics, step=step)
def open(self, env_name: str, step: int, expected: int | None) -> pr.Run:
"""Open the platform evaluation of one epoch. Blocking: runs in a worker thread."""
@@ -400,3 +439,7 @@ class PrimeEvalMonitor(Monitor):
await asyncio.to_thread(run.finish, status=pr.RunStatus.CANCELLED, error="interrupted")
except Exception as e:
self.logger.warning(f"Failed to close the {env_name} (Step {step}) evaluation: {type(e).__name__}: {e}")
if self.parent is not None:
# Drain only. The parent run belongs to the trainer and the platform: an
# eval process must never report its status, not even a clean completion.
await asyncio.to_thread(self.parent.flush, FINISH_TIMEOUT)
+4 -5
View File
@@ -2,8 +2,8 @@
The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm
is — a bundle of sampling and the per-token training signal. This package
turns the signal half into runtime objects (the sampling half is the env's
:class:`~prime_rl.orchestrator.generation_source.GenerationSource`):
turns the signal half into runtime objects (the sampling half is interpreted by
:class:`~prime_rl.orchestrator.envs.TrainEnv`):
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``, ``debug``) — each named
@@ -22,7 +22,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_client
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.orchestrator.algo.debug import DebugAlgorithm
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
@@ -56,7 +56,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
cls = ALGORITHM_CLASSES[config.type]
# The Algorithm is the runtime of the algorithm config's training signal
# (its sibling GenerationSource interprets the sampling half). Every algorithm is
# (its TrainEnv interprets the sampling half). Every algorithm is
# handed the live policy pool — opsd self-distills against it, others may
# judge against it or ignore it. Other models (a frozen teacher, a hint
# renderer) are built from the algorithm's own config in setup().
@@ -75,7 +75,6 @@ __all__ = [
"RAEAlgorithm",
"SFTDistillAlgorithm",
"build_algorithm",
"connect_frozen_client",
"assign_advantages",
"stamp_loss_routing",
]
+2 -26
View File
@@ -2,41 +2,17 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.orchestrator.clients import InferenceClient
async def connect_frozen_client(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferenceClient:
"""Connect to an externally hosted frozen model and wait for it."""
from prime_rl.orchestrator.clients import InferenceClient, check_inference_ready
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
if renderer_config is not None:
clients = InferenceClient(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
clients = InferenceClient(config, model_name=config.name)
await check_inference_ready(config, config.name)
return clients
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
def iter_trainable_traces(episodes: list[vf.Episode]):
"""Yield clean trainable traces that contain sampled tokens."""
for episode in episodes:
for trace in episode.traces:
if trace.has_error or not trace.agent.trainable:
if not episode.ok or trace.has_error or not trace.agent.trainable or trace.num_turns == 0:
continue
if any(any(node.mask) for node in trace.nodes):
yield episode, trace
+2 -3
View File
@@ -696,11 +696,10 @@ def _distribute_group(
def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBatch:
"""
Pad a micro batch with the given padding size sample
Return the padded micro batch.
Pad a micro batch with loss-masked tokens up to the next multiple of `pad_to_multiple_of`.
Args:
micro_batch: The micro batch to pad.
padding_size: The number of padding tokens to add.
pad_to_multiple_of: The multiple to pad the sequence length up to.
Returns:
The padded micro batch.
"""
+18 -2
View File
@@ -20,7 +20,8 @@ from verifiers.v1.configs.client import (
resolve_headers,
)
from prime_rl.configs.shared import ClientConfig
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.shared import ClientConfig, PolicyClientConfig
from prime_rl.utils.logger import get_logger
@@ -208,7 +209,7 @@ class AdminPlane:
await client.aclose()
def setup_admin_plane(client_config: ClientConfig, model_name: str) -> AdminPlane:
def setup_admin_plane(client_config: PolicyClientConfig, model_name: str) -> AdminPlane:
dynamo = client_config.dynamo
if dynamo is not None and dynamo.enabled:
from prime_rl.inference.dynamo import DynamoAdminPlane
@@ -228,6 +229,21 @@ async def check_inference_ready(client_config: ClientConfig, model_name: str) ->
await admin.aclose()
async def connect_frozen_client(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferenceClient:
"""Connect to an externally hosted frozen model and wait for it."""
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
if renderer_config is not None:
clients = InferenceClient(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
clients = InferenceClient(config, model_name=config.name)
await check_inference_ready(config, config.name)
return clients
def setup_client(
client_config: ClientConfig,
client_type: str = "openai_chat_completions",
+3 -2
View File
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any
import verifiers.v1 as vf
from prime_rl.orchestrator.algo.base import iter_trainable_traces
from prime_rl.orchestrator.curriculum.gates import AdmissionGate
from prime_rl.orchestrator.curriculum.samplers import TaskSampler
@@ -48,7 +49,7 @@ class Curriculum:
self.gates[name] = gate
def on_result(self, group: list[vf.Episode]) -> bool:
"""Observe every result, evaluate every gate, and combine with AND."""
"""Observe every result and admit trainable groups that pass every gate."""
if not group:
raise ValueError("Cannot report an empty rollout group")
task_keys = {episode.task.key for episode in group}
@@ -63,7 +64,7 @@ class Curriculum:
if not isinstance(decision, bool):
raise TypeError(f"AdmissionGate {name!r}.admit() must return bool, got {type(decision).__name__}")
decisions.append(decision)
return all(decisions)
return all(decisions) and any(iter_trainable_traces(group))
def state_dict(self) -> dict[str, Any]:
return {
@@ -27,7 +27,7 @@ class AdvRangeGate(AdmissionGate):
advantage
for episode in group
for trace in episode.traces
if not trace.has_error and trace.agent.trainable
if episode.ok and not trace.has_error and trace.agent.trainable
for node in trace.nodes
for advantage in node.advantages or []
]
@@ -68,7 +68,7 @@ class DifficultyPoolSampler(TaskSampler):
trace.reward
for episode in group
for trace in episode.traces
if not trace.has_error and trace.agent.trainable
if episode.ok and not trace.has_error and trace.agent.trainable and trace.num_turns > 0
]
if not rewards:
return
+22 -28
View File
@@ -5,7 +5,7 @@
the concurrency controller moves it via ``set_limit``; refills are
burst-capped so a raised (or drained) cap never lands all its prefills at
once.
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
- Optional rate limiting via ``AsyncLimiter(dispatch_per_minute, 60)``, one token per episode.
- Every dispatched attempt reaches ``out_q`` exactly once: as the native
episode returned by the environment, as a ``DispatchFailure`` when no
episode was produced, or under the group's ``GroupCancellation`` when the
@@ -139,13 +139,15 @@ class Dispatcher:
progress: Progress | None,
initial_max_inflight: int,
max_inflight_ceiling: int | None,
tasks_per_minute: float | None,
dispatch_per_minute: float | None,
max_off_policy_steps: int,
run_id: str,
run_name: str | None,
policy_weights_change: bool = True,
on_episode_complete: Callable[[int], None] | None = None,
) -> None:
self.policy = policy
self.policy_weights_change = policy_weights_change
self.progress = progress
self.train_envs = train_envs
self.eval_envs = eval_envs
@@ -166,7 +168,7 @@ class Dispatcher:
self.max_inflight = initial_max_inflight
self.current_inflight = 0
self.rate_limiter: AsyncLimiter | None = (
AsyncLimiter(tasks_per_minute, time_period=60) if tasks_per_minute else None
AsyncLimiter(dispatch_per_minute, time_period=60) if dispatch_per_minute else None
)
# Admission smoothing: the pool may only GROW by ``burst_cap`` per
# window. Replacing a completed episode is always free (each natural
@@ -214,10 +216,10 @@ class Dispatcher:
"""``(clients, model_name, is_live)`` for *train* rollouts of this env —
eval always uses the policy."""
assert self.train_envs is not None # train groups only exist when train is configured
source = self.train_envs.get(env_name).generation_source
if source.uses_live_policy:
return source.clients, self.policy.model_name, True
return source.clients, source.clients.model_name, False
env = self.train_envs.get(env_name)
if env.uses_live_policy:
return env.clients, self.policy.model_name, True
return env.clients, env.clients.model_name, False
@property
def inflight_train_count(self) -> int:
@@ -316,7 +318,7 @@ class Dispatcher:
return [
(self.progress.step - 1) - meta.policy_version
for meta in self.inflight.values()
if meta.kind == "train" and self.train_envs.get(meta.env_name).generation_source.uses_live_policy
if meta.kind == "train" and self.train_envs.get(meta.env_name).uses_live_policy
]
# ── lifecycle ──────────────────────────────────────────────────────────
@@ -423,7 +425,7 @@ class Dispatcher:
gid
for gid, group in self.groups.items()
if group.kind == "train"
and self.train_envs.get(group.env_name).generation_source.uses_live_policy
and self.train_envs.get(group.env_name).uses_live_policy
and group.policy_version_at_start < min_version
]
cancelled = 0
@@ -556,10 +558,8 @@ class Dispatcher:
if env_collection is None:
return False
env = env_collection.get(group.env_name)
# Frozen-sourced train rollouts hit a frozen pool; salting per policy
# version would invalidate its prefix cache every weight update for
# no reason.
if live_sourced:
# Only endpoints receiving policy weight updates need a cache salt.
if live_sourced and self.policy_weights_change:
cache_salt = str(group.policy_version_at_start)
else:
cache_salt = None
@@ -665,10 +665,6 @@ class Dispatcher:
)
return
if not episode.traces and episode.ok:
episode.ok = False
episode.errors.append(vf.Error(type="EmptyEpisode", message="Episode returned with no traces"))
for trace in episode.traces:
if trace.is_timeout and not trace.has_error and meta.kind == "train":
# Training keeps a timed-out rollout out of the batch: an error,
@@ -676,14 +672,6 @@ class Dispatcher:
trace.errors.append(vf.Error(type="Timeout", message=f"Trace stopped by {trace.stop_condition}"))
trace.ok = False
episode.ok = False
if not trace.has_error and not trace.is_timeout and trace.num_turns == 0:
# Empty trajectory: promote to an explicit error so the sink
# treats it like any other failure (``has_error`` reads ``ok``).
# A timed-out eval trace with no turns stays a timeout: scored, no samples.
trace.errors.append(vf.Error(type="EmptyTrajectory", message="Trace returned with no trajectory steps"))
trace.ok = False
episode.ok = False
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
if trace.has_error:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if trace.last_error is not None:
@@ -691,8 +679,14 @@ class Dispatcher:
f"Trace failed in group {meta.group_id} ({meta.env_name}) — "
f"{trace.last_error.type}: {trace.last_error.message}"
)
if not episode.ok and not episode.traces:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if not episode.ok:
if not any(trace.has_error for trace in episode.traces):
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
error = episode.last_error
get_logger().warning(
f"Episode failed in group {meta.group_id} ({meta.env_name})"
+ (f" — {error.type}: {error.message}" if error is not None else "")
)
if self.on_episode_complete is not None and meta.started_at > 0:
self.on_episode_complete(episode.num_total_tokens)
await self.emit_episode(meta, group, episode)
@@ -722,7 +716,7 @@ class Dispatcher:
live_policy = meta.kind == "eval"
if meta.kind == "train":
assert self.train_envs is not None
live_policy = self.train_envs.get(meta.env_name).generation_source.uses_live_policy
live_policy = self.train_envs.get(meta.env_name).uses_live_policy
policy = vf.PolicySpan(start=policy_version, end=self.policy.version) if live_policy else None
work: vf.WorkInfo = (
vf.EvalWorkInfo(step=meta.step, policy=policy)
+42 -27
View File
@@ -26,11 +26,13 @@ from pathlib import Path
from typing import Generic, TypeVar
import verifiers.v1 as vf
from renderers import RendererConfig
from verifiers.v1.serve import EnvClient
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
from prime_rl.orchestrator.generation_source import GenerationSource
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import env_address_file
@@ -65,7 +67,7 @@ class Env:
self.address_file = address_file
"""Where a launcher-managed server publishes its address; read when ``address``
is None."""
self.sampling_args: dict = {}
self.sampling = vf.SamplingConfig()
self.num_tasks: int | None = 0
"""Task count; ``None`` means the selected tasks never end."""
self.tasks: Iterator[vf.Task] | None = None
@@ -108,10 +110,10 @@ class Env:
get_logger().info(f"Env {self.name} ready in {format_time(time.perf_counter() - t0)} (num_tasks={num_tasks})")
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
sampling = {**self.sampling_args}
sampling = self.sampling
if cache_salt is not None:
sampling["extra_body"] = {**sampling.get("extra_body", {}), "cache_salt": cache_salt}
return vf.SamplingConfig(**sampling)
sampling = sampling.model_copy(update={"cache_salt": cache_salt})
return sampling
async def run(
self,
@@ -121,25 +123,16 @@ class Env:
task_data: dict,
on_delta: Callable[[dict], None] | None = None,
) -> vf.WireEpisode:
"""Run and return one typed episode. A failed multi-trace episode marks
its otherwise-clean traces failed so partial episodes never train.
"""Run and return the native typed episode.
``on_delta`` sees each delta of the env server's stream — a turn or a phase
change of one of the episode's traces — as it lands."""
episode = await self.env_client.run(
return await self.env_client.run(
task_data=task_data,
client=client,
model=model_name,
sampling=self._sampling(cache_salt),
on_delta=on_delta,
)
for trace in episode.traces:
if not episode.ok and trace.ok:
error = episode.last_error or vf.Error(
type="EpisodeFailed", message="A sibling trace in this episode failed"
)
trace.errors = [*trace.errors, error]
trace.ok = False
return episode
class TrainEnv(Env):
@@ -150,17 +143,39 @@ class TrainEnv(Env):
config: TrainSourceConfig,
address: str | None,
address_file: Path,
generation_source: GenerationSource,
clients: InferenceClient,
renderer_config: RendererConfig | None,
algorithm: Algorithm,
):
super().__init__(config, address, address_file)
self.generation_source = generation_source
# Train rollouts are generated from `clients`: the policy, or the frozen
# `sampling.source` connected in setup() with the renderer (token-in/out) client.
self.clients = clients
self.renderer_config = renderer_config
self.connected: InferenceClient | None = None
self.algorithm = algorithm
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
# Truncated policy sampling must ship the sampling masks the trainer replays.
self.requires_sampling_masks = (
config.sampling.truncates_distribution() and config.algo.sampling.source == "policy"
self.uses_live_policy = config.algo.sampling.source == "policy"
self.sampling = vf.SamplingConfig(
**config.sampling.model_dump(exclude_none=True),
# Only policy rollouts need sampling logprobs for importance ratios.
logprobs=True if self.uses_live_policy else None,
)
# Truncated policy sampling must ship the sampling masks the trainer replays.
self.requires_sampling_masks = config.sampling.truncates_distribution() and self.uses_live_policy
async def setup(self) -> None:
async def connect_source() -> None:
source = self.config.algo.sampling.source
if isinstance(source, FrozenModelConfig):
self.connected = await connect_frozen_client(source, renderer_config=self.renderer_config)
self.clients = self.connected
await asyncio.gather(connect_source(), self.algorithm.setup())
async def aclose(self) -> None:
for clients in (self.connected, self.algorithm.connected):
if clients is not None:
await clients.aclose()
class EvalEnv(Env):
@@ -168,7 +183,7 @@ class EvalEnv(Env):
def __init__(self, config: EvalSourceConfig, address: str | None, address_file: Path):
super().__init__(config, address, address_file)
self.sampling_args = config.sampling.to_sampling_args()
self.sampling = config.sampling
self.examples: list[vf.Task] = []
async def start(self) -> None:
@@ -218,9 +233,8 @@ class Envs(Generic[EnvT]):
class TrainEnvs(Envs[TrainEnv]):
"""Collection of training environments, each paired with its
:class:`GenerationSource` and runtime :class:`Algorithm`, built from the env's
resolved algorithm config."""
"""Collection of training environments, each with its runtime
:class:`Algorithm`, built from the env's resolved algorithm config."""
def __init__(
self,
@@ -238,7 +252,8 @@ class TrainEnvs(Envs[TrainEnv]):
config,
addresses[("train", config.resolved_name)],
env_address_file(config_dir, "train", config.resolved_name),
GenerationSource(config.algo.sampling, clients, renderer_config),
clients,
renderer_config,
build_algorithm(config.algo, clients),
)
self._envs[env.name] = env
+26 -27
View File
@@ -6,15 +6,18 @@ including startup. The dispatcher pulls via ``next_task()`` until
from __future__ import annotations
from collections import deque
import uuid
from collections import defaultdict, deque
from collections.abc import Iterable
from itertools import zip_longest
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from verifiers.v1.utils.eval import plan_rollouts
from prime_rl.orchestrator.types import TaskRequest
if TYPE_CHECKING:
import verifiers.v1 as vf
from prime_rl.orchestrator.envs import EvalEnvs
@@ -42,54 +45,50 @@ class EvalSource:
self.intervals[env.name] = intervals[env.name] if intervals is not None else 1
self.queue: deque[TaskRequest] = deque()
self.owed: dict[str, dict[str, int]] | None = None
self.groups: dict[str, dict[str, str]] = {}
# A fresh run evaluates the base policy. Resumed runs apply interval
# rules to the loaded checkpoint and later policies.
self.first_trigger = not is_resumed
def restore(self, owed: dict[str, dict[str, int]], groups: dict[str, dict[str, str]]) -> None:
"""Rollouts the next trigger still owes per env and task key, the rest having
landed before a resume; a task without an entry is complete. ``groups`` is the
group id the landed rollouts of a task carry, which the owed ones join."""
self.owed = owed
self.groups = groups
def trigger(self, step: int, *, force: bool = False) -> list[str]:
"""Fire eligible envs for ``step`` and return their names. On resume
def trigger(
self, step: int, *, force: bool = False, completed: Iterable[vf.WireEpisode] = ()
) -> tuple[list[str], list[vf.WireEpisode]]:
"""Fire eligible envs and return their names and matched saved episodes. On resume
``first_trigger`` is False, so the startup/base eval doesn't re-run.
``force`` fires every env regardless of interval (e.g. the evals process's
final-checkpoint eval)."""
is_first, self.first_trigger = self.first_trigger, False
if is_first and self.skip_first_step:
return []
return [], []
fired = [
name
for name, interval in self.intervals.items()
if (is_first or force or step % interval == 0) and self.tasks_by_env[name]
]
owed, self.owed = self.owed, None
saved: dict[str, list[vf.WireEpisode]] = defaultdict(list)
for episode in completed:
saved[episode.env.name or episode.env.id].append(episode)
restored: list[vf.WireEpisode] = []
# Round-robin across fired envs (A₁, B₁, A₂, B₂, …) so the
# dispatcher rotates at example granularity. ``try_schedule``'s
# continue-group branch still keeps each example's group_size
# rollouts back-to-back, so per-example prefix-cache locality holds
iters = [iter(self.tasks_by_env[name]) for name in fired]
iters = [iter(plan_rollouts(self.tasks_by_env[name], self.group_sizes[name], saved[name])) for name in fired]
for round_tasks in zip_longest(*iters):
for env_name, task in zip(fired, round_tasks, strict=True):
if task is None:
for env_name, planned in zip(fired, round_tasks, strict=True):
if planned is None:
continue
rollouts = self.group_sizes[env_name]
if owed is not None:
# duplicate tasks share a key: each takes up to a group of what the key owes
rollouts = min(rollouts, owed[env_name].get(task.key, 0))
owed[env_name][task.key] = owed[env_name].get(task.key, 0) - rollouts
task, kept, rollouts = planned
# Each selected occurrence owns one group, including its restored episodes.
group = vf.GroupInfo(id=str(uuid.uuid4()))
for episode in kept:
episode.group = group
restored.extend(kept)
if rollouts > 0:
group_id = self.groups.get(env_name, {}).get(task.key)
self.queue.append(
TaskRequest(env_name=env_name, task=task, step=step, rollouts=rollouts, group_id=group_id)
TaskRequest(env_name=env_name, task=task, step=step, rollouts=rollouts, group_id=group.id)
)
return fired
return fired, restored
def next_task(self) -> TaskRequest | None:
"""Pop the next eval task, or ``None`` when the queue is empty."""
@@ -1,49 +0,0 @@
"""Resolve the model source used to generate an env's train episodes."""
from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import FrozenModelConfig, SamplingConfig
from prime_rl.orchestrator.algo import connect_frozen_client
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.orchestrator.clients import InferenceClient
class GenerationSource:
"""One env's generation model and inference clients.
``clients`` is what train rollouts are generated from: the policy clients,
swapped for a connected frozen endpoint in :meth:`setup` when the source is
an inline frozen model. A frozen source *generates* rollouts, so it uses
the renderer (token-in/out) client (built from ``renderer_config``) — the
rollout must carry tokens for training."""
def __init__(self, config: SamplingConfig, clients: InferenceClient, renderer_config: RendererConfig | None = None):
assert config.source is not None, "sampling.source must be resolved by config validation"
self.config = config
self.clients: InferenceClient = clients
self.renderer_config = renderer_config
self.connected: InferenceClient | None = None # frozen clients connected in setup(); closed at shutdown
async def setup(self) -> None:
"""Connect clients to a frozen generation source and wait for
readiness. Must run before dispatching."""
if isinstance(self.config.source, FrozenModelConfig):
self.clients = await connect_frozen_client(self.config.source, renderer_config=self.renderer_config)
self.connected = self.clients
@property
def uses_live_policy(self) -> bool:
return self.config.source == "policy"
def sampling_args(self, args: dict) -> dict:
"""Source-specific sampling-arg overrides. Sampling logprobs are only
needed for importance ratios on policy-sampled tokens — frozen
endpoints may reject the knob."""
if not self.uses_live_policy:
args.pop("logprobs", None)
return args
+15 -24
View File
@@ -86,11 +86,6 @@ SHUTDOWN_TIMEOUT_S = 300
# resumed when the watcher advances ``policy.version``.
TARGET_LAG = 1
# Default wait for the trainer's startup weight broadcast when no ckpt block
# configures ``wait_for_weights_timeout`` (e.g. a from-scratch run). The
# broadcast is always coming, so wait rather than fail immediately.
STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200
class Orchestrator:
# Set in ``__init__``
@@ -282,10 +277,7 @@ class Orchestrator:
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
# Build + ready pools for each env's frozen generation source and the
# algorithm's frozen reference model
await asyncio.gather(
*(env.generation_source.setup() for env in self.train_envs),
*(env.algorithm.setup() for env in self.train_envs),
)
await asyncio.gather(*(env.setup() for env in self.train_envs))
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
@@ -305,9 +297,6 @@ class Orchestrator:
# scratch). The startup broadcast is always coming, so wait for it rather
# than failing immediately when it is not there yet.
sync_version = self.resume_step if self.resume_step is not None else 0
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
STARTUP_WEIGHT_WAIT_TIMEOUT_S
)
self.eval_source: EvalSource | None = (
EvalSource(
@@ -333,7 +322,7 @@ class Orchestrator:
progress=self.progress,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
tasks_per_minute=config.tasks_per_minute,
dispatch_per_minute=config.dispatch_per_minute,
max_off_policy_steps=config.max_off_policy_steps,
run_id=self.run_id,
run_name=self.run_name,
@@ -386,7 +375,7 @@ class Orchestrator:
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
t0 = time.perf_counter()
await self.watcher.sync_startup(sync_version, timeout=wait_timeout)
await self.watcher.sync_startup(sync_version, timeout=config.weight_broadcast.timeout)
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
async def start(self) -> None:
@@ -415,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)
@@ -441,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:
@@ -769,7 +762,7 @@ class Orchestrator:
if self.resume_step == step and self.config.eval is not None and not self.config.eval.retrigger_on_resume:
return
is_final = self.config.max_steps is not None and step >= self.config.max_steps
fired = self.eval_source.trigger(step, force=is_final)
fired, _ = self.eval_source.trigger(step, force=is_final)
if not fired:
return
self.eval_triggered_steps.add(step)
@@ -994,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."""
@@ -1024,11 +1017,9 @@ class Orchestrator:
if self.admin_plane is not None:
await self.admin_plane.aclose()
if self.train_envs is not None:
get_logger().debug("Stopping generation source and algorithm clients")
get_logger().debug("Stopping train env clients")
for env in self.train_envs:
for clients in (env.generation_source.connected, env.algorithm.connected):
if clients is not None:
await clients.aclose()
await env.aclose()
get_logger().info("Stopping orchestrator components")
t0 = time.perf_counter()
@@ -1039,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)}")
+1 -1
View File
@@ -255,7 +255,7 @@ class TrainSink:
return
samples_by_trace: dict[str, list[TrainingSample]] = {}
temperature = env.sampling_args["temperature"]
temperature = env.config.sampling.temperature
for trace in survivors:
samples = await asyncio.to_thread(trace_to_samples, trace, env_name=env_name)
for sample in samples:
+1 -1
View File
@@ -24,7 +24,7 @@ class WeightWatcher:
policy: Policy,
observers: list[VersionObserver],
ckpt_step: int = 0,
poll_interval: float = 1.0,
poll_interval: float = 0.1,
) -> None:
self.receiver = receiver
self.policy = policy
@@ -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 %}
+18 -8
View File
@@ -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 %}
@@ -599,17 +601,25 @@ while true; do
done
REMAINING_PIDS=$(jobs -p)
{%- if cleanup_grace_period %}
{%- if cleanup_grace_period and ckpt_dir %}
# Cross-node teardown is driven by `srun --kill-on-bad-exit=1`, which reaps peer
# tasks only once a task *exits* non-zero. So on a non-zero exit (crash, SIGTERM,
# wall-time) we stay alive for the grace period and signal nothing: this lets an
# in-flight trainer checkpoint on this node finish, and — because the task has
# not exited yet — keeps --kill-on-bad-exit from reaping checkpointing trainers
# on peer nodes. We then propagate the exit code so the allocation tears down. A
# clean (zero) exit cannot trip --kill-on-bad-exit, so we tear down immediately.
# wall-time) we stay alive and signal nothing while the newest trainer checkpoint
# is still being written (no DCP `.metadata` yet), up to the grace period: this lets
# it finish on this node, and — because the task has not exited yet — keeps
# --kill-on-bad-exit from reaping checkpointing trainers on peer nodes. We then
# propagate the exit code so the allocation tears down. A clean (zero) exit cannot
# trip --kill-on-bad-exit, so we tear down immediately.
if [ "$EXIT_CODE" -ne 0 ]; then
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for in-flight checkpoints to flush before teardown"
sleep {{ cleanup_grace_period }}
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for an in-flight trainer checkpoint to finish before teardown"
GRACE_DEADLINE=$((SECONDS + {{ cleanup_grace_period }}))
while [ "$SECONDS" -lt "$GRACE_DEADLINE" ]; do
LATEST_CKPT=$(ls -d {{ ckpt_dir }}/step_*/trainer 2>/dev/null | sort -V | tail -n 1)
if [ -z "$LATEST_CKPT" ] || [ -f "$LATEST_CKPT/.metadata" ]; then
break
fi
sleep 10
done
fi
{%- endif %}
echo "[$(hostname)] tearing down (exit code $EXIT_CODE) - terminating remaining processes"
@@ -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)
+24 -49
View File
@@ -16,10 +16,9 @@ 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 CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
from torch.distributed.fsdp import FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
from torch.distributed.fsdp._fully_shard._fsdp_common import FSDPMeshInfo, ShardPlacementResult
from torch.distributed.fsdp._fully_shard._fsdp_init import _get_mesh_info
from torch.distributed.tensor import 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
@@ -353,22 +356,15 @@ def get_model(
if subconfig is not None and hasattr(subconfig, "use_cache"):
subconfig.use_cache = False
model_config.dsa_backend = config.dsa_backend
if config.index_cache is not None:
# Auto-enable IndexShare from the model's own indexer schedule (e.g. GLM-5.2). The model
# reads `indexer_types` directly: shared layers reuse cached indices and carry no indexer weights.
indexer_types = getattr(model_config, "indexer_types", None)
if indexer_types and any(t == "shared" for t in indexer_types):
model_config.use_index_cache = True
model_config.index_topk_freq = config.index_cache.topk_freq
model_config.index_topk_pattern = config.index_cache.topk_pattern
# Explicit override supersedes the model's native IndexShare schedule.
model_config.indexer_types = None
else:
# Auto-enable IndexShare from the model's own indexer schedule (e.g. GLM-5.2). The model
# reads `indexer_types` directly: shared layers reuse cached indices and carry no indexer weights.
indexer_types = getattr(model_config, "indexer_types", None)
if indexer_types and any(t == "shared" for t in indexer_types):
model_config.use_index_cache = True
logger.info(
f"Auto-enabled IndexShare from indexer_types schedule "
f"({sum(t == 'full' for t in indexer_types)}/{len(indexer_types)} full layers)"
)
logger.info(
f"Auto-enabled IndexShare from indexer_types schedule "
f"({sum(t == 'full' for t in indexer_types)}/{len(indexer_types)} full layers)"
)
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
@@ -509,7 +505,7 @@ def _expert_shard_placement_fn(
def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims):
mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=DTYPE_MAP[config.reduce_dtype])
offload_policy: OffloadPolicy = CPUOffloadPolicy(pin_memory=True) if config.fsdp_cpu_offload else OffloadPolicy()
offload_policy: OffloadPolicy = OffloadPolicy()
fused_shard_placement_fn = get_fsdp_shard_placement_fn(model) if config.fusions.shard_fused_on_dim1 else None
hsdp_mesh = parallel_dims.get_mesh("hsdp")
@@ -593,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,
@@ -640,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
@@ -695,7 +690,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims):
device = "cpu" if config.fsdp_cpu_offload else "cuda"
device = "cuda"
model.to_empty(device=device)
torch.distributed.barrier()
@@ -705,7 +700,6 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
logger = get_logger()
if config.debug.random_init:
logger.warning("Randomly initializing model. Skipping loading weights from HF.")
_move_buffers_to_cuda(model, config)
return
if not Path(config.name).exists():
@@ -760,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")
@@ -773,9 +767,9 @@ 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)
_move_buffers_to_cuda(model, config)
lora_modules = [m for m in model.modules() if hasattr(m, "_init_lora_parameters")]
if lora_modules:
@@ -841,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})"
)
@@ -891,15 +877,6 @@ def configure_trainable_parameters(model: nn.Module, config: ModelConfig) -> nn.
return frozen_vision_encoder
def _move_buffers_to_cuda(model: nn.Module, config: ModelConfig) -> None:
"""FSDP CPU offloading only manages parameters, not buffers. Move buffers to CUDA."""
if not config.fsdp_cpu_offload:
return
for _, buffer in model.named_buffers():
if buffer.device.type == "cpu":
buffer.data = buffer.data.to("cuda")
def _reset_runtime_moe_buffers(model: nn.Module) -> None:
for module in model.modules():
if isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
@@ -1011,24 +988,22 @@ 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."
)
device = "cpu" if config.fsdp_cpu_offload else "cuda"
device = "cuda"
model.to_empty(device=device)
torch.distributed.barrier()
model.init_buffers_post_meta()
_move_buffers_to_cuda(model, config)
else:
load_dcp_from_hf(model, config, parallel_dims)
@@ -367,7 +367,9 @@ class AfmoeModel(AfmoePreTrainedModel):
for layer_idx, decoder_layer in enumerate(self.layers):
mask = causal_mask_mapping[decoder_layer.attention_type] if causal_mask_mapping is not None else None
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
@@ -267,7 +267,9 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
mhc_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous()
for layer_idx, decoder_layer in enumerate(self.layers):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
mhc_states = decoder_layer(
mhc_states,
input_ids=input_ids,
-39
View File
@@ -1,39 +0,0 @@
import torch
from torch import Tensor
def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
"""Quantize a 2D tensor to FP8 e4m3 with per-block scales."""
if weight.ndim != 2:
raise ValueError(f"FP8 quantization expects a 2D tensor, got shape={tuple(weight.shape)}")
rows, cols = weight.shape
pad_rows = (block_size - rows % block_size) % block_size
pad_cols = (block_size - cols % block_size) % block_size
if pad_rows or pad_cols:
padded = torch.zeros(
rows + pad_rows,
cols + pad_cols,
dtype=weight.dtype,
device=weight.device,
)
padded[:rows, :cols] = weight
else:
padded = weight.contiguous()
padded_rows, padded_cols = padded.shape
blocks = padded.view(
padded_rows // block_size,
block_size,
padded_cols // block_size,
block_size,
).permute(0, 2, 1, 3)
fp8_max = torch.finfo(torch.float8_e4m3fn).max
max_abs = blocks.float().abs().amax(dim=(2, 3))
scales = (max_abs / fp8_max).clamp(min=1e-12)
blocks_fp8 = (blocks.float() / scales[:, :, None, None]).clamp(-fp8_max, fp8_max).to(torch.float8_e4m3fn)
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
return quantized, scales.float().contiguous()
@@ -241,7 +241,9 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
cached_indices = None
use_index_cache = getattr(self.config, "use_index_cache", False)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states, next_cached_indices = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
@@ -148,7 +148,7 @@ class GptOssModel(GptOssPreTrainedModel):
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers):
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
layer_routed_experts = routed_experts[:, :, layer_idx].contiguous() if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
position_embeddings,
@@ -12,6 +12,7 @@ import triton.language as tl
FP8_MAX = 448.0
FP8_MIN = -448.0
FP8_EPS = 1e-10
KEY_ALIGNMENT = 16
@triton.jit
@@ -88,17 +89,6 @@ def per_token_group_quant_fp8(
return x_q, x_s
@triton.autotune(
configs=[
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 64}, num_warps=8, num_stages=2),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=8, num_stages=2),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=8, num_stages=3),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=8, num_stages=3),
],
key=["S_Q", "S_K_BUCKET", "H", "D"],
)
@triton.jit
def _triton_fp8_indexer_kernel(
Q_fp8,
@@ -116,7 +106,6 @@ def _triton_fp8_indexer_kernel(
stride_ws,
H: tl.constexpr,
D: tl.constexpr,
S_K_BUCKET: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
@@ -201,6 +190,8 @@ def fp8_indexer(
q_flat = q.reshape(S_q * H, D).contiguous()
q_fp8, q_scales = per_token_group_quant_fp8(q_flat, group_size=D, use_ue8m0=True)
S_k_aligned = triton.cdiv(S_k, KEY_ALIGNMENT) * KEY_ALIGNMENT
k = torch.nn.functional.pad(k, (0, 0, 0, S_k_aligned - S_k))
k_fp8, k_scales = per_token_group_quant_fp8(k.contiguous(), group_size=D, use_ue8m0=True)
q_fp8 = q_fp8.view(S_q, H, D).permute(1, 0, 2).contiguous()
@@ -209,12 +200,10 @@ def fp8_indexer(
q_scales = q_scales.view(S_q, H)
w = w * q_scales
logits = torch.empty(S_q, S_k, dtype=torch.float32, device=device)
logits = torch.empty(S_q, S_k_aligned, dtype=torch.float32, device=device)
grid = lambda meta: (
triton.cdiv(S_q, meta["BLOCK_M"]),
triton.cdiv(S_k, meta["BLOCK_N"]),
)
BLOCK_M, BLOCK_N = 64, 128
grid = (triton.cdiv(S_q, BLOCK_M), triton.cdiv(S_k_aligned, BLOCK_N))
_triton_fp8_indexer_kernel[grid](
q_fp8,
k_fp8,
@@ -224,16 +213,17 @@ def fp8_indexer(
ks,
ke,
S_q,
S_k,
S_k_aligned,
q_fp8.stride(0),
q_fp8.stride(1),
k_fp8.stride(0),
w.stride(0),
H=H,
D=D,
# Packed document tails change S_k between batches. Reuse tuning within
# a size bucket; exact S_k still controls strides and all bounds masks.
S_K_BUCKET=triton.next_power_of_2(S_k),
BLOCK_M=BLOCK_M,
BLOCK_N=BLOCK_N,
num_warps=4,
num_stages=2,
)
actual_topk = min(topk, S_k)
@@ -329,7 +329,9 @@ class LagunaModel(LagunaPreTrainedModel):
}
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
attention_mask=causal_mask_mapping[self.config.layer_types[layer_idx]],
@@ -1,3 +0,0 @@
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
__all__ = ["RMSNorm", "RMSNormConfig"]
@@ -177,7 +177,9 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
@@ -192,7 +192,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
torch._dynamo.mark_dynamic(cu_seqlens, 0)
for layer_idx, decoder_layer in enumerate(self.layers):
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
layer_routed_experts = routed_experts[:, :, layer_idx].contiguous() if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
cu_seqlens,
@@ -13,6 +13,8 @@ from prime_rl.utils.cp import CPContext
# FLA's stacked output buffer. Keep CP convolution eager until this is fixed:
# https://github.com/pytorch/pytorch/issues/155632
causal_conv1d_with_context_parallelism = torch.compiler.disable(causal_conv1d)
# CP setup searchsorts tensor-valued sequence boundaries; keep it outside the compiled graph.
build_cp_context_eager = torch.compiler.disable(build_cp_context)
class Qwen3_5GatedDeltaNet(nn.Module):
@@ -65,7 +67,7 @@ class Qwen3_5GatedDeltaNet(nn.Module):
context = None
if self.cp_context.cp_enabled:
context = build_cp_context(
context = build_cp_context_eager(
cu_seqlens=cu_seqlens.to(device=hidden_states.device, dtype=torch.int32),
group=self.cp_context.cp_group,
conv1d_kernel_size=self.conv_kernel_size,
@@ -210,7 +210,9 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,

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