Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f615de9383 | ||
|
|
1093f9b914 |
+16
-12
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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) :])
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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(
|
||||
@@ -203,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):
|
||||
@@ -220,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
|
||||
@@ -394,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.
|
||||
@@ -405,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(
|
||||
@@ -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:
|
||||
|
||||
@@ -192,7 +192,7 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
configs: Sequence[TrainSourceConfig],
|
||||
addresses: dict[tuple[str, str], str],
|
||||
*,
|
||||
policy_pool,
|
||||
clients,
|
||||
renderer_config=None,
|
||||
):
|
||||
self._envs: dict[str, TrainEnv] = {}
|
||||
@@ -202,8 +202,8 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
env = TrainEnv(
|
||||
config,
|
||||
addresses[("train", config.resolved_name)],
|
||||
GenerationSource(config.algo.sampling, policy_pool, renderer_config),
|
||||
build_algorithm(config.algo, policy_pool),
|
||||
GenerationSource(config.algo.sampling, clients, renderer_config),
|
||||
build_algorithm(config.algo, clients),
|
||||
)
|
||||
self._envs[env.name] = env
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -199,13 +206,14 @@ class Orchestrator:
|
||||
# references are external endpoints — each env's Algorithm builds its
|
||||
# own pools in ``setup()`` below.
|
||||
get_logger().info(f"Initializing policy inference pool ({config.model})")
|
||||
self.policy_inference = InferencePool(
|
||||
self.clients = InferenceClient(
|
||||
config.model.client,
|
||||
model_name=config.model.name,
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_config=config.renderer,
|
||||
)
|
||||
self.admin_clients = AdminClients(config.model.client)
|
||||
|
||||
await monitors.setup(
|
||||
wandb=config.monitors.wandb,
|
||||
@@ -230,7 +238,7 @@ class Orchestrator:
|
||||
self.train_envs = TrainEnvs(
|
||||
config.train.source,
|
||||
config.env_addresses,
|
||||
policy_pool=self.policy_inference,
|
||||
clients=self.clients,
|
||||
renderer_config=config.renderer,
|
||||
)
|
||||
if config.eval is not None:
|
||||
@@ -245,7 +253,7 @@ class Orchestrator:
|
||||
self.resume_step = resolve_latest_ckpt_step(self.ckpt_manager.ckpt_dir)
|
||||
|
||||
# Resume below may bump ``policy.version`` and the LoRA model name
|
||||
self.policy.model_name = self.policy_inference.model_name
|
||||
self.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
|
||||
@@ -261,7 +269,7 @@ class Orchestrator:
|
||||
# Transports are local setup — initialize them before the env and inference waits.
|
||||
self.packer = BatchPacker(config)
|
||||
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
|
||||
self.sender = setup_micro_batch_sender(
|
||||
self.sender = setup_batch_sender(
|
||||
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
|
||||
)
|
||||
if config.weight_broadcast.type == "filesystem":
|
||||
@@ -290,7 +298,7 @@ class Orchestrator:
|
||||
|
||||
get_logger().info("Waiting for policy inference pool to be ready")
|
||||
t0 = time.perf_counter()
|
||||
await self.policy_inference.wait_for_ready(config.model.name)
|
||||
await self.admin_clients.wait_for_ready(config.model.name)
|
||||
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
|
||||
# Build + ready pools for each env's frozen generation source and the
|
||||
# algorithm's frozen reference model
|
||||
@@ -306,7 +314,7 @@ class Orchestrator:
|
||||
t0 = time.perf_counter()
|
||||
if config.weight_broadcast.type == "nccl":
|
||||
await init_nccl_broadcast(
|
||||
self.policy_inference.admin_clients,
|
||||
self.admin_clients.clients,
|
||||
config.weight_broadcast.host,
|
||||
config.weight_broadcast.port,
|
||||
config.weight_broadcast.timeout,
|
||||
@@ -315,7 +323,7 @@ class Orchestrator:
|
||||
)
|
||||
else:
|
||||
await init_nixl_broadcast(
|
||||
self.policy_inference.admin_clients,
|
||||
self.admin_clients.clients,
|
||||
config.weight_broadcast.host,
|
||||
config.weight_broadcast.port,
|
||||
config.weight_broadcast.timeout,
|
||||
@@ -353,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.
|
||||
@@ -365,7 +373,7 @@ 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)}")
|
||||
@@ -389,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,
|
||||
@@ -409,7 +417,7 @@ class Orchestrator:
|
||||
# W&B mirroring is gated on the registered monitor (the collector logs
|
||||
# to the global W&B session, which only exists when init succeeded).
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.policy_inference.admin_clients,
|
||||
self.admin_clients.clients,
|
||||
roles=config.inference_metrics_roles,
|
||||
on_load=self.concurrency.observe,
|
||||
log_to_wandb=wandb_enabled and config.collect_inference_metrics,
|
||||
@@ -432,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,
|
||||
@@ -1041,14 +1050,16 @@ class Orchestrator:
|
||||
if self.inference_metrics is not None:
|
||||
get_logger().debug("Stopping inference metrics collector")
|
||||
await self.inference_metrics.stop()
|
||||
if getattr(self, "policy_inference", None) is not None:
|
||||
get_logger().debug("Stopping policy inference pool")
|
||||
await self.policy_inference.stop()
|
||||
if 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 pools")
|
||||
get_logger().debug("Stopping generation source and algorithm clients")
|
||||
for env in self.train_envs:
|
||||
for pool in (*env.generation_source.connected_pools, *env.algorithm.connected_pools):
|
||||
await pool.stop()
|
||||
for clients in (env.generation_source.connected, env.algorithm.connected):
|
||||
if clients is not None:
|
||||
await clients.aclose()
|
||||
|
||||
get_logger().info("Stopping orchestrator components")
|
||||
t0 = time.perf_counter()
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -134,7 +136,7 @@ class WeightWatcher:
|
||||
|
||||
get_logger().debug(f"Updating inference weights to policy v{next_step}")
|
||||
t1 = time.perf_counter()
|
||||
await self.inference.update_weights(weights_path, lora_name=self.lora_name, step=next_step)
|
||||
await 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(
|
||||
@@ -142,7 +144,7 @@ class WeightWatcher:
|
||||
)
|
||||
|
||||
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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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):
|
||||
+4
-4
@@ -1,12 +1,12 @@
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.transports.rollouts.base import MicroBatchReceiver, MicroBatchSender
|
||||
from prime_rl.transports.rollouts.types import MicroBatch
|
||||
from prime_rl.transports.batch.base import BatchReceiver, BatchSender
|
||||
from prime_rl.transports.batch.types import MicroBatch
|
||||
from prime_rl.utils.pathing import get_rollout_dir, get_step_path, sync_wait_for_path
|
||||
|
||||
|
||||
class FileSystemMicroBatchSender(MicroBatchSender):
|
||||
class FileSystemBatchSender(BatchSender):
|
||||
"""Filesystem-based micro batch sender that writes micro batches to disk."""
|
||||
|
||||
def __init__(self, output_dir: Path, data_world_size: int, current_step: int = 0):
|
||||
@@ -35,7 +35,7 @@ class FileSystemMicroBatchSender(MicroBatchSender):
|
||||
tmp_path.rename(step_path / f"rank_{data_rank}.bin")
|
||||
|
||||
|
||||
class FileSystemMicroBatchReceiver(MicroBatchReceiver):
|
||||
class FileSystemBatchReceiver(BatchReceiver):
|
||||
"""Filesystem-based micro batch receiver that reads micro batches from disk."""
|
||||
|
||||
def __init__(self, output_dir: Path, data_rank: int, current_step: int = 0):
|
||||
@@ -4,11 +4,11 @@ import zmq
|
||||
import zmq.asyncio
|
||||
|
||||
from prime_rl.configs.shared import ZMQTransportConfig
|
||||
from prime_rl.transports.rollouts.base import MicroBatchReceiver, MicroBatchSender
|
||||
from prime_rl.transports.rollouts.types import MicroBatch
|
||||
from prime_rl.transports.batch.base import BatchReceiver, BatchSender
|
||||
from prime_rl.transports.batch.types import MicroBatch
|
||||
|
||||
|
||||
class ZMQMicroBatchSender(MicroBatchSender):
|
||||
class ZMQBatchSender(BatchSender):
|
||||
def __init__(self, output_dir: Path, data_world_size: int, current_step: int, transport: ZMQTransportConfig):
|
||||
"""ZMQ micro batch sender that publishes per-rank micro batches to the trainers.
|
||||
There is one sender (in the orchestrator process) for the entire data world.
|
||||
@@ -87,7 +87,7 @@ class ZMQMicroBatchSender(MicroBatchSender):
|
||||
self.logger.debug("Closed ZMQ micro batch sender")
|
||||
|
||||
|
||||
class ZMQMicroBatchReceiver(MicroBatchReceiver):
|
||||
class ZMQBatchReceiver(BatchReceiver):
|
||||
def __init__(self, output_dir: Path, data_rank: int, current_step: int, transport: ZMQTransportConfig):
|
||||
"""ZMQ micro batch receiver that receives micro batches from the orchestrator. There is one receiver per data rank."""
|
||||
super().__init__(output_dir, data_rank)
|
||||
@@ -1,54 +0,0 @@
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.configs.shared import TransportConfig
|
||||
from prime_rl.transports.rollouts.base import MicroBatchReceiver, MicroBatchSender
|
||||
from prime_rl.transports.rollouts.filesystem import (
|
||||
FileSystemMicroBatchReceiver,
|
||||
FileSystemMicroBatchSender,
|
||||
)
|
||||
from prime_rl.transports.rollouts.types import (
|
||||
MicroBatch,
|
||||
RoutedExperts,
|
||||
TrainingSample,
|
||||
)
|
||||
from prime_rl.transports.rollouts.zmq import (
|
||||
ZMQMicroBatchReceiver,
|
||||
ZMQMicroBatchSender,
|
||||
)
|
||||
|
||||
|
||||
def setup_micro_batch_sender(
|
||||
output_dir: Path, data_world_size: int, current_step: int, transport: TransportConfig
|
||||
) -> MicroBatchSender:
|
||||
if transport.type == "filesystem":
|
||||
return FileSystemMicroBatchSender(output_dir, data_world_size, current_step)
|
||||
elif transport.type == "zmq":
|
||||
return ZMQMicroBatchSender(output_dir, data_world_size, current_step, transport)
|
||||
else:
|
||||
raise ValueError(f"Invalid transport type: {transport.type}")
|
||||
|
||||
|
||||
def setup_micro_batch_receiver(
|
||||
output_dir: Path, data_rank: int, current_step: int, transport: TransportConfig
|
||||
) -> MicroBatchReceiver:
|
||||
if transport.type == "filesystem":
|
||||
return FileSystemMicroBatchReceiver(output_dir, data_rank, current_step)
|
||||
elif transport.type == "zmq":
|
||||
return ZMQMicroBatchReceiver(output_dir, data_rank, current_step, transport)
|
||||
else:
|
||||
raise ValueError(f"Invalid transport type: {transport.type}")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"FileSystemMicroBatchSender",
|
||||
"FileSystemMicroBatchReceiver",
|
||||
"ZMQMicroBatchSender",
|
||||
"ZMQMicroBatchReceiver",
|
||||
"MicroBatchReceiver",
|
||||
"MicroBatchSender",
|
||||
"TrainingSample",
|
||||
"MicroBatch",
|
||||
"RoutedExperts",
|
||||
"setup_micro_batch_sender",
|
||||
"setup_micro_batch_receiver",
|
||||
]
|
||||
@@ -12,11 +12,11 @@ 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 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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"}
|
||||
|
||||
|
||||
@@ -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():
|
||||
@@ -80,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:
|
||||
|
||||
Reference in New Issue
Block a user