Compare commits

...
Author SHA1 Message Date
samsjaandGitHub 3925d27f4f feat(inference): allow MXFP8 online quantization (#4045)
## What

`[inference.vllm] quantization` is typed as `Literal["fp8_per_block"]`,
so it is currently impossible to serve with MXFP8. This PR adds
`"mxfp8"`.

## Why

vLLM supports `--quantization mxfp8` as an online shorthand: a BF16/FP16
checkpoint's weights are quantized to MXFP8 at load (E4M3 values with
block-32 E8M0 scales) and activations are quantized dynamically per
forward, for both dense linears and MoE experts. On Blackwell
(SM100/SM103) vLLM auto-selects native W8A8 block-scaled GEMMs
(FlashInfer CuTe-DSL); older GPUs fall back to W8A16 (Marlin). This is
useful for serving BF16 SFT exports on B200/B300 without building an FP8
checkpoint.

## How

The value already passes through verbatim to vLLM's `--quantization`;
the pydantic `Literal` was the only gate. vLLM validates the shorthand
and picks the kernel at startup (`Using <kernel> for MXFP8 GEMM`), so no
further wiring is needed. Unknown shorthands (e.g. `mxfp4`) stay
rejected.

Verified locally: `InferenceConfig(vllm={"quantization": "mxfp8"})`
validates, `ruff check`/`format` pass, and `tests/unit/test_configs.py`
shows no new failures (20 pre-existing failures reproduce on pristine
`origin/main` with this checkout's venv).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single-type widening in config validation with no runtime wiring
changes; vLLM still validates quantization at server startup.
> 
> **Overview**
> Extends **`inference.vllm.quantization`** so configs can set
**`mxfp8`** alongside the existing **`fp8_per_block`** option. That
value already forwards to vLLM’s `--quantization`; the only change is
lifting the Pydantic **`Literal`** gate that previously rejected MXFP8
at parse time.
> 
> This enables online MXFP8 serving (quantize BF16/FP16 weights at load,
dynamic activation quant) on supported hardware without a separate FP8
checkpoint—useful for BF16 SFT exports on Blackwell-class GPUs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
777ad501a85ced1985b1b735b4d633ff2ec2d71d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-13 17:48:24 -07:00
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
7 changed files with 84 additions and 13 deletions
@@ -29,7 +29,7 @@ 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)
QuantizationType = Literal["fp8_per_block"]
QuantizationType = Literal["fp8_per_block", "mxfp8"]
class VllmConfig(BaseConfig):
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "prime-rl"
version = "0.9.0"
version = "0.10.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
+60
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()
@@ -32,6 +33,65 @@ def apply_shared_vllm_patches():
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():
"""Let vLLM's `DeepseekV4Config` construct under a transformers pin below 5.15.
+5 -8
View File
@@ -152,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."""
@@ -230,6 +222,11 @@ class CheckpointManager:
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, 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):
+2 -2
View File
@@ -105,7 +105,7 @@ class FakeDataset(StatefulIterableDataset):
else self.seq_len
)
random_input_ids = (
torch.randint(0, self.vocab_size, (self.seq_len + 1,), generator=generator).long().tolist()
torch.randint(0, self.vocab_size, (seq_len + 1,), generator=generator).long().tolist()
if self.input_ids == "random"
else None
)
@@ -144,7 +144,7 @@ class FakeDataset(StatefulIterableDataset):
"mm_token_type_ids": None,
}
self.num_samples["fake"] += 1
self.num_tokens["fake"] += len(input_ids)
self.num_tokens["fake"] += seq_len
yield fake_sample
+14
View File
@@ -26,6 +26,20 @@ def test_fake_dataset_state():
assert dataset.state_dict() == {"step": 4, "epoch": 0}
@pytest.mark.parametrize("length", ["fixed", "variable"])
@pytest.mark.parametrize("input_ids", ["increasing", "random"])
def test_fake_dataset_sample_lengths(length: str, input_ids: str):
dataset = FakeDataset(vocab_size=10000, seq_len=128, length=length, input_ids=input_ids)
dataiter = iter(dataset)
for _ in range(20):
sample = next(dataiter)
seq_len = len(sample["input_ids"])
assert len(sample["target_ids"]) == seq_len
assert len(sample["position_ids"]) == seq_len
assert len(sample["loss_mask"]) == seq_len
assert sum(sample["seq_lens"]) == seq_len
@pytest.mark.parametrize("length", ["fixed", "variable"])
@pytest.mark.parametrize("data_world_size", [1, 2, 3])
def test_fake_dataset_random_resume(length: str, data_world_size: int):
Generated
+1 -1
View File
@@ -4999,7 +4999,7 @@ dev = [
[[package]]
name = "prime-rl"
version = "0.9.0"
version = "0.10.0"
source = { editable = "." }
dependencies = [
{ name = "aiolimiter" },