Compare commits

...
Author SHA1 Message Date
Pulipaka Sai KrishnaandGitHub 32b502bf0c feat(transports): trainer pulls each batch step (#4065)
Trainer ranks pull batches: every rank requests step N when it is ready
to train it, and the orchestrator sends N only once every trainer rank
asked. So the trainer only ever holds the batch it is training on, and
the last step the orchestrator sent is always the one the trainer is on.

- zmq: one ROUTER in the orchestrator, one DEALER per trainer rank (from
#4066). The orchestrator replies to each rank on the connection it asked
on, so there's no slow-joiner race, no READY barrier and no `hwm`.
`ROUTER_MANDATORY` raises on a vanished rank instead of dropping.
- Every trainer rank counts, not one per data rank: requests carry rank,
world size, data rank and step. A request for any other step raises,
since it means the two sides resumed from different steps.
- filesystem: each rank drops `step_N/rank_R.request` holding the world
size, and the orchestrator renames the step's files into place once all
are there.
- `send` blocks until the step went out and returns the hand-off
seconds, logged as `time/send_batch`. The wait before it is now
`time/wait_for_policy` (same key, measured at the send instead of while
the dispatcher is paused). Encoding happens before the wait.
- The ship-time policy-version hold is removed: it was a proxy for
"trainer is ready", which the request now says directly. The dispatch
gate and off-policy filter still bound rollout staleness.

Tested on telus (3x H200: 2 trainer ranks + 1 inference, reverse-text,
20 steps, `commit-4b3319f3a` + this patch):
- zmq: finished, mean step 4.14s (steps 2-20), `time/send_batch` mean
0.6ms / max 6ms
- filesystem: finished, both ranks wrote their request marker each step
- resume from step 15 (zmq): continued to step 20

Linear: RES-1384
2026-10-14 04:58:27 -05:00
minh hoangandGitHub 9b1904e7d2 improvement(prime-rl-configs): expose RL component serialization from the config package (#4082)
The k8s launcher (and potentially prime CLI for client side config
validation) needs to serialize validated RL configs using the selected
schema without importing runtime launchers. Expose
`dump_rl_components()` from the CPU config package and reuse it in the
local RL launcher when writing component JSON files.

The shared helper preserves schema fields and null values, retains the
existing inference launcher-field exclusions, and disables the inference
router for multi-node deployments. The launcher's JSON output behavior
stays the same.

Validation: Ruff and `git diff --check` passed on the rebased branch.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior-preserving refactor that centralizes existing JSON
serialization rules; no auth, data, or runtime wiring changes.
> 
> **Overview**
> Adds **`dump_rl_components()`** to the CPU-only `prime-rl-configs`
package so validated RL configs can be split into
trainer/orchestrator/inference dicts **without importing launchers or
writing files**—for k8s and client-side validation.
> 
> The helper reuses `dump_resolved_config` (JSON with explicit nulls),
applies the same inference exclusions (`deployment`, `slurm`,
`output_dir`, `dry_run`), and sets `inference["router"]` to `None` for
**multi-node** deployments. `RLConfig` is referenced only under
**`TYPE_CHECKING`** to keep the slim package lightweight.
> 
> The local RL launcher’s **`write_subconfigs`** now loops over
`dump_rl_components()` instead of inlining that logic; output paths and
JSON shape are unchanged (docstring updated from TOML to JSON).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
499aa13b77eda37fc2435d9e22c5f1f3cb44f88c. 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 21:44:52 -07:00
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
18 changed files with 361 additions and 199 deletions
+1 -1
View File
@@ -12,7 +12,7 @@ A `prime-rl` RL run is three cooperating processes:
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, and LoRA. You can read more in the dedicated [training documentation](training.md).
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses ZMQ, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap the rollout link to the local filesystem (`rollout_transport.type = "filesystem"`) if you want rollouts persisted to disk. See [Scaling](scaling.md) for the deployment options.
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses ZMQ (each trainer rank requests a step before the orchestrator sends it, so the trainer only ever holds the batch it is training on), and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap the rollout link to the local filesystem (`rollout_transport.type = "filesystem"`) if you want rollouts persisted to disk. See [Scaling](scaling.md) for the deployment options.
## Installation
@@ -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):
@@ -286,10 +286,7 @@ class ZMQTransportConfig(BaseTransportConfig):
"""Host address for ZMQ transport."""
port: int = 5555
"""Base port for ZMQ transport."""
hwm: int = 10
"""High-water mark (max in-flight messages per ZMQ socket)."""
"""Port for ZMQ transport."""
TransportConfig: TypeAlias = Annotated[FileSystemTransportConfig | ZMQTransportConfig, Field(discriminator="type")]
@@ -1,11 +1,14 @@
import os
from pathlib import Path
from typing import Any
from typing import TYPE_CHECKING, Any
from pydantic import BaseModel
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
from pydantic_config import cli # noqa: F401
if TYPE_CHECKING:
from prime_rl.configs.rl import RLConfig
def default_output_dir() -> Path:
"""Default output directory: ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
@@ -22,6 +25,24 @@ def dump_resolved_config(config: BaseModel, exclude: set[str] | None = None) ->
return config.model_dump(exclude=exclude, mode="json")
def dump_rl_components(config: "RLConfig") -> dict[str, dict]:
"""Serialize a validated RL config without importing launchers or writing files.
Keep arbitrary schema fields and explicit nulls. Hosted compilers can use
this from the CPU-only configs distribution, alongside the local launcher.
"""
components = {
"trainer": dump_resolved_config(config.trainer),
"orchestrator": dump_resolved_config(config.orchestrator),
}
if config.inference is not None:
inference = dump_resolved_config(config.inference, exclude={"deployment", "slurm", "output_dir", "dry_run"})
if config.deployment.type == "multi_node":
inference["router"] = None
components["inference"] = inference
return components
def find_package_resource(subdir: str) -> Path | None:
"""Find a directory contributed to the `prime_rl` namespace package by any installed wheel.
+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"
+6 -18
View File
@@ -12,7 +12,7 @@ from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
from prime_rl.entrypoints.inference import vllm_overrides_fragment
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.config import cli, dump_resolved_config, dump_rl_components
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import (
clean_future_steps,
@@ -82,24 +82,12 @@ def rl_config_components(config: RLConfig, config_dir: Path) -> list[tuple[str,
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
"""Write resolved subconfigs to disk as TOML files."""
"""Write resolved subconfigs to disk as JSON files."""
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_dir / TRAINER_CONFIG, "w") as f:
json.dump(dump_resolved_config(config.trainer), f, indent=2)
with open(output_dir / ORCHESTRATOR_CONFIG, "w") as f:
json.dump(dump_resolved_config(config.orchestrator), f, indent=2)
if config.inference is not None:
# Exclude launcher-only fields that are not needed by the vLLM server
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
inference_dict = dump_resolved_config(config.inference, exclude=exclude_inference)
if config.deployment.type == "multi_node":
# Per-rank processes run bare engines; the sbatch starts the single global router.
inference_dict["router"] = None
with open(output_dir / INFERENCE_CONFIG, "w") as f:
json.dump(inference_dict, f, indent=2)
filenames = {"trainer": TRAINER_CONFIG, "orchestrator": ORCHESTRATOR_CONFIG, "inference": INFERENCE_CONFIG}
for name, component in dump_rl_components(config).items():
with open(output_dir / filenames[name], "w") as f:
json.dump(component, f, indent=2)
# One EnvServerConfig per launcher-managed source: `env-server @ <path>` binds an
# OS-assigned port and publishes it to the source's address file, where the
+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.
+15 -36
View File
@@ -81,9 +81,10 @@ from prime_rl.utils.utils import clean_exit
# shutdown wedges (env-server ZMQ recv, vLLM admin aclose, etc)
SHUTDOWN_TIMEOUT_S = 300
# Maximum batches the orchestrator may run ahead of the trainer. The
# dispatcher is paused via ``update_dispatch_gate`` once this is exceeded;
# resumed when the watcher advances ``policy.version``.
# Maximum shipped batches that inference has not applied the policy for yet. The
# dispatcher is paused via ``update_dispatch_gate`` once this is exceeded; resumed
# when the watcher advances ``policy.version``. Shipping itself is paced by the
# trainer: a batch goes out only once every trainer rank requested it.
TARGET_LAG = 1
@@ -144,10 +145,8 @@ class Orchestrator:
self.last_batch_at = None
# Trigger timestamps so eval success logs can report epoch duration
self.eval_triggered_at = {}
self.gate_closed_at = None
# Pulsed after inference applies a policy so held work can re-check it.
# Pulsed after inference applies a policy, waking wait_for_version.
self.version_advanced = asyncio.Event()
self.wait_for_policy_time = 0.0
self.eval_triggered_steps: set[int] = set()
self.component_tasks = []
@@ -586,26 +585,6 @@ class Orchestrator:
f"({n_trainable / effective.num_traces:.1%}) — consider reviewing task difficulty"
)
# Ship batch ``step`` only once inference has applied v{step-1-TARGET_LAG}.
# Without this, fast envs fill batches from buffered rollouts and the
# orchestrator races arbitrarily far ahead of the trainer. Always
# satisfiable: the trainer broadcasts every version, and
# ``wait_for_final_broadcast`` keeps the watcher alive through the last
# rendezvous after the pipeline drains.
required_version = step - 1 - TARGET_LAG
if self.policy.version < required_version:
get_logger().info(
f"Holding batch {step} until inference applies policy v{required_version} "
f"(currently v{self.policy.version})"
)
hold_start = time.perf_counter()
while True:
self.version_advanced.clear()
if self.policy.version >= required_version:
break
await self.version_advanced.wait()
self.wait_for_policy_time += time.perf_counter() - hold_start
# The effective (clean, trained-on) subset is logged at ship time as annotation
# records against each trace's arrival record - membership, advantages, the step
# it shipped at - never a second episode copy.
@@ -615,7 +594,11 @@ class Orchestrator:
pack_start_time = time.perf_counter()
micro_batch_grid = await asyncio.to_thread(self.packer.pack, batch.samples)
pack_time = time.perf_counter() - pack_start_time
await self.sender.send(micro_batch_grid)
# Sending blocks until every trainer rank requested the batch, so the wait is the time
# the orchestrator spent waiting on the trainer for the next policy.
send_start_time = time.perf_counter()
send_batch_time = await self.sender.send(micro_batch_grid)
wait_for_policy_time = time.perf_counter() - send_start_time - send_batch_time
self.progress.step += 1
self.update_dispatch_gate()
# Checkpoint the step we just shipped (resume point: continue at step + 1).
@@ -667,7 +650,8 @@ class Orchestrator:
"time/step": step_time,
"time/pack": pack_time,
"time/save_ckpt": save_ckpt_time,
"time/wait_for_policy": self.wait_for_policy_time,
"time/send_batch": send_batch_time,
"time/wait_for_policy": wait_for_policy_time,
"step": step,
}
# Staleness of the shipped cohort, decomposed into its in-flight and
@@ -691,10 +675,10 @@ class Orchestrator:
metrics |= self.train_source.metrics()
await monitors.log(metrics, step=step)
active_step_time = max(step_time - self.wait_for_policy_time, 0.0)
if step_time > 0 and self.wait_for_policy_time >= active_step_time:
active_step_time = max(step_time - wait_for_policy_time, 0.0)
if step_time > 0 and wait_for_policy_time >= active_step_time:
get_logger().warning(
f"Orchestrator waited {format_time(self.wait_for_policy_time)} for policy updates, at least as long "
f"Orchestrator waited {format_time(wait_for_policy_time)} for policy updates, at least as long "
f"as its {format_time(active_step_time)} active step time. Train-inference compute is imbalanced; "
"add more trainer nodes."
)
@@ -722,7 +706,6 @@ class Orchestrator:
f"stale={num_stale}, errored={num_errored}, no_signal={num_no_signal}. Review max_off_policy_steps, "
"episode errors, and reward signal."
)
self.wait_for_policy_time = 0.0
if self.heart is not None:
self.heart.beat()
@@ -972,14 +955,10 @@ class Orchestrator:
f"Pausing dispatcher until inference applies policy v{self.progress.step - 1 - TARGET_LAG} "
f"(currently v{self.policy.version})"
)
self.gate_closed_at = time.perf_counter()
gate.clear()
else:
if not was_set:
get_logger().info(f"Resuming dispatcher (policy v{self.policy.version})")
if self.gate_closed_at is not None:
self.wait_for_policy_time += time.perf_counter() - self.gate_closed_at
self.gate_closed_at = None
gate.set()
async def on_policy_update(self, _step: int) -> None:
+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):
+8 -1
View File
@@ -209,7 +209,14 @@ class DataLoader:
non_dp_world_size = self.world.world_size // dp_world_size
dp_rank = self.world.rank // non_dp_world_size
self.receiver: BatchReceiver = setup_batch_receiver(output_dir, dp_rank, start_step, config)
self.receiver: BatchReceiver = setup_batch_receiver(
output_dir,
data_rank=dp_rank,
rank=self.world.rank,
world_size=self.world.world_size,
current_step=start_step,
transport=config,
)
def wait_for_batch(self) -> None:
self.receiver.wait()
+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
+3 -3
View File
@@ -32,12 +32,12 @@ def setup_batch_sender(
def setup_batch_receiver(
output_dir: Path, data_rank: int, current_step: int, transport: TransportConfig
output_dir: Path, data_rank: int, rank: int, world_size: int, current_step: int, transport: TransportConfig
) -> BatchReceiver:
if transport.type == "filesystem":
return FileSystemBatchReceiver(output_dir, data_rank, current_step)
return FileSystemBatchReceiver(output_dir, data_rank, rank, world_size, current_step)
elif transport.type == "zmq":
return ZMQBatchReceiver(output_dir, data_rank, current_step, transport)
return ZMQBatchReceiver(output_dir, data_rank, rank, world_size, current_step, transport)
else:
raise ValueError(f"Invalid transport type: {transport.type}")
+13 -11
View File
@@ -8,7 +8,11 @@ from prime_rl.utils.logger import get_logger
class BatchSender(ABC):
"""Base class for sending micro batches from the orchestrator to the train workers."""
"""Base class for sending micro batches from the orchestrator to the train workers.
Trainer ranks pull: a step goes out only once every trainer rank requested it, so the
trainer only ever holds the batch it is training on, and the last step sent is always the
one the trainer is on."""
def __init__(self, output_dir: Path, data_world_size: int):
self.logger = get_logger()
@@ -17,8 +21,9 @@ class BatchSender(ABC):
self.data_world_size = data_world_size
@abstractmethod
async def send(self, micro_batch_grid: list[list[MicroBatch]]) -> None:
"""Send grid of micro batches to the trainers."""
async def send(self, micro_batch_grid: list[list[MicroBatch]]) -> float:
"""Send grid of micro batches to the trainers once every trainer rank requested the step.
Returns the seconds spent handing the step to the transport, excluding the wait."""
pass
def close(self) -> None:
@@ -29,25 +34,22 @@ class BatchSender(ABC):
class BatchReceiver(ABC):
"""Base class for receiving micro batches from the orchestrator."""
def __init__(self, output_dir: Path, data_rank: int):
def __init__(self, output_dir: Path, data_rank: int, rank: int, world_size: int):
self.logger = get_logger()
self.decoder = msgspec.msgpack.Decoder(type=list[MicroBatch])
self.output_dir = output_dir
self.data_rank = data_rank
self.rank = rank
self.world_size = world_size
@abstractmethod
def wait(self) -> None:
"""Wait for a micro batch to be available."""
pass
@abstractmethod
def can_receive(self) -> bool:
"""Check if a micro batch is available."""
"""Request the current step from the orchestrator and block until it is available."""
pass
@abstractmethod
def receive(self) -> list[MicroBatch]:
"""Receive a micro batch from the orchestrator."""
"""Receive the micro batches ``wait`` requested."""
pass
def close(self) -> None:
+39 -16
View File
@@ -1,22 +1,34 @@
import asyncio
import time
from pathlib import Path
from prime_rl.transports.batch.base import BatchReceiver, BatchSender
from prime_rl.transports.batch.types import MicroBatch
from prime_rl.utils.pathing import get_batch_dir, get_step_path, sync_wait_for_path
REQUEST_POLL_INTERVAL_S = 0.1
def write_atomic(path: Path, data: bytes) -> None:
tmp_path = path.with_suffix(path.suffix + ".tmp")
tmp_path.write_bytes(data)
tmp_path.rename(path)
class FileSystemBatchSender(BatchSender):
"""Filesystem-based micro batch sender that writes micro batches to disk."""
"""Filesystem-based micro batch sender that writes micro batches to disk. Every trainer rank
drops a request marker holding the trainer world size into the step directory, and the step is
published only once every rank's marker is there."""
def __init__(self, output_dir: Path, data_world_size: int, current_step: int = 0):
super().__init__(output_dir, data_world_size)
self.batch_dir = get_batch_dir(output_dir)
self.current_step = current_step
async def send(self, micro_batch_grid: list[list[MicroBatch]]) -> None:
"""Send grid of micro batches to the trainers. Encode + write run in a worker
thread so the orchestrator event loop stays responsive during step transitions."""
async def send(self, micro_batch_grid: list[list[MicroBatch]]) -> float:
"""Send grid of micro batches to the trainers. Encode + write run in a worker thread so the
orchestrator event loop stays responsive, and before the wait, so only the rename sits
between the last request and the batch."""
assert len(micro_batch_grid) == self.data_world_size, "Number of micro batch lists must match data world size"
for micro_batch_list in micro_batch_grid:
assert len(micro_batch_list) == len(micro_batch_grid[0]), "All micro batch lists must have the same length"
@@ -24,22 +36,34 @@ class FileSystemBatchSender(BatchSender):
step_path = get_step_path(self.batch_dir, self.current_step)
step_path.mkdir(parents=True, exist_ok=True)
await asyncio.to_thread(self._encode_and_write, micro_batch_grid, step_path)
await self._wait_for_requests(step_path)
send_start = time.perf_counter()
for data_rank in range(self.data_world_size):
(step_path / f"rank_{data_rank}.bin.tmp").rename(step_path / f"rank_{data_rank}.bin")
send_end = time.perf_counter()
self.current_step += 1
return send_end - send_start
def _encode_and_write(self, micro_batch_grid: list[list[MicroBatch]], step_path: Path) -> None:
for data_rank in range(self.data_world_size):
buffer = self.encoder.encode(micro_batch_grid[data_rank])
tmp_path = step_path / f"rank_{data_rank}.bin.tmp"
with open(tmp_path, "wb") as f:
f.write(buffer)
tmp_path.rename(step_path / f"rank_{data_rank}.bin")
(step_path / f"rank_{data_rank}.bin.tmp").write_bytes(self.encoder.encode(micro_batch_grid[data_rank]))
async def _wait_for_requests(self, step_path: Path) -> None:
"""Block until every trainer rank requested the step. The markers hold the trainer world
size, so the first one says how many to wait for."""
while True:
request_paths = list(step_path.glob("rank_*.request"))
if request_paths and len(request_paths) == int(request_paths[0].read_text()):
return
await asyncio.sleep(REQUEST_POLL_INTERVAL_S)
class FileSystemBatchReceiver(BatchReceiver):
"""Filesystem-based micro batch receiver that reads micro batches from disk."""
def __init__(self, output_dir: Path, data_rank: int, current_step: int = 0):
super().__init__(output_dir, data_rank)
def __init__(self, output_dir: Path, data_rank: int, rank: int, world_size: int, current_step: int = 0):
super().__init__(output_dir, data_rank, rank, world_size)
self.batch_dir = get_batch_dir(output_dir)
self.current_step = current_step
@@ -47,13 +71,12 @@ class FileSystemBatchReceiver(BatchReceiver):
return get_step_path(self.batch_dir, self.current_step) / f"rank_{self.data_rank}.bin"
def wait(self) -> None:
"""Wait for the micro batch file to appear on disk."""
"""Request the current step, then wait for its micro batch file to appear on disk."""
step_path = get_step_path(self.batch_dir, self.current_step)
step_path.mkdir(parents=True, exist_ok=True)
write_atomic(step_path / f"rank_{self.rank}.request", str(self.world_size).encode())
sync_wait_for_path(self._get_micro_batch_path())
def can_receive(self) -> bool:
"""Check if the micro batch file exists."""
return self._get_micro_batch_path().exists()
def receive(self) -> list[MicroBatch]:
"""Read and return the micro batches from disk."""
with open(self._get_micro_batch_path(), "rb") as f:
+78 -95
View File
@@ -1,5 +1,7 @@
import time
from pathlib import Path
import msgspec
import zmq
import zmq.asyncio
@@ -8,134 +10,115 @@ from prime_rl.transports.batch.base import BatchReceiver, BatchSender
from prime_rl.transports.batch.types import MicroBatch
class BatchRequest(msgspec.Struct):
"""A trainer rank asking for its micro batches of one step."""
world_size: int
data_rank: int
step: int
class ZMQBatchSender(BatchSender):
def __init__(self, output_dir: Path, data_world_size: int, current_step: int, transport: ZMQTransportConfig):
"""ZMQ micro batch sender that publishes per-rank micro batches to the trainers.
There is one sender (in the orchestrator process) for the entire data world.
PUB never blocks: a message past a subscriber's HWM would be dropped
silently. The orchestrator's dispatch gate bounds in-flight steps to
TARGET_LAG + 1 (one message per rank per step), far below the HWM, so
drops cannot happen in steady state; the READY barrier below covers
slow joiners at startup.
"""
"""ZMQ micro batch sender. One ROUTER socket in the orchestrator answers the DEALER socket of
every trainer rank, replying to each rank on the connection it asked on."""
super().__init__(output_dir, data_world_size)
# Async context so ``send`` yields instead of blocking the orchestrator event loop
self.context = zmq.asyncio.Context.instance()
# Data channel (PUB)
self.socket: zmq.asyncio.Socket = self.context.socket(zmq.PUB)
self.socket.setsockopt(zmq.SNDHWM, transport.hwm)
self.socket: zmq.asyncio.Socket = self.context.socket(zmq.ROUTER)
# Replying to a rank that went away raises instead of dropping silently
self.socket.setsockopt(zmq.ROUTER_MANDATORY, 1)
self.socket.bind(f"tcp://{transport.host}:{transport.port}")
self.request_decoder = msgspec.msgpack.Decoder(type=BatchRequest)
self.current_step = current_step
self.logger.debug(f"Initialized ZMQ micro batch sender (endpoint=tcp://{transport.host}:{transport.port})")
# ready barrier socket, to avoid slow joiners dropping for step 0 (and generally at startup)
self.ready_socket: zmq.asyncio.Socket = self.context.socket(zmq.PULL)
self.ready_socket.setsockopt(zmq.RCVHWM, transport.hwm)
self.ready_socket.bind(f"tcp://{transport.host}:{transport.port + 1}")
self._ready = False
self.logger.debug(
f"Initialized ZMQ micro batch sender (endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm})"
)
self._topic_prefix = b"data_rank|"
self._current_step = current_step
async def _wait_for_ready(self) -> None:
if self._ready:
return
self.logger.debug(f"Waiting for {self.data_world_size} READY messages")
ready_ranks: set[int] = set()
# Block until all ranks have announced readiness
while len(ready_ranks) < self.data_world_size:
msg = await self.ready_socket.recv()
try:
rank = int(msg.decode("utf-8"))
except Exception:
continue
ready_ranks.add(rank)
self.logger.debug(f"All {self.data_world_size} ranks READY, starting PUB")
self._ready = True
async def send(self, micro_batch_grid: list[list[MicroBatch]]) -> None:
"""Send grid of micro batches to the trainers."""
async def send(self, micro_batch_grid: list[list[MicroBatch]]) -> float:
"""Send grid of micro batches to the trainers. Encoding happens before the wait, so only the
hand-off sits between the last request and the batch."""
assert len(micro_batch_grid) == self.data_world_size, "Number of micro batch lists must match data world size"
for micro_batch_list in micro_batch_grid:
assert len(micro_batch_list) == len(micro_batch_grid[0]), "All micro batch lists must have the same length"
# Ensure no slow-joiner drops for step 0 (and generally at startup)
await self._wait_for_ready()
buffers = [self.encoder.encode(micro_batch_list) for micro_batch_list in micro_batch_grid]
identity_to_request = await self._wait_for_requests()
send_start = time.perf_counter()
for identity, request in identity_to_request.items():
await self.socket.send_multipart([identity, buffers[request.data_rank]], copy=False)
send_end = time.perf_counter()
self.logger.debug(f"Sending micro batch grid for step {self._current_step}")
for data_rank in range(self.data_world_size):
buffer = self.encoder.encode(micro_batch_grid[data_rank])
topic = self._topic_prefix + str(data_rank).encode("utf-8") + b"|"
await self.socket.send_multipart([topic, buffer], copy=False)
self._current_step += 1
self.logger.debug(f"Sent micro batch grid for step {self.current_step} to {len(identity_to_request)} ranks")
self.current_step += 1
return send_end - send_start
def close(self) -> None:
try:
self.socket.close(linger=0)
self.ready_socket.close(linger=0)
finally:
self.logger.debug("Closed ZMQ micro batch sender")
async def _receive_request(self) -> tuple[bytes, BatchRequest]:
"""A rank requests the next step only after receiving this one, so any other step means the
orchestrator and trainer resumed from different steps."""
identity, payload = await self.socket.recv_multipart()
request = self.request_decoder.decode(payload)
if request.step != self.current_step:
raise RuntimeError(
f"A trainer rank requested step {request.step}, but the orchestrator is on step "
f"{self.current_step}. Resume both from the same checkpoint step."
)
return identity, request
async def _wait_for_requests(self) -> dict[bytes, BatchRequest]:
"""Collect one request per trainer rank for the current step. Each request carries the
trainer world size, so the first one says how many to wait for."""
identity, request = await self._receive_request()
identity_to_request = {identity: request}
while len(identity_to_request) < request.world_size:
identity, request = await self._receive_request()
identity_to_request[identity] = request
return identity_to_request
class ZMQBatchReceiver(BatchReceiver):
def __init__(self, output_dir: Path, data_rank: int, current_step: int, transport: ZMQTransportConfig):
"""ZMQ micro batch receiver that receives micro batches from the orchestrator. There is one receiver per data rank."""
super().__init__(output_dir, data_rank)
def __init__(
self,
output_dir: Path,
data_rank: int,
rank: int,
world_size: int,
current_step: int,
transport: ZMQTransportConfig,
):
"""ZMQ micro batch receiver. Every trainer rank owns one DEALER socket and requests each step
before reading it."""
super().__init__(output_dir, data_rank, rank, world_size)
self.context = zmq.Context.instance()
self.socket: zmq.Socket = self.context.socket(zmq.SUB)
self.socket.setsockopt(zmq.RCVHWM, transport.hwm)
self.socket: zmq.Socket = self.context.socket(zmq.DEALER)
self.socket.connect(f"tcp://{transport.host}:{transport.port}")
self._topic = b"data_rank|" + str(data_rank).encode("utf-8") + b"|"
self.socket.setsockopt(zmq.SUBSCRIBE, self._topic)
self.poller = zmq.Poller()
self.poller.register(self.socket, zmq.POLLIN)
# ready barrier socket, to avoid slow joiners dropping for step 0 (and generally at startup)
self.ready_socket: zmq.Socket = self.context.socket(zmq.PUSH)
self.ready_socket.setsockopt(zmq.SNDHWM, transport.hwm)
self.ready_socket.connect(f"tcp://{transport.host}:{transport.port + 1}")
# Announce readiness after connect+subscribe are set
self.ready_socket.send(str(data_rank).encode("utf-8"))
self.logger.debug(
f"Initialized ZMQ micro batch receiver (endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm})"
)
self._current_step = current_step
self.request_encoder = msgspec.msgpack.Encoder()
self.current_step = current_step
self.logger.debug(f"Initialized ZMQ micro batch receiver (endpoint=tcp://{transport.host}:{transport.port})")
def wait(self) -> None:
self.poller.poll(timeout=None)
def can_receive(self) -> bool:
events = dict(self.poller.poll(timeout=0))
return self.socket in events
request = BatchRequest(
world_size=self.world_size,
data_rank=self.data_rank,
step=self.current_step,
)
self.socket.send(self.request_encoder.encode(request))
self.socket.poll(timeout=None)
def receive(self) -> list[MicroBatch]:
"""Receive a micro batch from the orchestrator."""
_, payload = self.socket.recv_multipart(copy=False)
payload = self.socket.recv(copy=False)
micro_batches: list[MicroBatch] = self.decoder.decode(payload)
self.logger.debug(f"Received {len(micro_batches)} micro batches for step {self._current_step}")
self._current_step += 1
self.logger.debug(f"Received {len(micro_batches)} micro batches for step {self.current_step}")
self.current_step += 1
return micro_batches
def close(self) -> None:
try:
self.socket.close(linger=0)
self.ready_socket.close(linger=0)
finally:
self.logger.debug("Closed ZMQ micro batch receiver")
+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):
@@ -0,0 +1,91 @@
import asyncio
import socket
from collections.abc import Callable
from pathlib import Path
import pytest
from prime_rl.configs.shared import ZMQTransportConfig
from prime_rl.transports.batch.base import BatchReceiver, BatchSender
from prime_rl.transports.batch.filesystem import FileSystemBatchReceiver, FileSystemBatchSender
from prime_rl.transports.batch.types import MicroBatch
from prime_rl.transports.batch.zmq import ZMQBatchReceiver, ZMQBatchSender
def _micro_batch(token: int) -> MicroBatch:
return MicroBatch(
input_ids=[token],
loss_mask=[True],
advantages=[1.0],
inference_logprobs=[0.0],
position_ids=[0],
sequence_lengths=[1],
temperatures=[1.0],
env_names=["env"],
seq_lens=[1],
)
MICRO_BATCH_GRID = [[_micro_batch(0)], [_micro_batch(1)]]
# Two data ranks, each split across two trainer ranks (e.g. tensor parallel)
RANK_TO_DATA_RANK = [0, 0, 1, 1]
def _free_port() -> int:
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
def _filesystem(output_dir: Path) -> tuple[BatchSender, list[BatchReceiver]]:
sender = FileSystemBatchSender(output_dir, data_world_size=2)
receivers = [
FileSystemBatchReceiver(output_dir, data_rank, rank, world_size=len(RANK_TO_DATA_RANK))
for rank, data_rank in enumerate(RANK_TO_DATA_RANK)
]
return sender, receivers
def _zmq(output_dir: Path) -> tuple[BatchSender, list[BatchReceiver]]:
transport = ZMQTransportConfig(host="127.0.0.1", port=_free_port())
sender = ZMQBatchSender(output_dir, data_world_size=2, current_step=0, transport=transport)
receivers = [
ZMQBatchReceiver(
output_dir,
data_rank,
rank,
world_size=len(RANK_TO_DATA_RANK),
current_step=0,
transport=transport,
)
for rank, data_rank in enumerate(RANK_TO_DATA_RANK)
]
return sender, receivers
async def _send_while_ranks_request(
sender: BatchSender, receivers: list[BatchReceiver]
) -> tuple[bool, list[list[MicroBatch]]]:
send = asyncio.create_task(sender.send(MICRO_BATCH_GRID))
# every rank but the last asks, which covers both data ranks
early_requests = [asyncio.create_task(asyncio.to_thread(receiver.wait)) for receiver in receivers[:-1]]
await asyncio.sleep(0.5)
sent_before_last_request = send.done()
last_request = asyncio.create_task(asyncio.to_thread(receivers[-1].wait))
await asyncio.wait_for(asyncio.gather(send, *early_requests, last_request), timeout=10)
return sent_before_last_request, [receiver.receive() for receiver in receivers]
@pytest.mark.parametrize("setup_transport", [_filesystem, _zmq], ids=["filesystem", "zmq"])
def test_step_is_sent_only_after_every_trainer_rank_requests_it(
tmp_path: Path, setup_transport: Callable[[Path], tuple[BatchSender, list[BatchReceiver]]]
):
sender, receivers = setup_transport(tmp_path)
result = asyncio.run(_send_while_ranks_request(sender, receivers))
assert result == (False, [MICRO_BATCH_GRID[data_rank] for data_rank in RANK_TO_DATA_RANK])
for transport in [sender, *receivers]:
transport.close()
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" },