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