refactor: rename env servers to env worker pools (#4381)

The environment hosting entrypoint launches a broker and a pool of
episode workers. Calling that unit an "env server" obscures the source →
pool replica → broker/workers hierarchy. This follow-up to #4375 names
those roles consistently.

- Rename the command to `uv run env-worker-pool`, its schema to
`EnvWorkerPoolConfig` in `prime_rl.configs.env_worker_pool`, and the
orchestrator field to `env_worker_pool_replicas`.
- Rename `EnvServerPool` to `EnvWorkerPool`, `EnvServer` to `EnvWorker`
in `prime_rl.env.worker`, and `serve_env` to `run_env_worker_pool`.
Process titles distinguish `PRL::EnvBroker` and `PRL::EnvWorker`.
- Update the RL/eval launchers, the shared SFT/pretrain launcher, SLURM
templates, config helpers, CI paths, dashboard text, docs, and the
affected skills. Document per-source configuration, pool replicas, and
worker concurrency.
- Anchor the root virtualenv ignore rule so it does not hide
`src/prime_rl/env/` on case-insensitive filesystems.

`[serve]`, the wire protocol, pool sizing/dispatch behavior, and run
artifact paths are unchanged. This is a naming change; direct
worker-to-sink data delivery remains separate work.

## Breaking names

| Before | After |
| --- | --- |
| `env-server` | `env-worker-pool` |
| `prime_rl.configs.env_server.EnvServerConfig` |
`prime_rl.configs.env_worker_pool.EnvWorkerPoolConfig` |
| `OrchestratorConfig.env_server_replicas` |
`OrchestratorConfig.env_worker_pool_replicas` |
| `prime_rl.env.pool.EnvServerPool` | `prime_rl.env.pool.EnvWorkerPool`
|
| `prime_rl.env.server.EnvServer` | `prime_rl.env.worker.EnvWorker` |
| `prime_rl.env.serve_env` | `prime_rl.env.run_env_worker_pool` |
| `EnvClient.wait_for_server_startup` |
`EnvClient.wait_for_pool_startup` |

## Validation

- 447 focused CPU tests passed (env, configs, supported
orchestrator/eval/transport tests, dashboard artifacts and pathing);
four cases deselected. Tests requiring unavailable `torch`, `vllm`, and
TextArena dependencies were excluded.
- Temporary smoke script exercised static pools with 1/2 workers and
elastic pools capped at 1/unbounded: address discovery, task/error
round-trip through the broker and worker, process titles, graceful
shutdown, and IPC cleanup all passed. The smoke env deliberately raises
an episode error; it does not call inference.
- Both wheels build; wheel contents and the renamed console entrypoint
verified. Entrypoint help, touched TOML parsing, Ruff, and `pre-commit
run --all-files` pass.
- The deep-backlog ZMQ test timed out after 18 seconds on both unchanged
base `c0ad9e9f4` and this branch, so it was deselected. No GPU training
run.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking renames span the CLI, Python imports, and orchestrator config
fields; behavior is unchanged but existing scripts and TOML must be
updated.
> 
> **Overview**
> Renames the environment-hosting stack so **source → broker → workers**
is explicit: the CLI becomes **`uv run env-worker-pool`**, config schema
**`EnvWorkerPoolConfig`** (`prime_rl.configs.env_worker_pool`), and
orchestrator **`env_worker_pool_replicas`** replace the old `env-server`
/ `EnvServerConfig` / `env_server_replicas` names.
> 
> Runtime symbols align with that model—**`EnvWorkerPool`**,
**`EnvWorker`**, **`run_env_worker_pool`**, broker/worker process titles
(**`PRL::EnvBroker`** / **`PRL::EnvWorker`**), and
**`EnvClient.wait_for_pool_startup`**. RL/SFT/eval launchers, SLURM
templates, pathing helpers, CI filters, dashboard copy, docs, and skills
are updated to match; **`[serve]`**, the ZMQ wire protocol, and artifact
paths stay the same.
> 
> **.gitignore** anchors **`/ENV/`** so a root `ENV` venv directory is
not confused with **`src/prime_rl/env/`** on case-insensitive
filesystems.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
47c74d92f30d54524ad2e0c79ae1dae0e42def31. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
This commit is contained in:
Konstantin Dunas
2026-11-07 03:39:35 +01:00
committed by GitHub
parent 94171d1aa0
commit e18b36f059
58 changed files with 310 additions and 285 deletions
+3 -3
View File
@@ -82,7 +82,7 @@ jobs:
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.configs.env_worker_pool import EnvWorkerPoolConfig
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
from prime_rl.utils.validation import propagate_shared_fields
@@ -142,9 +142,9 @@ jobs:
- 'src/prime_rl/{trainer,multimodal,transports,utils}/**'
- 'tests/{__init__.py,conftest.py,utils.py}'
- 'tests/integration/{__init__.py,conftest.py}'
- 'packages/prime-rl-configs/src/prime_rl/configs/{eval,orchestrator,inference,env_server,algorithm,monitors}.py'
- 'packages/prime-rl-configs/src/prime_rl/configs/{eval,orchestrator,inference,env_worker_pool,algorithm,monitors}.py'
- 'src/prime_rl/{control,eval,orchestrator,monitors}/**'
- 'src/prime_rl/entrypoints/{eval,env_server}.py'
- 'src/prime_rl/entrypoints/{eval,env_worker_pool}.py'
- 'tests/integration/test_gsm8k_eval.py'
- 'configs/ci/integration/gsm8k-eval.toml'
+1 -1
View File
@@ -145,7 +145,7 @@ celerybeat.pid
.env
.venv
venv/
ENV/
/ENV/
env.bak/
venv.bak/
+1 -1
View File
@@ -1,6 +1,6 @@
# Multi env: 16 terminal-bench-2 tasks under two harnesses, bash and rlm, in prime
# sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout each with
# a ten-minute budget, against Prime Inference on the default model. One env server
# a ten-minute budget, against Prime Inference on the default model. One env worker pool
# per source; the sources share the taskset, so each carries its own name.
#
# uv run eval @ configs/debug/eval/multi-env.toml
+3 -3
View File
@@ -15,7 +15,7 @@ This page covers `uv run eval` — evaluating a model in one or more environment
- [Prime](#prime)
- [Metrics](#metrics)
`uv run eval` runs one epoch of every configured source and exits. It reuses the orchestrator's eval pipeline: env servers are spawned per source, episodes are admitted under the concurrency controller, and every episode streams into the run's trace stream and metrics.
`uv run eval` runs one epoch of every configured source and exits. It reuses the orchestrator's eval pipeline: env worker pools are spawned per source, episodes are admitted under the concurrency controller, and every episode streams into the run's trace stream and metrics.
## Launch
@@ -79,7 +79,7 @@ Per-source `group_size` and `sampling` override the top-level defaults. The top-
Each field a source sets in its `select` overrides the same field of the top-level `[select]`. `select` picks which tasks of the taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit` (see verifiers' [Selecting tasks](../deps/verifiers/docs/v1/tasksets.md#selecting-tasks)). Train sources take the same `select`.
Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
Every source's env worker pool is spawned by the eval process unless the source sets `serve.address`, in which case the pool is externally managed. A pool's broker binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
## Live Concurrency
@@ -118,7 +118,7 @@ Monitors receive the run's metrics and episodes through one abstraction. The fil
### File
The file monitor writes the run's metrics and trace stream under `output_dir / run.name / monitors/file/` and feeds the local [dashboard](training.md#dashboard). Env servers stream every rollout to the eval process as it happens: the trace's header when it is minted, then one delta per committed turn (the new messages and the model call behind them), per phase change (boot, setup, agent, finalize, scoring), and a preview of each model request's uncommitted messages, so a tool result shows the moment the model is asked about it rather than with the reply. The file monitor appends those deltas to `monitors/file/traces/live/<trace_id>.jsonl` and deletes the file when the episode lands in the finished trace stream, so that directory is exactly the live set and finished traces stay where they always were. The dashboard's traces tab shows live rollouts in the episode table itself: a pulsing dot in the `#` cell marks the row, a phase badge says where the rollout is (boot, setup, running, finalize, scoring), the `dispatched → arrived` column shows the dispatch time with the elapsed time in brackets, and the turn, token and branch counts grow as deltas land. The status filter toggles live and completed rows, and a live row opens in the trace viewer, which follows the rollout turn by turn (the transcript stays pinned to the newest turn until you scroll up; folded entries stay folded; the pending messages of the request in flight render dimmed with an `awaiting model` chip). The table and an open live trace poll once a second and transfer nothing while the rollout is unchanged. The progress line in `eval.log` counts the live rollouts by phase (`2 inflight episodes ... - boot 1 · running 1`). Read a live trace from a shell with `uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`. The same stream exists for RL runs, covering train and online-eval rollouts alike.
The file monitor writes the run's metrics and trace stream under `output_dir / run.name / monitors/file/` and feeds the local [dashboard](training.md#dashboard). Env worker pools stream every rollout to the eval process as it happens: the trace's header when it is minted, then one delta per committed turn (the new messages and the model call behind them), per phase change (boot, setup, agent, finalize, scoring), and a preview of each model request's uncommitted messages, so a tool result shows the moment the model is asked about it rather than with the reply. The file monitor appends those deltas to `monitors/file/traces/live/<trace_id>.jsonl` and deletes the file when the episode lands in the finished trace stream, so that directory is exactly the live set and finished traces stay where they always were. The dashboard's traces tab shows live rollouts in the episode table itself: a pulsing dot in the `#` cell marks the row, a phase badge says where the rollout is (boot, setup, running, finalize, scoring), the `dispatched → arrived` column shows the dispatch time with the elapsed time in brackets, and the turn, token and branch counts grow as deltas land. The status filter toggles live and completed rows, and a live row opens in the trace viewer, which follows the rollout turn by turn (the transcript stays pinned to the newest turn until you scroll up; folded entries stay folded; the pending messages of the request in flight render dimmed with an `awaiting model` chip). The table and an open live trace poll once a second and transfer nothing while the rollout is unchanged. The progress line in `eval.log` counts the live rollouts by phase (`2 inflight episodes ... - boot 1 · running 1`). Read a live trace from a shell with `uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`. The same stream exists for RL runs, covering train and online-eval rollouts alike.
The dashboard's overview tab reads the trace stream directly. It shows one env at a time; the filter menu picks the env and whether errored episodes join the distributions. A block bar has one cell per expected episode: landed episodes (errored ones in red; click one to open it), live rollouts as pulsing outlines (click one to follow it), and the rest empty, with the percentage beside it. The expected count is what the eval runner wrote to `monitors/file/plan.json` when it counted the epoch's tasks. Below the bar, a summary row gives the headline numbers: avg@k and pass@k, the error and truncation rates (yellow past 10%, red past 50%), mean turns and branches in one tile, mean episode time and tokens, and the total cost when the run has costs; hover a tile for its distribution. The env's own rewards and metrics follow, a beeswarm pane each, resizable like the training charts. The usage section is one pane splitting each episode's tokens into input and output, and the timing section is the same pane over the phases of a rollout (boot, setup, model, harness, finalize, scoring, and `other` for wall time no phase accounts for): an icicle bar shows the mean split, one strip per episode below shows the split per rollout, and a legend sits above. Hovering a phase highlights it across the pane; the strips show 40 episodes by default and all of them on `show all`. A metric every episode shares appears as a chip instead of a pane, and a metric with only a few distinct values, such as a binary reward, as a counted dot plot with the count and share of each value. Every dot is an episode (or a task): hover it for its value and click it to open the trace; hover the pane's background for the summary (min, p10, median, p90, max), with a faint boxplot behind the dots. Errored episodes stay out of the distributions until the filter includes them, where they read red. The metrics tab charts every key of the run's `metrics.jsonl`: the epoch's `eval/<env>/…` summaries and the time-keyed `inference/` and `concurrency/` rows the runner samples while the epoch is in flight.
+1 -1
View File
@@ -326,7 +326,7 @@ enable_router_replay = true # this will also auto-set inference.vllm.enable_retu
enable_return_routed_experts = true
```
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env worker pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
Router replay works with `inference.kv_cache_offload` (native and Mooncake). vLLM keeps routing rows in a local store keyed by block hash, and no connector moves them with the KV, so a loaded block has no rows on this instance. prime-rl therefore limits an offload load to the prompt tokens the client already has routing for: the blocks before `routed_experts_prompt_start`. Multi-turn rollouts keep their offload hits, because the reloaded earlier turns sit before that position. Offloaded prefixes past it (first turns, prompts shared across a group or across nodes) are recomputed. Loaded blocks then serve local GPU prefix hits like any other block, so a local hit is cut at the first loaded block that a request needs routing from (for example a first turn that hits a prefix reloaded by another rollout's later turn), and the rest is recomputed. Under P/D, decode-side loads are not limited: decode requests emit routing only from their first forward.
+32 -5
View File
@@ -42,9 +42,36 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
| `uv run pretrain` | Pretraining from scratch on tokenized shards. | Launches torchrun internally; see [Pretraining](#pretraining). |
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-server` per source. |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-worker-pool` per source. |
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. on their own host) and the launcher expects the server to already run there. |
| `uv run env-worker-pool` | One source's worker pool replica: a broker and its env workers. | Launchers start these automatically. Use this command for standalone pools, including sources whose `serve.address` points to an externally managed pool. |
### Env worker pools
Each train/eval source has its own env configuration. Two sources can use the same taskset
with different agents or settings. Each source can have multiple worker pool replicas:
single-node runs start one, and multi-node RL runs start one per inference node. An explicit
`serve.address` selects one externally managed pool instead.
```text
Orchestrator
└── Source (env configuration)
├── Pool replica 1: PRL::EnvBroker
│ ├── PRL::EnvWorker
│ └── PRL::EnvWorker
└── Pool replica 2: PRL::EnvBroker
└── PRL::EnvWorker
```
The orchestrator selects the least-loaded replica; its broker dispatches to the least-busy
worker. Each worker loads its own Verifiers env and can execute multiple episodes concurrently.
The orchestrator loads the dataset and sends task data with each request. Even a one-worker
pool has a broker and a separate worker process.
`[serve]` configures the pool's address, static/elastic worker count and per-worker episode
concurrency. Each broker publishes its bound address under
`configs/attempt_N/resolved/envs/<split>/<name>.address` (or `<name>.<replica>.address` for
multiple replicas). Broker and worker logs share the source's log file.
## RL Trainer
@@ -249,11 +276,11 @@ num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an online-eval process next to the trainer (it logs to `logs/attempt_<n>/eval.log`). NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the online-eval process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
The launcher starts the inference server, one env worker pool per eval source, and an online-eval process next to the trainer (it logs to `logs/attempt_<n>/eval.log`). NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the online-eval process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
#### Multi-Node Trainer and Inference Pool
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and online-eval process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env worker pools, and online-eval process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
```toml
[deployment]
@@ -517,7 +544,7 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
├── inference/
│ ├── node_*.log # per-node inference stdout (multi-node only)
│ └── router.log # the single global router (multi-node only)
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
└── envs/{train,eval}/<env_name>.log # source's worker pool (broker + worker processes)
```
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.level`. For multi-rank trainer debugging, drop into `logs/latest/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
+1 -1
View File
@@ -27,7 +27,7 @@ prime login # or: prime config set-api-key <your-key>
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
- `HF_TOKEN` — optional; the Qwen checkpoints are public, but a token avoids rate limits.
`math.toml` needs none of the above beyond W&B: its agents run as local subprocesses on the env server.
`math.toml` needs none of the above beyond W&B: its agents run as local subprocesses in the env workers.
## Setup
+2 -2
View File
@@ -2,7 +2,7 @@
Slim config schema for [`prime-rl`](https://github.com/PrimeIntellect-ai/prime-rl), with no GPU or ML deps.
`pip install prime-rl-configs` gives you `prime_rl.configs.*` (RL/SFT/inference/orchestrator/trainer/env-server schemas) without pulling in `torch`, `vllm`, `transformers`, `wandb`, etc. The full training stack lives in `prime-rl`, which depends on this package.
`pip install prime-rl-configs` gives you `prime_rl.configs.*` (RL/SFT/inference/orchestrator/trainer/env-worker-pool schemas) without pulling in `torch`, `vllm`, `transformers`, `wandb`, etc. The full training stack lives in `prime-rl`, which depends on this package.
## Install
@@ -21,6 +21,6 @@ from prime_rl.configs.rl import RLConfig
config = cli(RLConfig, args=["@", "path/to/rl.toml"])
```
Other config classes live alongside `RLConfig` under `prime_rl.configs.*` (`sft`, `inference`, `orchestrator`, `trainer`, `env_server`).
Other config classes live alongside `RLConfig` under `prime_rl.configs.*` (`sft`, `inference`, `orchestrator`, `trainer`, `env_worker_pool`).
`import prime_rl` on its own succeeds but is empty — it's a [PEP 420](https://peps.python.org/pep-0420/) namespace package with no top-level attributes. Always import a submodule.
@@ -9,7 +9,7 @@ from prime_rl.utils.config import BaseConfig, default_output_dir
class StaticPoolConfig(BaseConfig):
"""Fixed env-server pool: pre-spawn `num_workers` workers up front."""
"""Fixed env worker pool: pre-spawn `num_workers` workers up front."""
type: Literal["static"] = "static"
num_workers: int = Field(4, ge=1)
@@ -17,7 +17,7 @@ class StaticPoolConfig(BaseConfig):
class ElasticPoolConfig(BaseConfig):
"""Elastic env-server pool: start at one worker and scale up on demand."""
"""Elastic env worker pool: start at one worker and scale up on demand."""
type: Literal["elastic"] = "elastic"
max_workers: int | None = Field(None, ge=1)
@@ -39,17 +39,17 @@ class ServeConfig(BaseConfig):
"""Worker-pool sizing. `elastic` (default) starts at one worker and scales up on
demand; `static` pre-spawns a fixed `num_workers`."""
address: str | None = None
"""ZMQ address the ROUTER binds (and clients connect to). None binds an OS-assigned
loopback port and publishes it through the server's address file."""
"""ZMQ address the pool's broker binds (and clients connect to). None binds an
OS-assigned loopback port and publishes it through the pool's address file."""
max_concurrent: int | None = Field(None, ge=1)
"""Episodes in flight per worker (None = unbounded). How many agent runs one episode
carries is the env's own (`--env.max-concurrent-agents`, one at a time by default)."""
class EnvServerConfig(BaseConfig):
"""``uv run env-server``: what to serve (``[env]``) and how it's hosted (``[serve]``).
The launchers write one of these per train/eval source they manage, with
``address_file`` set: the server binds an OS-assigned port and publishes it there."""
class EnvWorkerPoolConfig(BaseConfig):
"""``uv run env-worker-pool``: one source's env and its broker/worker pool replica.
Launchers write one config per managed train/eval source. Each replica's broker
publishes its bound address to ``address_file``; its workers execute episodes."""
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
"""The environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
@@ -59,7 +59,7 @@ class EnvServerConfig(BaseConfig):
address_file: Path | None = None
"""Publish the bound address to this file once serving. Set by the launchers for the
servers they spawn, so the address never has to be agreed on up front (``serve.address``
pools they spawn, so the address never has to be agreed on up front (``serve.address``
unset binds an OS-assigned port)."""
log: LogConfig = LogConfig()
@@ -49,7 +49,7 @@ class ServedEvalConfig(EvalSourcesConfig):
@property
def env_addresses(self) -> dict[tuple[str, str], str | None]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
"""Where each eval source's env worker pool lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: an explicit ``serve.address``
is an externally managed server; None means the launcher spawns the server and the
eval learns its address from the file it publishes."""
@@ -63,7 +63,7 @@ class EvalResumeConfig(BaseConfig):
class EvalConfig(ServedEvalConfig):
"""``uv run eval``: evaluate the configured sources once against a live inference
server, then exit. Every source's env server is spawned by the eval process unless
pool, then exit. Every source's env worker pool is spawned by the eval process unless
the source sets ``serve.address``. Defaults to Prime Inference (``PRIME_API_KEY`` or
``prime login``) with the concurrency pinned at 128."""
@@ -14,7 +14,7 @@ from prime_rl.configs.algorithm import (
GRPOAlgoConfig,
)
from prime_rl.configs.diff import Frozen, Live
from prime_rl.configs.env_server import ServeConfig
from prime_rl.configs.env_worker_pool import ServeConfig
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
@@ -97,7 +97,10 @@ class EnvConfig(BaseConfig):
"""The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
serve: ServeConfig = ServeConfig()
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config; an unset ``address`` means the spawned server binds an OS-assigned port and publishes it for the orchestrator. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
"""How this source's env worker pool is hosted. Each replica has a broker endpoint
and workers running the source's env configuration. An unset ``address`` lets the
launcher start the pool and discover its bound address. Setting ``address`` selects
one externally managed pool; the launcher neither writes its config nor starts it."""
name: str | None = None
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
@@ -522,11 +525,11 @@ class OrchestratorConfig(BaseConfig):
rollout_transport: TransportConfig = ZMQTransportConfig()
"""Transport used to ship rollouts from orchestrator to trainer."""
env_server_replicas: int | None = Field(None, ge=1)
"""Replicas of each launcher-managed env server, each publishing its address to
env_worker_pool_replicas: int | None = Field(None, ge=1)
"""Replicas of each launcher-managed env worker pool, each publishing its address to
``<name>.<replica>.address``; the orchestrator spreads each source's episodes over them,
least loaded first. None means one server publishing to ``<name>.address``. Set by the
``rl`` launcher: multi-node runs start one replica per inference node, so env-server
least loaded first. None means one pool publishing to ``<name>.address``. Set by the
``rl`` launcher: multi-node runs start one replica per inference node, so pool
memory spreads over all of them."""
output_dir: Path = Field(default_factory=default_output_dir)
@@ -769,7 +772,7 @@ class OrchestratorConfig(BaseConfig):
@property
def env_sources(self) -> list[tuple[str, EnvConfig]]:
"""Every ``(split, source)`` this run pulls from, train first then eval — the
order that fixes each source's deterministic env-server port."""
order used by the launcher to write per-source pool configs."""
sources: list[tuple[str, EnvConfig]] = [("train", source) for source in self.train.source]
if self.eval is not None:
sources += [("eval", source) for source in self.eval.source]
@@ -777,8 +780,8 @@ class OrchestratorConfig(BaseConfig):
@property
def env_addresses(self) -> dict[tuple[str, str], str | None]:
"""Where each source's env server lives, keyed by ``(split, resolved_name)``: the
source's own ``serve.address`` when set (an externally managed server), else None —
the launcher spawns the server, which binds an OS-assigned port and publishes it
"""Where each source's env worker pool lives, keyed by ``(split, resolved_name)``: the
source's own ``serve.address`` when set (an externally managed pool), else None —
the launcher starts the pool, whose broker binds an OS-assigned port and publishes it
to the source's address file for the orchestrator to pick up."""
return {(split, source.resolved_name): source.serve.address for split, source in self.env_sources}
@@ -611,7 +611,7 @@ class RLConfig(BaseConfig):
def auto_setup_deployment(self):
pad_to_multiple_of = rl_micro_batch_multiple(self.trainer.model)
num_train_workers = self.orchestrator.num_train_workers
env_server_replicas = self.orchestrator.env_server_replicas
env_worker_pool_replicas = self.orchestrator.env_worker_pool_replicas
if self.deployment.type == "single_node": # single-node
# set num_train_workers to the number of data replicas
non_data_parallel_size = self.trainer.model.cp
@@ -641,7 +641,7 @@ class RLConfig(BaseConfig):
elif self.deployment.type == "multi_node": # multi-node
num_train_workers = self.deployment.num_train_nodes * self.deployment.gpus_per_node // self.trainer.model.cp
if self.deployment.total_infer_nodes > 0:
env_server_replicas = self.deployment.total_infer_nodes
env_worker_pool_replicas = self.deployment.total_infer_nodes
if (
self.inference is not None
@@ -715,7 +715,7 @@ class RLConfig(BaseConfig):
update={
"pad_to_multiple_of": pad_to_multiple_of,
"num_train_workers": num_train_workers,
"env_server_replicas": env_server_replicas,
"env_worker_pool_replicas": env_worker_pool_replicas,
}
)
return self
@@ -281,7 +281,7 @@ class PolicyClientConfig(VLLMClientConfig):
class LogConfig(BaseConfig):
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
"""Log level for the process and the verifiers library it runs, env servers included.
"""Log level for the process and the verifiers library it runs, env worker pools included.
Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``."""
json_logging: bool = False
@@ -218,7 +218,7 @@ class SupervisedTrainerConfig(BaseTrainerConfig):
if self.deployment.type == "multi_node":
# Dedicated nodes in the SFT allocation run the inference pool, router,
# env servers, and evals process.
# env worker pools, and evals process.
if self.inference is None:
raise ValueError(
"Multi-node online evals require an [inference] block - dedicated nodes in the "
+1 -1
View File
@@ -45,7 +45,7 @@ inference = "prime_rl.entrypoints.inference:main"
trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
eval = "prime_rl.entrypoints.eval:main"
env-server = "prime_rl.entrypoints.env_server:main"
env-worker-pool = "prime_rl.entrypoints.env_worker_pool:main"
dashboard = "prime_rl.entrypoints.dashboard:main"
[project.entry-points."vllm.general_plugins"]
+4 -4
View File
@@ -5,7 +5,7 @@ description: Launch and monitor prime-rl evals — the `uv run eval` entrypoint,
# Eval
`uv run eval` evaluates a model in one or more environments and exits after one epoch per source. It reuses the orchestrator's eval pipeline: one env server per source, a concurrency band, every episode through the monitors, and a trace stream that `--resume` continues from. Online evals of training runs are the `training` skill.
`uv run eval` evaluates a model in one or more environments and exits after one epoch per source. It reuses the orchestrator's eval pipeline: one env worker pool per source, a concurrency band, every episode through the monitors, and a trace stream that `--resume` continues from. Online evals of training runs are the `training` skill.
## Start an eval
@@ -25,7 +25,7 @@ uv run eval @ eval.toml --no-monitors.prime # keep the r
- Entrypoint: `src/prime_rl/entrypoints/eval.py`; implementation `src/prime_rl/eval/eval.py`, shared engine `src/prime_rl/eval/runner.py`.
- Shorthands (single-source runs): `<taskset-id>`, `--env.<field> <value>`, `-n` `select.limit`, `-s` `select.shuffle`, `-r` `group_size`, `-m` `model`, `-c N` pins `concurrency.min_inflight = max_inflight = N`. They cannot be combined with a TOML that defines `[[source]]` blocks.
- Concurrency: an API exposes no vLLM `/metrics`, so run pinned there; against `uv run inference` set `min_inflight < max_inflight` in `[concurrency]` to adapt to KV usage.
- Env servers: spawned per source on OS-assigned ports (published to `configs/attempt_N/resolved/envs/eval/<name>.address`) unless the source sets `serve.address`.
- Env worker pools: spawned per source on OS-assigned ports (published to `configs/attempt_N/resolved/envs/eval/<name>.address`) unless the source sets `serve.address`.
- Ready-made configs: `configs/debug/eval/*.toml`, one per shape (single turn, multi turn, resume, multi env, aime2026, tb2).
Minimal multi-source TOML (the eval block is flattened to the top level; per-source `select`, `group_size`, `sampling` override the top level):
@@ -91,7 +91,7 @@ Run dir: `output_dir / run.name` (auto `<envs>--<model>--<short-id>`; `ls -t out
├── configs/latest/ # command.txt, the launch TOML, resolved/eval.json
├── logs/latest/
│ ├── eval.log # the eval process
│ └── envs/eval/{name}.log # one log per env server
│ └── envs/eval/{name}.log # one log per env worker pool
└── monitors/file/ # metrics.jsonl, the trace stream, traces/live/ (one file per live trace), plan.json
```
@@ -106,4 +106,4 @@ The progress line in `eval.log` counts live rollouts by phase (`- boot 1 · runn
Metrics live under `eval/<env>/all/<agent>/…` (`reward/mean`, `is_truncated/mean` — raise `sampling.max_completion_tokens` when high, or score cut-off runs as 0 with `env.agent.scoring.skip_on_truncated` / `skip_on_timeout` (`env.agent.max_turn_tokens` caps each response and stops the run once one hits it, even in harnesses like RLM that continue past a capped turn), `has_error/mean`, the taskset's own metrics). Validate a result by reading a few traces in the dashboard rather than trusting the mean alone.
Stop a run with SIGINT/SIGTERM to the eval PID (`ps aux | grep PRL::Eval`); `--resume` restores the landed episodes from the trace stream and runs only the rollouts still owed. Any config may be overridden on resume (`select`/`group_size` change what is owed); keep the model, sampling and env config the same to keep the landed episodes comparable. Env servers are children of the eval process and exit with it.
Stop a run with SIGINT/SIGTERM to the eval PID (`ps aux | grep PRL::Eval`); `--resume` restores the landed episodes from the trace stream and runs only the rollouts still owed. Any config may be overridden on resume (`select`/`group_size` change what is owed); keep the model, sampling and env config the same to keep the landed episodes comparable. Env worker pools are children of the eval process and exit with it.
@@ -31,7 +31,7 @@ state is not automatically copied to the remote job.
The [Model Factory RL docs](https://docs.primeintellect.ai/hosted-training/hosted-rl#launching-a-run)
describe arbitrary secrets reaching trainer, inference, orchestrator, and
env-server processes. However, the CLI 0.14.0 implementation and public CLI source
env-worker-pool processes. However, the CLI 0.14.0 implementation and public CLI source
checked on 2026-10-23 still restrict dedicated runs to `WANDB_API_KEY` and
`HF_TOKEN`. Check the installed version and
[secret collection code](https://github.com/PrimeIntellect-ai/prime/blob/main/packages/prime/src/prime_cli/commands/rl.py)
@@ -41,7 +41,7 @@ rename it as an unrelated credential, or put it in the config to bypass rejectio
`PRIME_API_KEY` is reserved by the service. The run's token is supplied by the
platform, including for Prime services such as sandbox creation. Secrets projected
into a training/env-server process do not automatically enter a child sandbox:
into a training/env-worker-pool process do not automatically enter a child sandbox:
if sandbox code itself needs a key, configure that runtime's supported secret
injection. See [sandbox secrets](https://docs.primeintellect.ai/sandboxes/secrets).
@@ -54,7 +54,7 @@ selector. Inspect the taskset config and loader if the mapping is unclear.
Verify access with the same token before reserving GPUs, without displaying
private samples. Pass `-e HF_TOKEN` to the Model Factory launch and ensure the loader uses
it. If the taskset downloads in a sandbox rather than the env server, deliver the
it. If the taskset downloads in a sandbox rather than the env worker pool, deliver the
credential there explicitly. Custom loaders/scorers must be installed remotely;
see [custom code](custom-code.md).
+5 -5
View File
@@ -108,7 +108,7 @@ grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
### Live rollouts
`{run_dir}/monitors/file/traces/live/<trace_id>.jsonl` holds the env server's streamed deltas of one live rollout (train or eval) and disappears when its episode lands in the stream, so the directory is the live set. `uv run python -m prime_rl.monitors.file.traces {run_dir}` prints one row per live trace with `stage` (pending/boot/setup/running/finalize/scoring/done/error), turns, tokens, elapsed and the latest message; with a trace id it prints the assembled trace. The dashboard's traces tab shows them in the episode table (tinted, phase badge, growing counts; filter status → in flight) and opens them in the viewer.
`{run_dir}/monitors/file/traces/live/<trace_id>.jsonl` holds the env worker pool's streamed deltas of one live rollout (train or eval) and disappears when its episode lands in the stream, so the directory is the live set. `uv run python -m prime_rl.monitors.file.traces {run_dir}` prints one row per live trace with `stage` (pending/boot/setup/running/finalize/scoring/done/error), turns, tokens, elapsed and the latest message; with a trace id it prints the assembled trace. The dashboard's traces tab shows them in the episode table (tinted, phase badge, growing counts; filter status → in flight) and opens them in the viewer.
### Metrics
@@ -157,7 +157,7 @@ All metrics print to the console log (and W&B when configured).
| orchestrator | `time/wait_for_policy` | **high → trainer is bottleneck** |
| orchestrator | `dispatcher/inflight/{train,eval}`, `dispatcher/queued/eval` | dispatcher / async state |
| orchestrator | `staleness/token/{mean,masked}`, `staleness/rollout/{mean,max}`, `staleness/rollout/{in_flight,in_queue}/{mean,max}`, `staleness/rollout/dropped` | per-step token and rollout staleness of trained rollouts (rollout = max token staleness) |
| env server | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
| env worker pool | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
The trainer warns when batch wait time exceeds active trainer time. Add inference nodes when this warning persists. The orchestrator warns when policy wait time exceeds active orchestrator time. Add trainer nodes when this warning persists. The orchestrator also warns when it discards more than half of an episode window and reports stale, errored, and no-signal counts.
@@ -238,9 +238,9 @@ All processes use `setproctitle` so they're visible in `ps`/`htop`/`pstree`:
```
PRL::Launcher
├── PRL::Inference (vLLM server, GPU 0)
├── PRL::EnvServer (ZMQ broker; one per train/eval source)
│ └── env workers (spawned Python processes, 1..N per pool)
├── PRL::Orchestrator (CPU-only; connects to each env server)
├── PRL::EnvBroker (one worker pool replica per train/eval source)
│ └── PRL::EnvWorker (spawned processes, 1..N per pool; execute episodes)
├── PRL::Orchestrator (CPU-only; connects to each env worker pool)
├── torchrun
│ └── PRL::Trainer (GPU 1+)
└── tail trainer.log
+1 -1
View File
@@ -1786,7 +1786,7 @@ _live_folds = LiveFolds()
@app.get("/api/runs/{run}/live")
def live_traces(run: str, etag: str | None = None) -> dict:
"""The run's in-flight traces, folded from the env servers' streamed deltas
"""The run's in-flight traces, folded from the env worker pools' streamed deltas
(``monitors/file/traces/live/<trace_id>.jsonl``): one row per live trace with its
phase, turns, tokens, cost, elapsed time and last message. A trace whose file is
gone has finished and sits in the stream. ``etag`` is the fingerprint the client
+4 -4
View File
@@ -2654,7 +2654,7 @@ const BASE_LOG_PANES = [
{ comp: "envs", title: "all envs", match: (f) => f.component.startsWith("env:"), merged: true },
];
/* the panes this run can show: the fixed components plus one pane per env server
/* the panes this run can show: the fixed components plus one pane per env worker pool
(`env:<name>`), so a single env's log can be read on its own; "all envs" merges
them all and is the default, the per-env panes are opted into */
function logPanes() {
@@ -3309,7 +3309,7 @@ function episodeRowHtml(ep) {
</tr>`;
}
/* a live rollout, streamed by its env server: the same columns, a pulsing dot for
/* a live rollout, streamed by its env worker pool: the same columns, a pulsing dot for
its number, no arrival yet, counts that grow with every turn, no reward yet */
function liveRowHtml(r) {
return `<tr class="live stage-${esc(r.stage)}${r.landedAt ? " landing" : ""}" ${r.trace && !r.landedAt ? `data-live="${esc(r.trace)}"` : ""} title="${esc(r.task ?? "")}${r.last ? ` — ${esc(r.last)}` : ""}">
@@ -3356,7 +3356,7 @@ function renderEpisodeRows(reset = false) {
episodeRowH = 0;
}
if (!rows.length) {
if (!state.filter.status.done) showTraceEmpty("no live rollouts", "rollouts show here while their env servers stream them");
if (!state.filter.status.done) showTraceEmpty("no live rollouts", "rollouts show here while their env worker pools stream them");
else if (traceFiltered()) showTraceEmpty("no episodes", "nothing matches the current filters");
else showTraceEmpty("no traces yet");
return;
@@ -3378,7 +3378,7 @@ async function initTraces() {
/* ------------------------------------------------------------ live traces */
/* the env servers stream every live rollout turn by turn; the run's file
/* the env worker pools stream every live rollout turn by turn; the run's file
monitor keeps one file of deltas per live trace and drops it when the episode
lands in the stream, so this table is exactly what is running right now */
let liveInflight = false;
+1 -1
View File
@@ -273,7 +273,7 @@
<div class="dd-sec">filter</div>
<div class="dd-row flt-status-row"><span class="t-label">status</span>
<div class="seg toggle-seg flt-status">
<button data-status="live" class="on" title="live rollouts, streamed by their env servers">live</button>
<button data-status="live" class="on" title="live rollouts, streamed by their env worker pools">live</button>
<button data-status="done" class="on" title="episodes in the finished stream">completed</button>
</div>
</div>
@@ -7,27 +7,25 @@ from pathlib import Path
from verifiers.v1.runtimes import set_base_sandbox_labels
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.env import serve_env, set_episode_hook
from prime_rl.orchestrator.utils import setup_env_server_logging
from prime_rl.configs.env_worker_pool import EnvWorkerPoolConfig
from prime_rl.env import run_env_worker_pool, set_episode_hook
from prime_rl.orchestrator.utils import setup_env_worker_pool_logging
from prime_rl.transports.payload import PayloadHook
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.utils import clean_exit
def setup_worker(
log_level: str | None, json_logging: bool, sandbox_labels: list[str], bind_address: str | None
) -> None:
setup_env_server_logging(log_level, json_logging)
setup_env_worker_pool_logging(log_level, json_logging)
set_base_sandbox_labels(sandbox_labels)
# Episode streams never carry training arrays; the hook keeps them for the trainer.
set_episode_hook(PayloadHook(bind_address))
def publish_address(addresses: queue.SimpleQueue, path: Path) -> None:
"""Write the bound address once serve_env reports it (it blocks in the server loop
afterwards). Atomic, so a waiting client never reads a partial line."""
"""Publish the broker's bound address atomically for waiting clients."""
address = addresses.get()
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".address.tmp")
@@ -36,16 +34,15 @@ def publish_address(addresses: queue.SimpleQueue, path: Path) -> None:
@clean_exit
def run_server(config: EnvServerConfig):
def run_pool(config: EnvWorkerPoolConfig):
run_name = os.environ.get("PRL_RUN_NAME")
sandbox_labels = [run_name] if run_name else []
addresses: queue.SimpleQueue | None = None
if config.address_file is not None:
addresses = queue.SimpleQueue()
threading.Thread(target=publish_address, args=(addresses, config.address_file), daemon=True).start()
# ``serve.pool`` (static or elastic) sizes the server. serve_env applies the worker
# setup in this process and in every spawned worker.
serve_env(
# Apply logging, sandbox labels, and the payload hook in the broker and every worker.
run_env_worker_pool(
pool=config.serve.pool,
address=config.serve.address or "tcp://127.0.0.1:0",
address_queue=addresses,
@@ -62,13 +59,12 @@ def run_server(config: EnvServerConfig):
def main():
"""Main entry-point for the env server. Run using `uv run env-server`"""
set_proc_title("EnvServer")
"""Main entry-point for the env worker pool. Run using `uv run env-worker-pool`"""
# verifiers keys run-scoped state (creation limiters) by $VF_RUN_ID. Every launcher,
# the Python entrypoints and the SLURM templates alike, hands env servers $PRL_RUN_ID;
# a standalone server is a run of its own.
# the Python entrypoints and the SLURM templates alike, hands env worker pools $PRL_RUN_ID;
# a standalone pool is a run of its own.
os.environ.setdefault("VF_RUN_ID", os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex)
run_server(cli(EnvServerConfig))
run_pool(cli(EnvWorkerPoolConfig))
if __name__ == "__main__":
+15 -15
View File
@@ -127,11 +127,11 @@ def main():
format_log_message,
prepare_attempt_dirs,
prepare_run,
write_env_server_config,
write_env_worker_pool_config,
write_launch_artifacts,
)
# The run identity is stamped on every episode and inherited by the env servers.
# The run identity is stamped on every episode and inherited by the env worker pools.
prepare_run(config)
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
@@ -143,16 +143,16 @@ def main():
write_launch_artifacts(config_dir, "eval")
(config_dir / "eval.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
components: list[tuple[str, Path | str]] = [("Eval", config_dir / "eval.json")]
# One env server per source without an explicit `serve.address`, like the rl launcher's:
# `env-server @ <path>` binds an OS-assigned port and publishes it to the source's
# One env worker pool per source without an explicit `serve.address`, like the rl launcher's:
# `env-worker-pool @ <path>` binds an OS-assigned port and publishes it to the source's
# address file, where the eval picks it up.
env_servers = [source for source in config.source if source.serve.address is None]
env_names = [source.resolved_name for source in env_servers]
if env_servers:
env_worker_pools = [source for source in config.source if source.serve.address is None]
env_names = [source.resolved_name for source in env_worker_pools]
if env_worker_pools:
components.append(("Envs", f"{config_dir}/envs/eval/*.json"))
for source in env_servers:
for source in env_worker_pools:
components.append(
(f" {source.resolved_name}", write_env_server_config(config_dir, "eval", source, config.log))
(f" {source.resolved_name}", write_env_worker_pool_config(config_dir, "eval", source, config.log))
)
if config.dry_run:
logger.info(f"Configs:\n{format_config_message(config_dir, 'eval', components)}")
@@ -163,15 +163,15 @@ def main():
from prime_rl.eval.eval import run_eval
processes: list[Popen] = []
for source in env_servers:
for source in env_worker_pools:
name = source.resolved_name
logger.info(f"Starting {name} server")
env_server_log = log_dir / "envs" / "eval" / f"{name}.log"
env_server_log.parent.mkdir(parents=True, exist_ok=True)
with open(env_server_log, "w") as log_file_handle:
logger.info(f"Starting {name} env worker pool")
env_worker_pool_log = log_dir / "envs" / "eval" / f"{name}.log"
env_worker_pool_log.parent.mkdir(parents=True, exist_ok=True)
with open(env_worker_pool_log, "w") as log_file_handle:
processes.append(
Popen(
["env-server", "@", (config_dir / "envs" / "eval" / f"{name}.json").as_posix()],
["env-worker-pool", "@", (config_dir / "envs" / "eval" / f"{name}.json").as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS},
stdout=log_file_handle,
stderr=log_file_handle,
+16 -16
View File
@@ -23,7 +23,7 @@ from prime_rl.utils.pathing import (
prepare_attempt_dirs,
prepare_run,
resolve_latest_ckpt_step,
write_env_server_config,
write_env_worker_pool_config,
write_launch_artifacts,
)
from prime_rl.utils.process import (
@@ -43,7 +43,7 @@ ONLINE_EVAL_CONFIG = "eval.json"
ENVS_DIR = "envs"
def eval_env_servers(config: SupervisedTrainerConfig) -> list[OnlineEvalSourceConfig]:
def eval_env_worker_pools(config: SupervisedTrainerConfig) -> list[OnlineEvalSourceConfig]:
"""Every launcher-managed eval source. A source with ``serve.address`` set is
externally managed — the launcher neither writes its config nor spawns a server for it."""
if config.eval is None:
@@ -68,7 +68,7 @@ def resolve_resume_step(config: SupervisedTrainerConfig) -> int | None:
def build_online_eval_config(config: SupervisedTrainerConfig) -> SFTOnlineEvalConfig:
"""The online-eval process's config: the resolved ``[eval]`` block with the run-level
fields filled from the SFT config. The launcher spawns the env servers itself; the
fields filled from the SFT config. The launcher spawns the env worker pools itself; the
online-eval process finds each one through the address it publishes in the shared
config attempt."""
assert config.eval is not None
@@ -95,7 +95,7 @@ def config_components(
config: SupervisedTrainerConfig, config_dir: Path, entrypoint: str
) -> list[tuple[str, Path | str]]:
"""The resolved configs a launch leaves in ``config_dir``: the entrypoint's config and, with
online evals, the inference, online-eval and env-server configs."""
online evals, the inference, online-eval and env-worker-pool configs."""
components: list[tuple[str, Path | str]] = [(entrypoint, config_dir / f"{entrypoint}.json")]
if config.deployment.type == "multi_node":
components.append(("Trainer", config_dir / TRAINER_CONFIG))
@@ -103,7 +103,7 @@ def config_components(
if config.inference is not None:
components.append(("Inference", config_dir / INFERENCE_CONFIG))
components.append(("Eval", config_dir / ONLINE_EVAL_CONFIG))
if eval_env_servers(config):
if eval_env_worker_pools(config):
components.append(("Envs", f"{config_dir}/{ENVS_DIR}/eval/*.json"))
return components
@@ -116,7 +116,7 @@ def write_config(config: SupervisedTrainerConfig, config_path: Path, exclude: se
def write_eval_subconfigs(config: SupervisedTrainerConfig, config_dir: Path, strip_router: bool = False) -> None:
"""Write the inference, online-eval, and env-server configs for online evals."""
"""Write the inference, online-eval, and env-worker-pool configs for online evals."""
config_dir.mkdir(parents=True, exist_ok=True)
if config.inference is not None:
@@ -132,11 +132,11 @@ def write_eval_subconfigs(config: SupervisedTrainerConfig, config_dir: Path, str
with open(config_dir / ONLINE_EVAL_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_online_eval_config(config)), f, indent=2)
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>` binds an
# One EnvWorkerPoolConfig per launcher-managed eval source: `env-worker-pool @ <path>` binds an
# OS-assigned port and publishes it to the source's address file, where the
# online-eval process picks it up.
for source in eval_env_servers(config):
write_env_server_config(config_dir, "eval", source, config.log)
for source in eval_env_worker_pools(config):
write_env_worker_pool_config(config_dir, "eval", source, config.log)
def write_slurm_script(
@@ -205,7 +205,7 @@ def write_slurm_script(
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
},
"eval_env_names": [source.resolved_name for source in eval_env_servers(config)],
"eval_env_names": [source.resolved_name for source in eval_env_worker_pools(config)],
}
script = template.render(
**config.slurm.template_vars,
@@ -295,7 +295,7 @@ def launch_slurm(config: SupervisedTrainerConfig, entrypoint: str):
num_train_nodes=num_nodes,
eval=online_eval,
inference=online_eval,
env_names={"eval": [source.resolved_name for source in eval_env_servers(config)]} if online_eval else None,
env_names={"eval": [source.resolved_name for source in eval_env_worker_pools(config)]} if online_eval else None,
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
)
@@ -342,7 +342,7 @@ def launch_local(config: SupervisedTrainerConfig, entrypoint: str):
trainer=True,
eval=config.eval is not None,
inference=config.inference is not None,
env_names={"eval": [source.resolved_name for source in eval_env_servers(config)]},
env_names={"eval": [source.resolved_name for source in eval_env_worker_pools(config)]},
)
)
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
@@ -389,14 +389,14 @@ def launch_local(config: SupervisedTrainerConfig, entrypoint: str):
log_path=log_dir / "inference.log",
)
# Start one env server per eval source. The online-eval process waits for each
# Start one env worker pool per eval source. The online-eval process waits for each
# server's published address and polls until it answers.
for source in eval_env_servers(config):
for source in eval_env_worker_pools(config):
name = source.resolved_name
logger.info(f"Starting {name} server")
logger.info(f"Starting {name} env worker pool")
processes.start(
f"env/eval/{name}",
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
["env-worker-pool", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars},
log_path=log_dir / ENVS_DIR / "eval" / f"{name}.log",
)
+26 -26
View File
@@ -27,7 +27,7 @@ from prime_rl.utils.pathing import (
prepare_attempt_dirs,
prepare_run,
resolve_latest_ckpt_step,
write_env_server_config,
write_env_worker_pool_config,
write_launch_artifacts,
)
from prime_rl.utils.process import (
@@ -54,18 +54,18 @@ MODELEXPRESS_BIN_DIR = Path(__file__).resolve().parents[3] / "third_party" / "mo
MODELEXPRESS_READY_TIMEOUT_S = 120
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig]]:
def env_worker_pools(config: RLConfig) -> list[tuple[str, EnvConfig]]:
"""``(split, source)`` for every launcher-managed train/eval source. The launcher
runs one env server per source; each binds an OS-assigned port and publishes it to
runs one env worker pool per source; each binds an OS-assigned port and publishes it to
its address file, where the orchestrator picks it up. A source with ``serve.address``
set is externally managed — its server runs elsewhere and only the orchestrator
connects to it — so the launcher neither writes its TOML nor spawns a server for it."""
set is externally managed — its pool runs elsewhere and only the orchestrator
connects to it — so the launcher neither writes its TOML nor starts a pool for it."""
return [(split, source) for split, source in config.orchestrator.env_sources if source.serve.address is None]
def env_server_names(config: RLConfig, split: str) -> list[str]:
"""Names of the launcher-managed env servers for one split."""
return [source.resolved_name for source_split, source in env_servers(config) if source_split == split]
def env_worker_pool_names(config: RLConfig, split: str) -> list[str]:
"""Names of the launcher-managed env worker pools for one split."""
return [source.resolved_name for source_split, source in env_worker_pools(config) if source_split == split]
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | dict[str, Any] | None = None) -> None:
@@ -83,7 +83,7 @@ def rl_config_components(config: RLConfig, config_dir: Path) -> list[tuple[str,
]
if config.inference is not None:
components.append(("Inference", config_dir / INFERENCE_CONFIG))
if env_servers(config):
if env_worker_pools(config):
components.append(("Envs", f"{config_dir}/{ENVS_DIR}/*/*.json"))
return components
@@ -167,11 +167,11 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
if config.inference is not None:
write_pd_configs(config.inference, output_dir)
# One EnvServerConfig per launcher-managed source: `env-server @ <path>` binds an
# One EnvWorkerPoolConfig per launcher-managed source: `env-worker-pool @ <path>` binds an
# OS-assigned port and publishes it to the source's address file, where the
# orchestrator picks it up.
for split, source in env_servers(config):
write_env_server_config(output_dir, split, source, config.orchestrator.log)
for split, source in env_worker_pools(config):
write_env_worker_pool_config(output_dir, split, source, config.orchestrator.log)
def rl_local(config: RLConfig):
@@ -197,7 +197,7 @@ def rl_local(config: RLConfig):
trainer=True,
orchestrator=True,
inference=config.inference is not None,
env_names={split: env_server_names(config, split) for split in ("train", "eval")},
env_names={split: env_worker_pool_names(config, split) for split in ("train", "eval")},
)
)
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
@@ -273,15 +273,15 @@ def rl_local(config: RLConfig):
"otherwise rollouts will hang."
)
# Start one env server per source. The orchestrator waits for each server's
# published address and polls until it answers, so the servers and the
# Start one env worker pool per source. The orchestrator waits for each broker's
# published address and polls until it answers, so the pools and the
# orchestrator start in parallel.
for split, source in env_servers(config):
for split, source in env_worker_pools(config):
name = source.resolved_name
logger.info(f"Starting {name} server")
logger.info(f"Starting {name} env worker pool")
processes.start(
f"{split} env server {name}",
["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()],
f"{split} env worker pool {name}",
["env-worker-pool", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars, **config.orchestrator.env_vars},
log_path=log_dir / ENVS_DIR / split / f"{name}.log",
)
@@ -368,9 +368,9 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
else {}
)
# Env servers launch on every inference node, one replica per launcher-managed train/eval source.
train_env_names = env_server_names(config, "train")
eval_env_names = env_server_names(config, "eval")
# Env worker pools launch on every inference node, one replica per launcher-managed train/eval source.
train_env_names = env_worker_pool_names(config, "train")
eval_env_names = env_worker_pool_names(config, "eval")
# NIXL and ModelExpress weight broadcasts both rendezvous through a ModelExpress server.
mx_broadcast = (
@@ -511,8 +511,8 @@ def rl_slurm(config: RLConfig):
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean"})
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', [('RL', config_dir / RL_CONFIG)])}")
train_env_names = env_server_names(config, "train")
eval_env_names = env_server_names(config, "eval")
train_env_names = env_worker_pool_names(config, "train")
eval_env_names = env_worker_pool_names(config, "eval")
log_message = format_log_message(
log_dir=log_dir,
@@ -529,8 +529,8 @@ def rl_slurm(config: RLConfig):
components = [("RL", config_dir / RL_CONFIG), *rl_config_components(config, config_dir)]
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', components)}")
train_env_names = env_server_names(config, "train")
eval_env_names = env_server_names(config, "eval")
train_env_names = env_worker_pool_names(config, "train")
eval_env_names = env_worker_pool_names(config, "eval")
has_infer = config.deployment.infer_nodes_per_replica > 0
log_message = format_log_message(
+3 -3
View File
@@ -1,6 +1,6 @@
from prime_rl.env.client import EnvClient
from prime_rl.env.delta import EpisodeAssembly
from prime_rl.env.pool import serve_env
from prime_rl.env.server import set_episode_hook
from prime_rl.env.pool import run_env_worker_pool
from prime_rl.env.worker import set_episode_hook
__all__ = ["EnvClient", "EpisodeAssembly", "serve_env", "set_episode_hook"]
__all__ = ["EnvClient", "EpisodeAssembly", "run_env_worker_pool", "set_episode_hook"]
+15 -15
View File
@@ -1,4 +1,4 @@
"""ZMQ client for the env server.
"""ZMQ client for the env worker pool.
A DEALER socket + msgpack, with a single receive loop matching replies to
per-request futures by `request_id` and routing a run's `delta` frames to its
@@ -87,7 +87,7 @@ class EnvClient:
async def _receive_loop(self) -> None:
# The one receiver serves every in-flight request. Awaiting each frame would
# cost a loop turn per delta, which a busy loop turns into a hard cap on how
# fast a server's stream drains; so each wakeup takes everything queued.
# fast a pool's stream drains; so each wakeup takes everything queued.
while True:
try:
batch = [await self.socket.recv_multipart(copy=False)]
@@ -119,13 +119,13 @@ class EnvClient:
if len(frames) != 3:
raise ValueError(
f"expected [request_id, kind, data], got {len(frames)} frames - "
"is the env server speaking the same serve protocol?"
"is the env worker pool speaking the same serve protocol?"
)
request_id_frame, kind_frame, data_frame = frames
request_id = request_id_frame.bytes.decode()
kind = kind_frame.bytes
except Exception: # keep receiving for the other requests
get_logger().opt(exception=True).warning("Dropped malformed env server frame")
get_logger().opt(exception=True).warning("Dropped malformed env worker pool frame")
continue
if kind != b"delta":
routed.append((request_id, data_frame, None))
@@ -145,7 +145,7 @@ class EnvClient:
continue
delta = next(decoded)
if isinstance(delta, Exception):
get_logger().opt(exception=delta).warning("Dropped malformed env server frame")
get_logger().opt(exception=delta).warning("Dropped malformed env worker pool frame")
continue
# Cancellation may remove the handler while the worker decodes.
if self._deltas.get(request_id) is not on_delta:
@@ -153,7 +153,7 @@ class EnvClient:
try:
on_delta(delta)
except Exception: # keep receiving for the other requests
get_logger().opt(exception=True).warning("Dropped malformed env server frame")
get_logger().opt(exception=True).warning("Dropped malformed env worker pool frame")
async def _request(
self,
@@ -188,7 +188,7 @@ class EnvClient:
self._deltas.pop(request_id, None)
response = response_type.model_validate(unpack(data))
if not response.success:
raise RuntimeError(response.error or "env server request failed")
raise RuntimeError(response.error or "env worker pool request failed")
return response
async def _decode(self, decode: Callable[..., DecodedT], *args: object) -> DecodedT:
@@ -206,7 +206,7 @@ class EnvClient:
raise
def _cancel_run(self, run_request_id: str) -> None:
"""Fire-and-forget: tell the server the caller abandoned the run, so it aborts
"""Fire-and-forget: tell the pool the caller abandoned the run, so it aborts
the rollout (or frees what it kept for an episode already sent). A task on the
loop outlives the cancelled caller."""
task = asyncio.get_running_loop().create_task(self._send_cancel(run_request_id))
@@ -214,7 +214,7 @@ class EnvClient:
task.add_done_callback(self._cancel_tasks.discard)
async def _send_cancel(self, run_request_id: str) -> None:
"""Best-effort server-side abort of an abandoned run."""
"""Best-effort worker-side abort of an abandoned run."""
with contextlib.suppress(Exception):
payload = msgpack.packb(
CancelRequest(request_id=run_request_id).model_dump(mode="json"),
@@ -228,14 +228,14 @@ class EnvClient:
except TimeoutError:
return False
async def wait_for_server_startup(self, timeout: float = 120.0, interval: float = 1.0) -> None:
"""Poll `health` until the server answers or `timeout` elapses."""
async def wait_for_pool_startup(self, timeout: float = 120.0, interval: float = 1.0) -> None:
"""Poll `health` until the broker answers or `timeout` elapses."""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if await self.health(timeout=min(interval, 2.0)):
return
await asyncio.sleep(interval)
raise TimeoutError(f"env server at {self.address} did not become healthy in {timeout}s")
raise TimeoutError(f"env worker pool at {self.address} did not become healthy in {timeout}s")
async def run(
self,
@@ -246,7 +246,7 @@ class EnvClient:
on_delta: Callable[[dict], None] | None = None,
) -> WireEpisode:
"""Run one rollout; return its episode record — flat traces (typed
`Trace[WireTaskData]`) plus the shared stamp. The server takes the task
`Trace[WireTaskData]`) plus the shared stamp. The worker takes the task
itself (`task_data`, its dumped `TaskData`). The traces stream in as the
rollout runs, one delta per turn or phase change (`env.delta`); `on_delta`
sees each as it lands, so a caller can relay or persist the stream. The
@@ -277,7 +277,7 @@ class EnvClient:
assembly.finish(response.head, response.traces),
)
except BaseException:
# The reply already arrived, so the server counts the episode delivered;
# The reply already arrived, so the worker counts the episode delivered;
# tell it this caller never got the episode.
self._cancel_run(request_id)
raise
@@ -289,7 +289,7 @@ class EnvClient:
await self._receiver
self._receiver = None
# Let scheduled fire-and-forget cancels reach the socket first, or a
# run cancelled right before close() leaves its server-side rollout
# run cancelled right before close() leaves its worker-side rollout
# running. Pop before awaiting: awaiting finished tasks never yields
# (since CPython 3.12 a gather of them completes eagerly), so their
# queued `discard` callbacks cannot be what empties the set
+2 -2
View File
@@ -280,7 +280,7 @@ class EpisodeAssembly:
def finish(self, head: dict, summaries: list[TraceSummary]) -> dict:
"""The full episode record: `head` (the episode without its traces) joined with
the assembled traces in the server's order. A count mismatch means a delta was
the assembled traces in the worker's order. A count mismatch means a delta was
lost, which the wire never does in a live connection — fail loudly."""
traces = []
for summary in summaries:
@@ -291,7 +291,7 @@ class EpisodeAssembly:
if len(trace["nodes"]) != summary.nodes or len(trace["calls"]) != summary.calls:
raise RuntimeError(
f"served trace {summary.id} assembled {len(trace['nodes'])} nodes / "
f"{len(trace['calls'])} calls, server reports {summary.nodes} / {summary.calls}"
f"{len(trace['calls'])} calls, worker reports {summary.nodes} / {summary.calls}"
)
traces.append(trace)
return {**head, "traces": traces}
+30 -28
View File
@@ -1,12 +1,11 @@
"""Env-server worker pool: a ROUTER broker over N worker processes.
"""Env worker pool: a ROUTER broker over N worker processes.
A lone `EnvServer` runs every rollout as an `asyncio.Task` on one event loop, so
A lone `EnvWorker` runs every rollout as an `asyncio.Task` on one event loop, so
CPU-bound work (renderer tokenization, scoring) competes for that loop; the pool
spreads that work across processes.
A broker binds the client-facing ROUTER (the *same* wire protocol as an `EnvServer`,
so `EnvClient` speaks to either), starts one worker process and scales up to
`max_workers` on demand — each an ordinary `EnvServer` bound to its own ipc address —
A broker binds the client-facing ROUTER, starts one worker process and scales up to
`max_workers` on demand — each an ordinary `EnvWorker` bound to its own ipc address —
load-balancing requests to the least-busy worker over a `DEALER` per worker. The
worker's `client_id` (its reply identity) is the broker's DEALER identity; the broker
holds the real client identity in `pending` and routes the reply back by `request_id`.
@@ -34,23 +33,24 @@ import zmq
import zmq.asyncio
from verifiers.v1.utils.loaders import resolve_env_config
from prime_rl.configs.env_server import ElasticPoolConfig, PoolConfig, StaticPoolConfig
from prime_rl.env.server import LATE_CANCEL_SECONDS, EnvServer
from prime_rl.configs.env_worker_pool import ElasticPoolConfig, PoolConfig, StaticPoolConfig
from prime_rl.env.types import CancelResponse, HealthResponse
from prime_rl.env.worker import LATE_CANCEL_SECONDS, EnvWorker
from prime_rl.utils.logger import get_logger
from prime_rl.utils.process import set_proc_title
_HEALTH = msgpack.packb(HealthResponse().model_dump(mode="json"), use_bin_type=True)
_CANCEL_MISS = msgpack.packb(CancelResponse(cancelled=False).model_dump(mode="json"), use_bin_type=True)
def _arm_teardown(death_pipe=None) -> None:
"""Arm a process (the serve_env broker, or a pool worker) for clean
"""Arm a broker or worker process for clean
teardown: it inherits no signal handlers, so by default SIGTERM kills it abruptly, skipping
asyncio.run()'s serving() cleanup and orphaning host tunnels (and sandboxes).
- SIGTERM -> KeyboardInterrupt so the event loop runs its finallys (serve_env swallows it);
- with `death_pipe`, self-SIGTERM when the parent dies (pipe EOF, even on its SIGKILL) so no
child is orphaned (main -> serve_env and broker -> worker are both armed this way)."""
- SIGTERM -> KeyboardInterrupt so the event loop runs its finallys (run_env_worker_pool swallows it);
- with `death_pipe`, a worker self-SIGTERMs when the broker dies (pipe EOF, even on
SIGKILL) so the worker is not orphaned."""
def on_sigterm(*_) -> None:
signal.signal(signal.SIGTERM, signal.SIG_IGN)
@@ -68,8 +68,8 @@ def _arm_teardown(death_pipe=None) -> None:
threading.Thread(target=_watch, daemon=True).start()
class EnvServerPool:
"""ROUTER broker that elastically scales worker processes (least-busy dispatch).
class EnvWorkerPool:
"""One source's pool replica: a ROUTER broker with least-busy worker dispatch.
An elastic pool starts with a single worker and spawns another whenever in-flight
requests reach 90% of current capacity (`workers * multiplex`), up to `max_workers`.
@@ -112,7 +112,7 @@ class EnvServerPool:
address = f"ipc://{self._worker_path(i)}"
parent_conn, child_conn = self._mpctx.Pipe()
proc = self._mpctx.Process(
target=serve_worker,
target=run_env_worker,
kwargs=dict(
address=address,
config_data=self.config_data,
@@ -150,7 +150,7 @@ class EnvServerPool:
if in_flight >= 0.9 * len(self.workers) * self.pool.multiplex:
self._spawn_worker()
get_logger().info(
f"Grew env server pool to {len(self.workers)} worker(s) max_workers={self._cap_str} in_flight={in_flight}"
f"Grew env worker pool to {len(self.workers)} worker(s) max_workers={self._cap_str} in_flight={in_flight}"
)
@property
@@ -174,7 +174,7 @@ class EnvServerPool:
else f"num_workers={self.max_workers}"
)
get_logger().info(
f"Started env server pool address={self.address} pool={self.pool.type} workers={len(self.workers)} {sizing}"
f"Started env worker pool address={self.address} pool={self.pool.type} workers={len(self.workers)} {sizing}"
)
try:
in_flight = 0
@@ -295,10 +295,10 @@ class EnvServerPool:
os.rmdir(self._ipc_dir)
self.frontend.close()
self.ctx.term()
get_logger().info(f"Stopped env server pool address={self.address}")
get_logger().info(f"Stopped env worker pool address={self.address}")
def serve_worker(
def run_env_worker(
*,
address: str,
config_data: dict,
@@ -306,21 +306,22 @@ def serve_worker(
death_pipe,
worker_setup: Callable[[], None] | None,
) -> None:
"""A pool worker process: one `EnvServer` on its ipc address. It self-terminates if
"""A pool worker process: one `EnvWorker` on its ipc address. It self-terminates if
the broker dies — see `_arm_teardown`."""
set_proc_title("EnvWorker")
_arm_teardown(death_pipe)
if worker_setup is not None:
worker_setup()
try:
asyncio.run(EnvServer(resolve_env_config(config_data), address, max_concurrent).run())
asyncio.run(EnvWorker(resolve_env_config(config_data), address, max_concurrent).run())
except KeyboardInterrupt:
pass
except Exception:
get_logger().opt(exception=True).error("Failed to run env server worker")
get_logger().opt(exception=True).error("Failed to run env worker")
raise
def serve_env(
def run_env_worker_pool(
*,
pool: PoolConfig,
address: str,
@@ -329,26 +330,27 @@ def serve_env(
address_queue=None,
worker_setup: Callable[[], None] | None = None,
) -> None:
"""Serve one env over ZMQ: an `EnvServerPool` broker over worker processes. Reports
"""Run one source's pool replica: a ZMQ broker over env worker processes. Reports
the bound address on `address_queue` (for a spawner that passed an OS-assigned `:0`).
`config_data` is the env config as plain data (`model_dump(mode="json")`), since a
dynamically-narrowed config type can't be pickled into spawned workers.
`worker_setup` (a picklable callable) runs in this process and every spawned worker —
without it a spawned server inherits no log handlers and its logs are silently dropped."""
without it a spawned worker inherits no log handlers and its logs are silently dropped."""
# Graceful SIGTERM (run asyncio teardown). The re-raised KeyboardInterrupt is swallowed
# below for a clean exit (no spurious traceback).
set_proc_title("EnvBroker")
_arm_teardown()
if worker_setup is not None:
worker_setup()
try:
server = EnvServerPool(pool, address, config_data, max_concurrent, worker_setup)
broker = EnvWorkerPool(pool, address, config_data, max_concurrent, worker_setup)
if address_queue is not None:
address_queue.put(server.address)
asyncio.run(server.run())
address_queue.put(broker.address)
asyncio.run(broker.run())
except KeyboardInterrupt:
pass
except Exception:
get_logger().opt(exception=True).error("Failed to run env server pool")
get_logger().opt(exception=True).error("Failed to run env worker pool")
raise
+1 -1
View File
@@ -41,7 +41,7 @@ class CancelResponse(BaseResponse):
class RunRequest(BaseRequest):
"""One env-rollout, shipping the task itself: `task_data` is the dumped
`TaskData` the server validates into the taskset's declared type."""
`TaskData` the worker validates into the taskset's declared type."""
method: ClassVar[str] = "run"
task_data: dict
+6 -4
View File
@@ -86,7 +86,9 @@ class _Keeping:
self.hook.discard(self.episode)
class EnvServer:
class EnvWorker:
"""Execute episodes through one Verifiers env and stream their traces over ZMQ."""
def __init__(
self,
config: EnvConfig,
@@ -130,7 +132,7 @@ class EnvServer:
"""Rebuild a request's task from its wire data: validate into the taskset's
declared `TaskData` type and wrap it in the declared `Task` with the config's
task subtree — the same construction the taskset's own `load()` performs. The
client owns the taskset; this server never `load()`s data, so pool workers
client owns the taskset; this worker never `load()`s data, so pool workers
don't each pull the dataset."""
data = self.data_cls.model_validate(task_data)
return self.task_cls(data, self.env.config.taskset.task)
@@ -243,7 +245,7 @@ class EnvServer:
del self._delivered[request_id]
async def run(self) -> None:
get_logger().info(f"Started env server taskset={self.taskset_id} address={self.address}")
get_logger().info(f"Started env worker taskset={self.taskset_id} address={self.address}")
poller = zmq.asyncio.Poller()
poller.register(self.frontend, zmq.POLLIN)
tasks: set[asyncio.Task] = set()
@@ -275,4 +277,4 @@ class EnvServer:
task.cancel()
self.frontend.close()
self.ctx.term()
get_logger().info(f"Stopped env server taskset={self.taskset_id} address={self.address}")
get_logger().info(f"Stopped env worker taskset={self.taskset_id} address={self.address}")
+2 -2
View File
@@ -7,7 +7,7 @@ admits episodes under the adaptive ``ConcurrencyController``, fed by the
measurements and are never cancelled on load - a controller cut only blocks admission
until the pool drains.
Env servers belong to the launcher (``eval``, ``sft``), like the orchestrator's belong to
Env worker pools belong to the launcher (``eval``, ``sft``), like the orchestrator's belong to
``rl``: a source without an explicit ``serve.address`` is found through the address file
its server publishes; one with an address is reached directly."""
@@ -77,7 +77,7 @@ class EvalRunner:
# The heartbeat is beaten only by landed episodes — the first episode is its
# first beat. No startup ping on purpose: the run-start to first-episode gap
# (pool boot, env servers, the first episode's full duration) would otherwise
# (pool boot, env worker pools, the first episode's full duration) would otherwise
# sit inside the ping stream as an abnormally long silence and flip a healthy
# run stale. Until then the heartbeat has simply never been pinged.
if config.heartbeat is not None:
+1 -1
View File
@@ -58,7 +58,7 @@ class Monitor(ABC):
Monitors that only carry scalars ignore them."""
async def log_live(self, events: list[dict[str, Any]]) -> None:
"""Log the env servers' stream of in-flight traces: ``{"delta", "dispatch"}`` for
"""Log the env worker pools' stream of in-flight traces: ``{"delta", "dispatch"}`` for
each delta as it arrived, ``{"done": trace_id}`` when a trace's episode finished.
Monitors that only carry finished work ignore it."""
+1 -1
View File
@@ -1,6 +1,6 @@
"""Live traces: the in-flight rollouts, one file of deltas per trace.
Env servers stream every rollout as it happens (``prime_rl.env.delta``): the
Env worker pools stream every rollout as it happens (``prime_rl.env.delta``): the
trace's header when it is minted, then each committed turn and each phase change. The
file monitor appends those deltas to ``traces/live/<trace_id>.jsonl`` — the first line
also carries the ``dispatch`` identity (kind, env, group, task, step) — and deletes the
+1 -1
View File
@@ -290,7 +290,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
def _has_routing(sample: MicroBatch) -> bool:
"""Whether the sample's arrays, kept by an env server, include routing rows."""
"""Whether the sample's arrays, kept by an env worker, include routing rows."""
return any(payload is not None and "routed_experts" in payload.fields for payload in sample.payloads or [])
+2 -2
View File
@@ -1,7 +1,7 @@
"""Dispatcher: schedules rollouts under a shared permit counter.
- Capacity (``max_inflight``) is shared across train + eval. One permit is
one episode: one ``run`` request against an env server. The cap is dynamic —
one episode: one ``run`` request against an env worker pool. The cap is dynamic —
the concurrency controller moves it via ``set_limit``; refills are
burst-capped so a raised (or drained) cap never lands all its prefills at
once.
@@ -583,7 +583,7 @@ class Dispatcher:
return True
def _release_episodes(self, episodes: Iterable[vf.WireEpisode]) -> None:
"""Delete the training arrays env servers kept for episodes no sink will see."""
"""Delete the training arrays env workers kept for episodes no sink will see."""
delete_payloads(url for episode in episodes for trace in episode.traces for url in trace_payload_urls(trace))
async def _cancel_claimed(self, tasks: list[asyncio.Task]) -> None:
+26 -31
View File
@@ -1,19 +1,15 @@
"""Env wrappers over a v1 env server.
"""Clients for each source's env worker pool replicas.
Each ``Env`` holds an ``EnvClient`` onto each replica of its source's env server
(``OrchestratorConfig.env_server_replicas``; multi-node runs start one per inference
node) and routes each run to the least loaded one. A source's own ``serve.address``
names a single external server (``OrchestratorConfig.env_addresses``); otherwise each
launcher-managed replica publishes the address it bound, and the orchestrator connects. The
orchestrator never *runs* an environment — the agents and their runtimes live only
in the server — but it does own the *taskset*: a v1 env's tasks are loaded here,
once, and each dispatched episode ships its task's data on the request
(``task_data``); the server pydantic-validates it into the taskset's declared
``TaskData`` type and runs it. That keeps the server (and every worker in its
pool) stateless about data — no per-worker dataset loads, no idx-addressed task
cache — and gives the orchestrator real tasks to sample.
Each source has its own env configuration and one or more pool replicas
(``OrchestratorConfig.env_worker_pool_replicas``; one per inference node on multi-node
runs). The orchestrator routes to the least-loaded replica; its broker dispatches to
the least-busy worker. A source's ``serve.address`` instead names one external pool.
The server answers one ``Episode`` per run request, whose traces we validate into
The orchestrator owns task selection and loads the dataset once. Requests carry
``task_data``; each worker validates it into the taskset's declared ``TaskData`` type
and executes it through its own Verifiers env. Workers do not load the dataset.
The pool returns one ``Episode`` per run request, whose traces we validate into
``Trace[WireTaskData]`` — real ``vf.Trace``\\ s (never loose dicts) whose task
keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
"""
@@ -38,15 +34,14 @@ from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import env_address_file
# Max wait for the env server to answer health. Generous because the launcher spawns
# servers concurrently with the orchestrator, and a server imports its env package
# before serving.
ENV_SERVER_STARTUP_TIMEOUT = 600.0
# Pool replicas start concurrently with the orchestrator. Health checks reach the
# broker; a reply does not establish worker readiness.
ENV_WORKER_POOL_STARTUP_TIMEOUT = 600.0
async def wait_for_address(path: Path, timeout: float) -> str:
"""The address a launcher-managed env server published, polling for the file the
server writes once it has bound (it starts concurrently with this process)."""
"""The address a launcher-managed env worker pool published, polling for the file the
broker writes once it has bound (it starts concurrently with this process)."""
deadline = time.monotonic() + timeout
while True:
try:
@@ -55,19 +50,19 @@ async def wait_for_address(path: Path, timeout: float) -> str:
except FileNotFoundError:
pass
if time.monotonic() > deadline:
raise TimeoutError(f"env server never published its address to {path} within {timeout}s")
raise TimeoutError(f"env worker pool never published its address to {path} within {timeout}s")
await asyncio.sleep(0.5)
class Env:
"""Client onto a v1 env server. The orchestrator owns the taskset (loaded once,
client-side); the server owns agent/harness execution."""
"""Client onto a v1 env worker pool. The orchestrator owns the taskset (loaded once,
client-side); the pool's workers own agent/harness execution."""
def __init__(self, config: EnvConfig, address: str | None, address_files: list[Path]):
self.config = config
self.address = address
self.address_files = address_files
"""Where the replicas of a launcher-managed server publish their addresses; read
"""Where the replicas of a launcher-managed pool publish their addresses; read
when ``address`` is None."""
self.sampling = vf.SamplingConfig()
self.num_tasks: int | None = 0
@@ -92,21 +87,21 @@ class Env:
return self._env_clients
async def start(self) -> None:
"""Connect to the env server's replicas and load the taskset client-side."""
"""Connect to the env worker pool's replicas and load the taskset client-side."""
t0 = time.perf_counter()
if self.address is not None:
addresses = [self.address]
else:
addresses = await asyncio.gather(
*(wait_for_address(path, timeout=ENV_SERVER_STARTUP_TIMEOUT) for path in self.address_files)
*(wait_for_address(path, timeout=ENV_WORKER_POOL_STARTUP_TIMEOUT) for path in self.address_files)
)
get_logger().debug(f"Connecting {self.name} to env servers {addresses}")
get_logger().debug(f"Connecting {self.name} to env worker pools {addresses}")
self._env_clients = [EnvClient(address=address) for address in addresses]
self._in_flight = [0] * len(addresses)
# The servers may still be coming up (the launcher spawns them concurrently with
# The pools may still be coming up (the launcher spawns them concurrently with
# the orchestrator), so poll until they answer.
await asyncio.gather(
*(client.wait_for_server_startup(timeout=ENV_SERVER_STARTUP_TIMEOUT) for client in self.env_clients)
*(client.wait_for_pool_startup(timeout=ENV_WORKER_POOL_STARTUP_TIMEOUT) for client in self.env_clients)
)
taskset = vf.load_taskset(self.config.env.taskset).select(self.config.select)
if taskset.bounded:
@@ -134,7 +129,7 @@ class Env:
on_delta: Callable[[dict], None] | None = None,
) -> vf.WireEpisode:
"""Run and return the native typed episode.
``on_delta`` sees each delta of the env server's stream — a turn or a phase
``on_delta`` sees each delta of the env worker pool's stream — a turn or a phase
change of one of the episode's traces — as it lands. The run goes to the replica
with the fewest runs in flight."""
if cache_salt is not None:
@@ -265,7 +260,7 @@ class Envs(Generic[EnvT]):
return len(self._envs)
async def start(self) -> None:
"""Connect to all env servers in parallel — every address is known up front,
"""Connect to all env worker pools in parallel — every address is known up front,
so there's nothing to serialize on."""
# When several env.start()s load_dataset() concurrently, datasets' parallel arrow read
# (tqdm thread_map) races in ensure_lock's `del tqdm_class._lock` and crashes with
+1 -1
View File
@@ -25,7 +25,7 @@ class EvalSink:
self.pending_batch_cancellations: dict[tuple[str, int], int] = defaultdict(int)
def add(self, episode: vf.Episode) -> EvalBatch | None:
# Env servers keep every episode's training arrays; eval never trains on them.
# Env workers keep every episode's training arrays; eval never trains on them.
delete_payloads(url for trace in episode.traces for url in trace_payload_urls(trace))
key = (episode_env_name(episode), eval_work(episode).step)
self.pending_batches[key].append(episode)
+1 -1
View File
@@ -1,6 +1,6 @@
"""The dispatcher's side of the live traces.
Env servers stream every in-flight rollout as deltas (``prime_rl.env.delta``). The
Env worker pools stream every in-flight rollout as deltas (``prime_rl.env.delta``). The
dispatcher relays each delta to the monitors stamped with who dispatched it, and keeps
only what its own progress line needs: the phase and turn count of each live trace.
"""
+5 -5
View File
@@ -94,7 +94,7 @@ from prime_rl.utils.pathing import (
from prime_rl.utils.utils import clean_exit
# Wall-clock budget for post-training cleanup; force-exit if graceful
# shutdown wedges (env-server ZMQ recv, vLLM admin aclose, etc)
# shutdown wedges (env-worker-pool ZMQ recv, vLLM admin aclose, etc)
SHUTDOWN_TIMEOUT_S = 300
# Maximum shipped batches that inference has not applied the policy for yet. The
@@ -150,7 +150,7 @@ class Orchestrator:
write_resolved_config(config.output_dir, config, "orchestrator")
setup_logger(config.log.level, json_logging=config.log.json_logging)
# Route the in-process v1 library logging through our handler. The env
# server runs in a child process and sets up its own at the same level.
# worker pool runs in a child process and sets up its own at the same level.
intercept_vf_logging(logger="verifiers.v1", level=config.log.level)
get_logger().info("Starting orchestrator")
@@ -238,7 +238,7 @@ class Orchestrator:
# The launcher-set $PRL_RUN_ID is the run identity; a hosted launch sets only the
# platform's $RUN_ID, and standalone runs mint a local one.
self.run_id = os.environ.get("PRL_RUN_ID") or os.environ.get("RUN_ID") or uuid.uuid4().hex
# Base labels for sandboxes created in this process; env-server processes read
# Base labels for sandboxes created in this process; env-worker-pool processes read
# the same launcher-set env var themselves.
self.run_name = os.environ.get("PRL_RUN_NAME")
if self.run_name:
@@ -254,11 +254,11 @@ class Orchestrator:
config_dir,
clients=self.clients,
renderer_config=config.renderer,
replicas=config.env_server_replicas,
replicas=config.env_worker_pool_replicas,
)
if config.eval is not None:
self.eval_envs = EvalEnvs(
config.eval.source, config.env_addresses, config_dir, replicas=config.env_server_replicas
config.eval.source, config.env_addresses, config_dir, replicas=config.env_worker_pool_replicas
)
# Resume below may bump ``policy.version`` and the LoRA model name
+5 -5
View File
@@ -37,13 +37,13 @@ from prime_rl.utils.logger import get_logger
def _kept(sample: TrainingSample, field: str) -> bool:
"""Whether an env server keeps this array of the sample (see `prime_rl.transports.payload`)."""
"""Whether an env worker keeps this array of the sample (see `prime_rl.transports.payload`)."""
return sample.payload is not None and field in sample.payload.fields
# Training arrays reach the trainer only through env servers that keep them.
# Training arrays reach the trainer only through env workers that keep them.
_KEEP_ARRAYS_HINT = (
"Serve the env with prime-rl's `env-server` entrypoint, which keeps them for the trainer, "
"Serve the env with prime-rl's `env-worker-pool` entrypoint, which keeps them for the trainer, "
"and check its log for arrays it could not keep."
)
@@ -168,12 +168,12 @@ class TrainSink(Reconfigurable):
self._swept_step = 0
def _release(self, urls: Iterable[str]) -> None:
"""Env servers keep the arrays of delivered traces; the sink deletes those of every
"""Env workers keep the arrays of delivered traces; the sink deletes those of every
sample and trace it drops without shipping."""
delete_payloads(urls)
def release_samples(self, samples: Iterable[TrainingSample]) -> None:
"""Delete the env-server arrays of samples that will never ship."""
"""Delete the env workers' arrays of samples that will never ship."""
self._release(sample_payload_urls(samples))
def group_size_for(self, env_name: str) -> int:
+2 -2
View File
@@ -1,4 +1,4 @@
"""Turn a v1 `Trace` (the env server's native, typed output) into training data.
"""Turn a v1 `Trace` (the env worker's native, typed output) into training data.
The orchestrator holds a real `vf.Trace` (validated in `envs.py`), so everything here is
attribute access — no dicts. The trace is a message graph (`trace.nodes`); each `trace.branches`
@@ -126,7 +126,7 @@ def trace_to_samples(trace: vf.Trace, *, env_name: str = "") -> list[TrainingSam
placeholder ranges and `mm_token_type_ids`. Branches with no sampled tokens yield nothing.
"""
samples: list[TrainingSample] = []
# Set by the env server when it keeps the arrays (`prime_rl.transports.payload`).
# Set by the env worker when it keeps the arrays (`prime_rl.transports.payload`).
references = (trace.info.get(PAYLOAD_INFO_KEY) or {}).get("branches", {})
trained_loss_nodes: dict[str, set[int]] = {"rl": set(), "ce": set(), "ref_kl": set()}
for branch, mask in iter_trainable_branches(trace):
+1 -1
View File
@@ -110,7 +110,7 @@ class InflightEpisode:
dispatch_id: str = field(default_factory=lambda: uuid.uuid4().hex)
"""Names the episode on the live view from dispatch until its first trace streams."""
live: dict[str, LiveTrace] = field(default_factory=dict)
"""The episode's in-flight traces by id, as far as the env server's stream has
"""The episode's in-flight traces by id, as far as the env worker pool's stream has
told: which phase each is in and how many turns it has committed."""
+4 -4
View File
@@ -116,11 +116,11 @@ def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix
vf_logger.propagate = False
def setup_env_server_logging(log_level: str, json_logging: bool = False) -> None:
"""Configure logging for an env-server process: prime-rl's logger + routing v1's stdlib
logs through it. Passed to ``serve_env`` so it runs in the broker and in every spawned
def setup_env_worker_pool_logging(log_level: str, json_logging: bool = False) -> None:
"""Configure logging for an env-worker-pool process: prime-rl's logger + routing v1's stdlib
logs through it. Passed to ``run_env_worker_pool`` so it runs in the broker and in every spawned
worker — fresh ``spawn`` processes that otherwise have no handlers and would drop their
per-rollout logs. The launcher redirects an env server's stdout to its log file, so
per-rollout logs. The launcher redirects an env worker pool's stdout to its log file, so
the console sink colorizes only on a terminal."""
setup_logger(log_level, json_logging=json_logging, colorize=sys.stdout.isatty())
intercept_vf_logging(logger="verifiers.v1", level=log_level)
@@ -349,8 +349,8 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
ulimit -l unlimited
{%- if train_env_names or eval_env_names %}
# Every inference node runs a replica of every env server, and the orchestrator spreads
# each source's episodes over them, so env-server memory and CPU spread over all inference
# Every inference node runs a replica of every env worker pool, and the orchestrator spreads
# each source's episodes over them, so env-worker-pool memory and CPU spread over all inference
# nodes instead of piling up next to the orchestrator. Each binds this node so the
# orchestrator connects across nodes. They take the orchestrator env vars.
# NOTE: keep this block free of single quotes (see the orchestrator block).
@@ -361,7 +361,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
{%- for key, value in orchestrator_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
exec uv run env-server @ $CONFIG_DIR/envs/{{ split }}/{{ name }}.json --serve.address tcp://$LOCAL_IP:0 \
exec uv run env-worker-pool @ $CONFIG_DIR/envs/{{ split }}/{{ name }}.json --serve.address tcp://$LOCAL_IP:0 \
--address-file $CONFIG_DIR/envs/{{ split }}/{{ name }}.$INFER_NODE_RANK.address \
> $LOG_DIR/envs/{{ split }}/{{ name }}.$INFER_NODE_RANK.log 2>&1
) &
@@ -196,7 +196,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
mkdir -p $LOG_DIR/envs/eval
{%- for name in eval_env_names %}
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.json \
uv run env-worker-pool @ $CONFIG_DIR/envs/eval/{{ name }}.json \
> $LOG_DIR/envs/eval/{{ name }}.log 2>&1 &
{%- endfor %}
{%- endif %}
+1 -1
View File
@@ -265,7 +265,7 @@ class DataLoader:
return [self._micro_batch_to_tensor(mb) for mb in micro_batches]
def release_payloads(self) -> None:
"""Free the last batch's arrays on the env servers. Call once every rank that may
"""Free the last batch's arrays on the env workers. Call once every rank that may
read them has fetched them."""
delete_payloads(self.payload_urls)
self.payload_urls = []
+2 -2
View File
@@ -325,12 +325,12 @@ def train(config: TrainerConfig):
if world.rank % (world.world_size // dataloader.dp_world_size) == 0:
dataloader.release_payloads()
# A step where no micro batch's arrays could be fetched anywhere is not a
# transient failure (unreachable or mismatched env servers): stop instead of
# transient failure (unreachable or mismatched env worker pools): stop instead of
# training on nothing.
if failed.numel() and bool(failed.all()):
raise RuntimeError(
"Could not fetch the training arrays of any micro batch this step; check that "
"trainer ranks reach the env servers' payload URLs (see the trainer and env-server logs)"
"trainer ranks reach the env worker pools' payload URLs (see the trainer and env-worker-pool logs)"
)
dropped = failed[dataloader.dp_rank].nonzero().flatten().tolist()
drop_micro_batches(micro_batches, dropped)
+5 -5
View File
@@ -37,12 +37,12 @@ class TopLogprobs(msgspec.Struct, array_like=True, gc=False, omit_defaults=True)
counts: bytes
# Where an env server that keeps a trace's arrays leaves the references to them:
# Where an env worker that keeps a trace's arrays leaves the references to them:
# ``trace.info[PAYLOAD_INFO_KEY] = {"url": ..., "branches": {index: {"id", "fields", ...}}}``.
PAYLOAD_INFO_KEY = "prime_rl_payload"
# A sample's training arrays kept by the env-server worker at ``url`` (see
# A sample's training arrays kept by the env worker at ``url`` (see
# ``prime_rl.transports.payload``): the trainer fetches them by ``id`` and keeps the first
# ``num_tokens``.
class PayloadSlice(msgspec.Struct, array_like=True, gc=False):
@@ -54,7 +54,7 @@ class PayloadSlice(msgspec.Struct, array_like=True, gc=False):
routed_dtype: str | None = None
# One branch's training arrays as an env-server worker serves them.
# One branch's training arrays as an env worker serves them.
class BranchArrays(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
routed_experts: RoutedExperts | None = None
sampling_mask: SamplingMask | None = None
@@ -113,7 +113,7 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
branch_index: int | None = None
staleness: np.ndarray | None = None
# The branch's training arrays (routing rows, sampling mask, top-k head), kept by an
# env server; None when the branch has none.
# env worker; None when the branch has none.
payload: PayloadSlice | None = None
@@ -183,7 +183,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
# Trailing padding tokens, folded into the last sequence's length by ``pad_micro_batch``.
padding: int = 0
staleness: memoryview | None = None
# Per sequence, parallel to ``sequence_lengths``: the arrays an env server kept for it
# Per sequence, parallel to ``sequence_lengths``: the arrays an env worker kept for it
# (None if it has none). The trainer fetches them into ``routed_experts``,
# ``sampling_mask`` and ``top_logprobs``; None if no sequence has arrays.
payloads: list[PayloadSlice | None] | None = None
+8 -8
View File
@@ -1,7 +1,7 @@
"""Per-token training arrays passed by reference.
Training arrays (routing rows, sampling masks, top-k heads) never leave an env server
inline. When a train episode finishes, each env-server worker (`PayloadHook`) encodes every
Training arrays (routing rows, sampling masks, top-k heads) never leave an env worker
inline. When a train episode finishes, each env worker (`PayloadHook`) encodes every
trainable branch's arrays, keeps the blob and serves it over HTTP; the trace carries only
references in `trace.info[PAYLOAD_INFO_KEY]`. The orchestrator packs one `PayloadSlice` per
sample, and each trainer rank fetches its micro batches' blobs before the step and assembles
@@ -9,10 +9,10 @@ them into the micro batch's array fields.
Every kept blob is deleted exactly once, by whoever holds it last: the trainer deletes a
step's blobs once every rank fetched them; the orchestrator deletes the blobs of samples
and traces it drops without shipping; the env server deletes the blobs of episodes it
and traces it drops without shipping; the env worker deletes the blobs of episodes it
kept but did not deliver (`PayloadHook.discard`).
Nothing here imports torch: every env-server worker imports this module.
Nothing here imports torch: every env worker imports this module.
"""
from __future__ import annotations
@@ -303,7 +303,7 @@ class _HTTPServer(ThreadingHTTPServer):
class PayloadServer:
"""One env-server worker's arrays, served at `GET <url>/<id>` and freed by
"""One env worker's arrays, served at `GET <url>/<id>` and freed by
`DELETE <url>/<id>`."""
def __init__(self, bind_host: str, url_host: str | None = None):
@@ -419,7 +419,7 @@ class PayloadHook:
def trace_payload_urls(trace: vf.Trace) -> list[str]:
"""URLs of every blob an env server kept for the trace."""
"""URLs of every blob an env worker kept for the trace."""
payload = trace.info.get(PAYLOAD_INFO_KEY)
return [f"{payload['url']}/{reference['id']}" for reference in payload["branches"].values()] if payload else []
@@ -450,7 +450,7 @@ def _fetch(url: str, attempts: int = 3) -> BranchArrays | None:
class _Deleter:
"""Fire-and-forget DELETEs on daemon threads, so DELETEs still queued at exit (say,
to an env server that is gone) never hold the process up."""
to an env worker that is gone) never hold the process up."""
def __init__(self, num_threads: int = 8) -> None:
self.num_threads = num_threads
@@ -482,7 +482,7 @@ _deleter = _Deleter()
def delete_payloads(urls: Iterable[str]) -> None:
"""Free kept arrays on their env servers, without waiting. Call only once nothing will
"""Free kept arrays on their env workers, without waiting. Call only once nothing will
read them again."""
_deleter.submit(urls)
+9 -9
View File
@@ -134,7 +134,7 @@ def format_log_message(
log_lines.append(f"{i1}{'Inference:':<{col}}tail -F {log_dir}/inference.log")
if num_infer_nodes > 1:
log_lines.append(f"{i2}{'All nodes:':<{col - 1}}tail -F {log_dir}/inference/node_*.log")
# Env servers, by split (``envs/<split>/<name>.log``); one split lists its envs
# Env worker pools, by split (``envs/<split>/<name>.log``); one split lists its envs
# directly, several list them under the split.
splits = {split: names for split, names in (env_names or {}).items() if names}
if splits:
@@ -229,7 +229,7 @@ def format_config_message(config_dir: Path, name: str, components: list[tuple[st
launch_toml = attempt_dir / f"{name}.toml"
if launch_toml.is_file():
lines.append(f" {'Launch TOML:':<{col}}{launch_toml}")
# A label starting with a space is a sub-entry (an env server under its split), cut
# A label starting with a space is a sub-entry (an env worker pool under its split), cut
# to the column like the Logs block cuts env names.
for label, path in components:
if label.startswith(" "):
@@ -245,31 +245,31 @@ def write_launch_artifacts(config_dir: Path, name: str) -> None:
def env_address_file(config_dir: Path, split: str, name: str, replica: int | None = None) -> Path:
"""Where a launcher-managed env server publishes the address it bound
"""Where a launcher-managed env worker pool publishes the address it bound
(``envs/<split>/<name>.address``, next to its config, or ``<name>.<replica>.address``
for one of several replicas). The server binds an OS-assigned port, so two runs on one
for one of several replicas). The pool's broker binds an OS-assigned port, so two runs on one
host never race for the same one; a client waits for this file instead of assuming a
port."""
stem = name if replica is None else f"{name}.{replica}"
return config_dir / "envs" / split / f"{stem}.address"
def write_env_server_config(config_dir: Path, split: str, source: EnvConfig, log: LogConfig) -> Path:
"""Write the ``EnvServerConfig`` of a launcher-managed source
def write_env_worker_pool_config(config_dir: Path, split: str, source: EnvConfig, log: LogConfig) -> Path:
"""Write the ``EnvWorkerPoolConfig`` of a launcher-managed source
(``envs/<split>/<name>.json``) and return its path. The source's env and serve
blocks carry over; its other knobs (sampling, algo, name, ...) stay client-side. The
server publishes the OS-assigned port it binds to the address file next to it."""
broker publishes the OS-assigned port it binds to the address file next to it."""
env_dir = config_dir / "envs" / split
env_dir.mkdir(parents=True, exist_ok=True)
source_dict = dump_resolved_config(source)
server_config = {
pool_config = {
"env": source_dict["env"],
"serve": source_dict.get("serve") or {},
"address_file": env_address_file(config_dir, split, source.resolved_name).as_posix(),
"log": {"level": log.level, "json_logging": log.json_logging},
}
path = env_dir / f"{source.resolved_name}.json"
path.write_text(json.dumps(server_config, indent=2))
path.write_text(json.dumps(pool_config, indent=2))
return path
+1 -1
View File
@@ -107,7 +107,7 @@ async def test_interleaved_runs_see_their_deltas_in_order_before_the_reply():
await router.send_multipart([identity, request_id, b"reply", REPLY])
assert await asyncio.gather(*runs) == [list(range(n_deltas))] * n_runs
get_logger().remove(sink)
assert warnings.count("Dropped malformed env server frame") == 2
assert warnings.count("Dropped malformed env worker pool frame") == 2
@pytest.mark.asyncio
+1 -1
View File
@@ -1,4 +1,4 @@
"""The env server ships its env config to workers as plain data: a JSON-mode
"""The env worker pool ships its env config to workers as plain data: a JSON-mode
`model_dump` and `resolve_env_config` rebuilds the env's own config class, role-typed seats
included."""
+1 -1
View File
@@ -62,7 +62,7 @@ pytestmark = pytest.mark.slow
def _trace(rng: np.random.Generator, turns: int) -> vf.Trace:
"""A multi-turn trace with per-token streams as the env-server wire delivers them."""
"""A multi-turn trace with per-token streams as the env-worker-pool wire delivers them."""
n = TOKENS_PER_MESSAGE
nodes = []
for _ in range(turns):
@@ -1,4 +1,4 @@
"""Episodes decoded from the env-server wire hold per-token streams as numpy arrays (read-only
"""Episodes decoded from the env-worker-pool wire hold per-token streams as numpy arrays (read-only
views into the received bytes). Every record written to disk or uploaded must still carry
plain JSON lists."""
@@ -1,4 +1,4 @@
"""Strict payload accounting in the train sink: every array an env server kept for a
"""Strict payload accounting in the train sink: every array an env worker pool kept for a
delivered trace is either shipped in a batch (the trainer deletes it) or deleted by the
sink when it drops the sample or trace."""
@@ -21,7 +21,7 @@ from tests.unit.orchestrator.test_train_sink import episode, trace
def kept(hook: PayloadHook, **kwargs) -> vf.Trace:
"""A trace whose arrays an env server kept."""
"""A trace whose arrays an env worker pool kept."""
t = trace(**kwargs)
for node in t.nodes:
node.routed_experts = np.ones((len(node.token_ids), 2, 2), dtype=np.uint8)
@@ -90,7 +90,7 @@ def test_sink_deletes_stale_pruned_and_discarded_arrays_but_not_shipped_ones():
def test_eval_sink_deletes_the_arrays_of_eval_episodes():
"""Env servers keep arrays for every episode; eval never trains, so its sink frees them."""
"""Env worker pools keep arrays for every episode; eval never trains, so its sink frees them."""
hook = PayloadHook()
evaluated = episode([kept(hook)])
evaluated.run = vf.TrainRunInfo(id="run", work=vf.EvalWorkInfo(step=0))
+2 -2
View File
@@ -10,7 +10,7 @@ from pydantic_config import ConfigFileError
from renderers import custom_renderer_config
from prime_rl.configs.algorithm import GRPOAlgoConfig, LinearLengthPenaltyConfig, LinearSubagentLengthPenaltyConfig
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.configs.env_worker_pool import EnvWorkerPoolConfig
from prime_rl.configs.eval import EvalConfig, SFTOnlineEvalConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.orchestrator import (
@@ -39,7 +39,7 @@ CONFIG_CLASSES = [
PretrainConfig,
OrchestratorConfig,
InferenceConfig,
EnvServerConfig,
EnvWorkerPoolConfig,
EvalConfig,
]
+2 -2
View File
@@ -1,4 +1,4 @@
"""Training arrays kept by env servers: the trainer must assemble each branch's arrays,
"""Training arrays kept by env worker pools: the trainer must assemble each branch's arrays,
cut, packed and padded like its tokens, and the store must serve and free them."""
import base64
@@ -336,7 +336,7 @@ def test_short_routing_rows_fail_the_alignment_check():
payload._assert_aligned(mb, num_tokens=4)
def test_payload_server_binds_the_env_server_host():
def test_payload_server_binds_the_env_worker_pool_host():
assert payload_host(None) == ("127.0.0.1", "127.0.0.1")
assert payload_host("tcp://10.1.2.3:0") == ("10.1.2.3", "10.1.2.3")
bind, url = payload_host("tcp://*:5000")