Compare commits

...
Author SHA1 Message Date
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
Mika SenghaasandGitHub 947a02aafc feat: serve the LoRA adapter under the base model name (#3358)
## Summary

- Register the single training adapter under `config.model.name`: the
adapter shadows the base model (vLLM resolves `lora_requests` before the
base-model match; verified on the pinned vLLM 0.26), so requests keep
addressing one stable name and nothing switches model names mid-run.
- `update_weights` becomes artifact-driven: a weight dir holding
`adapter_config.json` is hot-swapped as an adapter (a vLLM-native
in-place reload, no engine pause); anything else is a full checkpoint
load.
- Deletes the adapter-naming machinery: the per-version model-name
rewrite in watcher/orchestrator/evals, evals' fixed `eval-adapter` name
and disk-sniff dance, `update_model_name`, and the dead
`unload_lora_adapter`.
- Guardrails: `modules_to_save` is rejected when the weight broadcast is
live (only adapter tensors ship - fully-trained modules would silently
diverge from inference); the LoRA/in-memory rejection states the real
reason (vLLM loads adapters only from a PEFT-shaped directory on disk).
The fallback, if a future vLLM rejects registering an adapter under a
served model name, is documented in the `/load_lora_adapter` wrapper: a
distinct constant name set once at startup.

## Breaking

- `orchestrator.model.lora.name` config field removed (with its
`r{rank}-a{alpha}` auto-derivation). External clients that addressed the
adapter name must use the base model name.
- Inference `max_loras` default 8 → 1 (in-place reload reuses one slot);
the `max_cpu_loras = 100` unload-era override is removed.

Part of the #3335 breakup (stack 5/6); re-lands #3356, whose
squash-merge landed on the stacked base branch instead of main. Verified
e2e as part of #3335 (LoRA reverse-text 15→20 with resume, reward
climbing under the base name).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the LoRA inference serving path and is a breaking config
change (`orchestrator.model.lora.name` removed, `max_loras` default
8→1). Wrong adapter naming or slot count would mis-serve or fail weight
updates.
> 
> **Overview**
> Registers the single training LoRA under `config.model.name` so the
adapter shadows the base model in vLLM. Requests keep using one stable
name; each policy version is an in-place reload (no engine pause, no
mid-run `model_name` rewrite).
> 
> `update_weights` is now artifact-driven: a dir with
`adapter_config.json` loads as LoRA; anything else is a full checkpoint.
Adapter-naming machinery is gone (`orchestrator.model.lora.name`, evals'
`eval-adapter`, `update_model_name`, `unload_lora_adapter`). `max_loras`
defaults to 1 and `max_cpu_loras` is dropped.
> 
> Rejects `modules_to_save` on live broadcasts (only adapter tensors
ship) and documents why LoRA needs filesystem broadcast. Clients that
used a custom adapter name must now hit the base model name.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7e4ba4ce153ee54b87816b573701cf9f95bda928. 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 19:58:13 -07:00
Mika SenghaasandGitHub f615de9383 refactor: split InferencePool into InferenceClient and AdminClients (#3355)
## Summary

- Split `InferencePool` into two explicit classes under
`prime_rl.orchestrator.clients` (moved out of `utils.client`):
`InferenceClient` (data plane: train/eval client configs, model name,
prefill scoring - single-valued, one router endpoint) and `AdminClients`
(admin plane: one httpx client per engine process, in GPU-rank order -
the `rank_offset` math in the broadcast init depends on it; readiness
checks).
- Data-plane variables are named `clients` across the codebase
(`policy_pool`/`pool`/`policy_inference` renamed; the dispatcher uses
`policy_clients` to distinguish from frozen-source clients).
- Fixes the httpx-client leak: `InferencePool.stop()` closed only the
prefill scorer, leaking N+1 admin/router clients per pool; `aclose()`
now closes all of them.
- Deletes the dispatcher's `pinned_client` - a no-op since the
single-URL router (the client for a group never changes).

Behavior-preserving otherwise: the LoRA-name plumbing and the NCCL_READY
marker semantics are untouched (they change in the stacked follow-ups).

Part of the #3335 breakup (stack 4/6).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches orchestrator inference wiring, weight updates, and shutdown,
but is a behavior-preserving split plus a resource-leak fix. NCCL
world-size is now required rather than defaulted.
> 
> **Overview**
> Splits the combined `InferencePool` into a **data plane**
(`InferenceClient`: train/eval clients, model name, prefill scoring) and
an **admin plane** (`AdminClients`: per-engine httpx clients in GPU-rank
order, readiness). Client helpers now live under
`prime_rl.orchestrator.clients`.
> 
> Call sites (orchestrator, evals, dispatcher, algorithms, generation
sources, watcher) take `clients` / `admin_clients` instead of a pool.
Frozen endpoints use a one-shot `check_inference_ready` instead of a
persistent admin plane.
> 
> Also **closes the httpx leak** (`aclose()` now shuts down admin/router
clients, not just the scorer), drops the unused dispatcher
`pinned_client`, and requires `inference_world_size` for NCCL init.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
19092eeb66bd30ff0fe34e5e64eb9a3276fa9c0f. 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 19:54:55 -07:00
Mika SenghaasandGitHub 1093f9b914 refactor: rename transports.rollouts to transports.batch (#3354)
## Summary

- Rename `transports.rollouts` → `transports.batch`: the module ships
packed training batches, not rollouts.
`MicroBatchSender`/`MicroBatchReceiver` (and the ZMQ/FileSystem
variants) become `BatchSender`/`BatchReceiver`;
`setup_micro_batch_{sender,receiver}` become
`setup_batch_{sender,receiver}`.
- The `MicroBatch` payload type, every `list[MicroBatch]` signature, and
the `rollout_transport` config field are unchanged.

Part of the #3335 breakup (stack 3/6).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-08-22 19:34:34 -07:00
Mika SenghaasandGitHub 67ab1d6667 chore: remove dead extra_headers_from_state config (#3353)
## Summary

- Remove the `client.extra_headers_from_state` config field and the
`auto_setup_session_headers` validator that populated it. The field has
no readers: v1 clients send the `X-Session-ID` sticky-routing header
themselves, from the rollout's trace id (`SESSION_ID_HEADER` in
`verifiers/v1/clients`, attached per request in `train.py` and
`eval.py`). Verified at the wire: requests through the real vf client
arrive at the router with the header and route sticky per session.

## Breaking

- `client.extra_headers_from_state` config field removed (dead - nothing
read it).

Part of the #3335 breakup (stack 2/6, on #3352).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-08-22 19:33:01 -07:00
58 changed files with 829 additions and 838 deletions
@@ -23,7 +23,6 @@ group_size = 16
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -20,7 +20,6 @@ group_size = 16
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
+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)
-1
View File
@@ -37,7 +37,6 @@ group_size = 16
initial_inflight = 1024
[orchestrator.model.lora]
name = "qwen3-4b-wiki-search"
[orchestrator.train.sampling]
max_completion_tokens = 512
@@ -111,14 +111,9 @@ class VllmConfig(BaseConfig):
enable_lora: bool = False
"""Enable LoRA."""
max_loras: int = 8
"""Maximum number of LoRAs."""
# TODO: The default value is very high because our areal impl for lora isn't ideal
# We add a lora with the same name instead of changing weights inplace
# Because we dont cancel requests that are past max_async, these requests could be using a LoRA that gets unloaded which will crash the inference server
max_cpu_loras: int = 100
"""Maximum number of LoRAs on CPU."""
max_loras: int = 1
"""Maximum number of concurrently served LoRAs. prime-rl serves one adapter and reloads
it in place every policy version (same name, same lora_int_id), so one slot suffices."""
max_lora_rank: int | None = None
"""Maximum LoRA rank. Rounded up to the nearest value vLLM accepts."""
@@ -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,
@@ -25,9 +26,6 @@ from prime_rl.utils.config import BaseConfig
class LoRAConfig(BaseConfig):
name: str | None = None
"""LoRA adapter name. If None, auto-generated from rank and alpha."""
rank: int | None = Field(None, ge=1)
"""LoRA rank for this run. Must be ≤ trainer's max rank. If None, uses the trainer's rank."""
@@ -376,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."""
@@ -543,12 +538,6 @@ class OrchestratorConfig(BaseConfig):
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def auto_setup_session_headers(self):
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
self.model.client.extra_headers_from_state.setdefault("X-Session-ID", "trajectory_id")
return self
@model_validator(mode="after")
def auto_setup_prime_monitor_name(self):
"""Default ``monitors.prime.name`` to the W&B run name when monitoring
@@ -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,
@@ -460,9 +463,13 @@ class RLConfig(BaseConfig):
self.weight_broadcast = SharedNCCLWeightBroadcastConfig()
if self.weight_broadcast.type != "filesystem" and self.trainer.model.lora is not None:
raise ValueError(
"LoRA training is not yet supported with in-memory weight broadcast. "
"Set weight_broadcast.type = 'filesystem'."
"LoRA requires weight_broadcast.type = 'filesystem': vLLM loads adapters only from a "
"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
@@ -474,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(
@@ -488,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)
@@ -568,11 +580,6 @@ class RLConfig(BaseConfig):
if self.orchestrator.model.lora.alpha is None:
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
if self.orchestrator.model.lora.name is None:
self.orchestrator.model.lora.name = (
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
)
if self.inference is not None:
self.inference.vllm.enable_lora = True
self.inference.vllm.max_lora_rank = self.trainer.model.lora.rank
@@ -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."""
@@ -169,9 +181,6 @@ class ClientConfig(BaseConfig):
headers_from_env: dict[str, str] = {}
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
extra_headers_from_state: dict[str, str] = {}
"""Maps HTTP header names to rollout-state field names. The header value is read from the rollout state dict on every request. e.g. ``{"X-Session-ID": "trajectory_id"}`` enables sticky routing at the inference router."""
skip_model_check: bool = False
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
@@ -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."""
@@ -733,7 +727,15 @@ class TrainerConfig(BaseConfig):
@model_validator(mode="after")
def validate_lora_broadcast(self):
if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "nixl"):
raise ValueError("In-memory weight broadcast does not support LoRA yet.")
raise ValueError(
"LoRA requires weight_broadcast.type = 'filesystem': vLLM loads adapters only from a "
"PEFT-shaped directory on disk - in-memory transports have no disk artifact to load from."
)
if self.model.lora is not None and self.model.lora.modules_to_save and self.data.fake is None:
raise ValueError(
"model.lora.modules_to_save cannot be served: the weight broadcast ships only the "
"adapter tensors, so fully-trained modules would silently diverge from inference."
)
return self
@model_validator(mode="after")
+94 -100
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,6 +32,8 @@ from subprocess import Popen
from prime_rl import monitors
from prime_rl.configs.evals import EvalsConfig
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
@@ -43,10 +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.utils.client import InferencePool, init_nccl_broadcast
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,10 +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).
LORA_NAME = "eval-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:
@@ -76,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()
@@ -95,7 +106,8 @@ class Evals:
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
self.pool = InferencePool(config.eval.client, model_name=config.model)
self.clients = InferenceClient(config.eval.client, model_name=config.model)
self.admin_clients = AdminClients(config.eval.client)
self.spawn_env_servers()
@@ -105,20 +117,23 @@ class Evals:
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
get_logger().info("Waiting for inference pool to be ready")
await self.pool.wait_for_ready(config.model)
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.pool.admin_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)
@@ -134,7 +149,7 @@ class Evals:
eval_envs=self.eval_envs,
train_source=None,
eval_source=self.eval_source,
policy_pool=self.pool,
policy_clients=self.clients,
policy=self.policy,
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
@@ -154,7 +169,7 @@ class Evals:
# The collector always polls — it feeds the concurrency controller;
# W&B mirroring is gated on the registered monitor.
self.inference_metrics = InferenceMetricsCollector(
self.pool.admin_clients,
self.admin_clients.clients,
on_load=self.concurrency.observe,
log_to_wandb=wandb_enabled,
)
@@ -166,7 +181,7 @@ class Evals:
if not await self.inference_metrics.probe():
concurrency = config.eval.concurrency
if concurrency.min_inflight != concurrency.max_inflight:
urls = ", ".join(str(client.base_url) for client in self.pool.admin_clients)
urls = ", ".join(str(client.base_url) for client in self.admin_clients.clients)
raise ValueError(
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
@@ -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,24 +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).
lora_name = LORA_NAME if (broadcast_dir / "adapter_config.json").exists() else None
try:
await self.pool.update_weights(broadcast_dir, lora_name=lora_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
if lora_name is not None:
self.pool.update_model_name(lora_name)
self.policy.model_name = lora_name
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
# between the trigger above and the weight reload completing.
self.policy.version = step
@@ -438,18 +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()
pool: InferencePool | None = getattr(self, "pool", None)
if pool is not None:
await pool.stop()
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)
+8 -4
View File
@@ -92,10 +92,14 @@ async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: R
"""Wrapper around vLLM's /v1/load_lora_adapter.
prime-rl reloads a fixed-name adapter with fresh weights every step (the path
changes per policy version; the name is constant, see orchestrator.lora_name).
vLLM's native loader rejects a same-name reload unless ``load_inplace=True``,
so we force it here — that makes the worker re-read the new weights during
``add_lora``, reusing the existing ``lora_int_id``.
changes per policy version; the name is constant — the base model name, which
the adapter shadows: ``_maybe_get_adapters`` resolves ``lora_requests`` before
the base-model match, so requests keep addressing one stable name. If a future
vLLM rejects registering an adapter under a served model name, fall back to a
distinct constant adapter name set once at startup.) vLLM's native loader
rejects a same-name reload unless ``load_inplace=True``, so we force it here —
that makes the worker re-read the new weights during ``add_lora``, reusing the
existing ``lora_int_id``.
We then reset the stored request's flag back to ``False``. ``load_inplace`` is
a sticky field on the ``LoRARequest`` that ``_maybe_get_adapters`` hands to
+5 -5
View File
@@ -22,7 +22,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_pool
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_client
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
from prime_rl.orchestrator.algo.hierarchical_grpo import HierarchicalGRPOAlgorithm
@@ -35,7 +35,7 @@ from prime_rl.orchestrator.algo.sft import SFTDistillAlgorithm
if TYPE_CHECKING:
from prime_rl.configs.algorithm import AlgoConfig
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
# Runtime dispatch is keyed on ``algo.type`` — it names the algorithm, and
# each config class's defaults are its vetted parameterization.
@@ -51,7 +51,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
}
def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> Algorithm:
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
cls = ALGORITHM_CLASSES[config.type]
assert cls.action_loss_type == config.action_loss_type # config and runtime declare in two places
# The Algorithm is the runtime of the algorithm config's training signal
@@ -59,7 +59,7 @@ def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> Algorithm
# handed the live policy pool — opsd self-distills against it, others may
# judge against it or ignore it. Other models (a frozen teacher, a hint
# renderer) are built from the algorithm's own config in setup().
return cls(config, policy_pool)
return cls(config, clients)
__all__ = [
@@ -73,7 +73,7 @@ __all__ = [
"RAEAlgorithm",
"SFTDistillAlgorithm",
"build_algorithm",
"connect_frozen_pool",
"connect_frozen_client",
"assign_advantages",
"stamp_loss_routing",
]
+15 -16
View File
@@ -12,24 +12,24 @@ from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
async def connect_frozen_pool(
async def connect_frozen_client(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferencePool:
) -> InferenceClient:
"""Connect to an externally hosted frozen model and wait for it."""
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient, check_inference_ready
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
if renderer_config is not None:
pool = InferencePool(
clients = InferenceClient(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
pool = InferencePool(config, model_name=config.name)
await pool.wait_for_ready(config.name)
return pool
clients = InferenceClient(config, model_name=config.name)
await check_inference_ready(config, config.name)
return clients
def iter_trainable_traces(episodes: list[vf.Episode]):
@@ -52,18 +52,17 @@ class Algorithm:
action_loss_type: ClassVar[ActionLossType] = "rl"
def __init__(self, config: AlgoConfig, policy_pool: InferencePool):
self.policy_pool = policy_pool
self.connected_pools: list[InferencePool] = []
def __init__(self, config: AlgoConfig, clients: InferenceClient):
self.clients = clients
self.connected: InferenceClient | None = None
async def setup(self) -> None:
"""Connect resources owned by the algorithm."""
async def connect(self, reference: FrozenModelConfig) -> InferencePool:
"""Connect and track a frozen model pool owned by this algorithm."""
pool = await connect_frozen_pool(reference)
self.connected_pools.append(pool)
return pool
async def connect(self, reference: FrozenModelConfig) -> InferenceClient:
"""Connect and track the frozen model pool owned by this algorithm."""
self.connected = await connect_frozen_client(reference)
return self.connected
async def score_episode(self, episode: vf.Episode) -> None:
"""Assign rollout-local annotations to one finalized episode."""
+3 -3
View File
@@ -11,7 +11,7 @@ from prime_rl.utils.utils import import_object
if TYPE_CHECKING:
import verifiers.v1 as vf
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class EchoAlgorithm(GRPOAlgorithm):
@@ -22,8 +22,8 @@ class EchoAlgorithm(GRPOAlgorithm):
mask and its denominator. An optional user filter narrows the selection
per rollout (e.g. dropping tool-output warnings)."""
def __init__(self, config: EchoAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
def __init__(self, config: EchoAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.role_weights = {
role: role_config.alpha
for role in ("system", "user", "assistant", "tool")
+3 -3
View File
@@ -10,7 +10,7 @@ from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
from prime_rl.orchestrator.algo.routing import assign_advantages
if TYPE_CHECKING:
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class GRPOAlgorithm(Algorithm):
@@ -18,8 +18,8 @@ class GRPOAlgorithm(Algorithm):
policy per example; credit = reward minus the group mean (optionally
length-shaped); action tokens feed the ``rl`` loss."""
def __init__(self, config: GRPOAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
def __init__(self, config: GRPOAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.length_penalty = config.length_penalty
async def score_group(self, episodes: list[vf.Episode]) -> None:
@@ -10,7 +10,7 @@ from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
from prime_rl.orchestrator.algo.routing import assign_advantages
if TYPE_CHECKING:
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class HierarchicalGRPOAlgorithm(Algorithm):
@@ -26,8 +26,8 @@ class HierarchicalGRPOAlgorithm(Algorithm):
within one episode. Other roles are compared across the full rollout group.
A comparison group with one trace produces zero advantage."""
def __init__(self, config: HierarchicalGRPOAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
def __init__(self, config: HierarchicalGRPOAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.episode_agents = set(config.episode_agents)
async def score_group(self, episodes: list[vf.Episode]) -> None:
+8 -8
View File
@@ -11,7 +11,7 @@ from prime_rl.orchestrator.algo.routing import assign_reference_logprobs
from prime_rl.orchestrator.trajectories import iter_trainable_branches
if TYPE_CHECKING:
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class OPDAlgorithm(Algorithm):
@@ -26,20 +26,20 @@ class OPDAlgorithm(Algorithm):
action_loss_type = "ref_kl"
def __init__(self, config: OPDAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
def __init__(self, config: OPDAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.teacher = config.teacher
self.teacher_pool: InferencePool | None = None # frozen teacher endpoint, connected in setup()
self.teacher_clients: InferenceClient | None = None # frozen teacher endpoint, connected in setup()
async def setup(self) -> None:
self.teacher_pool = await self.connect(self.teacher)
self.teacher_clients = await self.connect(self.teacher)
async def score_episode(self, episode: vf.Episode) -> None:
pool = self.teacher_pool
assert pool is not None, "teacher pool not connected — Algorithm.setup() must run first"
teacher = self.teacher_clients
assert teacher is not None, "teacher not connected — Algorithm.setup() must run first"
branches = [
branch for _, trace in iter_trainable_traces([episode]) for branch, _ in iter_trainable_branches(trace)
]
scores = await asyncio.gather(*(pool.score(branch.token_ids) for branch in branches))
scores = await asyncio.gather(*(teacher.score(branch.token_ids) for branch in branches))
for branch, logprobs in zip(branches, scores, strict=True):
assign_reference_logprobs(branch, logprobs)
+7 -7
View File
@@ -14,7 +14,7 @@ from prime_rl.orchestrator.utils import episode_env_name
if TYPE_CHECKING:
from renderers.base import Renderer
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class OPSDAlgorithm(Algorithm):
@@ -33,8 +33,8 @@ class OPSDAlgorithm(Algorithm):
action_loss_type = "ref_kl"
def __init__(self, config: OPSDAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
def __init__(self, config: OPSDAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.demo_key = config.demo_key
self.template = config.template
self.renderer_config = config.renderer
@@ -42,7 +42,7 @@ class OPSDAlgorithm(Algorithm):
# Self-distillation: the teacher *is* the live policy. Scoring against
# the shared policy pool tracks its current weights, model name, and
# endpoint churn for free.
self.teacher_pool = self.policy_pool
self.teacher_clients = self.clients
async def setup(self) -> None:
"""Build opsd's own hint-block renderer from config — it is not handed
@@ -51,7 +51,7 @@ class OPSDAlgorithm(Algorithm):
identically to the policy's own prompts."""
from renderers.base import create_renderer, load_tokenizer
self.renderer = create_renderer(load_tokenizer(self.policy_pool.model_name), self.renderer_config)
self.renderer = create_renderer(load_tokenizer(self.clients.model_name), self.renderer_config)
def _demonstration(self, episode: vf.Episode, trace: vf.Trace) -> str:
demonstration = trace.info.get(self.demo_key)
@@ -66,13 +66,13 @@ class OPSDAlgorithm(Algorithm):
return demonstration
async def score_episode(self, episode: vf.Episode) -> None:
pool = self.teacher_pool
teacher = self.teacher_clients
renderer = self.renderer
assert renderer is not None, "renderer not built — Algorithm.setup() must run first"
for _, trace in iter_trainable_traces([episode]):
hint = self.template.format(demonstration=self._demonstration(episode, trace))
hint_block = renderer.render_ids([{"role": "system", "content": hint}], add_generation_prompt=False)
branches = [branch for branch, _ in iter_trainable_branches(trace)]
scores = await asyncio.gather(*(pool.score(hint_block + branch.token_ids) for branch in branches))
scores = await asyncio.gather(*(teacher.score(hint_block + branch.token_ids) for branch in branches))
for branch, full_logprobs in zip(branches, scores, strict=True):
assign_reference_logprobs(branch, full_logprobs[len(hint_block) :])
+3 -3
View File
@@ -10,7 +10,7 @@ from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
from prime_rl.orchestrator.algo.routing import assign_advantages
if TYPE_CHECKING:
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class RAEAlgorithm(Algorithm):
@@ -31,8 +31,8 @@ class RAEAlgorithm(Algorithm):
live in orchestrator memory: a restart re-warms them over ~1/(1 − decay)
traces per agent."""
def __init__(self, config: RAEAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
def __init__(self, config: RAEAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.decay = config.decay
self.baselines: dict[str, float] = defaultdict(float)
+1 -1
View File
@@ -5,7 +5,7 @@ from __future__ import annotations
import verifiers.v1 as vf
from prime_rl.configs.algorithm import ActionLossType
from prime_rl.transports.rollouts import TrainingSample
from prime_rl.transports.batch import TrainingSample
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import os
from collections.abc import Callable
from pathlib import Path
import httpx
@@ -40,8 +41,9 @@ class PrefillScorer:
await self._client.close()
class InferencePool:
"""Inference pool with a single data-plane endpoint and one admin client per server."""
class InferenceClient:
"""Data-plane clients for one inference endpoint (the router of the policy
deployment, or an external API for frozen models)."""
def __init__(
self,
@@ -59,7 +61,31 @@ class InferencePool:
renderer_model_name=renderer_model_name,
)
self.eval_client = setup_client(client_config, client_type=eval_client_type)
self._admin_clients = setup_admin_clients(client_config)
self._scorer = PrefillScorer()
self.model_name = model_name
async def score(self, token_ids: list[int]) -> list[float]:
"""Prefill-score ``token_ids`` under this endpoint's model (one logprob
per token, 0.0 for the leading token)."""
return await self._scorer.score(self.train_client, self.model_name, token_ids)
async def aclose(self) -> None:
await self._scorer.aclose()
class AdminClients:
"""Admin plane of the policy inference deployment: one httpx client per
engine process. The router serves no admin routes (pause/resume,
update_weights, init_broadcaster, load_lora_adapter live on the engines),
so these clients bypass it via ``admin_base_url``.
The client order is load-bearing: ``admin_base_url`` order must match the
GPU rank order — the ``rank_offset`` math in ``init_nccl_broadcast`` /
``init_nixl_broadcast`` and the metrics collector's role list index into
it."""
def __init__(self, client_config: ClientConfig):
self.clients = setup_admin_clients(client_config)
# When admin URLs bypass a router, also health-check the client-facing
# (router) endpoint - it only starts serving once its workers are healthy.
self._router_clients = (
@@ -69,33 +95,25 @@ class InferencePool:
)
self._skip_model_check = client_config.skip_model_check
self._wait_for_ready_timeout = client_config.wait_for_ready_timeout
self._scorer = PrefillScorer()
self.model_name = model_name
@property
def admin_clients(self) -> list[AsyncClient]:
return self._admin_clients
async def wait_for_ready(self, model_name: str) -> None:
await check_health(self.clients + 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)
def update_model_name(self, model_name: str) -> None:
self.model_name = model_name
async def aclose(self) -> None:
for client in self.clients + self._router_clients:
await client.aclose()
async def wait_for_ready(self, model_name: str, timeout: int | None = None) -> None:
await check_health(
self._admin_clients + self._router_clients,
timeout=timeout if timeout is not None else self._wait_for_ready_timeout,
)
await maybe_check_has_model(self._admin_clients, model_name, skip_model_check=self._skip_model_check)
async def update_weights(self, weight_dir: Path | None, lora_name: str | None = None, step: int = 0) -> None:
await update_weights(self._admin_clients, weight_dir, lora_name=lora_name, step=step)
async def score(self, token_ids: list[int]) -> list[float]:
"""Prefill-score ``token_ids`` under this pool's model (one logprob per
token, 0.0 for the leading token). Delegates to the shared scorer."""
return await self._scorer.score(self.train_client, self.model_name, token_ids)
async def stop(self) -> None:
await self._scorer.aclose()
async def check_inference_ready(client_config: ClientConfig, model_name: str) -> None:
"""One-shot readiness check of an inference endpoint (health + model
listing) with transient clients — for frozen endpoints that never need a
persistent admin plane."""
admin = AdminClients(client_config)
try:
await admin.wait_for_ready(model_name)
finally:
await admin.aclose()
def setup_client(
@@ -203,9 +221,6 @@ async def check_health(
await asyncio.gather(*[_check_health(admin_client) for admin_client in admin_clients])
NCCL_READY_MARKER = "NCCL_READY"
def _is_retryable_admin_error(exception: BaseException) -> bool:
"""Check if an exception should trigger a retry for an admin op (pause/resume/update_weights)."""
if isinstance(exception, httpx.HTTPStatusError):
@@ -275,50 +290,39 @@ async def _resume_engines(admin_clients: list[AsyncClient]) -> None:
async def update_weights(
admin_clients: list[AsyncClient],
weight_dir: Path | None,
lora_name: str | None = None,
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 lora_name is not None and weight_dir is not None:
await load_lora_adapter(admin_clients, lora_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:
@@ -376,25 +380,12 @@ async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lo
await asyncio.gather(*[_load_lora_adapter(admin_client) for admin_client in admin_clients])
async def unload_lora_adapter(admin_clients: list[AsyncClient], lora_name: str) -> None:
"""Make a HTTP post request to the vLLM server to unload a LoRA adapter."""
logger = get_logger()
async def _unload_lora_adapter(admin_client: AsyncClient) -> None:
logger.debug(f"Sending request to unload LoRA adapter {lora_name}")
await admin_client.post("/v1/unload_lora_adapter", json={"lora_name": lora_name})
# TODO: The first one can fail, but subsequent ones should succeed.
# response.raise_for_status()
await asyncio.gather(*[_unload_lora_adapter(admin_client) for admin_client in admin_clients])
async def init_nccl_broadcast(
admin_clients: list[AsyncClient],
host: str,
port: int,
timeout: int,
inference_world_size: int | None = None,
inference_world_size: int,
quantize_in_weight_transfer: bool = False,
) -> None:
"""Initialize NCCL broadcast on all inference servers.
@@ -405,12 +396,6 @@ async def init_nccl_broadcast(
"""
logger = get_logger()
if inference_world_size is None:
inference_world_size = len(admin_clients)
logger.warning(
f"inference_world_size not provided, defaulting to {inference_world_size} (one GPU per admin client)"
)
gpus_per_server = inference_world_size // len(admin_clients)
logger.info(
+10 -12
View File
@@ -38,6 +38,7 @@ from typing import Literal
import verifiers.v1 as vf
from aiolimiter import AsyncLimiter
from prime_rl.orchestrator.clients import InferenceClient
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.train_source import TrainSource
@@ -53,7 +54,6 @@ from prime_rl.orchestrator.types import (
)
from prime_rl.orchestrator.utils import min_fresh_version
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import get_logger
@@ -151,7 +151,7 @@ class Dispatcher:
eval_envs: EvalEnvs | None,
train_source: TrainSource | None,
eval_source: EvalSource | None,
policy_pool: InferencePool,
policy_clients: InferenceClient,
policy: Policy,
progress: Progress | None,
initial_max_inflight: int,
@@ -168,7 +168,7 @@ class Dispatcher:
self.eval_envs = eval_envs
# Train rollouts go to the env's generation source; eval always
# evaluates the policy.
self.policy_pool = policy_pool
self.policy_clients = policy_clients
self.train_source = train_source
self.eval_source = eval_source
self.max_off_policy_steps = max_off_policy_steps
@@ -221,14 +221,14 @@ class Dispatcher:
self.stopped = asyncio.Event()
self.task: asyncio.Task | None = None
def _train_generation_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
"""``(pool, model_name, is_live)`` for *train* rollouts of this env —
def _train_generation_for(self, env_name: str) -> tuple[InferenceClient, str, bool]:
"""``(clients, model_name, is_live)`` for *train* rollouts of this env —
eval always uses the policy."""
assert self.train_envs is not None # train groups only exist when train is configured
source = self.train_envs.get(env_name).generation_source
if source.uses_live_policy:
return source.pool, self.policy.model_name, True
return source.pool, source.pool.model_name, False
return source.clients, self.policy.model_name, True
return source.clients, source.clients.model_name, False
@property
def inflight_train_count(self) -> int:
@@ -500,14 +500,12 @@ class Dispatcher:
# goes through the eval client (chat-completions) so eval scores stay
# comparable.
if group.kind == "eval":
pool, model_name = self.policy_pool, self.policy.model_name
clients, model_name = self.policy_clients, self.policy.model_name
live_sourced = True
else:
pool, model_name, live_sourced = self._train_generation_for(group.env_name)
clients, model_name, live_sourced = self._train_generation_for(group.env_name)
if group.pinned_client is None:
group.pinned_client = pool.eval_client if group.kind == "eval" else pool.train_client
client = group.pinned_client
client = clients.eval_client if group.kind == "eval" else clients.train_client
env_collection = self.train_envs if group.kind == "train" else self.eval_envs
if env_collection is None:
+3 -3
View File
@@ -192,7 +192,7 @@ class TrainEnvs(Envs[TrainEnv]):
configs: Sequence[TrainSourceConfig],
addresses: dict[tuple[str, str], str],
*,
policy_pool,
clients,
renderer_config=None,
):
self._envs: dict[str, TrainEnv] = {}
@@ -202,8 +202,8 @@ class TrainEnvs(Envs[TrainEnv]):
env = TrainEnv(
config,
addresses[("train", config.resolved_name)],
GenerationSource(config.algo.sampling, policy_pool, renderer_config),
build_algorithm(config.algo, policy_pool),
GenerationSource(config.algo.sampling, clients, renderer_config),
build_algorithm(config.algo, clients),
)
self._envs[env.name] = env
+12 -14
View File
@@ -5,38 +5,36 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import FrozenModelConfig, SamplingConfig
from prime_rl.orchestrator.algo import connect_frozen_pool
from prime_rl.orchestrator.algo import connect_frozen_client
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class GenerationSource:
"""One env's generation model and inference pool.
"""One env's generation model and inference clients.
``pool`` is the pool train rollouts are generated from: the policy pool,
swapped for a connected frozen pool in :meth:`setup` when the source is an
inline frozen model. A frozen source *generates* rollouts, so its pool uses
``clients`` is what train rollouts are generated from: the policy clients,
swapped for a connected frozen endpoint in :meth:`setup` when the source is
an inline frozen model. A frozen source *generates* rollouts, so it uses
the renderer (token-in/out) client (built from ``renderer_config``) — the
rollout must carry tokens for training."""
def __init__(
self, config: SamplingConfig, policy_pool: InferencePool, renderer_config: RendererConfig | None = None
):
def __init__(self, config: SamplingConfig, clients: InferenceClient, renderer_config: RendererConfig | None = None):
assert config.source is not None, "sampling.source must be resolved by config validation"
self.config = config
self.pool: InferencePool = policy_pool
self.clients: InferenceClient = clients
self.renderer_config = renderer_config
self.connected_pools: list[InferencePool] = [] # client pools connected in setup(); closed at shutdown
self.connected: InferenceClient | None = None # frozen clients connected in setup(); closed at shutdown
async def setup(self) -> None:
"""Connect a client pool to a frozen generation source and wait for
"""Connect clients to a frozen generation source and wait for
readiness. Must run before dispatching."""
if isinstance(self.config.source, FrozenModelConfig):
self.pool = await connect_frozen_pool(self.config.source, renderer_config=self.renderer_config)
self.connected_pools.append(self.pool)
self.clients = await connect_frozen_client(self.config.source, renderer_config=self.renderer_config)
self.connected = self.clients
@property
def uses_live_policy(self) -> bool:
+82 -117
View File
@@ -26,20 +26,19 @@ 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:
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.orchestrator.ckpt import CheckpointManager
from prime_rl.transports.rollouts.base import MicroBatchSender
from prime_rl.transports.batch.base import BatchSender
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
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
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
@@ -66,21 +65,21 @@ 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,
)
from prime_rl.orchestrator.watcher import WeightWatcher
from prime_rl.trainer.model import setup_tokenizer
from prime_rl.transports.rollouts import setup_micro_batch_sender
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
from prime_rl.transports.batch import setup_batch_sender
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.client import InferencePool, init_nccl_broadcast, init_nixl_broadcast
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,
)
@@ -121,8 +120,9 @@ class Orchestrator:
# Always set by ``setup()``
tokenizer: PreTrainedTokenizer
policy_inference: InferencePool
sender: MicroBatchSender | None
clients: InferenceClient | None
admin_clients: AdminClients | None
sender: BatchSender | None
packer: BatchPacker
train_envs: TrainEnvs
train_source: TrainSource
@@ -139,7 +139,7 @@ class Orchestrator:
eval_envs: EvalEnvs | None
eval_sink: EvalSink | None
eval_source: EvalSource | None
lora_name: str | None
receiver: WeightReceiver
resume_step: int | None
lag_task: asyncio.Task | None
@@ -170,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
@@ -177,10 +182,8 @@ class Orchestrator:
self.eval_envs = None
self.eval_sink = None
self.eval_source = None
self.lora_name = None
self.resume_step = None
self.lag_task = None
self.model_express = None
# ── lifecycle ──────────────────────────────────────────────────────────
@@ -199,13 +202,14 @@ class Orchestrator:
# references are external endpoints — each env's Algorithm builds its
# own pools in ``setup()`` below.
get_logger().info(f"Initializing policy inference pool ({config.model})")
self.policy_inference = InferencePool(
self.clients = InferenceClient(
config.model.client,
model_name=config.model.name,
train_client_type="renderer",
eval_client_type="openai_chat_completions",
renderer_config=config.renderer,
)
self.admin_clients = AdminClients(config.model.client)
await monitors.setup(
wandb=config.monitors.wandb,
@@ -230,7 +234,7 @@ class Orchestrator:
self.train_envs = TrainEnvs(
config.train.source,
config.env_addresses,
policy_pool=self.policy_inference,
clients=self.clients,
renderer_config=config.renderer,
)
if config.eval is not None:
@@ -245,8 +249,7 @@ class Orchestrator:
self.resume_step = resolve_latest_ckpt_step(self.ckpt_manager.ckpt_dir)
# Resume below may bump ``policy.version`` and the LoRA model name
self.policy.model_name = self.policy_inference.model_name
self.lora_name = config.model.lora.name if config.model.lora else None
self.policy.model_name = self.clients.model_name
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
@@ -261,12 +264,9 @@ class Orchestrator:
# Transports are local setup — initialize them before the env and inference waits.
self.packer = BatchPacker(config)
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
self.sender = setup_micro_batch_sender(
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.
@@ -290,7 +290,7 @@ class Orchestrator:
get_logger().info("Waiting for policy inference pool to be ready")
t0 = time.perf_counter()
await self.policy_inference.wait_for_ready(config.model.name)
await self.admin_clients.wait_for_ready(config.model.name)
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
# Build + ready pools for each env's frozen generation source and the
# algorithm's frozen reference model
@@ -299,74 +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.policy_inference.admin_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.policy_inference.admin_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 self.policy_inference.update_weights(weights_path, lora_name=self.lora_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,
)
if self.lora_name is not None:
self.policy_inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
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)}")
@@ -389,7 +346,7 @@ class Orchestrator:
eval_envs=self.eval_envs,
train_source=self.train_source,
eval_source=self.eval_source,
policy_pool=self.policy_inference,
policy_clients=self.clients,
policy=self.policy,
progress=self.progress,
initial_max_inflight=self.concurrency.max_inflight,
@@ -409,7 +366,7 @@ class Orchestrator:
# W&B mirroring is gated on the registered monitor (the collector logs
# to the global W&B session, which only exists when init succeeded).
self.inference_metrics = InferenceMetricsCollector(
self.policy_inference.admin_clients,
self.admin_clients.clients,
roles=config.inference_metrics_roles,
on_load=self.concurrency.observe,
log_to_wandb=wandb_enabled and config.collect_inference_metrics,
@@ -430,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,
inference=self.policy_inference,
observers=[self.dispatcher, self],
lora_name=self.lora_name,
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)
@@ -529,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.
@@ -555,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
@@ -765,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 —
@@ -1005,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:
@@ -1041,14 +1004,16 @@ class Orchestrator:
if self.inference_metrics is not None:
get_logger().debug("Stopping inference metrics collector")
await self.inference_metrics.stop()
if getattr(self, "policy_inference", None) is not None:
get_logger().debug("Stopping policy inference pool")
await self.policy_inference.stop()
if self.clients is not None:
await self.clients.aclose()
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 pools")
get_logger().debug("Stopping generation source and algorithm clients")
for env in self.train_envs:
for pool in (*env.generation_source.connected_pools, *env.algorithm.connected_pools):
await pool.stop()
for clients in (env.generation_source.connected, env.algorithm.connected):
if clients is not None:
await clients.aclose()
get_logger().info("Stopping orchestrator components")
t0 = time.perf_counter()
+1 -1
View File
@@ -2,7 +2,7 @@ from transformers import AutoConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
from prime_rl.transports.rollouts.types import MicroBatch, TrainingSample
from prime_rl.transports.batch.types import MicroBatch, TrainingSample
from prime_rl.utils.logger import get_logger
+1 -1
View File
@@ -22,7 +22,7 @@ from prime_rl.orchestrator.metrics import TrainEpisodes
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.orchestrator.types import GroupCancellation, Progress, TrainBatch
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, min_fresh_version, train_work
from prime_rl.transports.rollouts import TrainingSample
from prime_rl.transports.batch import TrainingSample
from prime_rl.utils.logger import get_logger
MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS = 10
+2 -2
View File
@@ -20,8 +20,8 @@ from collections.abc import Iterator
import numpy as np
import verifiers.v1 as vf
from prime_rl.transports.rollouts import TrainingSample
from prime_rl.transports.rollouts.types import EncodedTensor, RoutedExperts
from prime_rl.transports.batch import TrainingSample
from prime_rl.transports.batch.types import EncodedTensor, RoutedExperts
from prime_rl.utils.logger import get_logger
+2 -3
View File
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Literal, Protocol, TypeAlias
import verifiers.v1 as vf
from prime_rl.transports.rollouts import TrainingSample
from prime_rl.transports.batch import TrainingSample
if TYPE_CHECKING:
from prime_rl.orchestrator.metrics import EvalEpisodes, TrainEpisodes
@@ -81,7 +81,7 @@ class InflightEpisode:
@dataclass
class GroupState:
"""Per-group dispatcher state with pinned run context and client."""
"""Per-group dispatcher state with its pinned run step."""
kind: WorkKind
env_name: str
@@ -91,7 +91,6 @@ class GroupState:
episodes_to_schedule: int
target_episodes: int
emitted: int = 0
pinned_client: vf.ClientConfig | None = None
policy_version_at_start: int = 0
-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 -63
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.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.client import InferencePool
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,
inference: InferencePool,
observers: list[VersionObserver],
lora_name: str | None,
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.inference = inference
self.observers = observers
self.lora_name = lora_name
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,17 +99,13 @@ class WeightWatcher:
get_logger().debug(f"Updating inference weights to policy v{next_step}")
t1 = time.perf_counter()
await self.inference.update_weights(weights_path, lora_name=self.lora_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(
f"Updated inference weights to policy v{next_step} in {format_time(self.last_update_weights_time)}"
)
if self.lora_name is not None:
self.inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
for observer in self.observers:
try:
await observer.on_new_version(next_step)
@@ -153,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),
+1 -1
View File
@@ -6,7 +6,7 @@ from typing import Any
import numpy as np
from prime_rl.transports.rollouts.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
# Backfill value per component weight stream when a packed sample doesn't
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
-8
View File
@@ -55,14 +55,6 @@ class LoRAState:
"""Register an adapted module with its FQN prefix (e.g. "model.layers.0.self_attn.q_proj")."""
self._modules.append((prefix, module))
def named_adapter_parameters(self) -> list[tuple[str, nn.Parameter]]:
"""Named parameters of the adapter across all registered modules."""
params = []
for prefix, module in self._modules:
for name, param in module.named_parameters_for_adapter(0):
params.append((f"{prefix}.{name}.weight", param))
return params
def adapter_state_dict(self) -> dict[str, torch.Tensor]:
"""Adapter-only state dict, converted for HF compatibility when a converter is registered."""
state_dict = {}
+4 -4
View File
@@ -7,11 +7,11 @@ from torch import Tensor
from prime_rl.configs.trainer import FakeDataLoaderConfig
from prime_rl.trainer.world import get_world
from prime_rl.transports.rollouts import (
from prime_rl.transports.batch import (
BatchReceiver,
MicroBatch,
MicroBatchReceiver,
TransportConfig,
setup_micro_batch_receiver,
setup_batch_receiver,
)
@@ -174,7 +174,7 @@ class DataLoader:
non_dp_world_size = self.world.world_size // dp_world_size
dp_rank = self.world.rank // non_dp_world_size
self.receiver: MicroBatchReceiver = setup_micro_batch_receiver(output_dir, dp_rank, start_step, config)
self.receiver: BatchReceiver = setup_batch_receiver(output_dir, dp_rank, start_step, config)
def wait_for_batch(self) -> None:
self.receiver.wait()
+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)
+54
View File
@@ -0,0 +1,54 @@
from pathlib import Path
from prime_rl.configs.shared import TransportConfig
from prime_rl.transports.batch.base import BatchReceiver, BatchSender
from prime_rl.transports.batch.filesystem import (
FileSystemBatchReceiver,
FileSystemBatchSender,
)
from prime_rl.transports.batch.types import (
MicroBatch,
RoutedExperts,
TrainingSample,
)
from prime_rl.transports.batch.zmq import (
ZMQBatchReceiver,
ZMQBatchSender,
)
def setup_batch_sender(
output_dir: Path, data_world_size: int, current_step: int, transport: TransportConfig
) -> BatchSender:
if transport.type == "filesystem":
return FileSystemBatchSender(output_dir, data_world_size, current_step)
elif transport.type == "zmq":
return ZMQBatchSender(output_dir, data_world_size, current_step, transport)
else:
raise ValueError(f"Invalid transport type: {transport.type}")
def setup_batch_receiver(
output_dir: Path, data_rank: int, current_step: int, transport: TransportConfig
) -> BatchReceiver:
if transport.type == "filesystem":
return FileSystemBatchReceiver(output_dir, data_rank, current_step)
elif transport.type == "zmq":
return ZMQBatchReceiver(output_dir, data_rank, current_step, transport)
else:
raise ValueError(f"Invalid transport type: {transport.type}")
__all__ = [
"FileSystemBatchSender",
"FileSystemBatchReceiver",
"ZMQBatchSender",
"ZMQBatchReceiver",
"BatchReceiver",
"BatchSender",
"TrainingSample",
"MicroBatch",
"RoutedExperts",
"setup_batch_sender",
"setup_batch_receiver",
]
@@ -3,11 +3,11 @@ from pathlib import Path
import msgspec
from prime_rl.transports.rollouts.types import MicroBatch
from prime_rl.transports.batch.types import MicroBatch
from prime_rl.utils.logger import get_logger
class MicroBatchSender(ABC):
class BatchSender(ABC):
"""Base class for sending micro batches from the orchestrator to the train workers."""
def __init__(self, output_dir: Path, data_world_size: int):
@@ -26,7 +26,7 @@ class MicroBatchSender(ABC):
pass
class MicroBatchReceiver(ABC):
class BatchReceiver(ABC):
"""Base class for receiving micro batches from the orchestrator."""
def __init__(self, output_dir: Path, data_rank: int):
@@ -1,12 +1,12 @@
import asyncio
from pathlib import Path
from prime_rl.transports.rollouts.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transports.rollouts.types import MicroBatch
from prime_rl.transports.batch.base import BatchReceiver, BatchSender
from prime_rl.transports.batch.types import MicroBatch
from prime_rl.utils.pathing import get_rollout_dir, get_step_path, sync_wait_for_path
class FileSystemMicroBatchSender(MicroBatchSender):
class FileSystemBatchSender(BatchSender):
"""Filesystem-based micro batch sender that writes micro batches to disk."""
def __init__(self, output_dir: Path, data_world_size: int, current_step: int = 0):
@@ -35,7 +35,7 @@ class FileSystemMicroBatchSender(MicroBatchSender):
tmp_path.rename(step_path / f"rank_{data_rank}.bin")
class FileSystemMicroBatchReceiver(MicroBatchReceiver):
class FileSystemBatchReceiver(BatchReceiver):
"""Filesystem-based micro batch receiver that reads micro batches from disk."""
def __init__(self, output_dir: Path, data_rank: int, current_step: int = 0):
@@ -4,11 +4,11 @@ import zmq
import zmq.asyncio
from prime_rl.configs.shared import ZMQTransportConfig
from prime_rl.transports.rollouts.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transports.rollouts.types import MicroBatch
from prime_rl.transports.batch.base import BatchReceiver, BatchSender
from prime_rl.transports.batch.types import MicroBatch
class ZMQMicroBatchSender(MicroBatchSender):
class ZMQBatchSender(BatchSender):
def __init__(self, output_dir: Path, data_world_size: int, current_step: int, transport: ZMQTransportConfig):
"""ZMQ micro batch sender that publishes per-rank micro batches to the trainers.
There is one sender (in the orchestrator process) for the entire data world.
@@ -87,7 +87,7 @@ class ZMQMicroBatchSender(MicroBatchSender):
self.logger.debug("Closed ZMQ micro batch sender")
class ZMQMicroBatchReceiver(MicroBatchReceiver):
class ZMQBatchReceiver(BatchReceiver):
def __init__(self, output_dir: Path, data_rank: int, current_step: int, transport: ZMQTransportConfig):
"""ZMQ micro batch receiver that receives micro batches from the orchestrator. There is one receiver per data rank."""
super().__init__(output_dir, data_rank)
@@ -1,54 +0,0 @@
from pathlib import Path
from prime_rl.configs.shared import TransportConfig
from prime_rl.transports.rollouts.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transports.rollouts.filesystem import (
FileSystemMicroBatchReceiver,
FileSystemMicroBatchSender,
)
from prime_rl.transports.rollouts.types import (
MicroBatch,
RoutedExperts,
TrainingSample,
)
from prime_rl.transports.rollouts.zmq import (
ZMQMicroBatchReceiver,
ZMQMicroBatchSender,
)
def setup_micro_batch_sender(
output_dir: Path, data_world_size: int, current_step: int, transport: TransportConfig
) -> MicroBatchSender:
if transport.type == "filesystem":
return FileSystemMicroBatchSender(output_dir, data_world_size, current_step)
elif transport.type == "zmq":
return ZMQMicroBatchSender(output_dir, data_world_size, current_step, transport)
else:
raise ValueError(f"Invalid transport type: {transport.type}")
def setup_micro_batch_receiver(
output_dir: Path, data_rank: int, current_step: int, transport: TransportConfig
) -> MicroBatchReceiver:
if transport.type == "filesystem":
return FileSystemMicroBatchReceiver(output_dir, data_rank, current_step)
elif transport.type == "zmq":
return ZMQMicroBatchReceiver(output_dir, data_rank, current_step, transport)
else:
raise ValueError(f"Invalid transport type: {transport.type}")
__all__ = [
"FileSystemMicroBatchSender",
"FileSystemMicroBatchReceiver",
"ZMQMicroBatchSender",
"ZMQMicroBatchReceiver",
"MicroBatchReceiver",
"MicroBatchSender",
"TrainingSample",
"MicroBatch",
"RoutedExperts",
"setup_micro_batch_sender",
"setup_micro_batch_receiver",
]
+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 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.client import NCCL_READY_MARKER
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 -3
View File
@@ -153,14 +153,14 @@ def _scalar(episode: vf.Episode) -> float:
def _grpo(group: list[vf.Episode], length_penalty=None) -> list[float]:
"""Drive ``GRPOAlgorithm.score_group`` and read back each per-rollout scalar."""
algo = GRPOAlgorithm(GRPOAlgoConfig(length_penalty=length_penalty), policy_pool=None)
algo = GRPOAlgorithm(GRPOAlgoConfig(length_penalty=length_penalty), clients=None)
asyncio.run(algo.score_group(group))
return [_scalar(episode) for episode in group]
def _max_rl(group: list[vf.Episode]) -> list[float]:
"""Drive ``MaxRLAlgorithm.score_group`` and read back each per-rollout scalar."""
algo = MaxRLAlgorithm(MaxRLAlgoConfig(), policy_pool=None)
algo = MaxRLAlgorithm(MaxRLAlgoConfig(), clients=None)
asyncio.run(algo.score_group(group))
return [_scalar(episode) for episode in group]
@@ -223,7 +223,7 @@ def test_linear_context_term_penalizes_more_context():
_build_episode(1.0, sampled_lengths=[10], obs_lengths=[]),
_build_episode(1.0, sampled_lengths=[10], obs_lengths=[100]),
]
asyncio.run(GRPOAlgorithm(GRPOAlgoConfig(length_penalty=cfg), policy_pool=None).score_group(group))
asyncio.run(GRPOAlgorithm(GRPOAlgoConfig(length_penalty=cfg), clients=None).score_group(group))
advs = [_scalar(episode) for episode in group]
assert advs[0] > advs[1]
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
+1 -1
View File
@@ -10,7 +10,7 @@ from verifiers.v1.types import AssistantMessage, ToolMessage, UserMessage
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
from prime_rl.orchestrator.algo import EchoAlgorithm, assign_advantages, stamp_loss_routing
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.transports.rollouts.types import TrainingSample
from prime_rl.transports.batch.types import TrainingSample
FROZEN = {"name": "org/ref-model", "base_url": "http://ref:8001/v1"}
+1 -1
View File
@@ -4,7 +4,7 @@ import numpy as np
import pytest
from prime_rl.trainer.batch import _is_multimodal_sample, build_bin_cost, pad_micro_batch, prepare_batch, prepare_sample
from prime_rl.transports.rollouts.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
def _routed_experts(data, dtype=np.uint8):
@@ -6,7 +6,7 @@ import httpx
from verifiers.v1.configs.client import EvalClientConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.client import _is_retryable_lora_error, check_health, load_lora_adapter, setup_client
from prime_rl.orchestrator.clients import _is_retryable_lora_error, check_health, load_lora_adapter, setup_client
def test_is_retryable_lora_error_returns_true_for_404():
@@ -56,7 +56,6 @@ def test_setup_client_creates_renderer_client():
base_url="http://worker-a:8000/v1",
api_key_var="PRIME_API_KEY",
headers={"X-Test": "test"},
extra_headers_from_state={"X-Session-ID": "session_id"},
)
renderer_settings = Qwen3VLRendererConfig()
@@ -81,7 +80,7 @@ def test_check_health_retries_non_success_status():
client.get.side_effect = [unavailable, healthy]
client.base_url = httpx.URL("http://worker")
with patch("prime_rl.utils.client.asyncio.sleep", new=AsyncMock()):
with patch("prime_rl.orchestrator.clients.asyncio.sleep", new=AsyncMock()):
asyncio.run(check_health([client], interval=1, timeout=2))
assert client.get.await_count == 2
@@ -3,7 +3,7 @@ import json
import httpx
from prime_rl.utils.client import prefill_logprobs
from prime_rl.orchestrator.clients import prefill_logprobs
class _FakeOpenAIClient:
+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}")