Compare commits

...
Author SHA1 Message Date
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
Mika SenghaasandGitHub 04e796d21b fix: treat a resume past max_steps as the last step (#3352)
## Summary

- A run resumed from a checkpoint at or beyond `max_steps` never matched
the `is_last_step ==` check, so the trainer idled forever waiting for a
batch that would not come. `>=` makes it exit as the last step.

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-08-22 19:32:45 -07:00
9f29e5388e chore: clean up trainer and orchestrator logging (#3345)
## Summary

Log audit of the trainer and orchestrator, from a side-by-side read of a
full run's logs and the code that emitted them.

**Conventions** (applied everywhere):
- Every potentially slow action logs an active-tense info line first
(`Initializing X`, `Waiting for X`) — the last info line always names
the action that crashed or hung.
- Each one is paired with a debug completion carrying `format_time`
timing (`Initialized X in 1.2s`). All debug timings now use
`format_time`.
- Component inits log exactly `Initializing X ({config})`. Monitors log
a names-only summary plus one full-config line per monitor, from
`monitors.setup`.

**Gaps filled** (previously silent hang points): startup weight sync
(can block minutes), orchestrator teardown (info + one debug line per
stage, so a wedged component is identifiable),
`setup_torch_distributed`, device mesh init, trainer startup broadcast,
W&B finalize.

**Setup reorder** (orchestrator): local init first — sender, filesystem
weight broadcast — then the waits last before the main loop (env servers
→ inference pool → NCCL/NIXL handshake → startup sync). The NCCL/NIXL
handshake stays post-readiness (it POSTs to live engines); the
checkpoint's curricula restore follows `envs.start()` (`TrainSource`
needs loaded tasksets). One awaited metrics scrape primes the
concurrency controller so `Derived initial max inflight` logs before
`Starting orchestrator loop`.

**Renames and demotions** (highlights):
- `waiting for trainer to broadcast checkpoint N` → `Waiting for the
trainer to broadcast policy v{N}`; steps vs 0-indexed policy versions
untangled throughout.
- The inference wait is info every 30 s (`Waiting for inference server
at {url} to start up (30s elapsed)`), error at debug — was a warning
every 10 s.
- One identity line on all three processes: `Starting from scratch` /
`Resuming from step {N}`; `Broadcasting base policy weights (v{N})`.
- Launcher: `Starting {name} server`, `Starting orchestrator` (no
"process").
- Removed the per-group success debug in the train sink (flooded one
line per group); drop-path logs stay, renamed `Dropped group | ... |
reason=...`.
- Demoted to debug: ZMQ sender/receiver init/close, `Using shared W&B
mode`, `Loading model config`, executor setup, GC line. LoRA debug no
longer dumps the full model repr.
- Punctuation/tense/indexing: `Saving final checkpoint at step N`, no
trailing `.`/`!` on finish lines, 1-indexed micro steps.

## Verification

Ran alphabet-sort debug-level runs on this branch (from scratch,
`--resume.step 2`, and post-merge): clean startup → steps → drain →
teardown on both processes, all lines rendering as intended, e.g.

```
INFO  Syncing inference to the trainer's startup broadcast (v0)
DEBUG Synced inference to policy v0 in 115ms
INFO  Stopping orchestrator components
DEBUG Stopping dispatcher
SUCCESS Orchestrator finished
```

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Mostly logging, but orchestrator setup order, resume-step timing,
NCCL/NIXL after pool ready, and an extra metrics probe change real
startup/teardown sequencing. A hang or resume mismatch would show up at
run start.
> 
> **Overview**
> Makes trainer/orchestrator/launcher logs follow a consistent pattern:
an **info** line for each potentially slow action (`Initializing` /
`Waiting`), then a **debug** completion with `format_time`. Identity
lines are aligned (`Starting from scratch` / `Resuming from step N`),
policy versions are labeled `v{N}`, and noisy lines (ZMQ init, GC,
per-group success, full model repr) are demoted or removed.
> 
> **Orchestrator `setup` is reordered**, not just reworded: local work
(packer, micro-batch sender, filesystem broadcast) runs first; env
servers, inference readiness, NCCL/NIXL handshake, and startup weight
sync wait last. Resume step is applied before those waits. Teardown now
logs each stage. An awaited `inference_metrics.probe()` primes the
concurrency controller before the loop starts.
> 
> Inference health wait is info every 30s (errors at debug). Drop-path
logs stay as `Dropped group | … | reason=…`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f1f33c0fc2fa3a2193118991c256cee0aae232ff. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 16:59:26 -07:00
50 changed files with 480 additions and 410 deletions
@@ -543,12 +543,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
@@ -169,9 +169,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``."""
+2 -2
View File
@@ -252,7 +252,7 @@ def rl_local(config: RLConfig):
for split, source, address in env_servers(config):
name = source.resolved_name
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
logger.info(f"Starting {split} env server {name} at {address}")
logger.info(f"Starting {name} server")
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
env_server_log.parent.mkdir(parents=True, exist_ok=True)
@@ -282,7 +282,7 @@ def rl_local(config: RLConfig):
monitor_threads.append(monitor_thread)
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()]
logger.info("Starting orchestrator process")
logger.info("Starting orchestrator")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
with open(log_dir / "orchestrator.log", "w") as log_file:
orchestrator_process = Popen(
+2 -2
View File
@@ -446,7 +446,7 @@ def sft_local(config: SFTConfig):
# deterministic address, polling until the server is up.
for source, address in eval_env_servers(config):
name = source.resolved_name
logger.info(f"Starting eval env server {name} at {address}")
logger.info(f"Starting {name} server")
start_process(
f"env/eval/{name}",
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
@@ -455,7 +455,7 @@ def sft_local(config: SFTConfig):
)
if config.eval is not None:
logger.info("Starting evals process")
logger.info("Starting evals")
start_process(
"evals",
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
+16 -12
View File
@@ -30,6 +30,7 @@ from subprocess import Popen
from prime_rl import monitors
from prime_rl.configs.evals import EvalsConfig
from prime_rl.orchestrator.clients import AdminClients, InferenceClient, init_nccl_broadcast, update_weights
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs
@@ -43,7 +44,6 @@ 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.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
@@ -95,7 +95,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,14 +106,14 @@ 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":
get_logger().info(f"Initializing weight broadcast ({weight_broadcast})")
await init_nccl_broadcast(
self.pool.admin_clients,
self.admin_clients.clients,
weight_broadcast.host,
weight_broadcast.port,
weight_broadcast.timeout,
@@ -134,7 +135,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 +155,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 +167,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); "
@@ -354,7 +355,7 @@ class Evals:
# 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)
await update_weights(self.admin_clients.clients, 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.
@@ -363,7 +364,7 @@ class Evals:
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.clients.update_model_name(lora_name)
self.policy.model_name = lora_name
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
@@ -447,9 +448,12 @@ class Evals:
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()
clients: InferenceClient | None = getattr(self, "clients", None)
if clients is not None:
await clients.aclose()
admin_clients: AdminClients | None = getattr(self, "admin_clients", None)
if admin_clients is not None:
await admin_clients.aclose()
cleanup_processes(self.env_server_procs)
+13 -5
View File
@@ -9,6 +9,7 @@ down training.
from __future__ import annotations
import os
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, overload
@@ -18,7 +19,7 @@ from prime_rl.monitors.file import FileMonitor
from prime_rl.monitors.prime import PrimeMonitor
from prime_rl.monitors.wandb import WandbMonitor
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
if TYPE_CHECKING:
import verifiers.v1 as vf
@@ -60,12 +61,13 @@ async def setup(
if rank != 0:
return
monitors: list[tuple[Monitor, dict[str, Any]]] = []
monitors: list[tuple[str, Monitor, dict[str, Any]]] = []
if prime is not None:
monitors.append((PrimeMonitor(prime), dict(config=run_config)))
monitors.append(("prime", PrimeMonitor(prime), dict(config=run_config)))
if wandb is not None:
monitors.append(
(
"wandb",
WandbMonitor(wandb),
dict(
output_dir=output_dir,
@@ -77,11 +79,17 @@ async def setup(
)
)
if file is not None:
monitors.append((FileMonitor(file), dict(output_dir=output_dir)))
monitors.append(("file", FileMonitor(file), dict(output_dir=output_dir)))
if not monitors:
return
for monitor, init_kwargs in monitors:
get_logger().info(f"Initializing monitors ({', '.join(name for name, _, _ in monitors)})")
t0 = time.perf_counter()
for name, monitor, init_kwargs in monitors:
get_logger().info(f"Initializing {name} monitor ({monitor.config})")
await monitor.init(**init_kwargs)
MONITORS.append(monitor)
get_logger().debug(f"Initialized monitors in {format_time(time.perf_counter() - t0)}")
def get(monitor_cls: type[Monitor]) -> Monitor | None:
+1 -1
View File
@@ -28,7 +28,7 @@ class FileMonitor(Monitor):
self.path.parent.mkdir(parents=True, exist_ok=True)
# Line-buffered append so a concurrently-running dashboard can tail the file.
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
self.logger.info(f"Logging metrics to {self.path} and episodes to {output_dir / 'rollouts'}")
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
sanitized, dropped = sanitize(metrics)
+5 -2
View File
@@ -16,6 +16,7 @@ from prime_rl.configs.monitors import WandbMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.monitors.wandb.overview import ensure_overview_view
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import format_time
if TYPE_CHECKING:
import verifiers.v1 as vf
@@ -63,7 +64,7 @@ class WandbMonitor(Monitor):
x_primary=primary,
x_update_finish_state=finisher,
)
self.logger.info(f"Using shared W&B mode ({label=}, {primary=}, {finisher=})")
self.logger.debug(f"Using shared W&B mode ({label=}, {primary=}, {finisher=})")
is_online = True
else:
run_id = None
@@ -130,7 +131,7 @@ class WandbMonitor(Monitor):
except Exception as e:
self.logger.warning(f"Failed to create W&B overview view - {e}")
self.logger.info(f"Logging metrics to W&B run {self.wandb.id} ({self.wandb.url})")
self.logger.info(f"Logging metrics to W&B ({self.wandb.url})")
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
wandb.log({**metrics, "step": step})
@@ -140,6 +141,8 @@ class WandbMonitor(Monitor):
async def finalize(self) -> None:
self.logger.info(f"Finalizing W&B run {self.wandb.id}")
t0 = time.perf_counter()
# Explicit finish: in (experimental) shared mode the SDK's atexit finish does
# not land the run state - without this, even clean runs decay to "crashed".
await asyncio.to_thread(wandb.finish, exit_code=0)
self.logger.debug(f"Finalized W&B run in {format_time(time.perf_counter() - t0)}")
+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:
@@ -40,8 +40,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 +60,34 @@ 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
def update_model_name(self, model_name: str) -> None:
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 +97,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(
@@ -172,13 +192,13 @@ async def maybe_check_has_model(
async def check_health(
admin_clients: list[AsyncClient], interval: int = 1, log_interval: int = 10, timeout: int = 1800
admin_clients: list[AsyncClient], interval: int = 1, log_interval: int = 30, timeout: int = 1800
) -> None:
logger = get_logger()
async def _check_health(admin_client: AsyncClient) -> None:
wait_time = 0
logger.debug("Starting pinging /health to check health")
logger.debug("Pinging /health until the inference server is ready")
while wait_time < timeout:
try:
response = await admin_client.get("/health")
@@ -190,9 +210,10 @@ async def check_health(
return
except Exception as e:
if wait_time % log_interval == 0 and wait_time > 0:
logger.warning(
f"Inference server was not reached after {wait_time} seconds (Error: {e}) on {admin_client.base_url}"
logger.info(
f"Waiting for inference server at {admin_client.base_url} to start up ({wait_time}s elapsed)"
)
logger.debug(f"Inference server at {admin_client.base_url} not reachable: {e!r}")
await asyncio.sleep(interval)
wait_time += interval
msg = f"Inference server is not ready after {wait_time} (>{timeout}) seconds. Aborting..."
@@ -202,9 +223,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):
@@ -219,6 +237,8 @@ def _is_retryable_admin_error(exception: BaseException) -> bool:
return False
NCCL_READY_MARKER = "NCCL_READY"
# Per-attempt read timeout for admin ops, overridable per call. The admin
# AsyncClient uses `timeout=None`, so without this a stuck server would hang the
# weight update forever: the read timeout converts a hang into a TimeoutException
@@ -253,7 +273,7 @@ async def _admin_post(client: AsyncClient, path: str, *, timeout_s: float = ADMI
async def _pause_engines(admin_clients: list[AsyncClient], *, step: int) -> None:
"""Pause all inference engines, waiting for in-flight requests to drain."""
logger = get_logger()
logger.info(f"Updating policy in-flight to v{step}")
logger.debug(f"Pausing inference engines to update weights to policy v{step}")
await asyncio.gather(
*[_admin_post(client, "/pause", params={"mode": "keep", "clear_cache": "false"}) for client in admin_clients]
)
@@ -393,7 +413,7 @@ async def init_nccl_broadcast(
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.
@@ -404,12 +424,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(
+11 -13
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:
@@ -678,7 +676,7 @@ class Dispatcher:
env_name = group.env_name if group is not None else claimed[-1][1].env_name
self.metrics.record_cancellation(kind=kind, env_name=env_name, n=cancelled)
get_logger().debug(
f"drop {kind} | group={str(group_id)[:8]} env={env_name} reason={reason} | "
f"Dropped {kind} group | group={str(group_id)[:8]} env={env_name} reason={reason} | "
f"cancelled={cancelled} (inflight={inflight_cancelled} unscheduled={unscheduled_cancelled})"
)
await self.out_q.put(
+8 -5
View File
@@ -20,6 +20,7 @@ keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
from __future__ import annotations
import asyncio
import time
from collections.abc import Iterator, Sequence
from itertools import islice
from typing import Generic, TypeVar
@@ -30,7 +31,7 @@ from verifiers.v1.serve import EnvClient
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
from prime_rl.orchestrator.generation_source import GenerationSource
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
# Max wait for the env server to answer health. Generous because the launcher spawns
# servers concurrently with the orchestrator, and a server imports its env package
@@ -68,6 +69,7 @@ class Env:
async def start(self) -> None:
"""Connect to the env server and load the taskset client-side."""
get_logger().debug(f"Connecting {self.name} to env server {self.address}")
t0 = time.perf_counter()
self._env_client = EnvClient(address=self.address)
# The server may still be coming up (the launcher spawns it concurrently with
# the orchestrator), so poll until it answers.
@@ -82,7 +84,7 @@ class Env:
self.tasks = iter(materialized)
self.num_tasks = len(materialized)
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks}")
get_logger().info(f"Env {self.name} ready in {format_time(time.perf_counter() - t0)} (num_tasks={num_tasks})")
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
sampling = {**self.sampling_args}
@@ -190,17 +192,18 @@ class TrainEnvs(Envs[TrainEnv]):
configs: Sequence[TrainSourceConfig],
addresses: dict[tuple[str, str], str],
*,
policy_pool,
clients,
renderer_config=None,
):
self._envs: dict[str, TrainEnv] = {}
for config in configs:
assert config.algo is not None, "TrainSourceConfig.algo must be resolved before env construction"
get_logger().info(f"Initializing {config.algo.type} algorithm for {config.resolved_name}")
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:
+130 -91
View File
@@ -34,12 +34,19 @@ 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,
init_nccl_broadcast,
init_nixl_broadcast,
update_weights,
)
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
@@ -73,10 +80,9 @@ from prime_rl.orchestrator.utils import (
)
from prime_rl.orchestrator.watcher import WeightWatcher
from prime_rl.trainer.model import setup_tokenizer
from prime_rl.transports.rollouts import setup_micro_batch_sender
from prime_rl.transports.batch import setup_batch_sender
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
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.utils import (
@@ -121,8 +127,9 @@ class Orchestrator:
# Always set by ``setup()``
tokenizer: PreTrainedTokenizer
policy_inference: InferencePool
sender: MicroBatchSender | None
clients: InferenceClient
admin_clients: AdminClients
sender: BatchSender | None
packer: BatchPacker
train_envs: TrainEnvs
train_source: TrainSource
@@ -149,8 +156,7 @@ class Orchestrator:
# Route the in-process v1 library logging through our handler. The
# env server runs in a child process, so its logging is separate.
intercept_vf_logging(logger="verifiers.v1", level="WARN")
algorithms = sorted({env.algo.type for env in config.train.source if env.algo is not None})
get_logger().info(f"Starting orchestrator (algorithm: {', '.join(algorithms)})")
get_logger().info("Starting orchestrator")
self.progress = Progress()
self.ckpt_manager = setup_ckpt_manager(config.output_dir, config.ckpt)
@@ -192,23 +198,23 @@ class Orchestrator:
set_default_executor()
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
t0 = time.perf_counter()
self.tokenizer = setup_tokenizer(config.tokenizer)
get_logger().debug(f"Initialized tokenizer in {format_time(time.perf_counter() - t0)}")
# The one model prime-rl hosts: the live policy. Frozen model
# references are external endpoints — each env's Algorithm builds its
# own pools in ``setup()`` below.
get_logger().info(
f"Initializing policy inference pool (base_url={config.model.client.base_url}, model={config.model.name})"
)
self.policy_inference = InferencePool(
get_logger().info(f"Initializing policy inference pool ({config.model})")
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)
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
wandb=config.monitors.wandb,
prime=config.monitors.prime,
@@ -229,25 +235,14 @@ class Orchestrator:
if config.heartbeat is not None:
self.heart = Heartbeat(config.heartbeat.url)
get_logger().info("Loading training environments")
self.train_envs = TrainEnvs(
config.train.source,
config.env_addresses,
policy_pool=self.policy_inference,
clients=self.clients,
renderer_config=config.renderer,
)
get_logger().debug(
f"Loaded {len(self.train_envs)} training environment(s) ({', '.join(self.train_envs.names)})"
)
await self.train_envs.start()
get_logger().success("Train environment(s) ready")
if config.eval is not None:
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.eval.source, config.env_addresses)
get_logger().debug(f"Loaded {len(self.eval_envs)} eval environment(s) ({', '.join(self.eval_envs.names)})")
await self.eval_envs.start()
get_logger().success("Eval environment(s) ready")
if config.resume is not None:
if config.resume.dir is not None:
@@ -258,11 +253,53 @@ 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.policy.model_name = self.clients.model_name
self.lora_name = config.model.lora.name if config.model.lora else None
# 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
# trainer even when ``ckpt.skip_progress`` leaves the counter unrestored. The curricula
# themselves are restored below, once the envs are loaded.
if self.resume_step is not None:
self.progress.step = self.resume_step + 1
get_logger().info(f"Resuming from step {self.resume_step}")
else:
get_logger().info("Starting from scratch")
# 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_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.
get_logger().info(f"Loading train environments ({', '.join(self.train_envs.names)})")
t0 = time.perf_counter()
await self.train_envs.start()
get_logger().success(f"Train environments ready in {format_time(time.perf_counter() - t0)}")
if self.eval_envs is not None:
get_logger().info(f"Loading eval environments ({', '.join(self.eval_envs.names)})")
t0 = time.perf_counter()
await self.eval_envs.start()
get_logger().success(f"Eval environments ready in {format_time(time.perf_counter() - t0)}")
self.train_source = TrainSource(self.train_envs)
if self.resume_step is not None:
resume = self.config.resume
resume_path = resume.dir / "orchestrator" if resume is not None and resume.dir is not None else None
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step, path=resume_path)
self.progress.step = self.resume_step + 1
get_logger().info("Waiting for policy inference pool to be ready")
await self.policy_inference.wait_for_ready(config.model.name)
get_logger().success("Policy inference pool ready")
t0 = time.perf_counter()
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
await asyncio.gather(
@@ -270,61 +307,46 @@ class Orchestrator:
*(env.algorithm.setup() for env in self.train_envs),
)
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
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,
)
elif config.weight_broadcast.type == "nixl":
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)
self.lora_name = config.model.lora.name if config.model.lora else None
self.train_source = TrainSource(self.train_envs)
if self.resume_step is not None:
resume = self.config.resume
resume_path = resume.dir / "orchestrator" if resume is not None and resume.dir is not None else None
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step, path=resume_path)
# 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
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
self.progress.step = self.resume_step + 1
get_logger().info(f"Resuming orchestrator from checkpoint step {self.resume_step}")
else:
get_logger().info("Training from scratch")
self.packer = BatchPacker(config)
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
self.sender = setup_micro_batch_sender(
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
)
# The in-memory broadcast transports rendezvous with live inference
# engines, so their setup must follow pool readiness.
if config.weight_broadcast.type in ("nccl", "nixl"):
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
if config.weight_broadcast.type == "nccl":
await init_nccl_broadcast(
self.admin_clients.clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
inference_world_size=config.weight_broadcast.inference_world_size,
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
)
else:
await init_nixl_broadcast(
self.admin_clients.clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
config.weight_broadcast.inference_world_size,
config.weight_broadcast.session_id,
)
self.model_express = ModelExpressSession(
client=MxClient(server_url=f"{config.weight_broadcast.host}:{config.weight_broadcast.port}"),
role="orchestrator",
rank=0,
session_id=config.weight_broadcast.session_id,
worker_id="orchestrator",
)
self.model_express.publish()
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
get_logger().debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
# 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).
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:
@@ -339,7 +361,7 @@ class Orchestrator:
)
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)
await update_weights(self.admin_clients.clients, 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.
@@ -351,9 +373,10 @@ class Orchestrator:
timeout=config.weight_broadcast.timeout,
)
if self.lora_name is not None:
self.policy_inference.update_model_name(self.lora_name)
self.clients.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
self.policy.version = sync_version
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
self.eval_source: EvalSource | None = (
EvalSource(
@@ -374,7 +397,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,
@@ -394,12 +417,15 @@ 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,
)
await self.inference_metrics.start()
# One awaited scrape so the concurrency controller derives (and logs) its
# initial limit before the loop-start line; failures are tolerated.
await self.inference_metrics.probe()
self.train_sink = TrainSink(
config,
tokenizer=self.tokenizer,
@@ -414,7 +440,8 @@ class Orchestrator:
self.watcher = WeightWatcher(
config,
policy=self.policy,
inference=self.policy_inference,
clients=self.clients,
admin_clients=self.admin_clients,
observers=[self.dispatcher, self],
lora_name=self.lora_name,
ckpt_step=self.policy.version,
@@ -502,13 +529,13 @@ class Orchestrator:
# first ship).
if self.config.ckpt is not None and self.progress.step > 1:
self.progress.step -= 1
get_logger().info("Writing final checkpoint")
get_logger().info(f"Saving final checkpoint at step {self.progress.step}")
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
await self.stop()
if clean_exit:
get_logger().success("Orchestrator finished.")
get_logger().success("Orchestrator finished")
else:
get_logger().warning("Orchestrator cleanup complete (forced).")
get_logger().warning("Orchestrator cleanup complete (forced)")
trim_process_memory()
async def wait_for_final_broadcast(self) -> None:
@@ -971,13 +998,14 @@ class Orchestrator:
if lead > TARGET_LAG:
if was_set:
get_logger().info(
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
f"Pausing dispatcher until the trainer publishes policy v{self.progress.step - 1 - TARGET_LAG} "
f"(currently v{self.policy.version})"
)
self.gate_closed_at = time.perf_counter()
gate.clear()
else:
if not was_set:
get_logger().info("Resuming dispatcher")
get_logger().info(f"Resuming dispatcher (policy v{self.policy.version})")
if self.gate_closed_at is not None:
self.wait_for_policy_time += time.perf_counter() - self.gate_closed_at
self.gate_closed_at = None
@@ -1003,10 +1031,13 @@ class Orchestrator:
training artifacts are already persisted before this is reached."""
async def teardown() -> None:
get_logger().debug("Closing micro batch sender")
self.sender.close()
if self.dispatcher is not None:
get_logger().debug("Stopping dispatcher")
await self.dispatcher.stop()
if self.watcher is not None:
get_logger().debug("Stopping weight watcher")
await self.watcher.stop()
if self.periodic_logger is not None:
await self.periodic_logger.stop()
@@ -1017,14 +1048,21 @@ class Orchestrator:
await safe_cancel(task)
self.component_tasks.clear()
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:
await self.policy_inference.stop()
if getattr(self, "clients", None) is not None:
await self.clients.aclose()
if getattr(self, "admin_clients", None) is not None:
await self.admin_clients.aclose()
if self.train_envs is not None:
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()
task = asyncio.create_task(teardown())
_, pending = await asyncio.wait({task}, timeout=SHUTDOWN_TIMEOUT_S)
if pending:
@@ -1034,6 +1072,7 @@ class Orchestrator:
)
os._exit(0)
await task
get_logger().debug(f"Stopped orchestrator components in {format_time(time.perf_counter() - t0)}")
@clean_exit
+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
+5 -12
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
@@ -230,8 +230,8 @@ class TrainSink:
self.pending_episodes.extend(group, admitted=False, cancelled=True)
self._record_zero_output(group, [], n_owed)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | dropped: cancelled (stale)"
f"Dropped group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reason=cancelled (stale)"
)
return
@@ -244,8 +244,8 @@ class TrainSink:
self._record_zero_output(group, survivors, n_owed)
reason = "no trainable survivors" if not survivors else "rejected by curriculum"
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | dropped: {reason}"
f"Dropped group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reason={reason}"
)
return
@@ -285,13 +285,6 @@ class TrainSink:
self.zero_output_units = 0
self.reported_zero_output_windows = 0
rewards = [trace.reward for trace in survivors if trace.id in samples_by_trace]
avg_reward = sum(rewards) / len(rewards)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reward={avg_reward:.4f}"
)
def _trace(self, trace_id: str) -> vf.Trace:
episode = self.episode_by_trace[trace_id]
return next(trace for trace in episode.traces if trace.id == trace_id)
+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
+1 -1
View File
@@ -88,7 +88,7 @@ def setup_env_server_logging(log_level: str, json_logging: bool = False) -> None
def set_default_executor(max_workers: int = 64) -> None:
"""Scale the default asyncio thread pool so asyncio.to_thread has enough capacity."""
get_logger().info(f"Setting default executor to ThreadPoolExecutor(max_workers={max_workers})")
get_logger().debug(f"Setting default executor to ThreadPoolExecutor(max_workers={max_workers})")
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=max_workers))
+12 -11
View File
@@ -10,10 +10,10 @@ import time
from modelexpress import p2p_pb2
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.clients import AdminClients, InferenceClient, update_weights
from prime_rl.orchestrator.types import Policy, VersionObserver
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
from prime_rl.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
@@ -27,7 +27,8 @@ class WeightWatcher:
config: OrchestratorConfig,
*,
policy: Policy,
inference: InferencePool,
clients: InferenceClient,
admin_clients: AdminClients,
observers: list[VersionObserver],
lora_name: str | None,
ckpt_step: int = 0,
@@ -36,7 +37,8 @@ class WeightWatcher:
) -> None:
self.config = config
self.policy = policy
self.inference = inference
self.clients = clients
self.admin_clients = admin_clients
self.observers = observers
self.lora_name = lora_name
self.ckpt_step = ckpt_step
@@ -103,10 +105,7 @@ class WeightWatcher:
weights_path = get_step_path(broadcast_dir, next_step)
stable_marker = weights_path / "STABLE"
if not stable_marker.exists():
get_logger().info(
f"Orchestrator paused: waiting for trainer to broadcast checkpoint {next_step}. "
"Training is progressing normally."
)
get_logger().info(f"Waiting for the trainer to broadcast policy v{next_step}")
await wait_for_path(stable_marker)
self.last_wait_for_ckpt_time = time.perf_counter() - t0
@@ -135,15 +134,17 @@ class WeightWatcher:
f"Observer {type(observer).__name__}.on_version_pending({next_step}) raised: {exc!r}"
)
get_logger().debug(f"Updating weights to step {next_step}")
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 update_weights(self.admin_clients.clients, weights_path, lora_name=self.lora_name, step=next_step)
self.last_update_weights_time = time.perf_counter() - t1
self.update_count += 1
get_logger().debug(f"Updated weights to step {next_step} in {format_time(self.last_update_weights_time)}")
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.clients.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
for observer in self.observers:
+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
+3 -3
View File
@@ -21,7 +21,7 @@ from prime_rl.configs.shared import ResumeConfig
from prime_rl.configs.trainer import CheckpointConfig
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path
@@ -194,7 +194,7 @@ class CheckpointManager:
# Save sharded state
dcp_save(state_dict, checkpoint_id=path)
self.logger.debug(f"Training checkpoint saved in {time.perf_counter() - start_time:.2f} seconds")
self.logger.debug(f"Saved training checkpoint in {format_time(time.perf_counter() - start_time)}")
def load_from_path(
self,
@@ -232,7 +232,7 @@ class CheckpointManager:
)
dataloader.load_state_dict(torch.load(dataloader_path, weights_only=False))
self.logger.debug(f"Training checkpoint loaded in {time.perf_counter() - start_time:.2f} seconds")
self.logger.debug(f"Loaded training checkpoint in {format_time(time.perf_counter() - start_time)}")
def load(
self,
+1 -1
View File
@@ -241,7 +241,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
)
raise RuntimeError("Cannot apply LoRA to FSDP-wrapped model. Apply LoRA before setup_fsdp().")
logger.debug(f"Applying LoRA to model: {model} for {config.target_modules}")
logger.debug(f"Applying LoRA to {type(model).__name__} (target_modules={config.target_modules})")
target_modules = _find_target_modules(model, config.target_modules)
logger.debug(
f"Found {len(target_modules)} target modules for LoRA: {target_modules[:10]} ... {target_modules[-10:]}"
+3 -3
View File
@@ -595,7 +595,7 @@ def get_model(
config: ModelConfig, device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.bfloat16
) -> nn.Module:
logger = get_logger()
logger.info(
logger.debug(
f"Loading model config (name={config.name}, attn={config.attn}, trust_remote_code={config.trust_remote_code})"
)
@@ -778,7 +778,7 @@ def get_model(
trust_remote_code=config.trust_remote_code,
**dtype_kwarg,
)
logger.debug(f"Loaded model {config.name} in {time.perf_counter() - load_model_start_time:.2f} seconds")
logger.debug(f"Loaded model {config.name} in {format_time(time.perf_counter() - load_model_start_time)}")
assert model.lm_head.weight.dtype == dtype, (
f"LM head dtype wasnt loaded correctly {model.lm_head.weight.dtype} != {dtype}"
@@ -1057,7 +1057,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
generator = torch.Generator(device="cuda").manual_seed(seed_tensor.item())
for module in lora_modules:
module._init_lora_parameters(generator)
logger.debug(f"Loaded weights using HF DCP in {time.perf_counter() - load_dcp_start_time:.2f} seconds")
logger.debug(f"Loaded weights using HF DCP in {format_time(time.perf_counter() - load_dcp_start_time)}")
def can_reinit_empty_buffers(model: nn.Module):
+6 -1
View File
@@ -17,6 +17,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import time
from dataclasses import dataclass
from functools import cached_property
@@ -25,7 +26,7 @@ from torch._utils import _get_available_device_type
from torch.distributed.device_mesh import DeviceMesh, init_device_mesh
from prime_rl.configs.trainer import ModelConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
device_type = _get_available_device_type() or "cuda"
@@ -105,7 +106,9 @@ class ParallelDims:
names.append(name)
self.logger.info(f"Building {len(dims)}-D device mesh with {names}, {dims}")
t0 = time.perf_counter()
mesh = init_device_mesh(device_type, dims, mesh_dim_names=names)
self.logger.debug(f"Built device mesh in {format_time(time.perf_counter() - t0)}")
# Create all the submesh here to ensure all required process groups are
# initialized:
@@ -163,7 +166,9 @@ class ParallelDims:
names.append(name)
self.logger.info(f"Building {len(dims)}-D device mesh with {names}, {dims}")
t0 = time.perf_counter()
mesh = init_device_mesh(device_type, dims, mesh_dim_names=names)
self.logger.debug(f"Built device mesh in {format_time(time.perf_counter() - t0)}")
# Create all the submesh here to ensure all required process groups are
# initialized:
+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()
+29 -18
View File
@@ -79,10 +79,9 @@ def train(config: TrainerConfig):
config.log.level,
json_logging=config.log.json_logging,
)
logger.info(f"Starting RL trainer in {world} in {config.output_dir}")
logger.info(f"Starting RL trainer in {world} (output_dir={config.output_dir})")
# Setup the monitors
logger.info(f"Initializing monitors ({config.monitors})")
asyncio.run(
monitors.setup(
wandb=config.monitors.wandb, file=config.monitors.file, output_dir=config.output_dir, run_config=config
@@ -140,19 +139,21 @@ def train(config: TrainerConfig):
# Initialize the model and tokenizer
logger.info(f"Initializing model ({config.model})")
t0 = time.perf_counter()
loading_from_ckpt_later = checkpoint_step is not None
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
logger.debug(f"Initialized model in {format_time(time.perf_counter() - t0)}")
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
raise ValueError("Packed multimodal training requires model support")
# Set up the loss function for the RL loss type (ce / ref_kl are fixed)
logger.info(f"Setting up loss function ({config.loss})")
logger.info(f"Initializing loss function ({config.loss})")
rl_loss_fn = setup_rl_loss_fn(config.loss)
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
t0 = time.perf_counter()
optimizer, gradient_manager = setup_optimizer(
config.optim,
list(model.named_parameters()),
@@ -164,9 +165,10 @@ def train(config: TrainerConfig):
get_full_offload_dtype_policy(model, config.model) if config.model.full_offload is not None else None
),
)
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
logger.debug(f"Initialized optimizer in {format_time(time.perf_counter() - t0)}")
logger.info(f"Using `{config.scheduler.type}` scheduler ({config.scheduler})")
logger.info(f"Initializing scheduler ({config.scheduler})")
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
# Set up weight broadcast (skip when using fake data since there's no inference server)
if config.data.fake:
@@ -174,12 +176,14 @@ def train(config: TrainerConfig):
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(
config.output_dir,
config.weight_broadcast,
parallel_dims,
config.model.lora,
)
logger.debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
if parallel_dims.cp_enabled:
cp_group = parallel_dims.world_mesh["cp"].get_group()
@@ -228,14 +232,16 @@ def train(config: TrainerConfig):
)
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
progress.step += 1
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
logger.info(
f"Starting from step {progress.step} (total_tokens={progress.total_tokens}, total_samples={progress.total_samples})"
)
logger.info(
f"Resuming from step {checkpoint_step} "
f"(total_tokens={progress.total_tokens}, total_samples={progress.total_samples})"
)
else:
logger.info("Starting from scratch")
# Set up the data loader (Optionally, use a fake data loader for debugging)
logger.info(f"Initializing data loader ({config.data})")
t0 = time.perf_counter()
if config.data.fake:
dataloader = FakeDataLoader(config.data.fake, config.model.seq_len, parallel_dims.get_mesh("dp").size())
else:
@@ -245,6 +251,7 @@ def train(config: TrainerConfig):
parallel_dims.get_mesh("dp").size(),
config.rollout_transport,
)
logger.debug(f"Initialized data loader in {format_time(time.perf_counter() - t0)}")
token_exporter = setup_token_exporter(config, parallel_dims, world, logger)
@@ -263,7 +270,7 @@ def train(config: TrainerConfig):
torch.cuda.reset_peak_memory_stats()
if gc_handler is not None:
gc_handler.run(progress.step)
is_last_step = config.max_steps is not None and progress.step == config.max_steps
is_last_step = config.max_steps is not None and progress.step >= config.max_steps
logger.debug(f"Starting training step {progress.step}")
step_start_time = time.perf_counter()
@@ -273,22 +280,26 @@ def train(config: TrainerConfig):
# 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 startup policy weights (v{progress.step - 1}) to inference engines")
logger.info(f"Broadcasting base policy weights (v{progress.step - 1}) to inference engines")
t0 = time.perf_counter()
weight_broadcast.broadcast_weights(model, step=progress.step - 1)
logger.debug(
f"Broadcast base policy weights (v{progress.step - 1}) in {format_time(time.perf_counter() - t0)}"
)
# Wait for the batch to be available
logger.debug("Waiting for training batch to arrive")
wait_for_batch_start_time = time.perf_counter()
dataloader.wait_for_batch()
wait_for_batch_time = time.perf_counter() - wait_for_batch_start_time
logger.debug(f"Waited for batch to arrive for {wait_for_batch_time:.2f} seconds")
logger.debug(f"Waited for batch for {format_time(wait_for_batch_time)}")
# Load the training batch
logger.debug("Loading batch")
load_data_start_time = time.perf_counter()
micro_batches = dataloader.get_batch()
load_data_time = time.perf_counter() - load_data_start_time
logger.debug(f"Loaded batch in {load_data_time:.2f} seconds")
logger.debug(f"Loaded batch in {format_time(load_data_time)}")
batch_size = len(micro_batches)
memory_profiler = None
@@ -539,7 +550,7 @@ def train(config: TrainerConfig):
tensors[key].append(loss_tensor.detach().to("cpu"))
# Debug log with *local, micro step* stats
micro_step_message = f"Micro Step {micro_step}/{len(micro_batches)} | Loss {tensors['loss'][-1].mean().item():.4f} | Entropy {tensors['entropy/all'][-1].mean().item():.4f}"
micro_step_message = f"Micro Step {micro_step + 1}/{len(micro_batches)} | Loss {tensors['loss'][-1].mean().item():.4f} | Entropy {tensors['entropy/all'][-1].mean().item():.4f}"
if has_mismatch_tokens:
micro_step_message += f" | Mismatch KL {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
if "max_vio" in tensors:
@@ -726,7 +737,7 @@ def train(config: TrainerConfig):
# Write final checkpoint
if config.ckpt is not None:
logger.info("Writing final checkpoint")
logger.info(f"Saving final checkpoint at step {progress.step}")
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
ckpt_manager.maybe_clean()
@@ -734,7 +745,7 @@ def train(config: TrainerConfig):
gradient_manager.close()
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
logger.success("RL trainer finished!")
logger.success("RL trainer finished")
# Stop metrics/health server if configured
if metrics_server is not None:
+11 -10
View File
@@ -72,10 +72,9 @@ def train(config: SFTConfig):
config.log.level,
json_logging=config.log.json_logging,
)
logger.info(f"Starting SFT trainer in {world}")
logger.info(f"Starting SFT trainer in {world} (output_dir={config.run_dir})")
# Setup the monitors
logger.info(f"Initializing monitors ({config.monitors})")
asyncio.run(
monitors.setup(
wandb=config.monitors.wandb,
@@ -184,7 +183,7 @@ def train(config: SFTConfig):
renderer = create_renderer(tokenizer, config.renderer)
if processor is not None and hasattr(renderer, "_processor"):
renderer._processor = processor
logger.info(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
logger.debug(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
@@ -208,7 +207,7 @@ def train(config: SFTConfig):
if config.max_steps is not None and (config.ckpt and config.ckpt.skip_scheduler and checkpoint_step is not None)
else config.max_steps
)
logger.info(f"Setting up {config.scheduler.type} scheduler with {scheduler_steps} steps ({config.scheduler})")
logger.info(f"Initializing scheduler with {scheduler_steps} steps ({config.scheduler})")
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
# Set up the dataset and dataloader
@@ -237,16 +236,18 @@ def train(config: SFTConfig):
dataloader=dataloader if not skip.skip_dataloader else None,
path=resume_dir / "trainer" if resume_dir is not None else None,
)
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
if not skip.skip_progress:
progress.step += 1
# This redundant setup is necessary because loading the optimizer's state has side effects on the scheduler state dict
if skip.skip_scheduler:
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
logger.info(
f"Starting from step {progress.step} (total_tokens={progress.total_tokens}, total_samples={progress.total_samples}, dataset_state={get_dataset_state(dataloader)})"
)
logger.info(
f"Resuming from step {checkpoint_step} (total_tokens={progress.total_tokens}, "
f"total_samples={progress.total_samples}, dataset_state={get_dataset_state(dataloader)})"
)
else:
logger.info("Starting from scratch")
# Create the iterator only after a potential resume: iter() forks workers with a
# copy of the dataset's *current* state, so a later load_state_dict never reaches
@@ -705,7 +706,7 @@ def train(config: SFTConfig):
# Write final checkpoint
if config.ckpt is not None:
logger.info("Writing final checkpoint")
logger.info(f"Saving final checkpoint at step {progress.step}")
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
ckpt_manager.maybe_clean()
@@ -720,7 +721,7 @@ def train(config: SFTConfig):
gradient_manager.close()
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
logger.success("SFT trainer finished!")
logger.success("SFT trainer finished")
def main():
+5 -2
View File
@@ -17,7 +17,7 @@ from torchtitan.distributed.utils import clip_grad_norm_ as torch_clip_grad_norm
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
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
@@ -52,7 +52,7 @@ class GarbageCollection:
def _collect(self, generation: int = 1):
begin = time.monotonic()
gc.collect(generation)
get_logger().info(f"[GC] collection took {time.monotonic() - begin:.2f}s")
get_logger().debug(f"Collected garbage in {format_time(time.monotonic() - begin)}")
def prepare_gradient_offload(
@@ -172,6 +172,8 @@ def setup_full_cpu_optimizer_offload(config: "OptimizerInBackwardOffloadConfig")
def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: bool = False):
get_logger().info(f"Initializing torch distributed (timeout={int(timeout.total_seconds())}s)")
t0 = time.perf_counter()
device_id = get_world().local_rank
torch.cuda.set_device(device_id)
# Use Gloo backend for CPU and NCCL for GPU when CPU offloading is enabled
@@ -189,6 +191,7 @@ def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: b
dist.distributed_c10d.default_pg_timeout = timeout
dist.init_process_group(backend=backend, timeout=timeout, device_id=device_id)
get_logger().debug(f"Initialized torch distributed in {format_time(time.perf_counter() - t0)}")
def print_sample(input_ids: list[int], loss_mask: list[bool], tokenizer: PreTrainedTokenizer):
+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.
@@ -35,9 +35,9 @@ class ZMQMicroBatchSender(MicroBatchSender):
self._ready = False
self.logger.info(
f"ZMQ micro batch sender initialized: endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm}"
self.logger.debug(
f"Initialized ZMQ micro batch sender (endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm})"
)
self._topic_prefix = b"data_rank|"
@@ -84,10 +84,10 @@ class ZMQMicroBatchSender(MicroBatchSender):
self.socket.close(linger=0)
self.ready_socket.close(linger=0)
finally:
self.logger.info("ZMQ micro batch sender closed")
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)
@@ -111,9 +111,9 @@ class ZMQMicroBatchReceiver(MicroBatchReceiver):
# Announce readiness after connect+subscribe are set
self.ready_socket.send(str(data_rank).encode("utf-8"))
self.logger.info(
f"ZMQ micro batch receiver initialized: endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm}"
self.logger.debug(
f"Initialized ZMQ micro batch receiver (endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm})"
)
self._current_step = current_step
@@ -138,4 +138,4 @@ class ZMQMicroBatchReceiver(MicroBatchReceiver):
self.socket.close(linger=0)
self.ready_socket.close(linger=0)
finally:
self.logger.info("ZMQ micro batch receiver closed")
self.logger.debug("Closed ZMQ micro batch receiver")
@@ -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",
]
@@ -11,6 +11,7 @@ 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.utils.weights import (
convert_state_dict_to_hf,
@@ -28,11 +29,11 @@ class FileSystemWeightBroadcast(WeightBroadcast):
):
super().__init__(output_dir, lora_config)
self.world = get_world()
self.logger.debug("Filesystem broadcast initialized")
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("Starting broadcasting weights to inference engine via shared filesystem")
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
@@ -67,7 +68,7 @@ class FileSystemWeightBroadcast(WeightBroadcast):
if self.world.is_master:
self._notify_orchestrator(save_dir)
self.logger.debug(f"Weights broadcasted in {time.perf_counter() - start_time:.2f}s")
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."""
+6 -6
View File
@@ -12,12 +12,12 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
from vllm.distributed.utils import StatelessProcessGroup
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
from prime_rl.orchestrator.clients import NCCL_READY_MARKER
from prime_rl.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 get_logger
from prime_rl.utils.logger import format_time, 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
@@ -132,9 +132,9 @@ class NCCLWeightBroadcastSender:
host=host, port=port, rank=rank, world_size=world_size, store_timeout=timeout
)
self.communicator = PyNcclCommunicator(pg, device=device)
self.logger.debug("NCCL broadcast initialized on master rank")
self.logger.debug("Initialized NCCL broadcast on master rank")
else:
self.logger.debug("NCCL broadcast initialized on non-master rank (no communicator)")
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:
@@ -194,7 +194,7 @@ class NCCLWeightBroadcast(WeightBroadcast):
@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("Starting broadcasting weights to inference engine via NCCL")
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:
@@ -209,7 +209,7 @@ class NCCLWeightBroadcast(WeightBroadcast):
if self.world.world_size > 1:
dist.barrier()
self.nccl_broadcast_sender.broadcast_weights(model, step)
self.logger.debug(f"Weights broadcasted in {time.perf_counter() - start_time:.2f}s")
self.logger.debug(f"Broadcast policy weights (v{step}) in {format_time(time.perf_counter() - start_time)}")
def _notify_orchestrator(self, save_dir: Path) -> None:
"""Create the STABLE marker the orchestrator's weight watcher polls for."""
+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: