Compare commits

...
Author SHA1 Message Date
Garrett GoonandGitHub 9aa5f1f2c8 docs(install): document pre-commit hook install step (#3366)
`uv sync --group dev` only installs the pre-commit package; the git hook
stays inert until `uv run pre-commit install` runs, which the install
skill omitted (README's Development section already covers it).
2026-08-24 14:25:05 -04:00
Matej SirovatkaandGitHub c09bb0b30c fix(nccl): avoid cloning received weight tensors (#3365)
## Summary

- yield tensor views into the contiguous NCCL receive buffer instead of
cloning every reconstructed tensor
- avoid duplicating checkpoint payloads while vLLM performs layerwise
weight loading

The change intentionally keeps the existing flat receive stream and vLLM
reload lifecycle. Trainer state-dict boundaries are transport framing,
not loader semantics: vLLM tracks layer completion from the weights
loaded for each module.

## Safety

Each yielded tensor is a disjoint view of the receive buffer. A view
retains its underlying storage, so the buffer cannot be released while
the loader still references one of its tensors. The existing consumers
either copy tensors directly into model parameters or synchronously
process the ordered checkpoint stream.

## H200 reproduction

The reported Laguna-S-2.1 failure was reproduced with one EP8 trainer
node, one TP8 inference node, BF16 checkpoint transfer, and
`gpu_memory_utilization = 0.94`. The receiver code at the tested
baseline (`f53e4d9c`) is unchanged on current `main`.

| Receiver | Startup v0 | Post-training v1 |
|---|---:|---:|
| `main` | OOM on a 20 MiB clone in state dict 3/49; HTTP 500; retry
decoded `54639` state dicts | — |
| this change | 49/49 on all 8 ranks; HTTP 200 | 49/49 on all 8 ranks;
HTTP 200 |

Both successful transfers took approximately 12 seconds by broadcast
markers; the trainer reported `time/broadcast_weights = 13.2418s` for
v1. The inference server subsequently completed two rollout batches, and
the trainer completed its first optimization step.

At `gpu_memory_utilization = 0.97`, the baseline failed earlier while
allocating the 4.64 GiB receive buffer itself, so `0.94` was used to
isolate the additional clone allocation.

## Validation

- `uv run --no-sync pytest -q tests/unit/inference
tests/unit/transports/test_nccl_broadcast.py` — 14 passed, 1 existing
skip
- `uv run --no-sync ruff check
src/prime_rl/inference/vllm/worker/nccl.py`
- `uv run --no-sync python -m py_compile
src/prime_rl/inference/vllm/worker/nccl.py`
- `git diff --check`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches distributed weight-transfer memory semantics on the inference
path; incorrect view lifetime could corrupt loads, but consumers copy
into model parameters synchronously.
> 
> **Overview**
> Fixes GPU OOM during NCCL weight broadcast by **not cloning** each
tensor when splitting the per-dtype receive buffer in
`receive_state_dict`.
> 
> Reconstructed weights are now **views** into the contiguous
`concatenated` buffer (`view(shape)` only), so checkpoint payloads are
not duplicated while vLLM runs layerwise loading via
`load_weights_checkpoint_layerwise` / `load_weights_kernel`. The flat
NCCL stream and per-state-dict receive lifecycle stay the same; disjoint
views keep the buffer alive until consumers finish using yielded
tensors.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d7bd908099d5cffb6792b9b40bdbd322851bc19a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 11:12:34 -07:00
3e93371dad chore: bump verifiers and prime-envs to latest main (#3363)
## Summary
- Bump the `deps/verifiers` submodule from `d4f3d5a8c` to `807aaf389`
(latest `main`).
  - Pulls in:
- [vf#2425](https://github.com/PrimeIntellect-ai/verifiers/pull/2425):
forward sampling parameters across dialects.
- [vf#2428](https://github.com/PrimeIntellect-ai/verifiers/pull/2428):
centralize v1 egress policy decisions.
- [vf#2427](https://github.com/PrimeIntellect-ai/verifiers/pull/2427):
simplify v1 CLI plumbing.
- Bump the `deps/prime-envs` submodule from `b30aad36` to `26dafdc9`
(latest `main`).
  - Pulls in:
-
[prime-envs#761](https://github.com/PrimeIntellect-ai/prime-envs/pull/761):
environment-design rules in AGENTS.md.
-
[prime-envs#762](https://github.com/PrimeIntellect-ai/prime-envs/pull/762):
CI fix for swebench 5 + prime-sandboxes 0.2.37.
-
[prime-envs#684](https://github.com/PrimeIntellect-ai/prime-envs/pull/684):
deshuffle-papers environment.
-
[prime-envs#675](https://github.com/PrimeIntellect-ai/prime-envs/pull/675):
DeepSWE environment.
- Relock `uv.lock`: new workspace members `deep-swe` and
`deshuffle-papers`; `mcp-atlas` 0.3.0 → 0.3.1, `swesmith-env` 0.1.2 →
0.1.3.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Dependency/submodule bump that pulls new training environments and
tighter swebench/prime-sandboxes pins; not auth-critical, but can change
eval/training behavior.
> 
> **Overview**
> Bumps `deps/verifiers` and `deps/prime-envs` to latest `main` and
relocks `uv.lock`.
> 
> **verifiers** picks up sampling-parameter forwarding across dialects,
centralized v1 egress policy, and simpler v1 CLI plumbing.
> 
> **prime-envs** adds the `deep-swe` and `deshuffle-papers` workspace
environments, plus env-design AGENTS.md rules. `mcp-atlas` goes 0.3.0 →
0.3.1 (`prime-sandboxes>=0.2.37`); `swesmith-env` goes 0.1.2 → 0.1.3
(`swebench>=4.1.0,<5`).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b5b07f4795eb911daf72d30203dbd617dec63b37. 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 Fable 5 <noreply@anthropic.com>
2026-08-23 18:11:10 -07:00
f53e4d9c63 fix: health-check only the router when admin clients bypass it (#3359)
## Summary

- `AdminClients.wait_for_ready` still health-checks every engine and the
router, but when admin URLs bypass a router, the per-engine waiting
lines log at debug. Startup then logs one info waiting line instead of
one per engine plus the router:

```
03:18:09    INFO Waiting for inference server at http://localhost:8000 to start up (30s elapsed)
03:18:09    INFO Waiting for inference server at http://localhost:8100 to start up (30s elapsed)
```

- `check_health` grows a `quiet` flag that demotes its periodic waiting
lines to debug.
- Deployments without a router (no `client.admin_base_url`) keep logging
at info, as before.

Waiting only on the router is not enough: the llm-d router (Envoy) only
routes `/v1/` and `/inference/v1/`, so `/health` 404s and `check_health`
treats that as "no health route" and skips. The engines therefore stay
part of the readiness wait for correctness; the router just owns the
info-level log. Caveat: on llm-d deployments the info-level waiting line
disappears once Envoy binds its port (the engine waits continue at
debug).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Readiness polling and log-level only; no change to auth, weights, or
request serving. Timeout behavior is the same, just split across two
concurrent health waits.
> 
> **Overview**
> Fixes readiness for llm-d/Envoy routers: `/health` on the router 404s
and was treated as “no health route,” so waiting on the router alone was
not a real ready signal.
> 
> `AdminClients.wait_for_ready` now health-checks engines and router in
parallel. Engine waits use a new `quiet` flag so periodic “waiting”
lines log at debug when a router is present; the router still logs at
info. Deployments without `admin_base_url` are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5167b63bac1ed60edf3f79a99ed470d25a6a026e. 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 Fable 5 <noreply@anthropic.com>
2026-08-22 22:03:11 -07:00
Mika SenghaasandGitHub cabbd132eb feat: unified weight transport protocol (#3357)
## Summary

The weight-broadcast core: one protocol for every transport instead of
three private ones.

- **One handshake per version, on every transport**:
`WeightSender.broadcast` is a template method - the trainer resets the
step dir and offers (`.sender_ready`), blocks until the consumer
acknowledges (`.receiver_ready`), transfers (`.started`), commits
(`.finished`), and cleans old dirs. Filesystem does the full handshake:
no consumer run-ahead while the trainer writes, no version skipping ("fs
== nccl behavior").
- **`WeightReceiver`**: consumer-side counterpart, colocated with its
sender per transport file
(`transports/weights/{base,filesystem,nccl,nixl}`). The weight watcher,
the orchestrator startup rendezvous, and the evals process drive the
same object; discovery is uniform on `.sender_ready`. Every offered
version must be received - a failed receive fails the run. This deletes
the NIXL version-cap/cycle-counting hack (markers are versioned on every
transport). The engine-side byte receiver stays in
`inference/vllm/worker`.
- **Consumption-driven sequencing**: broadcast `v{N}` iff something
consumes it. `broadcast_final` lives once on the shared
`BaseWeightBroadcastConfig`, launcher-stamped, never user-set (RL:
`orchestrator.eval is not None`; SFT: `True`). With evals, the final
eval measures `v{max_steps}` on every transport.
- **Bounded handshake**: the trainer's wait for the receiver raises
`TimeoutError` after `weight_broadcast.timeout` (now on the shared
config base, so filesystem has it too), with progress warnings every
60s.
- **Unified cleaning**: keep exactly `{step, step-1}` - broadcasts are
purely transitive, `checkpoints/` owns persistence. Fixes NCCL/NIXL dirs
leaking forever.
- **Fail-fast startup**: RL and SFT both broadcast the incoming policy
before the first step; resume hygiene (`prune_broadcasts_beyond`) lives
at the trainer call sites and prunes stale future dirs.

## Breaking

- On-disk sentinels replaced: `STARTED`/`STABLE`/`NCCL_READY` →
`.sender_ready`/`.receiver_ready`/`.started`/`.finished`, one uniform
handshake per version. Trainer and orchestrator must ship together. A
resume over old broadcast dirs re-broadcasts the startup version.
- Filesystem runs in lockstep with its consumer: the trainer blocks
until each version is acknowledged (bounded by
`weight_broadcast.timeout`), no longer writes versions nobody consumes,
and the consumer no longer skips to the newest version.
- RL with evals broadcasts `v{max_steps}` and the final eval measures it
(metric shift). Without evals, `v{max_steps}` is skipped on every
transport.
- Broadcast-dir retention: exactly the last 2 dirs on every transport
(NCCL/NIXL dirs were previously leaked; SFT kept newest-only).

## Verification

Stack 6/6 of the #3335 breakup; the composed stack is tree-identical to
the e2e-verified #3335 branch (FFT NCCL 10→20 with resume, FFT
filesystem 10→20 with resume, LoRA filesystem 15→20 with resume,
LoRA+NCCL config rejection - all green; per-leg details in #3335).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Rewrites the trainer–inference weight-sync protocol (handshake,
version sequencing, eval/startup rendezvous) across all transports. A
mismatch or timeout now blocks or fails the run rather than skipping a
version.
> 
> **Overview**
> Unifies filesystem, NCCL, and NIXL weight updates onto one lockstep
handshake so every offered policy version is acknowledged before
transfer.
> 
> Trainer `WeightSender.broadcast` now always offers `.sender_ready`,
waits for `.receiver_ready` (bounded by `weight_broadcast.timeout`),
then marks `.started` / `.finished`. Orchestrator, evals, and the weight
watcher all drive a shared `WeightReceiver` instead of per-transport
polling (`STABLE` / `NCCL_READY` / ModelExpress cycle counting). Failed
receives fail the run; filesystem no longer lets the consumer skip ahead
while the trainer writes.
> 
> Broadcasts are consumption-driven: `v{max_steps}` is sent only when a
final eval will measure it (`broadcast_final`, launcher-stamped). Both
RL and SFT fail-fast with a startup broadcast, prune stale future dirs
on resume, and keep only `{step, step-1}` on disk. Trainer and consumer
must ship together — on-disk sentinels are a breaking change.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
53da37d3028a5755afc3615581c9664bfc47bf85. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-22 20:04:36 -07:00
29 changed files with 639 additions and 577 deletions
+1 -1
+1 -1
View File
@@ -159,7 +159,7 @@ Algorithms operate on native verifier artifacts and annotate their message graph
The pipeline drives these through `finalize_episode` and `finalize_group`. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy pool (`self.policy_pool`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
## Async / Off-Policy Training
+1 -9
View File
@@ -191,15 +191,7 @@ Both backends support the 2 most important things:
### Routing policies
The 2 policies you might want to configure are:
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - this works by hashing a request header to determine where to route the request to. You can configure what to hash by setting
`orchestrator.model.client.extra_headers_from_state` to the header the `router` expects to be set.
We set it to a sensible default, that works with all verifiers environments.
```toml
[orchestrator.model.client.extra_headers_from_state]
X-Session-ID = "trajectory_id" # this is the default - each rollout has a unique trajectory_id and router expects X-Session-ID
```
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - it hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica.
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
+1 -1
View File
@@ -198,7 +198,7 @@ num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at every step an eval env is due, and the evals process watches `broadcasts/step_{n}` for synchronization markers before it drives the NCCL receive. It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
#### Multi-Node (Decoupled Trainer and Inference Pool)
@@ -112,7 +112,8 @@ class VllmConfig(BaseConfig):
"""Enable LoRA."""
max_loras: int = 1
"""Maximum number of LoRAs. The single training adapter is reloaded in place every policy version, reusing one slot."""
"""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."""
@@ -12,6 +12,7 @@ from prime_rl.configs.algorithm import (
from prime_rl.configs.monitors import OrchestratorMonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
BaseWeightBroadcastConfig,
ClientConfig,
EnvVars,
HeartbeatConfig,
@@ -373,20 +374,17 @@ class CheckpointConfig(BaseConfig):
"""Skip loading the progress from checkpoint."""
class FileSystemWeightBroadcastConfig(BaseConfig):
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["filesystem"] = "filesystem"
class InMemoryWeightBroadcastConfig(BaseConfig):
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
host: str = "localhost"
"""Weight transfer host."""
port: int
"""Weight transfer port."""
timeout: int = 1200
"""Weight transfer timeout in seconds."""
inference_world_size: int = Field(1, ge=1)
"""Total inference workers across all servers."""
@@ -136,7 +136,7 @@ class SharedInMemoryWeightBroadcastConfig(BaseConfig):
"""Weight transfer port."""
timeout: int = 1200
"""Timeout in seconds for in-memory weight transfer."""
"""Timeout in seconds for the broadcast handshake and transfer."""
class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
@@ -162,6 +162,9 @@ class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
class SharedFileSystemWeightBroadcastConfig(BaseConfig):
type: Literal["filesystem"] = "filesystem"
timeout: int = 1200
"""Timeout in seconds for the broadcast handshake and transfer."""
SharedWeightBroadcastConfig: TypeAlias = Annotated[
SharedFileSystemWeightBroadcastConfig | SharedNCCLWeightBroadcastConfig | SharedNIXLWeightBroadcastConfig,
@@ -464,6 +467,9 @@ class RLConfig(BaseConfig):
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
"have no disk artifact to load from."
)
# The final version v{max_steps} is broadcast iff something consumes it:
# training never samples from it, but a configured final eval measures it.
broadcast_final = self.orchestrator.eval is not None
if self.weight_broadcast.type in ("nccl", "nixl"):
inference_world_size = (
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
@@ -475,6 +481,7 @@ class RLConfig(BaseConfig):
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
inference_world_size=inference_world_size,
broadcast_final=broadcast_final,
)
if self.weight_broadcast.type == "nccl":
transport_config = dict(
@@ -489,8 +496,12 @@ class RLConfig(BaseConfig):
self.trainer.weight_broadcast = trainer_config_type(**common_config, **transport_config)
self.orchestrator.weight_broadcast = orchestrator_config_type(**common_config, **transport_config)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig(
timeout=self.weight_broadcast.timeout, broadcast_final=broadcast_final
)
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig(
timeout=self.weight_broadcast.timeout, broadcast_final=broadcast_final
)
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
@@ -37,6 +37,18 @@ EnvVars: TypeAlias = Annotated[dict[str, str], AfterValidator(reject_protected_e
"""A per-component `env_vars` mapping, validated to not clobber `PROTECTED_ENV_VARS`."""
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."""
broadcast_final: bool = True
"""Internal - stamped by the RL/SFT launcher, never set by users: whether the
trainer broadcasts the final version v{max_steps}. True iff something consumes
it (a configured final eval) - training itself never samples from the final
version."""
class RunConfig(BaseConfig):
name: str | None = None
"""Run name. Auto-generated as ``<envs>--<model>--<short-id>`` when unset, so every launch gets a fresh, readable run directory; set an explicit name (e.g. an experiment name) to get a predictable run directory, which is also required to resume a previous run. Unless set explicitly, the W&B run name and the Prime platform run name inherit it."""
@@ -7,6 +7,7 @@ from pydantic import BeforeValidator, Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
BaseWeightBroadcastConfig,
EnvVars,
HeartbeatConfig,
MetricsServerConfig,
@@ -545,10 +546,6 @@ class DataLoaderConfig(BaseConfig):
"""Use a fake data loader sampling random micro-batches (for debugging)."""
class BaseWeightBroadcastConfig(BaseConfig):
pass
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["filesystem"] = "filesystem"
@@ -560,9 +557,6 @@ class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
port: int
"""Weight transfer port."""
timeout: int = 1200
"""Weight transfer timeout in seconds."""
# TODO: Should not be configurable, but auto-inferred
inference_world_size: int = 1
"""Number of inference workers."""
+2
View File
@@ -29,6 +29,8 @@ uv sync --all-extras --all-packages # + all env packages (needed to train
uv sync --package prime-rl --package gsm8k # core + just one env
```
`uv sync --group dev` installs the `pre-commit` package but leaves the git hook inert until it's wired up — run `uv run pre-commit install` once per clone (see `README.md`'s Development section).
Environment packages are uv **workspace members**. Those under `deps/prime-envs/environments/*/*` are auto-discovered — adding a new env there needs no `pyproject.toml` change. verifiers' example envs are enumerated explicitly in `[tool.uv.workspace].members` (only the ones prime-rl trains or tests on) — to use another, add its path to the list. Members are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
+88 -93
View File
@@ -2,11 +2,13 @@
Standalone (no ``[online]``), it runs one epoch of every configured eval
source against the weights the inference server currently serves, then exits.
With ``[online]``, it watches a broadcasts directory for new weight
broadcasts — the trainer writes ``broadcasts/step_{n}`` with a ``STABLE``
marker on completion — tells the inference server to receive each eligible
broadcast, and runs the configured evals against the updated weights,
sequentially per broadcast so every epoch measures exactly one policy version.
With ``[online]``, it watches a broadcasts directory for offered weight
broadcasts through a ``WeightReceiver`` (announced by their
``.sender_ready`` marker), moves the inference server onto each of them, and
runs the configured evals against the updated weights, sequentially per
broadcast so every epoch measures exactly one policy version. Every offered
broadcast must be received, even when no eval is due — the trainer blocks
inside the handshake until the receiver acknowledges.
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
@@ -30,7 +32,8 @@ from subprocess import Popen
from prime_rl import monitors
from prime_rl.configs.evals import EvalsConfig
from prime_rl.orchestrator.clients import AdminClients, InferenceClient, init_nccl_broadcast, update_weights
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs
@@ -44,9 +47,10 @@ from prime_rl.orchestrator.patches import (
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.types import EvalBatch, Policy
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.config import dump_resolved_config
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir, get_step_path
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
from prime_rl.utils.utils import clean_exit
@@ -56,9 +60,9 @@ monkey_patch_chat_completion_logprobs()
# How often to re-scan the broadcasts directory for new weight broadcasts.
POLL_INTERVAL_S = 2.0
# Served model name for adapter broadcasts of LoRA runs. Reloading the same name
# with fresh weights each step is supported (the server forces an in-place
# reload, see /load_lora_adapter).
# Budget for the trainer's startup broadcast: it is always coming, but only
# after the trainer has finished loading the model.
STARTUP_BROADCAST_TIMEOUT_S = 1200
class Evals:
@@ -75,6 +79,14 @@ class Evals:
self.env_server_procs: list[Popen] = []
self.dispatcher_task: asyncio.Task | None = None
# Assigned in setup(); None-initialized so stop() can tear down a
# partially completed setup with plain attribute checks.
self.clients: InferenceClient | None = None
self.admin_clients: AdminClients | None = None
self.dispatcher: Dispatcher | None = None
self.inference_metrics: InferenceMetricsCollector | None = None
self.periodic_logger: PeriodicLogger | None = None
async def setup(self) -> None:
config = self.config
set_default_executor()
@@ -108,17 +120,20 @@ class Evals:
await self.admin_clients.wait_for_ready(config.model)
get_logger().success("Inference pool ready")
weight_broadcast = config.weight_broadcast
if weight_broadcast is not None and weight_broadcast.type == "nccl":
self.receiver: WeightReceiver | None = None
if config.online is not None:
assert config.online.broadcasts_dir is not None
# A hand-written online config may omit the transport; broadcasts
# are then plain filesystem checkpoints.
weight_broadcast = config.weight_broadcast or FileSystemWeightBroadcastConfig()
get_logger().info(f"Initializing weight broadcast ({weight_broadcast})")
await init_nccl_broadcast(
self.admin_clients.clients,
weight_broadcast.host,
weight_broadcast.port,
weight_broadcast.timeout,
inference_world_size=weight_broadcast.inference_world_size,
quantize_in_weight_transfer=weight_broadcast.quantize_in_weight_transfer,
self.receiver = setup_weight_receiver(
config.online.broadcasts_dir,
weight_broadcast,
admin_clients=self.admin_clients.clients,
model_name=config.model,
)
await self.receiver.initialize()
is_resumed = config.online is not None and config.online.resume_step is not None
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=is_resumed)
@@ -242,65 +257,55 @@ class Evals:
assert config.online is not None
online = config.online
# Rendezvous with the trainer's startup broadcast (v0 fresh, the
# checkpoint step on resume) — always, for every transport: an
# in-memory trainer blocks inside its startup broadcast until this
# receive, and for filesystem it guarantees the served weights match
# the trainer's incoming policy.
assert self.receiver is not None
startup_step = online.resume_step or 0
await self.receiver.sync_startup(startup_step, timeout=STARTUP_BROADCAST_TIMEOUT_S)
self.policy.version = startup_step
if online.resume_step is None:
# Base-model eval: the inference server starts with the untrained weights,
# so no reload is needed. The first trigger fires every env (policy v0)
# unless ``skip_first_step``.
# The first trigger fires every env (policy v0) unless ``skip_first_step``.
await self.maybe_run_evals(step=0)
elif config.eval.retrigger_on_resume:
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
# evals). The trainer rebroadcasts the resumed policy on startup, but only
# after loading the model — wait for that broadcast instead of checking
# once. A newer stable broadcast means the resume step's was already
# cleaned away (only the newest is kept) and can never reappear. The
# evals); the startup rendezvous above already loaded its weights. The
# final broadcast force-fires every env, exactly like the watch loop below.
assert online.broadcasts_dir is not None and online.resume_step is not None
while True:
if (get_step_path(online.broadcasts_dir, online.resume_step) / "STABLE").exists():
is_final = online.max_steps is not None and online.resume_step >= online.max_steps
await self.maybe_run_evals(step=online.resume_step, reload_weights=True, force=is_final)
break
newer_stable = any(
step > online.resume_step and (get_step_path(online.broadcasts_dir, step) / "STABLE").exists()
for step in get_all_ckpt_steps(online.broadcasts_dir)
)
if newer_stable:
get_logger().warning(
f"Broadcast for resume step {online.resume_step} was cleaned before it could be "
"re-evaluated (broadcast cleaning outpaced the evals process) - skipping the retrigger"
)
break
await asyncio.sleep(POLL_INTERVAL_S)
is_final = online.max_steps is not None and online.resume_step >= online.max_steps
await self.maybe_run_evals(step=online.resume_step, force=is_final)
get_logger().info(f"Watching {online.broadcasts_dir} for new weight broadcasts (max_steps={online.max_steps})")
while True:
assert online.broadcasts_dir is not None # resolved by the config validator
steps = get_all_ckpt_steps(online.broadcasts_dir)
stable = {step: (get_step_path(online.broadcasts_dir, step) / "STABLE").exists() for step in steps}
newest_stable = max((step for step in steps if stable[step]), default=None)
published = {step: self.receiver.is_published(step) for step in steps}
newest_published = max((step for step in steps if published[step]), default=None)
# Also walk eval-due steps that are no longer on disk: broadcast cleaning
# (the trainer keeps only the newest broadcast) can delete a step before
# this scan sees it, and a vanished step would otherwise be skipped
# without a trace.
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_stable)):
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_published)):
if step <= self.last_step:
continue
if step not in stable:
if step not in published:
get_logger().warning(
f"Weight broadcast for eval step {step} was deleted before it could be "
"evaluated (broadcast cleaning outpaced the evals process) - skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
if not stable[step]:
if not published[step]:
# The trainer writes broadcasts in ascending order, so a marker-less
# step below a stable one is an abandoned partial write (e.g. a crash
# mid-save), not one in progress — skip it instead of wedging on it.
if newest_stable is None or newest_stable < step:
# step below a published one is an abandoned partial write (e.g. a
# crash mid-save), not one in progress — skip it instead of wedging.
if newest_published is None or newest_published < step:
break # still being written — later steps can't be ready either
get_logger().warning(
f"Weight broadcast step {step} has no STABLE marker but newer stable "
"broadcasts exist - treating it as abandoned and skipping its evals"
f"Weight broadcast step {step} is not marked published but newer "
"broadcasts are - treating it as abandoned and skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
@@ -310,33 +315,42 @@ class Evals:
break
await asyncio.sleep(POLL_INTERVAL_S)
def deleted_due_steps(self, steps: list[int], newest_stable: int | None) -> set[int]:
"""Eval-due steps up to the newest stable broadcast that are missing from the
broadcasts dir — the trainer wrote them (it broadcasts at every due step), so
their absence means broadcast cleaning removed them before they were
def deleted_due_steps(self, steps: list[int], newest_published: int | None) -> set[int]:
"""Eval-due steps up to the newest published broadcast that are missing from
the broadcasts dir — the trainer wrote them (it broadcasts at every due step),
so their absence means broadcast cleaning removed them before they were
evaluated."""
if newest_stable is None:
if newest_published is None:
return set()
due = {
step
for interval in self.eval_source.intervals.values()
for step in range(interval, newest_stable + 1, interval)
for step in range(interval, newest_published + 1, interval)
}
return due - set(steps)
async def maybe_run_evals(self, step: int, *, reload_weights: bool = False, force: bool = False) -> None:
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
reloading the inference weights first. No-op when no env is due."""
reloading the inference weights first. No-op when no env is due — except
that a live transport's broadcast must always be received (the trainer
is blocked inside it), eval or no eval."""
if reload_weights:
assert self.config.online is not None and self.config.online.broadcasts_dir is not None
broadcast_dir = get_step_path(self.config.online.broadcasts_dir, step)
if not (broadcast_dir / "STABLE").exists():
get_logger().warning(f"No stable weight broadcast for step {step} ({broadcast_dir}) - skipping eval")
assert self.receiver is not None
broadcast_dir = self.receiver.step_dir(step)
if not self.receiver.is_published(step):
get_logger().warning(f"No published weight broadcast for step {step} ({broadcast_dir}) - skipping eval")
self.last_step = max(self.last_step, step)
return
fired = self.eval_source.trigger(step, force=force)
self.last_step = max(self.last_step, step)
if reload_weights:
# Every offered version must be received: the trainer blocks inside
# the handshake, so a failed receive fails the run loudly.
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
await self.receiver.receive(step)
if not fired:
return
@@ -348,20 +362,6 @@ class Evals:
for env_name in fired
)
if reload_weights:
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
# LoRA runs broadcast the raw adapter; load it under a fixed adapter name
# and serve the evals against that name (mirrors WeightWatcher).
try:
await update_weights(self.admin_clients.clients, broadcast_dir, self.clients.model_name, step=step)
except Exception as exc:
# Skip this step instead of killing the run; drain the queued examples
# so they don't leak into a later epoch with the wrong step.
while self.eval_source.next_task() is not None:
pass
get_logger().error(f"Failed to update inference weights to step {step} - skipping evals: {exc!r}")
return
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
# between the trigger above and the weight reload completing.
self.policy.version = step
@@ -434,21 +434,16 @@ class Evals:
async def stop(self) -> None:
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
periodic_logger: PeriodicLogger | None = getattr(self, "periodic_logger", None)
if periodic_logger is not None:
await periodic_logger.stop()
inference_metrics: InferenceMetricsCollector | None = getattr(self, "inference_metrics", None)
if inference_metrics is not None:
await inference_metrics.stop()
dispatcher: Dispatcher | None = getattr(self, "dispatcher", None)
if dispatcher is not None:
await dispatcher.stop()
clients: InferenceClient | None = getattr(self, "clients", None)
if clients is not None:
await clients.aclose()
admin_clients: AdminClients | None = getattr(self, "admin_clients", None)
if admin_clients is not None:
await admin_clients.aclose()
if self.periodic_logger is not None:
await self.periodic_logger.stop()
if self.inference_metrics is not None:
await self.inference_metrics.stop()
if self.dispatcher is not None:
await self.dispatcher.stop()
if self.clients is not None:
await self.clients.aclose()
if self.admin_clients is not None:
await self.admin_clients.aclose()
cleanup_processes(self.env_server_procs)
+1 -1
View File
@@ -51,7 +51,7 @@ def receive_state_dict(communicator: PyNcclCommunicator) -> Generator[tuple[str,
# Split concatenated tensor back into individual tensors
offset = 0
for key, shape, numel in tensor_info_list:
tensor = concatenated[offset : offset + numel].view(shape).clone()
tensor = concatenated[offset : offset + numel].view(shape)
offset += numel
try:
yield key, tensor
+39 -42
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import os
from collections.abc import Callable
from pathlib import Path
import httpx
@@ -96,7 +97,14 @@ class AdminClients:
self._wait_for_ready_timeout = client_config.wait_for_ready_timeout
async def wait_for_ready(self, model_name: str) -> None:
await check_health(self.clients + self._router_clients, timeout=self._wait_for_ready_timeout)
# The engines are waited on even when a router fronts them: the llm-d
# router (Envoy) 404s /health, which check_health treats as "no health
# route", so the router alone is not a readiness signal. The router
# owns the info-level waiting log; the per-engine waits log at debug.
await asyncio.gather(
check_health(self.clients, timeout=self._wait_for_ready_timeout, quiet=bool(self._router_clients)),
check_health(self._router_clients, timeout=self._wait_for_ready_timeout),
)
await maybe_check_has_model(self.clients, model_name, skip_model_check=self._skip_model_check)
async def aclose(self) -> None:
@@ -189,8 +197,15 @@ async def maybe_check_has_model(
async def check_health(
admin_clients: list[AsyncClient], interval: int = 1, log_interval: int = 30, timeout: int = 1800
admin_clients: list[AsyncClient],
interval: int = 1,
log_interval: int = 30,
timeout: int = 1800,
quiet: bool = False,
) -> None:
"""Wait until every client's /health responds. With ``quiet``, the periodic
waiting lines log at debug instead of info - used for engines fronted by a
router, so startup logs one waiting line instead of one per engine."""
logger = get_logger()
async def _check_health(admin_client: AsyncClient) -> None:
@@ -207,9 +222,8 @@ async def check_health(
return
except Exception as e:
if wait_time % log_interval == 0 and wait_time > 0:
logger.info(
f"Waiting for inference server at {admin_client.base_url} to start up ({wait_time}s elapsed)"
)
log = logger.debug if quiet else logger.info
log(f"Waiting for inference server at {admin_client.base_url} to start up ({wait_time}s elapsed)")
logger.debug(f"Inference server at {admin_client.base_url} not reachable: {e!r}")
await asyncio.sleep(interval)
wait_time += interval
@@ -234,8 +248,6 @@ def _is_retryable_admin_error(exception: BaseException) -> bool:
return False
NCCL_READY_MARKER = "NCCL_READY"
# Per-attempt read timeout for admin ops, overridable per call. The admin
# AsyncClient uses `timeout=None`, so without this a stuck server would hang the
# weight update forever: the read timeout converts a hang into a TimeoutException
@@ -291,54 +303,39 @@ async def _resume_engines(admin_clients: list[AsyncClient]) -> None:
async def update_weights(
admin_clients: list[AsyncClient],
weight_dir: Path | None,
model_name: str,
step: int = 0,
on_paused: Callable[[], None] | None = None,
) -> None:
"""Update weights on static inference servers.
Pauses all engines first to drain in-flight requests, then performs the
weight update, then resumes. This ensures all DP workers are idle and can
participate in the collective weight transfer.
participate in the collective weight transfer. ``on_paused`` runs between
the pause and the update RPC — the NCCL receiver signals the trainer there.
Note: the prefix cache is intentionally not reset on weight update. The orchestrator
salts the prefix cache per weight version (``cache_salt`` in the sampling request, see
``orchestrator/envs.py``), so KV computed under old weights is never reused.
"""
logger = get_logger()
weight_dir_posix = weight_dir.as_posix() if weight_dir is not None else None
if weight_dir is not None and (weight_dir / "adapter_config.json").exists():
# A LoRA run broadcasts the PEFT-shaped adapter; register it under the
# base model name - the single adapter shadows it (vLLM resolves
# lora_requests before the base-model match), so requests keep
# addressing one stable name and no engine pause is needed.
await load_lora_adapter(admin_clients, model_name, weight_dir)
else:
# Pause engines so all DP workers drain in-flight work and can join the NCCL broadcast
await _pause_engines(admin_clients, step=step)
try:
# Create ready marker before servers enter receive path (used by NCCL broadcast)
if weight_dir is not None:
nccl_ready_file = weight_dir / NCCL_READY_MARKER
nccl_ready_file.parent.mkdir(parents=True, exist_ok=True)
nccl_ready_file.touch()
logger.debug(f"Created NCCL_READY marker at {nccl_ready_file}")
await asyncio.gather(
*[
_admin_post(
admin_client,
"/update_weights",
json={"weight_dir": weight_dir_posix},
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
)
for admin_client in admin_clients
]
)
finally:
await _resume_engines(admin_clients)
await _pause_engines(admin_clients, step=step)
try:
if on_paused is not None:
on_paused()
await asyncio.gather(
*[
_admin_post(
admin_client,
"/update_weights",
json={"weight_dir": weight_dir_posix},
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
)
for admin_client in admin_clients
]
)
finally:
await _resume_engines(admin_clients)
def _is_retryable_lora_error(exception: BaseException) -> bool:
+65 -104
View File
@@ -26,8 +26,6 @@ import uuid
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from modelexpress import p2p_pb2
from modelexpress.client import MxClient
from verifiers.v1.runtimes import set_base_sandbox_labels
if TYPE_CHECKING:
@@ -40,13 +38,7 @@ from prime_rl import monitors
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.algo.routing import is_trainable
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
from prime_rl.orchestrator.clients import (
AdminClients,
InferenceClient,
init_nccl_broadcast,
init_nixl_broadcast,
update_weights,
)
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
@@ -73,7 +65,6 @@ from prime_rl.orchestrator.utils import (
episode_group_id,
episode_staleness,
eval_work,
get_weight_dir,
intercept_vf_logging,
set_default_executor,
trim_process_memory,
@@ -81,12 +72,14 @@ from prime_rl.orchestrator.utils import (
from prime_rl.orchestrator.watcher import WeightWatcher
from prime_rl.trainer.model import setup_tokenizer
from prime_rl.transports.batch import setup_batch_sender
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import get_broadcast_dir
from prime_rl.utils.utils import (
clean_exit,
final_broadcast_version,
resolve_latest_ckpt_step,
)
@@ -127,8 +120,8 @@ class Orchestrator:
# Always set by ``setup()``
tokenizer: PreTrainedTokenizer
clients: InferenceClient
admin_clients: AdminClients
clients: InferenceClient | None
admin_clients: AdminClients | None
sender: BatchSender | None
packer: BatchPacker
train_envs: TrainEnvs
@@ -146,6 +139,7 @@ class Orchestrator:
eval_envs: EvalEnvs | None
eval_sink: EvalSink | None
eval_source: EvalSource | None
receiver: WeightReceiver
resume_step: int | None
lag_task: asyncio.Task | None
@@ -176,6 +170,11 @@ class Orchestrator:
self.wait_for_policy_time = 0.0
self.component_tasks = []
# Always assigned by ``setup()``; None-initialized so teardown can run
# on a partially completed setup with plain attribute checks
self.clients = None
self.admin_clients = None
# Optional attributes — ``setup()`` populates them when the relevant
# config is present
self.heart = None
@@ -185,7 +184,6 @@ class Orchestrator:
self.eval_source = None
self.resume_step = None
self.lag_task = None
self.model_express = None
# ── lifecycle ──────────────────────────────────────────────────────────
@@ -269,9 +267,6 @@ class Orchestrator:
self.sender = setup_batch_sender(
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
)
if config.weight_broadcast.type == "filesystem":
# Nothing to set up client-side — the watcher polls the broadcast dir.
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
# Wait phase: envs, then inference, then the trainer's startup broadcast —
# the last things before the main loop starts.
@@ -304,71 +299,31 @@ class Orchestrator:
*(env.algorithm.setup() for env in self.train_envs),
)
# The in-memory broadcast transports rendezvous with live inference
# engines, so their setup must follow pool readiness.
if config.weight_broadcast.type in ("nccl", "nixl"):
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
if config.weight_broadcast.type == "nccl":
await init_nccl_broadcast(
self.admin_clients.clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
inference_world_size=config.weight_broadcast.inference_world_size,
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
)
else:
await init_nixl_broadcast(
self.admin_clients.clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
config.weight_broadcast.inference_world_size,
config.weight_broadcast.session_id,
)
self.model_express = ModelExpressSession(
client=MxClient(server_url=f"{config.weight_broadcast.host}:{config.weight_broadcast.port}"),
role="orchestrator",
rank=0,
session_id=config.weight_broadcast.session_id,
worker_id="orchestrator",
)
self.model_express.publish()
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
get_logger().debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
# A LoRA run's adapter is registered under the base model name: the
# single adapter shadows it (vLLM resolves lora_requests before the
# base-model match), so requests keep addressing one stable name.
self.receiver = setup_weight_receiver(
get_broadcast_dir(config.output_dir),
config.weight_broadcast,
admin_clients=self.admin_clients.clients,
model_name=config.model.name,
)
await self.receiver.initialize()
get_logger().debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
# Sync inference to the incoming policy before the first step, rendezvousing
# with the trainer's startup broadcast (v{resume_step} on resume, v0 from
# scratch).
# 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
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
t0 = time.perf_counter()
if config.weight_broadcast.type == "nixl":
weights_path = None
else:
check_exists = config.weight_broadcast.type == "filesystem"
# The trainer's startup broadcast is always coming, so wait for it
# rather than failing immediately when the directory is not there yet.
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
STARTUP_WEIGHT_WAIT_TIMEOUT_S
)
weights_path = get_weight_dir(
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
)
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
await update_weights(self.admin_clients.clients, weights_path, config.model.name, step=sync_version)
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
# Complete the startup rendezvous before the watcher begins its next cycle.
await asyncio.to_thread(
self.model_express.wait_for,
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
timeout=config.weight_broadcast.timeout,
)
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
STARTUP_WEIGHT_WAIT_TIMEOUT_S
)
await self.receiver.sync_startup(sync_version, timeout=wait_timeout)
self.policy.version = sync_version
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
@@ -432,13 +387,10 @@ class Orchestrator:
self.eval_sink = EvalSink(eval_envs=self.eval_envs) if self.eval_envs is not None else None
self.watcher = WeightWatcher(
config,
self.receiver,
policy=self.policy,
clients=self.clients,
admin_clients=self.admin_clients,
observers=[self.dispatcher, self],
ckpt_step=self.policy.version,
model_express=self.model_express,
)
# Single periodic logger for the whole pipeline. It's the only
# consumer of ``dispatcher.metrics.drained()`` (which clears on read)
@@ -531,23 +483,23 @@ class Orchestrator:
get_logger().warning("Orchestrator cleanup complete (forced)")
trim_process_memory()
async def wait_for_final_broadcast(self) -> None:
"""Stay alive for the trainer's last in-memory broadcast (v{max_steps-1};
nothing samples from v{max_steps}, so it is never sent). An in-memory
broadcast is a blocking collective — tearing down the watcher before
the rendezvous would strand the trainer inside it."""
config = self.config
if config.weight_broadcast.type not in ("nccl", "nixl") or config.max_steps is None:
@property
def final_version(self) -> int | None:
"""Newest policy version the trainer will ever broadcast."""
if self.config.max_steps is None:
return None
return final_broadcast_version(self.config.max_steps, self.config.weight_broadcast.broadcast_final)
async def wait_for_version(self, version: int, reason: str) -> None:
"""Bounded wait until the watcher has applied v{version}."""
if self.policy.version >= version:
return
final_version = config.max_steps - 1
if self.policy.version >= final_version:
return
get_logger().info(f"Waiting for the trainer's final broadcast (v{final_version}) before shutdown")
get_logger().info(f"Waiting for the trainer to broadcast v{version} {reason}")
async def wait() -> None:
while self.policy.version < final_version:
while self.policy.version < version:
self.version_advanced.clear()
if self.policy.version >= final_version:
if self.policy.version >= version:
return
# A dead watcher can never deliver the broadcast — fail out
# instead of idling until the timeout.
@@ -557,13 +509,19 @@ class Orchestrator:
except asyncio.TimeoutError:
pass
timeout = self.config.weight_broadcast.timeout
try:
await asyncio.wait_for(wait(), timeout=config.weight_broadcast.timeout)
await asyncio.wait_for(wait(), timeout=timeout)
except asyncio.TimeoutError:
get_logger().warning(
f"Trainer did not broadcast v{final_version} within {config.weight_broadcast.timeout}s — "
"shutting down anyway"
)
get_logger().warning(f"Trainer did not broadcast v{version} within {timeout}s — proceeding anyway")
async def wait_for_final_broadcast(self) -> None:
"""Stay alive for the trainer's last broadcast. Every broadcast is a
blocking rendezvous — tearing down the watcher before it would strand
the trainer inside the handshake."""
if self.final_version is None:
return
await self.wait_for_version(self.final_version, reason="before shutdown")
async def main_loop(self) -> None:
"""Consume completed episodes and ``GroupCancellation`` events from the
@@ -767,6 +725,13 @@ class Orchestrator:
self.log_train_batch(batch, step=step, step_time=step_time)
# The final eval must measure the final weights: hold until the
# trainer's last broadcast (v{max_steps} when evals consume it) has
# been applied before triggering it. Satisfiable — the trainer
# broadcasts right after consuming the batch this call just shipped.
if config.eval is not None and config.max_steps is not None and step >= config.max_steps:
assert self.final_version is not None
await self.wait_for_version(self.final_version, reason="for the final eval")
self.maybe_trigger_eval(self.progress.step)
# Drain right after shipping the final batch. Waiting for a further
# batch to fill would burn inference on data that can never train —
@@ -1007,15 +972,11 @@ class Orchestrator:
async def on_version_pending(self, step: int) -> None:
"""``VersionObserver`` hook, fired at publish confirmation (pre-apply):
``policy.version`` already carries the new version, so wake a held ship."""
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
self.version_advanced.set()
async def on_new_version(self, step: int) -> None:
"""``VersionObserver`` hook: the weight update completed;
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.update_dispatch_gate()
async def stop(self) -> None:
@@ -1043,9 +1004,9 @@ class Orchestrator:
if self.inference_metrics is not None:
get_logger().debug("Stopping inference metrics collector")
await self.inference_metrics.stop()
if getattr(self, "clients", None) is not None:
if self.clients is not None:
await self.clients.aclose()
if getattr(self, "admin_clients", None) is not None:
if self.admin_clients is not None:
await self.admin_clients.aclose()
if self.train_envs is not None:
get_logger().debug("Stopping generation source and algorithm clients")
-52
View File
@@ -3,19 +3,12 @@ import ctypes
import gc
import logging
import math
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any
import verifiers.v1 as vf
from prime_rl.utils.logger import InterceptHandler, get_logger, setup_logger
from prime_rl.utils.utils import (
get_broadcast_dir,
get_ckpt_dir,
get_step_path,
)
def episode_env_name(episode: vf.Episode[Any, Any, Any]) -> str:
@@ -101,51 +94,6 @@ def trim_process_memory() -> None:
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
def get_weight_dir(output_dir: Path, step: int, check_exists: bool = True, wait_timeout: int | None = None) -> Path:
"""Get the weight directory for a given checkpoint step.
Args:
output_dir: The output directory for the run.
step: The checkpoint step.
check_exists: If True, raises FileNotFoundError if no weight directory exists.
If False, returns the broadcast directory path without checking existence
(useful for NCCL mode where weights are broadcasted, not stored on disk).
wait_timeout: Maximum time in seconds to wait for a stable directory to appear.
If None, no waiting is performed.
"""
ckpt_weight_dir = get_step_path(get_ckpt_dir(output_dir), step) / "weight"
broadcast_weight_dir = get_step_path(get_broadcast_dir(output_dir), step)
def find_stable_dir() -> Path | None:
# For checkpoint weights, check STABLE file in parent directory (checkpoints/step_{step}/STABLE)
ckpt_step_dir = get_step_path(get_ckpt_dir(output_dir), step)
if (ckpt_step_dir / "STABLE").exists() and ckpt_weight_dir.exists():
return ckpt_weight_dir
# For broadcast weights, check STABLE file in the broadcast directory itself
if (broadcast_weight_dir / "STABLE").exists() and broadcast_weight_dir.exists():
return broadcast_weight_dir
return None
# Check immediately, then wait if needed
result = find_stable_dir()
if result is None and wait_timeout:
start_time = time.time()
while time.time() - start_time < wait_timeout:
time.sleep(1)
result = find_stable_dir()
if result:
break
if result:
return result
if not check_exists:
return broadcast_weight_dir
raise FileNotFoundError(f"No weight directory found for checkpoint step {step}")
def compute_pass_metrics(rewards: list[float]) -> dict[str, float]:
"""Unbiased pass@k and pass^k for one example's binary (0/1) rewards.
+9 -59
View File
@@ -1,22 +1,16 @@
"""WeightWatcher: polls the broadcast dir, advances ``Policy``, notifies
observers (dispatcher → staleness cancel). Standalone async task; the
orchestrator's barrier bounds the in-flight lead."""
"""WeightWatcher: discovers new policy versions via the transport's receiver,
advances ``Policy``, and notifies observers (dispatcher → staleness cancel).
Standalone async task; the orchestrator's barrier bounds the in-flight lead."""
from __future__ import annotations
import asyncio
import time
from modelexpress import p2p_pb2
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.clients import AdminClients, InferenceClient, update_weights
from prime_rl.orchestrator.types import Policy, VersionObserver
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
from prime_rl.transports.weights import WeightReceiver
from prime_rl.utils.async_utils import safe_cancel
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_broadcast_dir, get_step_path, wait_for_path
from prime_rl.utils.utils import get_latest_ckpt_step
class WeightWatcher:
@@ -24,24 +18,18 @@ class WeightWatcher:
def __init__(
self,
config: OrchestratorConfig,
receiver: WeightReceiver,
*,
policy: Policy,
clients: InferenceClient,
admin_clients: AdminClients,
observers: list[VersionObserver],
ckpt_step: int = 0,
poll_interval: float = 1.0,
model_express: ModelExpressSession | None = None,
) -> None:
self.config = config
self.receiver = receiver
self.policy = policy
self.clients = clients
self.admin_clients = admin_clients
self.observers = observers
self.ckpt_step = ckpt_step
self.poll_interval = poll_interval
self.model_express = model_express
self.last_update_weights_time: float = 0.0
self.last_wait_for_ckpt_time: float = 0.0
@@ -55,7 +43,7 @@ class WeightWatcher:
self.task = asyncio.current_task()
try:
while not self.stopped.is_set():
next_step = self.compute_next_ckpt_step()
next_step = self.receiver.next_version(self.ckpt_step)
if next_step > self.ckpt_step:
await self.apply_policy_update(next_step)
await asyncio.sleep(self.poll_interval)
@@ -74,20 +62,6 @@ class WeightWatcher:
await safe_cancel(self.task)
self.task = None
def compute_next_ckpt_step(self) -> int:
"""Return the next policy version exposed by the configured transport."""
if self.model_express is not None:
# The trainer broadcasts every version except v{max_steps}.
if self.config.max_steps is not None and self.ckpt_step >= self.config.max_steps - 1:
return self.ckpt_step
# ModelExpress status changes are unversioned, so its rendezvous advances
# exactly one policy version per READY/INITIALIZING cycle.
return self.ckpt_step + 1
broadcast_dir = get_broadcast_dir(self.config.output_dir)
latest_ckpt_step = get_latest_ckpt_step(broadcast_dir) or 0
return max(self.policy.version, latest_ckpt_step)
async def apply_policy_update(self, next_step: int) -> None:
async with self.update_lock:
if next_step <= self.ckpt_step:
@@ -95,16 +69,7 @@ class WeightWatcher:
return
t0 = time.perf_counter()
weights_path = None
if self.model_express is not None:
await self.wait_for_model_express_status(p2p_pb2.SOURCE_STATUS_READY)
else:
broadcast_dir = get_broadcast_dir(self.config.output_dir)
weights_path = get_step_path(broadcast_dir, next_step)
stable_marker = weights_path / "STABLE"
if not stable_marker.exists():
get_logger().info(f"Waiting for the trainer to broadcast policy v{next_step}")
await wait_for_path(stable_marker)
await self.receiver.wait_published(next_step, cancelled=self.stopped.is_set)
self.last_wait_for_ckpt_time = time.perf_counter() - t0
# Publish confirmed: the policy version advances here, before the
@@ -134,7 +99,7 @@ class WeightWatcher:
get_logger().debug(f"Updating inference weights to policy v{next_step}")
t1 = time.perf_counter()
await update_weights(self.admin_clients.clients, weights_path, self.clients.model_name, step=next_step)
await self.receiver.receive(next_step)
self.last_update_weights_time = time.perf_counter() - t1
self.update_count += 1
get_logger().debug(
@@ -149,21 +114,6 @@ class WeightWatcher:
f"Observer {type(observer).__name__}.on_new_version({next_step}) raised: {exc!r}"
)
if self.model_express is not None:
await self.wait_for_model_express_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
async def wait_for_model_express_status(self, status: int) -> None:
while not self.stopped.is_set():
found = await asyncio.to_thread(
self.model_express.exists_role_with_status,
"trainer",
status,
)
if found:
return
await asyncio.sleep(self.poll_interval)
raise asyncio.CancelledError
def gauges(self) -> dict[str, float]:
return {
"watcher/policy_version": float(self.policy.version),
+18 -21
View File
@@ -9,7 +9,7 @@ from datetime import timedelta
# ruff: noqa: I001
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
from prime_rl.transports.weights import setup_weight_broadcast
from prime_rl.transports.weights import prune_broadcasts_beyond, setup_weight_sender
from prime_rl.utils.act_offloading import maybe_activation_offloading
import torch
import torch.distributed as dist
@@ -67,7 +67,7 @@ from prime_rl.utils.metrics_server import HealthServer, MetricsServer
from prime_rl import monitors
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
from prime_rl.utils.utils import clean_exit, final_broadcast_version, resolve_latest_ckpt_step
from ring_flash_attn import substitute_hf_flash_attn
@@ -172,12 +172,12 @@ def train(config: TrainerConfig):
# Set up weight broadcast (skip when using fake data since there's no inference server)
if config.data.fake:
weight_broadcast = None
weight_sender = None
logger.info("Skipping weight broadcast setup (fake data mode)")
else:
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
weight_broadcast = setup_weight_broadcast(
weight_sender = setup_weight_sender(
config.output_dir,
config.weight_broadcast,
parallel_dims,
@@ -279,12 +279,15 @@ def train(config: TrainerConfig):
# rollouts so the trainer and inference pool join the same update lifecycle,
# and so a broken broadcast path fails at startup instead of after the first
# optimizer step.
if progress.step == start_step and weight_broadcast is not None:
logger.info(f"Broadcasting base policy weights (v{progress.step - 1}) to inference engines")
if progress.step == start_step and weight_sender is not None:
startup_version = progress.step - 1
if world.is_master:
prune_broadcasts_beyond(config.output_dir, startup_version)
logger.info(f"Broadcasting startup policy weights (v{startup_version}) to inference engines")
t0 = time.perf_counter()
weight_broadcast.broadcast_weights(model, step=progress.step - 1)
weight_sender.broadcast(model, startup_version)
logger.debug(
f"Broadcast base policy weights (v{progress.step - 1}) in {format_time(time.perf_counter() - t0)}"
f"Broadcast startup policy weights (v{startup_version}) in {format_time(time.perf_counter() - t0)}"
)
# Wait for the batch to be available
@@ -584,16 +587,14 @@ def train(config: TrainerConfig):
forward_backward_time = time.perf_counter() - forward_backward_start_time
# Broadcast the model just produced (policy v{progress.step}) so the orchestrator can
# sample its next step from it. Only the final version is unused (nothing samples from
# v{max_steps}) — the orchestrator stays alive for every other in-memory rendezvous;
# filesystem broadcast still writes every version for resume.
if weight_broadcast is None:
# sample its next step from it. Every broadcast is a handshake with the consumer, so
# versions past the last consumed one are skipped (``final_broadcast_version``:
# training never samples v{max_steps}, but a configured final eval measures it).
if weight_sender is None:
broadcast_weights_time = 0
else:
broadcast_unused = (
config.weight_broadcast.type in ("nccl", "nixl")
and config.max_steps is not None
and progress.step >= config.max_steps
broadcast_unused = config.max_steps is not None and progress.step > final_broadcast_version(
config.max_steps, config.weight_broadcast.broadcast_final
)
if not broadcast_unused:
broadcast_weights_start_time = time.perf_counter()
@@ -601,12 +602,8 @@ def train(config: TrainerConfig):
# resident weights; release cached blocks (incl. offload-stream
# pools) so the broadcast gets the full headroom.
torch.cuda.empty_cache()
weight_broadcast.broadcast_weights(model, step=progress.step)
weight_sender.broadcast(model, step=progress.step)
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
if config.weight_broadcast.type == "filesystem":
interval_to_keep = config.ckpt and config.ckpt.interval
weight_broadcast.maybe_clean(progress.step, interval_to_keep)
else:
broadcast_weights_time = 0
+15 -23
View File
@@ -21,8 +21,7 @@ from prime_rl.trainer.ckpt import Progress, setup_ckpt_manager
from prime_rl.utils.pathing import resolve_latest_ckpt_step
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.trainer import CheckpointConfig
from prime_rl.transports.weights import setup_weight_broadcast
from prime_rl.transports.weights.filesystem import FileSystemWeightBroadcast
from prime_rl.transports.weights import prune_broadcasts_beyond, setup_weight_sender
from prime_rl.utils.cp import setup_cp_params, shard_for_cp
from prime_rl.trainer.lora import get_lora_state
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
@@ -409,27 +408,24 @@ def train(config: SFTConfig):
def is_online_eval_step(step: int) -> bool:
return any(step % interval == 0 for interval in online_eval_intervals)
weight_broadcast = None
weight_sender = None
if online_eval_intervals:
assert config.weight_broadcast is not None
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
weight_broadcast = setup_weight_broadcast(
weight_sender = setup_weight_sender(
config.run_dir,
config.weight_broadcast,
parallel_dims,
config.model.lora,
)
if (
checkpoint_step is not None
and isinstance(weight_broadcast, FileSystemWeightBroadcast)
and not weight_broadcast.is_stable(checkpoint_step)
):
# Rebroadcast the resumed policy so the evals process can re-trigger at
# the resume step (older broadcasts may have been cleaned). Skipped when
# the previous run's broadcast survived: rewriting the same dir in place
# would race an evals process already reloading it.
weight_broadcast.broadcast_weights(model, step=checkpoint_step)
weight_broadcast.clean_older(checkpoint_step)
# Startup broadcast of the incoming policy: fails fast on a broken
# transport and lets the evals process re-trigger at the resume step
# (older broadcasts may have been cleaned).
startup_version = checkpoint_step or 0
if world.is_master:
prune_broadcasts_beyond(config.run_dir, startup_version)
logger.info(f"Broadcasting startup policy weights (v{startup_version}) for online evals")
weight_sender.broadcast(model, startup_version)
logger.info(f"Starting training loop (max_steps={config.max_steps or 'infinite'})")
max_memory = torch.cuda.mem_get_info()[1] / 1024**3 # GiB
@@ -574,12 +570,10 @@ def train(config: SFTConfig):
ckpt_manager.maybe_clean()
broadcast_weights_time = 0
if weight_broadcast is not None and not is_last_step and is_online_eval_step(progress.step):
if weight_sender is not None and not is_last_step and is_online_eval_step(progress.step):
logger.info(f"Broadcasting weights at step {progress.step}")
broadcast_start_time = time.perf_counter()
weight_broadcast.broadcast_weights(model, step=progress.step)
if isinstance(weight_broadcast, FileSystemWeightBroadcast):
weight_broadcast.clean_older(progress.step)
weight_sender.broadcast(model, step=progress.step)
broadcast_weights_time = time.perf_counter() - broadcast_start_time
# Optionally, dump memory snapshot
@@ -711,11 +705,9 @@ def train(config: SFTConfig):
ckpt_manager.maybe_clean()
# Broadcast the final weights so the evals process can run its forced final epoch
if weight_broadcast is not None:
if weight_sender is not None:
logger.info("Broadcasting final weights")
weight_broadcast.broadcast_weights(model, step=progress.step)
if isinstance(weight_broadcast, FileSystemWeightBroadcast):
weight_broadcast.clean_older(progress.step)
weight_sender.broadcast(model, step=progress.step)
if gradient_manager is not None:
gradient_manager.close()
-18
View File
@@ -19,7 +19,6 @@ from transformers.tokenization_utils import PreTrainedTokenizer
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_ckpt_dir
from prime_rl.utils.utils import get_step_path
if TYPE_CHECKING:
from prime_rl.configs.trainer import OptimizerInBackwardOffloadConfig
@@ -347,20 +346,3 @@ class MemoryProfiler:
f"Finished dumping memory snapshot in {time.monotonic() - begin:.2f} seconds, load {file_path} at https://docs.pytorch.org/memory_viz to visualize the memory usage"
)
self.step_num += 1
def maybe_clean(path: Path, step: int, interval_to_keep: int | None) -> None:
"""Delete the broadcast dir from 2 trainer steps ago.
With a 1-step async barrier, the orchestrator at trainer step ``step`` is still consuming the
ckpt from ``step - 1``; ``step - 2`` is therefore safe to remove unless it falls on a
checkpoint interval that we want to preserve.
"""
logger = get_logger()
candidate_step = max(step - 2, 0)
candidate_path = get_step_path(path, candidate_step)
if interval_to_keep and candidate_step % interval_to_keep == 0:
logger.debug(f"Keeping path {candidate_path} (on ckpt interval)")
return
logger.debug(f"Removing path {candidate_path}")
shutil.rmtree(candidate_path, ignore_errors=True)
+34 -9
View File
@@ -1,26 +1,51 @@
from pathlib import Path
import torch
from httpx import AsyncClient
from prime_rl.configs.trainer import LoRAConfig, WeightBroadcastConfig
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.transports.weights.filesystem import FileSystemWeightBroadcast
from prime_rl.transports.weights.nccl import NCCLWeightBroadcast
from prime_rl.transports.weights.nixl import NIXLWeightBroadcast
from prime_rl.transports.weights.base import WeightReceiver, WeightSender, prune_broadcasts_beyond
from prime_rl.transports.weights.filesystem import FileSystemWeightReceiver, FileSystemWeightSender
from prime_rl.transports.weights.nccl import NCCLWeightReceiver, NCCLWeightSender
from prime_rl.transports.weights.nixl import NIXLWeightReceiver, NIXLWeightSender
__all__ = [
"WeightReceiver",
"WeightSender",
"prune_broadcasts_beyond",
"setup_weight_receiver",
"setup_weight_sender",
]
def setup_weight_broadcast(
def setup_weight_sender(
output_dir: Path,
config: WeightBroadcastConfig,
parallel_dims: ParallelDims,
lora_config: LoRAConfig | None = None,
) -> WeightBroadcast:
) -> WeightSender:
if config.type == "nccl":
return NCCLWeightBroadcast(output_dir, config, torch.cuda.current_device())
return NCCLWeightSender(output_dir, config, torch.cuda.current_device())
elif config.type == "filesystem":
return FileSystemWeightBroadcast(output_dir, config, lora_config)
return FileSystemWeightSender(output_dir, config, lora_config)
elif config.type == "nixl":
return NIXLWeightBroadcast(output_dir, config, parallel_dims)
return NIXLWeightSender(output_dir, config, parallel_dims)
else:
raise ValueError(f"Invalid weight broadcast type: {config.type}")
def setup_weight_receiver(
broadcast_dir: Path,
config: WeightBroadcastConfig,
admin_clients: list[AsyncClient],
model_name: str,
) -> WeightReceiver:
if config.type == "nccl":
return NCCLWeightReceiver(broadcast_dir, config, admin_clients, model_name)
elif config.type == "filesystem":
return FileSystemWeightReceiver(broadcast_dir, config, admin_clients, model_name)
elif config.type == "nixl":
return NIXLWeightReceiver(broadcast_dir, config, admin_clients, model_name)
else:
raise ValueError(f"Invalid weight broadcast type: {config.type}")
+157 -6
View File
@@ -1,18 +1,169 @@
import asyncio
import shutil
import time
from abc import ABC, abstractmethod
from collections.abc import Callable
from pathlib import Path
from typing import final
import torch.nn as nn
from httpx import AsyncClient
from prime_rl.configs.trainer import LoRAConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_broadcast_dir, get_step_path
# Broadcast-dir sentinels. Every transport goes through the same four stages:
# the trainer resets the step dir and raises ``.sender_ready``, the consumer
# joins the transfer and replies ``.receiver_ready`` (for NCCL with the
# engines paused inside the receive RPC), the trainer raises ``.started`` and
# moves the weights, then raises ``.finished`` — for filesystem, the weights
# are fully on disk.
SENDER_READY_MARKER = ".sender_ready"
RECEIVER_READY_MARKER = ".receiver_ready"
STARTED_MARKER = ".started"
FINISHED_MARKER = ".finished"
class WeightBroadcast(ABC):
def __init__(self, output_dir: Path, lora_config: LoRAConfig | None = None):
def prune_broadcasts_beyond(output_dir: Path, step: int) -> None:
"""Remove broadcast dirs beyond ``step``. Resume hygiene, run by the
trainer master before its startup broadcast: stale leftovers of a longer
crashed run would otherwise steer the consumer past the resume point."""
broadcast_dir = get_broadcast_dir(output_dir)
for old_step in get_all_ckpt_steps(broadcast_dir):
if old_step > step:
shutil.rmtree(get_step_path(broadcast_dir, old_step), ignore_errors=True)
class WeightSender(ABC):
"""Trainer-side weight publisher. ``broadcast`` wraps the transport's
``_broadcast`` with the shared sentinel handshake: every version is
offered (``.sender_ready``), acknowledged by the consumer
(``.receiver_ready``), transferred (``.started``), and committed
(``.finished``). The trainer therefore runs in lockstep with its consumer
on every transport — a broadcast nobody receives blocks and then fails."""
def __init__(self, output_dir: Path, timeout: int):
self.logger = get_logger()
self.world = get_world()
self.output_dir = output_dir
self.lora_config = lora_config
self.timeout = timeout
@final
def broadcast(self, model: nn.Module, step: int) -> None:
"""Broadcast policy v{step} to the inference pool."""
start_time = time.perf_counter()
step_dir = self.step_dir(step)
if self.world.is_master:
# Reset per attempt so a re-broadcast (e.g. on resume) never trips
# the consumer or the trainer on stale markers of a previous run.
shutil.rmtree(step_dir, ignore_errors=True)
step_dir.mkdir(parents=True)
(step_dir / SENDER_READY_MARKER).touch()
self._wait_for_receiver_ready(step_dir)
(step_dir / STARTED_MARKER).touch()
self._broadcast(model, step, step_dir)
if self.world.is_master:
(step_dir / FINISHED_MARKER).touch()
self._clean(step)
self.logger.debug(f"Broadcasted weights for step {step} in {time.perf_counter() - start_time:.2f}s")
def step_dir(self, step: int) -> Path:
return get_step_path(get_broadcast_dir(self.output_dir), step)
def _wait_for_receiver_ready(self, step_dir: Path) -> None:
"""Wait for the consumer to acknowledge the offered version. Bounded:
a consumer that dies mid-handshake must fail the run instead of
stranding the trainer forever."""
ready_file = step_dir / RECEIVER_READY_MARKER
self.logger.debug(f"Waiting for the receiver at {ready_file}")
start = time.monotonic()
last_log = start
while not ready_file.exists():
now = time.monotonic()
if now - start > self.timeout:
raise TimeoutError(f"No receiver joined the broadcast within {self.timeout}s ({ready_file})")
if now - last_log > 60:
# A busy consumer (e.g. an evals process mid-epoch) can lag legitimately;
# raise weight_broadcast.timeout if this trips on long eval epochs.
self.logger.warning(f"Still waiting for the broadcast receiver after {now - start:.0f}s")
last_log = now
time.sleep(0.1)
self.logger.debug("Receiver ready, starting the transfer")
@abstractmethod
def broadcast_weights(self, model: nn.Module, step: int):
pass
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
"""Move v{step}'s weights to the consumer. Rank synchronization is the
transport's own job — non-master ranks must be held back until the
master finished the handshake (see ``NCCLWeightSender._broadcast``)."""
def _clean(self, step: int) -> None:
"""Remove old broadcast dirs, keeping ``step`` and ``step - 1`` (a
lagging consumer may still be reading it). Broadcasts are purely
transitive — run state persistence is the checkpoint's job."""
broadcast_dir = get_broadcast_dir(self.output_dir)
for old_step in get_all_ckpt_steps(broadcast_dir):
if old_step < step - 1:
shutil.rmtree(get_step_path(broadcast_dir, old_step), ignore_errors=True)
class WeightReceiver(ABC):
"""Consumer-side counterpart of ``WeightSender`` — moves the inference
engines onto trainer-offered policy versions. It runs in the consumer
process (the RL orchestrator, or the SFT evals process): the weight
watcher, the orchestrator's startup rendezvous, and the evals process all
drive the same object instead of hand-rolling transport branches. The
engines' in-process receive hooks are its data plane, reached through the
admin clients."""
def __init__(
self,
broadcast_dir: Path,
config: WeightBroadcastConfig,
admin_clients: list[AsyncClient],
model_name: str,
) -> None:
self.logger = get_logger()
self.broadcast_dir = broadcast_dir
self.config = config
self.admin_clients = admin_clients
self.model_name = model_name
async def initialize(self) -> None:
"""One-time transport bootstrap (rendezvous groups, sessions)."""
def step_dir(self, step: int) -> Path:
return get_step_path(self.broadcast_dir, step)
def is_published(self, step: int) -> bool:
"""Whether the trainer has offered v{step}."""
return (self.step_dir(step) / SENDER_READY_MARKER).exists()
def next_version(self, current: int) -> int:
"""Newest version offered beyond ``current``; ``current`` if none."""
published = [step for step in get_all_ckpt_steps(self.broadcast_dir) if self.is_published(step)]
return max(published, default=current)
async def wait_published(self, step: int, cancelled: Callable[[], bool] | None = None) -> None:
"""Block until the trainer offers v{step}. Runs before the orchestrator
advances ``policy.version`` — the version must never move ahead of a
confirmed offer."""
sender_ready = self.step_dir(step) / SENDER_READY_MARKER
while not sender_ready.exists():
if cancelled is not None and cancelled():
raise asyncio.CancelledError
await asyncio.sleep(0.2)
def _ack(self, step: int) -> None:
"""Acknowledge the offered version — unblocks the waiting trainer."""
(self.step_dir(step) / RECEIVER_READY_MARKER).touch()
@abstractmethod
async def receive(self, step: int) -> None:
"""Acknowledge the offered v{step} and move the engines onto it."""
async def sync_startup(self, step: int, timeout: float) -> None:
"""Rendezvous with the trainer's startup broadcast of v{step}."""
await asyncio.wait_for(self.wait_published(step), timeout=timeout)
await self.receive(step)
+33 -50
View File
@@ -1,5 +1,3 @@
import shutil
import time
from pathlib import Path
import torch.distributed as dist
@@ -7,12 +5,10 @@ import torch.nn as nn
from torch.distributed.tensor import DTensor
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig, LoRAConfig
from prime_rl.orchestrator.clients import load_lora_adapter, update_weights
from prime_rl.trainer.lora import get_lora_state, save_lora_config
from prime_rl.trainer.utils import maybe_clean
from prime_rl.trainer.world import get_world
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.utils.logger import format_time
from prime_rl.utils.utils import get_all_ckpt_steps, get_broadcast_dir, get_step_path
from prime_rl.transports.weights.base import FINISHED_MARKER, WeightReceiver, WeightSender
from prime_rl.utils.pathing import wait_for_path
from prime_rl.utils.weights import (
convert_state_dict_to_hf,
gather_weights_parallel,
@@ -21,27 +17,22 @@ from prime_rl.utils.weights import (
)
class FileSystemWeightBroadcast(WeightBroadcast):
"""Broadcast weights into the inference engine via shared filesystem."""
class FileSystemWeightSender(WeightSender):
"""Broadcast weights by saving a HF-compatible checkpoint (or, for LoRA
runs, the PEFT-shaped adapter) to a shared filesystem."""
def __init__(
self, output_dir: Path, config: FileSystemWeightBroadcastConfig, lora_config: LoRAConfig | None = None
self,
output_dir: Path,
config: FileSystemWeightBroadcastConfig,
lora_config: LoRAConfig | None = None,
):
super().__init__(output_dir, lora_config)
self.world = get_world()
super().__init__(output_dir, config.timeout)
self.lora_config = lora_config
self.logger.debug("Initialized filesystem weight broadcast")
def broadcast_weights(self, model: nn.Module, step: int) -> None:
"""Broadcast weights by saving a HF-compatible checkpoint to shared filesystem and notifies the orchestrator."""
self.logger.debug(f"Broadcasting policy weights (v{step}) via the shared filesystem")
start_time = time.perf_counter()
adapter_only = self.lora_config is not None
save_dir = get_step_path(get_broadcast_dir(self.output_dir), step)
if self.world.is_master:
save_dir.mkdir(parents=True, exist_ok=True)
if adapter_only:
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
if self.lora_config is not None:
# All ranks must participate in DTensor gathering, but only master saves
state_dict = get_lora_state().adapter_state_dict()
for key, value in state_dict.items():
@@ -50,11 +41,11 @@ class FileSystemWeightBroadcast(WeightBroadcast):
if self.world.is_master:
state_dict[key] = value.to("cpu", non_blocking=False)
if self.world.is_master:
self.logger.debug(f"Saving weights to {save_dir}")
save_state_dict(state_dict, save_dir, save_sharded=False, adapter=True)
self.logger.debug(f"Saving adapter to {step_dir}")
save_state_dict(state_dict, step_dir, save_sharded=False, adapter=True)
save_lora_config(
model,
save_dir,
step_dir,
rank=self.lora_config.rank,
alpha=self.lora_config.alpha,
dropout=self.lora_config.dropout,
@@ -63,30 +54,22 @@ class FileSystemWeightBroadcast(WeightBroadcast):
dist.barrier()
state_dict = gather_weights_parallel(model)
state_dict = convert_state_dict_to_hf(model, state_dict)
self.logger.debug(f"Saving weights to {save_dir}")
save_state_dict_parallel(state_dict, save_dir)
self.logger.debug(f"Saving weights to {step_dir}")
save_state_dict_parallel(state_dict, step_dir)
if self.world.is_master:
self._notify_orchestrator(save_dir)
self.logger.debug(f"Broadcast policy weights (v{step}) in {format_time(time.perf_counter() - start_time)}")
def _notify_orchestrator(self, save_dir: Path):
"""Notify the orchestrator that the weights have been broadcast by writing a 'STABLE' file to a shared filesystem."""
stable_file = save_dir / "STABLE"
stable_file.touch()
class FileSystemWeightReceiver(WeightReceiver):
"""Loads broadcasts from the shared filesystem. The acknowledgement lets
the trainer start writing; the engines are only touched once the weights
are fully on disk. An adapter broadcast (PEFT dir) is hot-swapped under
live traffic — an in-place adapter reload is a vLLM-native op that needs
no engine pause; a full checkpoint pauses the engines for the load."""
def maybe_clean(self, step: int, interval_to_keep: int | None):
maybe_clean(get_broadcast_dir(self.output_dir), step, interval_to_keep)
def is_stable(self, step: int) -> bool:
"""Whether a complete broadcast for ``step`` is already on disk."""
return (get_step_path(get_broadcast_dir(self.output_dir), step) / "STABLE").exists()
def clean_older(self, step: int) -> None:
"""Remove all broadcast dirs older than ``step``, keeping only the newest."""
if not self.world.is_master:
return
broadcast_dir = get_broadcast_dir(self.output_dir)
for old_step in get_all_ckpt_steps(broadcast_dir):
if old_step < step:
shutil.rmtree(get_step_path(broadcast_dir, old_step), ignore_errors=True)
async def receive(self, step: int) -> None:
weights_dir = self.step_dir(step)
self._ack(step)
await wait_for_path(weights_dir / FINISHED_MARKER)
if (weights_dir / "adapter_config.json").exists():
await load_lora_adapter(self.admin_clients, self.model_name, weights_dir)
else:
await update_weights(self.admin_clients, weights_dir, step=step)
+39 -43
View File
@@ -1,5 +1,4 @@
import pickle
import time
from pathlib import Path
from typing import Callable, Generator, cast
@@ -12,15 +11,13 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
from vllm.distributed.utils import StatelessProcessGroup
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
from prime_rl.orchestrator.clients import NCCL_READY_MARKER
from prime_rl.orchestrator.clients import init_nccl_broadcast, update_weights
from prime_rl.trainer.conversion_utils import get_max_layer_num
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.utils import get_world
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
from prime_rl.utils.logger import get_logger
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
from prime_rl.utils.pathing import sync_wait_for_path
from prime_rl.utils.utils import get_broadcast_dir, get_step_path
from prime_rl.utils.vlm import get_layer_prefix
@@ -108,7 +105,7 @@ def preprocess_layer_quantized(
return model.convert_layer_to_vllm_kernel(layer_state_dict, layer_idx, quantize_fp8=True)
class NCCLWeightBroadcastSender:
class NCCLBroadcaster:
def __init__(
self,
host: str,
@@ -117,12 +114,11 @@ class NCCLWeightBroadcastSender:
world_size: int,
device: int | str | torch.device,
timeout: int,
dtype: torch.dtype = torch.bfloat16,
quantize_in_weight_transfer: bool = False,
):
self.logger = get_logger()
self.world = get_world()
self.dtype = dtype
self.dtype = torch.bfloat16
self.quantize_in_weight_transfer = quantize_in_weight_transfer
if self.world.is_master:
@@ -137,7 +133,7 @@ class NCCLWeightBroadcastSender:
self.logger.debug("Initialized NCCL broadcast on non-master rank (no communicator)")
@torch.no_grad()
def broadcast_weights(self, model: nn.Module, step: int) -> None:
def send(self, model: nn.Module) -> None:
"""Broadcast the state dict of a model into the inference pool using NCCL."""
state_dict = model.state_dict()
layer_prefix = get_layer_prefix(model.config)
@@ -167,7 +163,7 @@ class NCCLWeightBroadcastSender:
return state_dict
class NCCLWeightBroadcast(WeightBroadcast):
class NCCLWeightSender(WeightSender):
"""Broadcast weights into the inference engine using NCCL."""
def __init__(
@@ -175,50 +171,50 @@ class NCCLWeightBroadcast(WeightBroadcast):
output_dir: Path,
config: NCCLWeightBroadcastConfig,
device: int | str | torch.device,
dtype: torch.dtype = torch.bfloat16,
):
super().__init__(output_dir)
self.logger = get_logger()
self.world = get_world()
self.nccl_broadcast_sender = NCCLWeightBroadcastSender(
super().__init__(output_dir, config.timeout)
self.nccl_broadcast_sender = NCCLBroadcaster(
config.host,
config.port,
0,
config.inference_world_size + 1,
device,
config.timeout,
dtype,
quantize_in_weight_transfer=config.quantize_in_weight_transfer,
)
@torch.no_grad()
def broadcast_weights(self, model: nn.Module, step: int) -> None:
"""Broadcast the state dict of a model into the inference pool using NCCL and notifies the orchestrator."""
self.logger.debug(f"Broadcasting policy weights (v{step}) via NCCL")
start_time = time.perf_counter()
# Only the master touches the filesystem to notify the orchestrator, but all
# ranks must wait for the inference pool before entering the broadcast path:
# the broadcast preparation (DTensor resolution, quantization) enqueues
# collectives on non-master ranks, and if those ranks start prep before
# the orchestrator has paused inference, the collectives sit unmatched
# until NCCL's watchdog kills the process after 10 min.
save_dir = get_step_path(get_broadcast_dir(self.output_dir), step)
if self.world.is_master:
self._notify_orchestrator(save_dir)
self._wait_for_nccl_ready(save_dir)
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
# The master enters only after the receiver acknowledged the handshake,
# but all ranks must be held back until then: the broadcast preparation
# (DTensor resolution, quantization) enqueues collectives on non-master
# ranks, and if those start before the receiver has paused inference,
# the collectives sit unmatched until NCCL's watchdog kills the process.
if self.world.world_size > 1:
dist.barrier()
self.nccl_broadcast_sender.broadcast_weights(model, step)
self.logger.debug(f"Broadcast policy weights (v{step}) in {format_time(time.perf_counter() - start_time)}")
self.nccl_broadcast_sender.send(model)
def _notify_orchestrator(self, save_dir: Path) -> None:
"""Create the STABLE marker the orchestrator's weight watcher polls for."""
save_dir.mkdir(parents=True, exist_ok=True)
(save_dir / "STABLE").touch()
def _wait_for_nccl_ready(self, save_dir: Path):
"""Wait for inference workers to signal they are ready to receive NCCL broadcast."""
nccl_ready_file = save_dir / NCCL_READY_MARKER
self.logger.debug(f"Waiting for NCCL_READY marker at {nccl_ready_file}")
sync_wait_for_path(nccl_ready_file, interval=0.1, log_interval=10)
self.logger.debug("Inference workers ready for NCCL broadcast")
class NCCLWeightReceiver(WeightReceiver):
"""Joins the trainer's NCCL collective. The receiver pauses the engines,
acknowledges, and sends them into the receive RPC — only then does the
trainer enter the collective, so the handshake can never race a stale
marker."""
async def initialize(self) -> None:
await init_nccl_broadcast(
self.admin_clients,
self.config.host,
self.config.port,
self.config.timeout,
inference_world_size=self.config.inference_world_size,
quantize_in_weight_transfer=self.config.quantize_in_weight_transfer,
)
async def receive(self, step: int) -> None:
await update_weights(
self.admin_clients,
self.step_dir(step),
step=step,
on_paused=lambda: self._ack(step),
)
@@ -1,5 +1,5 @@
"""NIXL weight broadcasting and transfer helpers."""
from prime_rl.transports.weights.nixl.nixl import NIXLWeightBroadcast
from prime_rl.transports.weights.nixl.nixl import NIXLWeightReceiver, NIXLWeightSender
__all__ = ["NIXLWeightBroadcast"]
__all__ = ["NIXLWeightReceiver", "NIXLWeightSender"]
+60 -7
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
import re
import time
from collections import defaultdict
@@ -20,10 +21,10 @@ from torch.distributed.tensor import DTensor
from torch.distributed.tensor._utils import compute_local_shape_and_global_offset
from prime_rl.configs.trainer import NIXLWeightBroadcastConfig
from prime_rl.orchestrator.clients import init_nixl_broadcast, update_weights
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.utils import get_world
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
from prime_rl.transports.weights.nixl.agent import NixlAgent, make_agent_name, set_ucx_env_defaults
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
size_cuda_buffers,
@@ -67,12 +68,16 @@ class TransferGroupIndex:
layer_to_group: dict[int, int]
class NIXLWeightBroadcast(WeightBroadcast):
def __init__(self, output_dir: Path, config: NIXLWeightBroadcastConfig, parallel_dims: ParallelDims) -> None:
super().__init__(output_dir)
class NIXLWeightSender(WeightSender):
def __init__(
self,
output_dir: Path,
config: NIXLWeightBroadcastConfig,
parallel_dims: ParallelDims,
) -> None:
super().__init__(output_dir, config.timeout)
self.config = config
self.parallel_dims = parallel_dims
self.world = get_world()
if self.is_serving_rank:
set_ucx_env_defaults()
self.nixl_agent = NixlAgent(make_agent_name("trainer", self.world.rank))
@@ -82,6 +87,8 @@ class NIXLWeightBroadcast(WeightBroadcast):
self.staged_shards_by_group: dict[int, list[StagedTensorShard]] = {}
self.staging_arenas: dict[torch.dtype, torch.Tensor] = {}
self.staging_buffer_count: int
self.model_express: ModelExpressSession | None = None
self.buffer_sessions: list[ModelExpressSession] = []
@property
def is_serving_rank(self) -> bool:
@@ -405,7 +412,7 @@ class NIXLWeightBroadcast(WeightBroadcast):
dist.barrier()
@torch.no_grad()
def broadcast_weights(self, model: nn.Module, step: int) -> None:
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
self.initialize_transfer(model)
start = time.perf_counter()
@@ -463,3 +470,49 @@ class NIXLWeightBroadcast(WeightBroadcast):
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
dist.barrier()
self.logger.info(f"NIXL+ModelExpress policy v{step} synchronized in {time.perf_counter() - start:.2f}s")
class NIXLWeightReceiver(WeightReceiver):
"""Drives the orchestrator's side of the ModelExpress rendezvous. Version
discovery runs on the shared sentinels; the unversioned ModelExpress
statuses only choreograph the transfer itself."""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.session = ModelExpressSession(
client=MxClient(server_url=f"{self.config.host}:{self.config.port}"),
role="orchestrator",
rank=0,
session_id=self.config.session_id,
worker_id="orchestrator",
)
async def initialize(self) -> None:
await init_nixl_broadcast(
self.admin_clients,
self.config.host,
self.config.port,
self.config.timeout,
self.config.inference_world_size,
self.config.session_id,
)
self.session.publish()
await self.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
async def set_status(self, status: int) -> None:
await asyncio.to_thread(self.session.set_status, status)
async def receive(self, step: int) -> None:
# ACK the trainer (it waits for the orchestrator's READY before the
# engines' INITIALIZING), run the transfer, then close the cycle.
self._ack(step)
await self.set_status(p2p_pb2.SOURCE_STATUS_READY)
await update_weights(self.admin_clients, None, step=step)
await self.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
await asyncio.to_thread(
self.session.wait_for,
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
timeout=self.config.timeout,
)
+5 -9
View File
@@ -163,15 +163,11 @@ def get_free_port() -> int:
return port
def get_latest_ckpt_step(weights_dir: Path) -> int | None:
step_dirs = list(weights_dir.glob("step_*"))
if len(step_dirs) == 0:
return None
steps = sorted([int(step_dir.name.split("_")[-1]) for step_dir in step_dirs])
for latest_step in steps[::-1]:
if Path(weights_dir / f"step_{latest_step}" / "STABLE").exists():
return latest_step
return None
def final_broadcast_version(max_steps: int, broadcast_final: bool) -> int:
"""Newest policy version the trainer will ever broadcast: v{max_steps} when
something consumes it (a configured final eval), else v{max_steps - 1} -
training never samples from the final version."""
return max_steps if broadcast_final else max_steps - 1
@contextmanager
+3 -5
View File
@@ -4,7 +4,7 @@ import pytest
import torch
from prime_rl.inference.vllm.worker.nccl import NCCLWeightBroadcastReceiver
from prime_rl.transports.weights.nccl import NCCLWeightBroadcastSender
from prime_rl.transports.weights.nccl import NCCLBroadcaster
pytestmark = [pytest.mark.gpu]
@@ -16,9 +16,7 @@ def test_nccl_broadcast(free_port):
def send():
device = torch.device(f"cuda:{0}")
nccl_broadcast = NCCLWeightBroadcastSender(
host=host, port=free_port, rank=0, world_size=2, device=device, timeout=10
)
nccl_broadcast = NCCLBroadcaster(host=host, port=free_port, rank=0, world_size=2, device=device, timeout=10)
class SubModel(torch.nn.Module):
def __init__(self):
@@ -43,7 +41,7 @@ def test_nccl_broadcast(free_port):
for param in model.parameters():
param.data = torch.ones_like(param.data)
nccl_broadcast.broadcast_weights(model, step=0)
nccl_broadcast.send(model)
def receive():
device = torch.device(f"cuda:{1}")
Generated
+32 -4
View File
@@ -50,8 +50,10 @@ members = [
"charxiv",
"clbench",
"color-codeword",
"deep-swe",
"deepdive",
"deepseek-prover",
"deshuffle-papers",
"drug-discovery-bench",
"enterprise-ops-gym",
"forth-lang",
@@ -1305,6 +1307,17 @@ wheels = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", hash = "sha256:3a9e4472b86e8e7e2c77cc76951c886bbe7a23a1f5908958969ab5b9c707a2f3" },
]
[[package]]
name = "deep-swe"
version = "0.1.0"
source = { editable = "deps/prime-envs/environments/swe/deep_swe" }
dependencies = [
{ name = "verifiers", extra = ["harbor"] },
]
[package.metadata]
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.0" }]
[[package]]
name = "deepdiff"
version = "9.1.0"
@@ -1375,6 +1388,21 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/cf/65/4df6936130b56e1429114e663e7c1576cf845f3aef1b2dd200c0a5d19dba/depyf-0.20.0-py3-none-any.whl", hash = "sha256:d31effad4261cebecb58955d832e448ace88f432328f95f82fd99c30fd9308d4", size = 39381, upload-time = "2025-10-13T12:33:33.647Z" },
]
[[package]]
name = "deshuffle-papers"
version = "0.1.0"
source = { editable = "deps/prime-envs/environments/reasoning/deshuffle_papers" }
dependencies = [
{ name = "huggingface-hub" },
{ name = "verifiers" },
]
[package.metadata]
requires-dist = [
{ name = "huggingface-hub", specifier = ">=0.20" },
{ name = "verifiers", specifier = ">=0.3.0" },
]
[[package]]
name = "detect-installer"
version = "0.1.0"
@@ -3365,7 +3393,7 @@ wheels = [
[[package]]
name = "mcp-atlas"
version = "0.3.0"
version = "0.3.1"
source = { editable = "deps/prime-envs/environments/tool_use/mcp_atlas" }
dependencies = [
{ name = "datasets" },
@@ -3378,7 +3406,7 @@ dependencies = [
requires-dist = [
{ name = "datasets", specifier = ">=4.0.0,<5" },
{ name = "httpx" },
{ name = "prime-sandboxes", specifier = ">=0.2.19" },
{ name = "prime-sandboxes", specifier = ">=0.2.37" },
{ name = "verifiers", specifier = ">=0.3.0" },
]
@@ -6610,7 +6638,7 @@ source = { git = "https://github.com/SWE-bench/SWE-smith.git?rev=9b74ac0#9b74ac0
[[package]]
name = "swesmith-env"
version = "0.1.2"
version = "0.1.3"
source = { editable = "deps/prime-envs/environments/swe/swesmith_env" }
dependencies = [
{ name = "datasets" },
@@ -6622,7 +6650,7 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "datasets" },
{ name = "swebench" },
{ name = "swebench", specifier = ">=4.1.0,<5" },
{ name = "swesmith", git = "https://github.com/SWE-bench/SWE-smith.git?rev=9b74ac0" },
{ name = "verifiers", specifier = ">=0.2.2.dev27" },
]