Compare commits

...
Author SHA1 Message Date
Mika SenghaasandGitHub c2a25f0622 feat: soft and hard kv cap (#3307)
* Split kv trims into soft and hard tiers

A trim at the 0.8 trigger now only lowers the cap and lets completions
drain the pool — at that level there is still headroom, and at steady
state completions usually outrun in-place context growth, so
cancelling immediately pays a certain cost to avoid a merely possible
one. Only if usage climbs past 0.9 despite the closed gate does the
trim also cancel the excess (the prior behavior), preserving the
thrash-cliff guarantee: worst case, a soft trim escalates to a hard
one a cooldown later, still well before the cliff. Emergency cuts are
unchanged.

* Add 2-node concurrency debug config

GLM-4.5-Air scaleswe on the bash harness, 1 train + 1 infer node,
default concurrency, 100-instance SWE-Bench eval.

* Rename trim thresholds to KV_USAGE_SOFT_CAP / KV_USAGE_HARD_CAP

* Fix stale header in the concurrency debug config
2026-08-19 16:00:14 -07:00
bc9e186963 feat: adaptive concurrency for online evals (#3309)
* feat: first-class evaluator with adaptive concurrency

Promote the evaluator out of the orchestrator package into
prime_rl.evaluator and let it run standalone multi-env evals (no
[online] block: one epoch against the served weights, then exit) as
well as SFT online evals ([online]: watch the weights dir per
checkpoint; the sft launcher writes this config).

Scheduling reuses the orchestrator pipeline 1:1: an eval-only
Dispatcher sized by the adaptive ConcurrencyController
([eval.concurrency], replaces eval.max_inflight_episodes), fed by the
InferenceMetricsCollector's /metrics polls. Overload cuts only block
admission - eval episodes are measurements and always run to
completion.

The evaluator spawns an env server per source without an explicit
serve.address; the sft launcher keeps spawning its own and stamps the
derived addresses into the evaluator config.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: stop evaluator collectors before monitor finalize

The periodic logger and the inference-metrics collector log to the W&B
run, so a poll landing after monitors.finalize() warns about a finished
run - mirror the orchestrator and stop them on the clean path first.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: fail fast when adaptive concurrency has no metrics

External inference APIs (e.g. Prime Inference) expose no vLLM /metrics,
so the concurrency controller never bootstraps and the cap would
silently sit at min_inflight forever. The evaluator now probes /metrics
once at startup: no engine metrics + an adaptive band raises with the
fix (pin min_inflight = max_inflight); a pinned band runs fixed with a
warning. A successful probe also bootstraps the controller before the
first dispatch.

Add examples/evals/swe.toml: SWE-bench Verified + Terminal-Bench 2
against deepseek/deepseek-v4-flash on Prime Inference, 1h agent cap,
pinned band.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: rename evaluator command and configs to evals

Per review: the command is uv run evals, the config classes are
EvalsConfig / EvalsEvalConfig in prime_rl.configs.evals, the package is
prime_rl.evals, and the launcher artifacts follow (evals.json,
evals.log, shared-W&B labels). Docs section is Evals. Add EvalsConfig
to the config-load CI check so examples/evals/*.toml are validated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: drop the Evaluator name entirely

Class Evals in prime_rl.evals.evals, run_evals wrapper, Evals proc
title and log lines; prose refers to the evals process. No identifier
or doc references evaluator anymore.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: drop the standalone evals section for now

Keep the online-evals doc updates (command rename, [eval.concurrency])
and the start-run skill runbook.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: reject skip_first_step on standalone evals

The first trigger honors skip_first_step, and standalone mode has only
that trigger - the run would exit successfully without evaluating
anything. Reject the combination at config time.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: cap CI concurrency at 128 in-flight episodes

The adaptive ramp on CI's small engine floods the router until its
circuit breakers open (ProviderError: No available workers) - 512 is
still past what the deployment sustains.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: lower wiki-search initial_inflight to the CI cap

initial_inflight must not exceed max_inflight.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 15:05:19 -07:00
NeoandGitHub bfb0fe346e Remove pipeline sync in inner loss function loop by replacing the bra… (#3294)
* Remove pipeline sync in inner loss function loop by replacing the branch with branchless code

* Ruff format
2026-08-19 12:56:19 -07:00
NeoandGitHub 2acb19eccd Increase chunk size to 8k (#3302) 2026-08-19 12:53:00 -07:00
43 changed files with 983 additions and 547 deletions
+1 -1
View File
@@ -20,7 +20,7 @@ batch_size = 128
group_size = 8
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 384
@@ -23,7 +23,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
@@ -20,7 +20,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
@@ -23,7 +23,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -25,7 +25,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.algo]
type = "opd"
@@ -25,7 +25,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.algo]
type = "sft"
@@ -23,7 +23,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -20,7 +20,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
+1 -1
View File
@@ -19,7 +19,7 @@ batch_size = 512
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[[orchestrator.train.source]]
name = "alphabet-sort"
+1 -1
View File
@@ -19,7 +19,7 @@ group_size = 8
seq_len = 8192
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[[orchestrator.train.source]]
name = "hendrycks-math"
+1 -1
View File
@@ -19,7 +19,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[[orchestrator.train.source]]
name = "reverse-text"
+2 -2
View File
@@ -19,8 +19,8 @@ batch_size = 512
group_size = 16
[orchestrator.concurrency]
initial_inflight = 512
max_inflight = 512
initial_inflight = 128
max_inflight = 128
[[orchestrator.train.source]]
name = "wiki-search"
+1 -1
View File
@@ -19,7 +19,7 @@ batch_size = 512
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[[orchestrator.train.source]]
name = "wordle"
@@ -18,7 +18,7 @@ batch_size = 256
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 64
+155
View File
@@ -0,0 +1,155 @@
# Concurrency-controller debug run: GLM-4.5-Air on the v1 `scaleswe` SWE taskset,
# bash harness on a prime sandbox runtime, 1 train + 1 infer node, eval on 100
# SWE-Bench Verified instances. Concurrency is fully default: the controller
# derives its start from the measured KV budget and adapts from there — watch
# the concurrency/* gauges in W&B or the "Concurrency ..." lines in the
# orchestrator log.
#
# Inference serves FP8 via online per-tensor quantization of the bf16
# checkpoint; weight broadcasts re-quantize through the same path on every
# update. The trainer fits on one node via cp=4 (ulysses), full CPU optimizer
# offload with the stateless sign-SGD optimizer, plus the memory improvements
# from the GLM-5.1 prod run: LM-head token chunking, activation checkpointing
# (freq=1) + activation offloading (max_inflight=1), and skip-gather /
# skip-optimizer checkpointing. Router replay is enabled — GLM-4.5-Air is a
# glm4_moe model, which supports routed_experts.
#
# GRPO uses the linear length penalty with the input-token and turns
# coefficients set to 0.1.
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "debug-concurrency"
partition = "all"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "debug-concurrency" -y || true'
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
num_infer_replicas = 1
[monitors.wandb]
project = "swe-ablations"
name = "debug-concurrency"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
[resume]
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
optim_cpu_offload = false
full_offload = true
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
type = "sign_sgd"
# --- Orchestrator ---
[orchestrator]
batch_size = 128
group_size = 8
max_off_policy_steps = 32
[orchestrator.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
[[orchestrator.train.source]]
name = "scaleswe"
[orchestrator.train.source.env.taskset]
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
labels = ["debug-concurrency"]
[monitors.prime]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
num_examples = 100
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["debug-concurrency"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
# --- Inference ---
[inference]
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
quantization = "fp8"
enable_return_routed_experts = true
+1 -1
+1 -1
View File
@@ -211,7 +211,7 @@ The orchestrator continuously sizes how many episodes run against the inference
The controller's idea is to treat the engines as ground truth and probe, instead of modeling episode cost: while the engines show headroom, admit a little more; when they show pressure, back off. Three behaviors, in increasing severity:
- **Grow**: while the engines look healthy and the current cap is fully used, raise it multiplicatively. Growth is clocked by the pipeline itself — the cap rises by a fixed factor each time the in-flight pool has turned over once — so a fast single-turn workload ramps in seconds while a slow agentic workload ramps at its own pace, with no tuning per workload.
- **Trim**: episodes grow their context *while running*, so a pool that fit comfortably an hour ago can outgrow memory without a single new admission. When KV usage nears the ceiling, the controller shrinks the cap *and* the pool, cancelling the youngest episodes (least work lost) until the engines are comfortable again.
- **Trim**: episodes grow their context *while running*, so a pool that fit comfortably an hour ago can outgrow memory without a single new admission. When KV usage nears the ceiling, the controller first lowers the cap and lets completions drain the pool naturally (soft — no work lost); only if usage keeps climbing despite the closed gate does it also cancel the youngest episodes (hard — least work lost).
- **Cut**: when the engines are demonstrably overloaded — requests being preempted, or piling up in the waiting queue — cut the pool hard, cancel the excess, and hold further cuts until the system settles.
The cap starts from a safe bound derived from the engines (KV capacity divided by the maximum context length), or from `initial_inflight` when a good value is known, and always stays within `[min_inflight, max_inflight]`.
+4 -4
View File
@@ -204,17 +204,17 @@ num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an `evaluator` process next to the trainer. The handoff is the filesystem, not NCCL: the trainer writes an HF weight checkpoint at every step an eval env is due (in addition to `ckpt.interval`), and the evaluator watches `weights/step_{n}`, points the inference server at each stable checkpoint (`/update_weights` reload from disk), and runs the due envs against it — sequentially per checkpoint, so every epoch measures exactly one policy version. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final checkpoint always fires every env.
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. The handoff is the filesystem, not NCCL: the trainer writes an HF weight checkpoint at every step an eval env is due (in addition to `ckpt.interval`), and the evals process watches `weights/step_{n}`, points the inference server at each stable checkpoint (`/update_weights` reload from disk), and runs the due envs against it — sequentially per checkpoint, so every epoch measures exactly one policy version. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final checkpoint always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
#### Multi-Node (Decoupled Trainer and Inference Pool)
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two independent SLURM jobs**. `deployment.num_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evaluator:
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two independent SLURM jobs**. `deployment.num_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2 # trainer job
num_infer_nodes = 1 # eval job (inference pool + evaluator)
num_infer_nodes = 1 # eval job (inference pool + evals)
[inference.vllm]
tensor_parallel_size = 8
@@ -223,7 +223,7 @@ tensor_parallel_size = 8
job_name = "my-run"
```
The only coupling is weight checkpoints on the shared filesystem, so the jobs' lifetimes are independent: when training finishes, the trainer job exits and releases its nodes even while evals are still running; the eval job keeps draining pending checkpoints and exits after evaluating the final one (`max_steps` — without it the eval job never sees a final checkpoint and holds its allocation until walltime). Trainer and evaluator log to a single shared W&B run across both jobs — the trainer creates it, the evaluator finalizes it. Any train × inference layout works: `num_nodes` and `num_infer_nodes` are fully independent.
The only coupling is weight checkpoints on the shared filesystem, so the jobs' lifetimes are independent: when training finishes, the trainer job exits and releases its nodes even while evals are still running; the eval job keeps draining pending checkpoints and exits after evaluating the final one (`max_steps` — without it the eval job never sees a final checkpoint and holds its allocation until walltime). Trainer and evals log to a single shared W&B run across both jobs — the trainer creates it, the evals process finalizes it. Any train × inference layout works: `num_nodes` and `num_infer_nodes` are fully independent.
### SFT-Specific Knobs
+44
View File
@@ -0,0 +1,44 @@
# Standalone SWE evals: SWE-bench Verified + Terminal-Bench 2, one epoch each,
# against DeepSeek V4 Flash on Prime Inference.
#
# export PRIME_API_KEY=<your Prime Inference key>
# uv run evals @ examples/evals/swe.toml
#
# The tasksets run in prime sandboxes (the default runtime), so the key also
# authenticates sandbox creation. External API endpoints expose no vLLM
# /metrics, so adaptive concurrency has no load signal - the band must be
# pinned (min_inflight = max_inflight) or the evals process refuses to start.
model = "deepseek/deepseek-v4-flash"
[eval.client]
base_url = "https://api.pinference.ai/api/v1"
api_key_var = "PRIME_API_KEY"
[eval.concurrency]
min_inflight = 32
max_inflight = 32
[[eval.source]]
name = "swebench-verified"
[eval.source.env.taskset]
id = "swebench-verified"
[eval.source.env.agent.harness]
id = "bash"
[eval.source.env.agent.timeout]
rollout = 3600
[[eval.source]]
name = "terminal-bench-2"
[eval.source.env.taskset]
id = "terminal-bench-2"
[eval.source.env.agent.harness]
id = "bash"
[eval.source.env.agent.timeout]
rollout = 3600
@@ -0,0 +1,109 @@
from pathlib import Path
from pydantic import Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig
from prime_rl.utils.config import BaseConfig
class EvalsEvalConfig(EvalConfig):
"""Evals against a live inference server. Extends the orchestrator ``EvalConfig``
(sources, sampling, intervals) with the client of the inference deployment and
evals-side knobs."""
client: ClientConfig = ClientConfig()
"""Client of the inference server evals run against. Auto-wired from the
``[inference]`` block when the launcher manages the server."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the eval source at position ``i`` is
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
keep it instead, without shifting the other sources' ports."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: sources with an explicit
``serve.address`` are externally managed; the evals process spawns an env server at
the derived address for every other source."""
return {
("eval", source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, source in enumerate(self.source)
}
class OnlineConfig(BaseConfig):
"""Checkpoint-driven online evals: watch a weights directory for new HF checkpoints
and evaluate each eligible one. Without this block the evals process runs every eval
source once against the weights the inference server currently serves, then exits."""
weights_dir: Path | None = None
"""Directory to watch for ``step_{n}`` HF weight checkpoints. The ``sft`` launcher
fills it from ``ckpt.output_dir`` when checkpoints are redirected to another volume;
defaults to ``<output_dir>/weights``."""
max_steps: int | None = None
"""Trainer step at which the run ends. The final checkpoint always fires every
eval env, and the evals process exits after processing it. If None, the evals process
runs until terminated."""
resume_step: int | None = None
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
this step."""
class EvalsConfig(BaseConfig):
"""``uv run evals``: run the configured evals against a live inference server.
Standalone (no ``[online]``), one epoch of every eval source runs against the
served weights and the evals process exits. With ``[online]``, the evals process watches a
weights directory for new HF checkpoints, points the inference server at each one
(``/update_weights`` from disk), and runs the configured evals against the updated
weights — the ``sft`` launcher writes this config; it also works standalone against
any trainer that writes ``weights/step_{n}`` HF checkpoints with ``STABLE`` markers."""
model: str = "Qwen/Qwen3-0.6B"
"""Name the inference server serves the model under — the ``model`` field of every
eval request and the startup model check. Auto-filled from ``model.name`` by the
``sft`` launcher; the name stays fixed across checkpoint reloads (weights are
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
eval: EvalsEvalConfig
"""Eval sources, sampling, intervals, concurrency, and the inference client."""
online: OnlineConfig | None = None
"""Checkpoint watching (``[online]``). None runs the evals once and exits."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer for online evals."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
@model_validator(mode="after")
def auto_setup_weights_dir(self):
if self.online is not None and self.online.weights_dir is None:
self.online.weights_dir = self.output_dir / "weights"
return self
@model_validator(mode="after")
def validate_skip_first_step_is_online_only(self):
"""``skip_first_step`` gates the base-model eval between checkpoints; a
standalone run has only that one epoch, so skipping it would exit
successfully without evaluating anything."""
if self.online is None and self.eval.skip_first_step:
raise ValueError(
"eval.skip_first_step only applies to online evals - a standalone run "
"would skip its only eval epoch. Remove it or add an [online] block."
)
return self
@@ -1,84 +0,0 @@
from pathlib import Path
from pydantic import Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig
from prime_rl.utils.config import BaseConfig
class OnlineEvalConfig(EvalConfig):
"""Online evals against a live inference server, driven by weight checkpoints
on disk. Extends the orchestrator ``EvalConfig`` (sources, sampling, intervals)
with the client of the inference deployment and evaluator-side knobs."""
client: ClientConfig = ClientConfig()
"""Client of the inference server evals run against. Auto-wired from the
``[inference]`` block when the launcher manages the server."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the eval source at position ``i`` is
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
keep it instead, without shifting the other sources' ports."""
max_inflight_episodes: int = Field(128, ge=1)
"""Maximum eval episodes in flight — one episode is one agent run against an env server."""
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: the launcher binds env
servers at exactly these addresses and the evaluator connects to them."""
return {
("eval", source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, source in enumerate(self.source)
}
class EvaluatorConfig(BaseConfig):
"""``uv run evaluator``: watch a weights directory for new HF checkpoints, point
the inference server at each one (``/update_weights`` from disk), and run the
configured evals against the updated weights. The ``sft`` launcher writes this
config; it can also be run standalone against any trainer that writes
``weights/step_{n}`` HF checkpoints with ``STABLE`` markers."""
model: str = "Qwen/Qwen3-0.6B"
"""Name the inference server serves the model under — the ``model`` field of every
eval request and the startup model check. Auto-filled from ``model.name`` by the
``sft`` launcher; the name stays fixed across checkpoint reloads (weights are
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
eval: OnlineEvalConfig
"""Eval sources, sampling, intervals, and the inference client."""
weights_dir: Path | None = None
"""Directory to watch for ``step_{n}`` HF weight checkpoints. The ``sft`` launcher
fills it from ``ckpt.output_dir`` when checkpoints are redirected to another volume;
defaults to ``<output_dir>/weights``."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer."""
max_steps: int | None = None
"""Trainer step at which the run ends. The final checkpoint always fires every
eval env, and the evaluator exits after processing it. If None, the evaluator
runs until terminated."""
resume_step: int | None = None
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
this step."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
@model_validator(mode="after")
def auto_setup_weights_dir(self):
if self.weights_dir is None:
self.weights_dir = self.output_dir / "weights"
return self
@@ -8,7 +8,7 @@ from pydantic import AliasChoices, Field, model_validator
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
from renderers.base import MODEL_RENDERER_MAP
from prime_rl.configs.evaluator import OnlineEvalConfig
from prime_rl.configs.evals import EvalsEvalConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
@@ -195,7 +195,7 @@ class SFTConfig(BaseConfig):
val: SFTValConfig | None = None
"""Validation configuration. If None, no validation runs."""
eval: OnlineEvalConfig | None = None
eval: EvalsEvalConfig | None = None
"""Online evaluation configuration: rollout-based evals against a live inference
server that reloads the trainer's HF weight checkpoints from disk. If None, no
online evals run."""
@@ -362,18 +362,18 @@ class SFTConfig(BaseConfig):
if self.ckpt.keep_last is not None or self.ckpt.keep_interval is not None:
warnings.warn(
"ckpt.keep_last / ckpt.keep_interval can delete a weight checkpoint before the "
"evaluator consumes it when evals run slower than training - such steps are "
"evals consumes it when evals run slower than training - such steps are "
"skipped with a warning instead of evaluated.",
stacklevel=2,
)
if self.deployment.type == "multi_node":
# Decoupled deployment: the launcher submits a dedicated SLURM job running the
# inference pool (one engine per DP rank behind a router) plus the evaluator.
# inference pool (one engine per DP rank behind a router) plus the evals process.
if self.inference is None:
raise ValueError(
"Multi-node online evals require an [inference] block - the launcher submits "
"a dedicated SLURM job running the inference pool and the evaluator."
"a dedicated SLURM job running the inference pool and the evals process."
)
if self.deployment.num_infer_nodes < 1:
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
@@ -398,7 +398,7 @@ class SFTConfig(BaseConfig):
)
if self.max_steps is None:
warnings.warn(
"Online evals without max_steps: the evaluator never sees a final checkpoint, "
"Online evals without max_steps: the evals process never sees a final checkpoint, "
"so the eval SLURM job holds its allocation until its walltime.",
stacklevel=2,
)
@@ -411,7 +411,7 @@ class SFTConfig(BaseConfig):
"Online evals are configured without an [inference] block - the launcher will not "
f"start an inference server. Make sure one is running at eval.client.base_url "
f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', "
"otherwise the evaluator will hang waiting for it. If a router fronts the "
"otherwise the evals process will hang waiting for it. If a router fronts the "
"deployment, set eval.client.admin_base_url to the engine URLs - admin ops "
"(pause/update_weights/resume) must bypass the router.",
stacklevel=2,
@@ -256,7 +256,7 @@ class ModelConfig(BaseModelConfig):
debug: DebugModelConfig = DebugModelConfig()
"""Debugging knobs for the model and distributed training."""
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 1024
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 8192
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
@model_validator(mode="after")
+1 -1
View File
@@ -53,7 +53,7 @@ sft = "prime_rl.entrypoints.sft:main"
inference = "prime_rl.entrypoints.inference:main"
trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
evaluator = "prime_rl.entrypoints.evaluator:main"
evals = "prime_rl.entrypoints.evals:main"
env-server = "prime_rl.entrypoints.env_server:main"
[project.entry-points."vllm.general_plugins"]
+2 -2
View File
@@ -66,7 +66,7 @@ After a restart, verify all processes are back up and progress resumed before th
{run_dir}/logs/latest/
├── trainer.log # rank 0 stdout
├── orchestrator.log # orchestrator stdout
├── evaluator.log # SFT online-eval evaluator stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evaluator.log)
├── evals.log # SFT online-eval evals stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evals.log)
├── inference.log # vLLM stdout
├── trainer/
│ ├── node_*.log # per-node (multi-node only)
@@ -82,7 +82,7 @@ Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough
Scan for problems:
```bash
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evaluator,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evals,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
```
+42 -1
View File
@@ -1,6 +1,6 @@
---
name: start-run
description: How to launch prime-rl training runs — the `rl`, `sft`, and `inference` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
description: How to launch prime-rl training runs — the `rl`, `sft`, `inference`, and `evals` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
---
# Start a run
@@ -88,6 +88,46 @@ curl http://localhost:8000/v1/chat/completions \
- Entrypoint: `src/prime_rl/entrypoints/inference.py`
- SLURM: single-node, multi-node, and disaggregated deployments
## `evals` — multi-env evals
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`weights_dir`, `max_steps`, `resume_step`): watch the weights dir for stable `step_{n}` HF checkpoints and evaluate each — the `sft` launcher writes this config for online evals.
```bash
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
uv run evals @ eval.toml
```
Minimal standalone `eval.toml`:
```toml
model = "Qwen/Qwen3-4B"
[eval.client]
base_url = "http://localhost:8000/v1"
[eval.concurrency] # adaptive; same controller as [orchestrator.concurrency]
min_inflight = 8
max_inflight = 128
[[eval.source]]
num_examples = 32 # always cap eval size for smokes
group_size = 4
[eval.source.env.taskset]
id = "aime25"
[eval.source.env.agent.harness]
id = "null"
[eval.source.env.agent.runtime]
type = "subprocess"
```
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/envs/eval/{name}.log`.
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
## Summary
| Command | Purpose | Typical use |
@@ -95,6 +135,7 @@ curl http://localhost:8000/v1/chat/completions \
| `rl` | Full RL pipeline | Production RL training |
| `sft` | Supervised fine-tuning | SFT and hard-distill |
| `inference` | vLLM server | Standalone serving / debugging |
| `evals` | Multi-env evals | Standalone evals / SFT online evals |
## Key paths
+24
View File
@@ -0,0 +1,24 @@
"""Lightweight launcher for the online evals.
Defers heavy ML imports until after ``cli()`` parses CLI args, so
``evals --help`` short-circuits in ``cli()``. The actual implementation
lives in ``prime_rl.evals.evals``.
"""
import asyncio
from prime_rl.configs.evals import EvalsConfig
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Evals")
config = cli(EvalsConfig)
from prime_rl.evals.evals import run_evals
asyncio.run(run_evals(config))
if __name__ == "__main__":
main()
-24
View File
@@ -1,24 +0,0 @@
"""Lightweight launcher for the online evaluator.
Defers heavy ML imports until after ``cli()`` parses CLI args, so
``evaluator --help`` short-circuits in ``cli()``. The actual implementation
lives in ``prime_rl.orchestrator.evaluator``.
"""
import asyncio
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Evaluator")
config = cli(EvaluatorConfig)
from prime_rl.orchestrator.evaluator import run_evaluator
asyncio.run(run_evaluator(config))
if __name__ == "__main__":
main()
+44 -36
View File
@@ -9,7 +9,7 @@ from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.configs.evals import EvalsConfig, OnlineConfig
from prime_rl.configs.orchestrator import EvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.shared import LogConfig
@@ -46,7 +46,7 @@ EVAL_SBATCH = "eval.sbatch"
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
INFERENCE_CONFIG = "inference.json"
EVALUATOR_CONFIG = "evaluator.json"
EVALS_CONFIG = "evals.json"
ENVS_DIR = "envs"
@@ -80,16 +80,24 @@ def resolve_resume_step(config: SFTConfig) -> int | None:
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
def build_evaluator_config(config: SFTConfig) -> EvaluatorConfig:
"""Derive the evaluator subconfig from the resolved SFT config."""
def build_evals_config(config: SFTConfig) -> EvalsConfig:
"""Derive the evals subconfig from the resolved SFT config. The launcher
spawns the env servers itself, so each source's derived address is stamped in,
marking it externally managed for the evals process."""
assert config.eval is not None
return EvaluatorConfig(
eval_config = config.eval.model_copy(deep=True)
addresses = config.eval.env_addresses
for source in eval_config.source:
source.serve.address = addresses[("eval", source.resolved_name)]
return EvalsConfig(
model=config.model.name,
eval=config.eval,
weights_dir=get_weights_dir(get_ckpt_base(config)),
eval=eval_config,
online=OnlineConfig(
weights_dir=get_weights_dir(get_ckpt_base(config)),
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
),
output_dir=config.run_dir,
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
monitors=config.monitors,
)
@@ -103,7 +111,7 @@ def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None
def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: bool = False) -> None:
"""Write the inference, evaluator, and env-server configs for online evals."""
"""Write the inference, evals, and env-server configs for online evals."""
config_dir.mkdir(parents=True, exist_ok=True)
if config.inference is not None:
@@ -116,11 +124,11 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
with open(config_dir / INFERENCE_CONFIG, "w") as f:
json.dump(inference_dict, f, indent=2)
with open(config_dir / EVALUATOR_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_evaluator_config(config)), f, indent=2)
with open(config_dir / EVALS_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_evals_config(config)), f, indent=2)
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>`
# binds at the source's deterministic address, where the evaluator connects.
# binds at the source's deterministic address, where the evals process connects.
for source, address in eval_env_servers(config):
env_dir = config_dir / ENVS_DIR / "eval"
env_dir.mkdir(parents=True, exist_ok=True)
@@ -176,7 +184,7 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Path, prl_run_id: str | None) -> None:
"""Write the SLURM script for the decoupled online-eval job (inference pool +
env servers + evaluator) to disk."""
env servers + evals) to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
@@ -199,7 +207,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
**config.env_vars,
**config.inference.env_vars,
}
evaluator_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
evals_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
script = template.render(
**config.slurm.template_vars,
@@ -214,7 +222,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
enable_expert_parallel=config.inference.vllm.enable_expert_parallel,
inference_env_vars=inference_env_vars,
evaluator_env_vars=evaluator_env_vars,
evals_env_vars=evals_env_vars,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
prl_run_id=prl_run_id,
run_name=config.run.name,
@@ -226,7 +234,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
def sft_slurm(config: SFTConfig):
"""Run SFT training via SLURM. With online evals on a multi-node deployment, the
trainer and the eval deployment (inference pool + evaluator) are two independent
trainer and the eval deployment (inference pool + evals) are two independent
SLURM jobs: the handoff is weight checkpoints on the shared filesystem, so the
trainer job releases its allocation when training finishes while the eval job
keeps draining evals and exits after the final checkpoint."""
@@ -250,7 +258,7 @@ def sft_slurm(config: SFTConfig):
write_config(config, config_path, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
# Trainer and evaluator processes log to a single shared W&B run across both jobs,
# Trainer and evals processes log to a single shared W&B run across both jobs,
# keyed by the launcher's run id.
prl_run_id: str | None = None
if decoupled_eval and config.monitors.wandb is not None:
@@ -261,8 +269,8 @@ def sft_slurm(config: SFTConfig):
logger.info(f"Wrote SLURM script to {script_path}")
# The trainer job is submitted first and the eval job depends on it having started:
# the trainer creates the shared W&B run, and the evaluator's joiner init only
# retries for a bounded window — starting the evaluator while the trainer job pends
# the trainer creates the shared W&B run, and the evals process's joiner init only
# retries for a bounded window — starting the evals process while the trainer job pends
# would crash it at wandb init.
script_paths = [script_path]
if decoupled_eval:
@@ -283,7 +291,7 @@ def sft_slurm(config: SFTConfig):
# The eval job logs at stable (non-attempt) paths under the run dir.
log_message += "\n" + format_log_message(
log_dir=get_log_dir(config.run_dir),
evaluator=True,
evals=True,
inference=True,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
num_infer_nodes=config.deployment.num_infer_nodes,
@@ -292,7 +300,7 @@ def sft_slurm(config: SFTConfig):
if config.dry_run:
submit = "\n".join(f" sbatch {path}" for path in script_paths)
note = (
"\n\nSubmit the trainer job first — the evaluator joins the W&B run the trainer creates."
"\n\nSubmit the trainer job first — the evals process joins the W&B run the trainer creates."
if decoupled_eval
else ""
)
@@ -360,17 +368,17 @@ def sft_local(config: SFTConfig):
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
# Trainer and evaluator log to a single shared W&B run whose id ($WANDB_RUN_ID)
# Trainer and evals log to a single shared W&B run whose id ($WANDB_RUN_ID)
# equals $PRL_RUN_ID, one label per process.
wandb_shared_env: dict[str, str] = {}
if config.eval is not None:
# The trainer creates the run; the evaluator (which drains its final evals
# The trainer creates the run; the evals process (which drains its final evals
# after the trainer exits) finalizes it.
wandb_shared_env = {
"WANDB_SHARED_MODE": "1",
"WANDB_RUN_ID": os.environ["PRL_RUN_ID"],
"WANDB_SHARED_PRIMARY": "trainer",
"WANDB_SHARED_FINISHER": "evaluator",
"WANDB_SHARED_FINISHER": "evals",
"WANDB_PROGRAM": "uv run sft",
"WANDB_ARGS": json.dumps(sys.argv),
}
@@ -419,7 +427,7 @@ def sft_local(config: SFTConfig):
log_path=log_dir / "inference.log",
)
# Start one env server per eval source. The evaluator connects to each source's
# Start one env server per eval source. The evals process connects to each source's
# deterministic address, polling until the server is up.
for source, address in eval_env_servers(config):
name = source.resolved_name
@@ -432,19 +440,19 @@ def sft_local(config: SFTConfig):
)
if config.eval is not None:
logger.info("Starting evaluator process")
logger.info("Starting evals process")
start_process(
"evaluator",
["evaluator", "@", (config_dir / EVALUATOR_CONFIG).as_posix()],
"evals",
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "evaluator",
"WANDB_SHARED_LABEL": "evals",
},
log_path=log_dir / "evaluator.log",
log_path=log_dir / "evals.log",
)
from prime_rl.utils.utils import get_free_port
@@ -487,11 +495,11 @@ def sft_local(config: SFTConfig):
)
processes.append(tail_process)
# Wait for the trainer (and the evaluator, which drains its final evals after
# Wait for the trainer (and the evals process, which drains its final evals after
# the trainer's last checkpoint) while surfacing any process failure.
terminal_events = [stop_events["trainer"]]
if "evaluator" in stop_events:
terminal_events.append(stop_events["evaluator"])
if "evals" in stop_events:
terminal_events.append(stop_events["evals"])
while True:
pending = [event for event in terminal_events if not event.is_set()]
if error_queue:
@@ -529,12 +537,12 @@ def sft_local(config: SFTConfig):
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
"""Remove eval artifacts a previous run left behind: weight checkpoints and rollout
trace dirs — everything on a fresh start, steps past the resume step on resume.
Without this the evaluator would replay stale checkpoints (and then skip the
Without this the evals process would replay stale checkpoints (and then skip the
re-trained ones at the same steps), and the append-only trace files would mix two
policies' rollouts under one step."""
logger = setup_logger(config.log.level or "info")
if os.environ.get("NEVER_CLEAN"):
logger.warning("NEVER_CLEAN is set - keeping stale weight checkpoints; the evaluator may replay them")
logger.warning("NEVER_CLEAN is set - keeping stale weight checkpoints; the evals process may replay them")
return
resume_step = resolve_resume_step(config)
weights_dir = get_weights_dir(get_ckpt_base(config))
View File
+443
View File
@@ -0,0 +1,443 @@
"""Evals: multi-env evals against a live inference server.
Standalone (no ``[online]``), it runs one epoch of every configured eval
source against the weights the inference server currently serves, then exits.
With ``[online]``, it watches a weights directory for new HF checkpoints —
the trainer writes ``weights/step_{n}`` with a ``STABLE`` marker on
completion — tells the inference server to reload each eligible checkpoint
from disk (``/update_weights``, no NCCL rendezvous), and runs the configured
evals against the updated weights, sequentially per checkpoint so every epoch
measures exactly one policy version.
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
fed by the ``InferenceMetricsCollector``'s ``/metrics`` polls. Eval episodes
are version-pinned measurements, so an overload cut only blocks admission and
the in-flight pool drains through natural completions.
Env servers: sources without an explicit ``serve.address`` get an env server
spawned by the evals process at their derived address; sources with one are
externally managed (e.g. spawned by the ``sft`` launcher, which stamps the
derived addresses into this config)."""
from __future__ import annotations
import asyncio
import json
import os
import time
import uuid
from subprocess import Popen
import verifiers.v1 as vf
from prime_rl import monitors
from prime_rl.configs.evals import EvalsConfig
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.types import EvalBatch, Policy, Rollout
from prime_rl.orchestrator.utils import group_episodes, intercept_vf_logging, set_default_executor
from prime_rl.utils.client import InferencePool
from prime_rl.utils.config import dump_resolved_config
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir, get_step_path
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
from prime_rl.utils.utils import clean_exit
monkey_patch_oai_iterable_types()
monkey_patch_chat_completion_logprobs()
# How often to re-scan the weights directory for new checkpoints.
POLL_INTERVAL_S = 2.0
class Evals:
def __init__(self, config: EvalsConfig) -> None:
self.config = config
setup_logger(config.log.level, json_logging=config.log.json_logging)
intercept_vf_logging(logger="verifiers.v1", level="WARN")
mode = f"online (weights_dir={config.online.weights_dir})" if config.online is not None else "standalone"
get_logger().info(f"Starting evals ({mode})")
# The last weight-checkpoint step already handled (evaluated or skipped).
self.last_step = (config.online.resume_step if config.online is not None else None) or 0
self.eval_triggered_at: dict[tuple[str, int], float] = {}
self.env_server_procs: list[Popen] = []
self.dispatcher_task: asyncio.Task | None = None
async def setup(self) -> None:
config = self.config
set_default_executor()
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
wandb=config.monitors.wandb,
file=config.monitors.file,
output_dir=config.output_dir,
run_config=config,
eval_env_names=[source.resolved_name for source in config.eval.source],
overview_flavor="sft",
)
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
self.run_name = os.environ.get("PRL_RUN_NAME")
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
self.pool = InferencePool(config.eval.client, model_name=config.model)
self.spawn_env_servers()
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.eval.source, config.eval.env_addresses)
await self.eval_envs.start()
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
get_logger().info("Waiting for inference pool to be ready")
await self.pool.wait_for_ready(config.model)
get_logger().success("Inference pool ready")
is_resumed = config.online is not None and config.online.resume_step is not None
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=is_resumed)
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
self.policy = Policy(version=0, model_name=config.model)
# Pessimistic per-episode token cost for the controller's starting cap,
# only used when the engine doesn't report its max context length.
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.eval.source) or 8192
self.concurrency = ConcurrencyController(config.eval.concurrency, fallback_cost=fallback_cost)
self.dispatcher = Dispatcher(
train_envs=None,
eval_envs=self.eval_envs,
train_source=None,
eval_source=self.eval_source,
policy_pool=self.pool,
policy=self.policy,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.eval.concurrency.max_inflight,
tasks_per_minute=None,
max_off_policy_steps=0,
on_episode_complete=self.concurrency.record_episode,
)
# No ``on_overload``: eval episodes are measurements and are never
# cancelled — a cut only blocks admission until the pool drains.
self.concurrency.bind(
set_limit=self.dispatcher.set_limit,
get_inflight=lambda: self.dispatcher.current_inflight,
)
# The collector always polls — it feeds the concurrency controller;
# W&B mirroring is gated on the registered monitor.
self.inference_metrics = InferenceMetricsCollector(
self.pool.admin_clients,
on_load=self.concurrency.observe,
log_to_wandb=wandb_enabled,
)
# Fail fast when adaptivity has no signal: external API endpoints
# (e.g. Prime Inference) expose no vLLM /metrics, so without a probe
# hit the cap would silently sit at min_inflight forever. A pinned
# band (min_inflight = max_inflight) makes the controller inert and
# is the supported way to run against such endpoints.
if not await self.inference_metrics.probe():
concurrency = config.eval.concurrency
if concurrency.min_inflight != concurrency.max_inflight:
urls = ", ".join(str(client.base_url) for client in self.pool.admin_clients)
raise ValueError(
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
"pin the concurrency by setting eval.concurrency.min_inflight = max_inflight."
)
get_logger().warning(f"No engine metrics - running with concurrency pinned at {concurrency.min_inflight}")
await self.inference_metrics.start()
self.periodic_logger = PeriodicLogger(
name="Evals",
collect=self.collect_pipeline_view,
metric_keys=[
*list(self.dispatcher.gauges().keys()),
*list(self.concurrency.gauges().keys()),
*DispatcherMetrics.drain_keys(train_envs=set(), eval_envs={env.name for env in self.eval_envs}),
],
interval=config.log.interval,
wandb_enabled=wandb_enabled,
)
def spawn_env_servers(self) -> None:
"""Spawn one env server per source without an explicit ``serve.address``,
at the source's derived address."""
config = self.config
addresses = config.eval.env_addresses
config_dir = get_config_dir(config.output_dir) / "envs" / "eval"
log_dir = get_log_dir(config.output_dir) / "envs" / "eval"
for source in config.eval.source:
if source.serve.address is not None:
continue
name = source.resolved_name
address = addresses[("eval", name)]
source_dict = dump_resolved_config(source)
server_config = {
"env": source_dict["env"],
"serve": {**(source_dict.get("serve") or {}), "address": address},
"log": {"level": config.log.vf_level, "json_logging": config.log.json_logging},
}
config_dir.mkdir(parents=True, exist_ok=True)
config_path = config_dir / f"{name}.json"
config_path.write_text(json.dumps(server_config, indent=2))
log_dir.mkdir(parents=True, exist_ok=True)
log_path = log_dir / f"{name}.log"
get_logger().info(f"Starting env server {name} at {address} (logs: {log_path})")
with open(log_path, "w") as log_file:
process = Popen(
["env-server", "@", config_path.as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS},
stdout=log_file,
stderr=log_file,
)
self.env_server_procs.append(process)
async def run(self) -> None:
await self.setup()
self.dispatcher_task = asyncio.create_task(self.dispatcher.start(), name="dispatcher")
await self.periodic_logger.start()
if self.config.online is None:
await self.maybe_run_evals(step=0)
else:
await self.watch()
# The periodic logger and the collector log to the W&B run, so they
# must stop before finalize marks the run finished.
await self.periodic_logger.stop()
await self.inference_metrics.stop()
get_logger().success("Evals finished!")
async def watch(self) -> None:
"""Online mode: evaluate each eligible weight checkpoint as it appears."""
config = self.config
assert config.online is not None
online = config.online
if online.resume_step is None:
# Base-model eval: the inference server starts with the untrained weights,
# so no reload is needed. The first trigger fires every env (policy v0)
# unless ``skip_first_step``.
await self.maybe_run_evals(step=0)
elif config.eval.retrigger_on_resume:
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
# evals). Requires the resume step's weights on disk. The final checkpoint
# force-fires every env, exactly like the watch loop below.
is_final = online.max_steps is not None and online.resume_step >= online.max_steps
await self.maybe_run_evals(step=online.resume_step, reload_weights=True, force=is_final)
get_logger().info(f"Watching {online.weights_dir} for new weight checkpoints (max_steps={online.max_steps})")
while True:
assert online.weights_dir is not None # resolved by the config validator
steps = get_all_ckpt_steps(online.weights_dir)
stable = {step: (get_step_path(online.weights_dir, step) / "STABLE").exists() for step in steps}
newest_stable = max((step for step in steps if stable[step]), default=None)
# Also walk eval-due steps that are no longer on disk: checkpoint cleaning
# (ckpt.keep_last / keep_interval) can delete a step before this scan sees
# it, and a vanished step would otherwise be skipped without a trace.
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_stable)):
if step <= self.last_step:
continue
if step not in stable:
get_logger().warning(
f"Weight checkpoint for eval step {step} was deleted before it could be "
"evaluated (checkpoint cleaning outpaced the evals process) - skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
if not stable[step]:
# The trainer writes checkpoints in ascending order, so a marker-less
# step below a stable one is an abandoned partial write (e.g. a crash
# mid-save), not one in progress — skip it instead of wedging on it.
if newest_stable is None or newest_stable < step:
break # still being written — later steps can't be ready either
get_logger().warning(
f"Weight checkpoint step {step} has no STABLE marker but newer stable "
"checkpoints exist - treating it as abandoned and skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
is_final = online.max_steps is not None and step >= online.max_steps
await self.maybe_run_evals(step=step, reload_weights=True, force=is_final)
if online.max_steps is not None and self.last_step >= online.max_steps:
break
await asyncio.sleep(POLL_INTERVAL_S)
def deleted_due_steps(self, steps: list[int], newest_stable: int | None) -> set[int]:
"""Eval-due steps up to the newest stable checkpoint that are missing from the
weights dir — the trainer wrote them (it saves at every due step), so their
absence means checkpoint cleaning removed them before they were evaluated."""
if newest_stable is None:
return set()
due = {
step
for interval in self.eval_source.intervals.values()
for step in range(interval, newest_stable + 1, interval)
}
return due - set(steps)
async def maybe_run_evals(self, step: int, *, reload_weights: bool = False, force: bool = False) -> None:
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
reloading the inference weights first. No-op when no env is due."""
if reload_weights:
assert self.config.online is not None and self.config.online.weights_dir is not None
weight_dir = get_step_path(self.config.online.weights_dir, step)
if not (weight_dir / "STABLE").exists():
get_logger().warning(f"No stable weight checkpoint for step {step} ({weight_dir}) - skipping eval")
self.last_step = max(self.last_step, step)
return
fired = self.eval_source.trigger(step, force=force)
self.last_step = max(self.last_step, step)
if not fired:
return
now = time.perf_counter()
for env_name in fired:
self.eval_triggered_at[(env_name, step)] = now
total_rollouts = sum(
self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
for env_name in fired
)
if reload_weights:
get_logger().info(f"Updating inference weights to checkpoint step {step} ({weight_dir})")
try:
await self.pool.update_weights(weight_dir, step=step)
except Exception as exc:
# Skip this step instead of killing the run; drain the queued examples
# so they don't leak into a later epoch with the wrong eval_step.
while self.eval_source.next_example() is not None:
pass
get_logger().error(f"Failed to update inference weights to step {step} - skipping evals: {exc!r}")
return
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
# between the trigger above and the weight reload completing.
self.policy.version = step
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=f"eval was triggered at step {step}")
await self.consume_epoch(fired)
async def consume_epoch(self, fired: list[str]) -> None:
"""Consume dispatcher episodes until every fired env's epoch finalizes,
routing them through the sink and monitors."""
# An env with no examples emits no episodes, so its epoch can never finalize.
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
while pending:
episode: list[Rollout] = await self.dispatcher.out_q.get()
step = episode[0].eval_step
assert step is not None
run = vf.EvalRunInfo(id=self.run_id, name=self.run_name, step=step)
for rollout in episode:
rollout.record_run(
run,
env_name=rollout.env_name,
group_id=str(rollout.group_id),
episode_id=rollout.episode_id,
policy_version=rollout.policy_version,
)
await monitors.log(group_episodes(episode), step, "eval", "all")
eval_batch = self.eval_sink.add(episode)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
pending.discard(eval_batch.env_name)
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
if not batch.rollouts:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
return
await monitors.log(group_episodes(batch.rollouts.effective.rollouts), batch.step, "eval", "effective")
rollouts = batch.rollouts
effective = rollouts.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", rollouts), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
eff, full = effective.metrics, rollouts.metrics
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
get_logger().success(
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
)
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
"""Pipeline view for the ``PeriodicLogger``: per-env epoch progress plus the
in-flight pool against the controller's current cap."""
disp_gauges = self.dispatcher.gauges()
disp_drain = self.dispatcher.metrics.drained(train_envs=set(), eval_envs={env.name for env in self.eval_envs})
parts = []
for env_name, _step, arrived, expected, buffered in sorted(self.eval_sink.batch_progress()):
part = f"{env_name} {arrived}/{expected} ({arrived / expected:.1%})" if expected else env_name
if buffered:
part += f" (+{buffered} buffered)"
parts.append(part)
progress_part = " | ".join(parts) if parts else "Idle"
body = (
f"{progress_part}; {self.dispatcher.inflight_eval_count} inflight episodes "
f"(cap {self.dispatcher.max_inflight}, signal {self.concurrency.signal})"
)
payload = {**disp_gauges, **disp_drain, **self.concurrency.gauges()}
return body, payload
async def stop(self) -> None:
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
periodic_logger: PeriodicLogger | None = getattr(self, "periodic_logger", None)
if periodic_logger is not None:
await periodic_logger.stop()
inference_metrics: InferenceMetricsCollector | None = getattr(self, "inference_metrics", None)
if inference_metrics is not None:
await inference_metrics.stop()
dispatcher: Dispatcher | None = getattr(self, "dispatcher", None)
if dispatcher is not None:
await dispatcher.stop()
pool: InferencePool | None = getattr(self, "pool", None)
if pool is not None:
await pool.stop()
cleanup_processes(self.env_server_procs)
@clean_exit
async def run_evals(config: EvalsConfig) -> None:
evals = Evals(config)
try:
await evals.run()
# Finalize only on a clean exit — a crashed evals must not mark the run completed.
await monitors.finalize()
finally:
await evals.stop()
def main() -> None:
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
set_proc_title("Evals")
asyncio.run(run_evals(cli(EvalsConfig)))
if __name__ == "__main__":
main()
+1 -1
View File
@@ -55,7 +55,7 @@ class WandbMonitor(Monitor):
primary = label == primary_label
# The primary creates the run; the finisher writes its final state. They can
# differ when the run's creator is not its last-alive writer (e.g. the SFT
# trainer creates the run, the evaluator outlives it and finalizes).
# trainer creates the run, the evals process outlives it and finalizes).
finisher = label == os.environ.get("WANDB_SHARED_FINISHER", primary_label)
settings = wandb.Settings(
mode="shared",
+25 -10
View File
@@ -7,9 +7,10 @@ pressure off the engines and reacts at the pipeline's own pace (AIMD):
- **Grow** the cap multiplicatively per pipeline turnover (each completion
advances the turnover by ``1/inflight``) while the engines are clear, KV
usage is below ``KV_USAGE_GROW``, and the cap binds admission.
- **Trim** above ``KV_USAGE_TRIGGER``: resize cap and pool to what the
engines hold at ``KV_USAGE_TARGET`` and cancel the excess, youngest first.
Cap moves alone cannot relieve pressure from units maturing in place.
- **Trim** above ``KV_USAGE_SOFT_CAP``: lower the cap to what the engines
hold at ``KV_USAGE_TARGET`` and let completions drain the pool (soft). If
usage still climbs past ``KV_USAGE_HARD_CAP`` — units maturing in place
outpace completions — also cancel the excess, youngest first (hard).
- **Cut** on overload: preemptions (single-shot loads) or a persistent
capacity queue (agentic loads never preempt — admission control parks
excess load in the waiting queue). Cut, cancel the excess, then freeze
@@ -46,8 +47,14 @@ BINDING_FRACTION = 0.9
KV_USAGE_GROW = 0.6
"""Grow only while every decode engine's KV usage is below this."""
KV_USAGE_TRIGGER = 0.8
"""Above this usage, trim the cap and the in-flight pool."""
KV_USAGE_SOFT_CAP = 0.8
"""Above this usage, soft-trim: lower the cap and let completions drain the
pool naturally — no work is cancelled."""
KV_USAGE_HARD_CAP = 0.9
"""Above this usage, hard-trim: in-place context growth is outpacing
completions despite the closed gate, so also cancel the pool excess before
thrash onset (a cliff, not a slope)."""
KV_USAGE_TARGET = 0.7
"""A trim resizes to inflight * target / usage — below the trigger, so pool growth has headroom before the next trim."""
@@ -271,19 +278,27 @@ class ConcurrencyController:
self.escalated = True
return
if max_usage > KV_USAGE_TRIGGER and inflight > 0 and self.trim_cooldown == 0:
if max_usage > KV_USAGE_SOFT_CAP and inflight > 0 and self.trim_cooldown == 0:
hard = max_usage > KV_USAGE_HARD_CAP
target = int(self.clamp(inflight * KV_USAGE_TARGET / max_usage))
self.resize_down(target, inflight, reason=f"kv headroom (usage {max_usage:.2f})")
self.resize_down(
target,
inflight,
reason=f"kv headroom (usage {max_usage:.2f}, {'hard' if hard else 'soft'} trim)",
cancel=hard,
)
self.trim_cooldown = KV_TRIM_COOLDOWN_POLLS
# ── internals ────────────────────────────────────────────────────────────
def resize_down(self, target: int, inflight: int, *, reason: str) -> None:
"""Lower the cap (never raise) and cancel the in-flight excess."""
def resize_down(self, target: int, inflight: int, *, reason: str, cancel: bool = True) -> None:
"""Lower the cap (never raise) and, with ``cancel``, shed the
in-flight excess; without it, admission stays blocked until the pool
drains below the new cap on its own."""
target = min(target, self.max_inflight)
self.cap = float(target)
self.apply_limit(target, reason=reason)
if self.on_overload is not None and inflight > target:
if cancel and self.on_overload is not None and inflight > target:
self.on_overload(inflight - target)
def apply_limit(self, n_max: int, *, reason: str | None) -> None:
+6 -3
View File
@@ -140,9 +140,9 @@ class Dispatcher:
def __init__(
self,
*,
train_envs: TrainEnvs,
train_envs: TrainEnvs | None,
eval_envs: EvalEnvs | None,
train_source: TrainSource,
train_source: TrainSource | None,
eval_source: EvalSource | None,
policy_pool: InferencePool,
policy: Policy,
@@ -181,7 +181,7 @@ class Dispatcher:
self.admission_window_s = 5.0
self.admission_window_start = time.monotonic()
self.admissions_in_window = 0
self.min_burst = max((env.config.group_size for env in train_envs), default=8)
self.min_burst = max((env.config.group_size for env in train_envs or ()), default=8)
self.inflight: dict[asyncio.Task, InflightEpisode] = {}
self.groups: dict[uuid.UUID, GroupState] = {}
@@ -211,6 +211,7 @@ class Dispatcher:
def _train_pool_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
"""``(pool, model_name, is_live)`` for *train* rollouts of this env —
the env sampler's pool. (Eval always uses the policy.)"""
assert self.train_envs is not None # train groups only exist when train is configured
sampler = self.train_envs.get(env_name).sampler
if sampler.samples_from_live_policy:
return sampler.pool, self.policy.model_name, True
@@ -365,6 +366,7 @@ class Dispatcher:
continue
# Frozen-sourced rollouts never go stale — their sampler doesn't
# change with policy updates.
assert self.train_envs is not None
if not self.train_envs.get(meta.env_name).sampler.samples_from_live_policy:
continue
meta.off_policy_steps += 1
@@ -448,6 +450,7 @@ class Dispatcher:
"""Pop the next example from the corresponding source and wrap it in
a ``GroupState``. Returns ``None`` if the source is empty."""
if kind == "train":
assert self.train_source is not None
source = self.train_source
else:
assert self.eval_source is not None
+1 -1
View File
@@ -46,7 +46,7 @@ class EvalSource:
def trigger(self, step: int, *, force: bool = False) -> list[str]:
"""Fire eligible envs for ``step`` and return their names. On resume
``first_trigger`` is False, so the startup/base eval doesn't re-run.
``force`` fires every env regardless of interval (e.g. the evaluator's
``force`` fires every env regardless of interval (e.g. the evals process's
final-checkpoint eval)."""
is_first, self.first_trigger = self.first_trigger, False
if is_first and self.eval_config.skip_first_step:
-320
View File
@@ -1,320 +0,0 @@
"""Online evaluator: disk-checkpoint-driven evals against a live inference server.
The trainer writes HF weight checkpoints to ``weights/step_{n}`` (``STABLE``
marker on completion) — that is its signal that a new policy is ready. The
evaluator watches the directory, tells the inference server to reload each
eligible checkpoint from disk (``/update_weights``, no NCCL rendezvous), and
runs the configured evals against the updated weights, sequentially per
checkpoint so every epoch measures exactly one policy version.
Reuses the orchestrator's eval components — ``EvalEnvs`` / ``EvalSource`` /
``EvalSink`` / ``EvalRollouts`` — and logs metrics and episodes through the same
monitors (``eval/{env}/...`` metrics, episode traces via the file monitor).
"""
from __future__ import annotations
import asyncio
import os
import time
import uuid
import verifiers.v1 as vf
from prime_rl import monitors
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.orchestrator.envs import EvalEnv, EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.types import EvalBatch, Rollout
from prime_rl.orchestrator.utils import group_episodes, intercept_vf_logging, set_default_executor
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_step_path
from prime_rl.utils.utils import clean_exit
monkey_patch_oai_iterable_types()
monkey_patch_chat_completion_logprobs()
# How often to re-scan the weights directory for new checkpoints.
POLL_INTERVAL_S = 2.0
class Evaluator:
def __init__(self, config: EvaluatorConfig) -> None:
self.config = config
setup_logger(config.log.level, json_logging=config.log.json_logging)
intercept_vf_logging(logger="verifiers.v1", level="WARN")
get_logger().info(f"Starting evaluator (weights_dir={config.weights_dir})")
# The last weight-checkpoint step already handled (evaluated or skipped).
self.last_step = config.resume_step or 0
self.eval_triggered_at: dict[tuple[str, int], float] = {}
async def setup(self) -> None:
config = self.config
set_default_executor()
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
wandb=config.monitors.wandb,
file=config.monitors.file,
output_dir=config.output_dir,
run_config=config,
eval_env_names=[source.resolved_name for source in config.eval.source],
overview_flavor="sft",
)
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
self.run_name = os.environ.get("PRL_RUN_NAME")
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
self.pool = InferencePool(config.eval.client, model_name=config.model)
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.eval.source, config.eval.env_addresses)
await self.eval_envs.start()
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
get_logger().info("Waiting for inference pool to be ready")
await self.pool.wait_for_ready(config.model)
get_logger().success("Inference pool ready")
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=config.resume_step is not None)
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
async def run(self) -> None:
await self.setup()
config = self.config
if config.resume_step is None:
# Base-model eval: the inference server starts with the untrained weights,
# so no reload is needed. The first trigger fires every env (policy v0)
# unless ``skip_first_step``.
await self.maybe_run_evals(step=0)
elif config.eval.retrigger_on_resume:
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
# evals). Requires the resume step's weights on disk. The final checkpoint
# force-fires every env, exactly like the watch loop below.
is_final = config.max_steps is not None and config.resume_step >= config.max_steps
await self.maybe_run_evals(step=config.resume_step, reload_weights=True, force=is_final)
get_logger().info(f"Watching {config.weights_dir} for new weight checkpoints (max_steps={config.max_steps})")
while True:
assert config.weights_dir is not None # resolved by the config validator
steps = get_all_ckpt_steps(config.weights_dir)
stable = {step: (get_step_path(config.weights_dir, step) / "STABLE").exists() for step in steps}
newest_stable = max((step for step in steps if stable[step]), default=None)
# Also walk eval-due steps that are no longer on disk: checkpoint cleaning
# (ckpt.keep_last / keep_interval) can delete a step before this scan sees
# it, and a vanished step would otherwise be skipped without a trace.
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_stable)):
if step <= self.last_step:
continue
if step not in stable:
get_logger().warning(
f"Weight checkpoint for eval step {step} was deleted before it could be "
"evaluated (checkpoint cleaning outpaced the evaluator) - skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
if not stable[step]:
# The trainer writes checkpoints in ascending order, so a marker-less
# step below a stable one is an abandoned partial write (e.g. a crash
# mid-save), not one in progress — skip it instead of wedging on it.
if newest_stable is None or newest_stable < step:
break # still being written — later steps can't be ready either
get_logger().warning(
f"Weight checkpoint step {step} has no STABLE marker but newer stable "
"checkpoints exist - treating it as abandoned and skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
is_final = config.max_steps is not None and step >= config.max_steps
await self.maybe_run_evals(step=step, reload_weights=True, force=is_final)
if config.max_steps is not None and self.last_step >= config.max_steps:
break
await asyncio.sleep(POLL_INTERVAL_S)
get_logger().success("Evaluator finished!")
def deleted_due_steps(self, steps: list[int], newest_stable: int | None) -> set[int]:
"""Eval-due steps up to the newest stable checkpoint that are missing from the
weights dir — the trainer wrote them (it saves at every due step), so their
absence means checkpoint cleaning removed them before they were evaluated."""
if newest_stable is None:
return set()
due = {
step
for interval in self.eval_source.intervals.values()
for step in range(interval, newest_stable + 1, interval)
}
return due - set(steps)
async def maybe_run_evals(self, step: int, *, reload_weights: bool = False, force: bool = False) -> None:
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
reloading the inference weights first. No-op when no env is due."""
assert self.config.weights_dir is not None # resolved by the config validator
weight_dir = get_step_path(self.config.weights_dir, step)
if reload_weights and not (weight_dir / "STABLE").exists():
get_logger().warning(f"No stable weight checkpoint for step {step} ({weight_dir}) - skipping eval")
self.last_step = max(self.last_step, step)
return
fired = self.eval_source.trigger(step, force=force)
self.last_step = max(self.last_step, step)
if not fired:
return
now = time.perf_counter()
for env_name in fired:
self.eval_triggered_at[(env_name, step)] = now
total_rollouts = sum(
self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
for env_name in fired
)
if reload_weights:
get_logger().info(f"Updating inference weights to checkpoint step {step} ({weight_dir})")
try:
await self.pool.update_weights(weight_dir, step=step)
except Exception as exc:
# Skip this step instead of killing the run; drain the queued examples
# so they don't leak into a later epoch with the wrong eval_step.
while self.eval_source.next_example() is not None:
pass
get_logger().error(f"Failed to update inference weights to step {step} - skipping evals: {exc!r}")
return
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
await self.run_evals(step)
async def run_evals(self, step: int) -> None:
"""Drain the eval queue for one step under bounded concurrency, routing
finished episodes through the sink and finalizing each env's epoch."""
semaphore = asyncio.Semaphore(self.config.eval.max_inflight_episodes)
tasks: list[asyncio.Task] = []
while (example := self.eval_source.next_example()) is not None:
env = self.eval_envs.get(example["env_name"])
group_id = uuid.uuid4()
for _ in range(env.config.group_size):
tasks.append(asyncio.create_task(self.run_episode(env, example, group_id, step, semaphore)))
for future in asyncio.as_completed(tasks):
episode = await future
run = vf.EvalRunInfo(id=self.run_id, name=self.run_name, step=step)
for rollout in episode:
rollout.record_run(
run,
env_name=rollout.env_name,
group_id=str(rollout.group_id),
episode_id=rollout.episode_id,
policy_version=rollout.policy_version,
)
await monitors.log(group_episodes(episode), step, "eval", "all")
eval_batch = self.eval_sink.add(episode)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
async def run_episode(
self,
env: EvalEnv,
example: dict,
group_id: uuid.UUID,
step: int,
semaphore: asyncio.Semaphore,
) -> list[Rollout]:
"""Run one episode against the env server; failures synthesize an
error-marker rollout so the sink's count-based finalization still fires."""
async with semaphore:
try:
rollouts = await env.run(
client=self.pool.eval_client,
model_name=self.pool.model_name,
cache_salt=str(step),
task_data=example["task"].data.model_dump(mode="json"),
)
except Exception as exc:
get_logger().warning(f"Rollout task failed in group {group_id} ({env.name}): {exc!r}")
rollout = Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=example["task"].data.idx, prompt=None)),
agent=vf.AgentInfo(config=vf.AgentConfig()),
)
rollout.record_error(exc)
rollouts = [rollout]
for rollout in rollouts:
if not rollout.has_error and rollout.num_turns == 0:
rollout.errors.append(
vf.Error(type="EmptyTrajectory", message="Rollout returned with no trajectory steps")
)
rollout.ok = False
get_logger().warning(f"Empty trajectory in group {group_id} ({env.name})")
rollout.kind = "eval"
rollout.env_name = env.name
rollout.group_id = group_id
# For SFT-driven evals the policy version *is* the checkpoint step.
rollout.policy_version = step
rollout.eval_step = step
return rollouts
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
if not batch.rollouts:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
return
await monitors.log(group_episodes(batch.rollouts.effective.rollouts), batch.step, "eval", "effective")
rollouts = batch.rollouts
effective = rollouts.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", rollouts), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
eff, full = effective.metrics, rollouts.metrics
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
get_logger().success(
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
)
async def stop(self) -> None:
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
pool = getattr(self, "pool", None)
if pool is not None:
await pool.stop()
@clean_exit
async def run_evaluator(config: EvaluatorConfig) -> None:
evaluator = Evaluator(config)
try:
await evaluator.run()
# Finalize only on a clean exit — a crashed evaluator must not mark the run completed.
await monitors.finalize()
finally:
await evaluator.stop()
def main() -> None:
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
set_proc_title("Evaluator")
asyncio.run(run_evaluator(cli(EvaluatorConfig)))
if __name__ == "__main__":
main()
@@ -307,6 +307,22 @@ class InferenceMetricsCollector:
self.task = asyncio.create_task(poll_loop())
async def probe(self, attempts: int = 3, interval: float = 2.0) -> bool:
"""Scrape once, outside the poll loop, and report whether any engine
answered with metrics. External API endpoints (no vLLM ``/metrics``)
fail every attempt immediately; the retries only cover a real engine
racing its first exposition."""
for attempt in range(attempts):
if attempt > 0:
await asyncio.sleep(interval)
try:
await self.collect_and_log()
except Exception as e:
get_logger().warning(f"Inference metrics probe failed: {e!r}")
if self.previous:
return True
return False
async def collect_and_log(self):
now = time.monotonic()
@@ -42,15 +42,15 @@ ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
{% if prl_run_id %}
# Trainer and evaluator (separate SLURM job) log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evaluator (which
# Trainer and evals (separate SLURM job) log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
# outlives the trainer) finalizes it.
export PRL_RUN_ID={{ prl_run_id }}
export PRL_RUN_NAME={{ run_name }}
export WANDB_RUN_ID=$PRL_RUN_ID
export WANDB_SHARED_MODE=1
export WANDB_SHARED_PRIMARY=trainer
export WANDB_SHARED_FINISHER=evaluator
export WANDB_SHARED_FINISHER=evals
export WANDB_SHARED_LABEL=trainer
export WANDB_PROGRAM="uv run sft"
{% endif %}
@@ -22,7 +22,7 @@
#SBATCH --error={{ output_dir }}/eval_job_%j.log
# Online-eval job for a decoupled SFT run: the inference pool (one vLLM engine per
# DP rank behind a single router) plus the evaluator and its env servers. The trainer
# DP rank behind a single router) plus the evals process and its env servers. The trainer
# runs in a separate SLURM job and hands weights over via checkpoints on the shared
# filesystem, so this job outlives the trainer and exits after evaluating the final
# checkpoint (max_steps).
@@ -50,22 +50,22 @@ export OUTPUT_DIR={{ output_dir }}
mkdir -p $OUTPUT_DIR/logs/inference
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
# A clean evaluator exit cannot trip srun --kill-on-bad-exit (which only propagates
# A clean evals exit cannot trip srun --kill-on-bad-exit (which only propagates
# failures), so node 0 publishes completion through this job-scoped sentinel and the
# other nodes watch for it to release their engines. Stale sentinels from other job
# IDs are inert, so only this job's own path needs clearing.
export EVAL_DONE=$OUTPUT_DIR/.eval_done_$SLURM_JOB_ID
rm -f "$EVAL_DONE"
{% if prl_run_id %}
# Trainer (separate SLURM job) and evaluator log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evaluator (which
# Trainer (separate SLURM job) and evals log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
# outlives the trainer) finalizes it.
export PRL_RUN_ID={{ prl_run_id }}
export PRL_RUN_NAME={{ run_name }}
export WANDB_RUN_ID=$PRL_RUN_ID
export WANDB_SHARED_MODE=1
export WANDB_SHARED_PRIMARY=trainer
export WANDB_SHARED_FINISHER=evaluator
export WANDB_SHARED_FINISHER=evals
export WANDB_PROGRAM="uv run sft"
{% endif %}
# Networking
@@ -139,7 +139,7 @@ CLEANUP_SH
# Run the eval deployment
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a crashed engine/router/evaluator terminates the SLURM job instead
# tasks so a crashed engine/router/evals terminates the SLURM job instead
# of leaving the surviving ranks holding nodes.
#
# The body goes to bash on stdin through a quoted heredoc instead of a
@@ -204,9 +204,9 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
{%- if eval_env_names %}
# One env server per eval source next to the evaluator, which connects to each
# One env server per eval source next to the evals process, which connects to each
# source at its deterministic loopback address (so this node), polling until
# they are up - the servers and the evaluator start in parallel.
# they are up - the servers and the evals process start in parallel.
{%- for name in eval_env_names %}
mkdir -p $OUTPUT_DIR/logs/envs/eval
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.json \
@@ -214,30 +214,30 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
{%- endfor %}
{%- endif %}
# The evaluator watches the trainer's weights dir on the shared filesystem and
# The evals process watches the trainer's weights dir on the shared filesystem and
# drives the pool: data plane through the router, admin ops per rank.
{%- for key, value in evaluator_env_vars.items() %}
{%- for key, value in evals_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
WANDB_SHARED_LABEL=evaluator uv run evaluator \
@ $CONFIG_DIR/evaluator.json \
WANDB_SHARED_LABEL=evals uv run evals \
@ $CONFIG_DIR/evals.json \
--eval.client.base-url $INFER_URLS \
--eval.client.admin-base-url $ADMIN_URLS \
2>&1 | tee $OUTPUT_DIR/logs/evaluator.log &
EVALUATOR_PID=$!
2>&1 | tee $OUTPUT_DIR/logs/evals.log &
EVALS_PID=$!
else
# Watch for the completion sentinel so this node's wait below returns when
# the evaluator (on node 0) finishes cleanly.
# the evals process (on node 0) finishes cleanly.
( until [ -f "$EVAL_DONE" ]; do sleep 10; done ) &
fi
# Wait for the first background job to exit and propagate its exit code. This
# turns background process crashes (engines, router, env servers, evaluator)
# turns background process crashes (engines, router, env servers, evals)
# into task failures that --kill-on-bad-exit=1 can broadcast to the other nodes
# so the whole job tears down instead of leaving zombies holding the allocation.
wait -n -p FINISHED_PID
EXIT_CODE=$?
if [ "${FINISHED_PID:-}" = "${EVALUATOR_PID:-none}" ]; then
if [ "${FINISHED_PID:-}" = "${EVALS_PID:-none}" ]; then
# Publish completion so the sentinel watchers on the other nodes release too
# (a zero exit here never trips --kill-on-bad-exit).
touch "$EVAL_DONE"
+1 -1
View File
@@ -498,7 +498,7 @@ class WeightCheckpointManager:
# Always keep the newest weight checkpoint — it is the current policy. With
# keep_interval-only cleaning, a freshly saved non-aligned final checkpoint would
# otherwise be deleted immediately, and the online evaluator would wait for the
# otherwise be deleted immediately, and the online evals would wait for the
# max_steps checkpoint forever.
if self.ckpt_steps:
steps_to_keep.add(self.ckpt_steps[-1])
+15 -11
View File
@@ -136,16 +136,20 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
m, s, t = _online_logsumexp_and_weighted_update(m, s, t, scaled_logits)
mask = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
if torch.any(mask):
idx = (labels_chunk[mask] - vocab_start).to(torch.long)
target_logits[mask] = scaled_logits[mask, idx]
# Branchless target extraction - we don't want to stall the GPU here (because: if torch.any()) calls bool(Tensor) calls Tensor.items() <- sync here we don't want
in_range = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
local_idx = (labels_chunk - vocab_start).clamp(0, vocab_end - vocab_start - 1).to(torch.int64)
chunk_target = scaled_logits.gather(1, local_idx.unsqueeze(1)).squeeze(1)
target_logits = torch.where(in_range, chunk_target, target_logits)
logz_chunk = m + torch.log(s)
logz[start:end] = logz_chunk
logprobs[start:end] = target_logits - logz_chunk
entropy[start:end] = logz_chunk - (t / s)
ctx.set_materialize_grads(
False
) # Without materialized grads unused outputs get grad None instead of zeros and backward can reject them without a sync
ctx.save_for_backward(hidden, weight, labels, inv_temperature, logz)
ctx.chunk_size = chunk_size
@@ -153,9 +157,9 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
@staticmethod
def backward(ctx, grad_logprobs: torch.Tensor, grad_entropy: torch.Tensor | None):
assert grad_entropy is None or torch.all(grad_entropy == 0.0), (
"Backward through entropy is not implemented in FusedOutputLinear"
)
# Grads are not materialized (see forward above) so an unused entropy output arrives becomes None, and as we don't compare values we don't have any sync
assert grad_entropy is None, "Backward through entropy is not implemented in FusedOutputLinear"
assert grad_logprobs is not None, "FusedOutputLinear backward requires logprobs gradients"
hidden, weight, labels, inv_temperature, logz = ctx.saved_tensors
chunk_size: int = ctx.chunk_size
@@ -184,10 +188,10 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
probs = torch.exp(scaled_logits - logz_chunk.unsqueeze(-1))
grad_logits = (-grad_chunk).unsqueeze(-1) * probs
mask = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
if torch.any(mask):
idx = (labels_chunk[mask] - vocab_start).to(torch.long)
grad_logits[mask, idx] += grad_chunk[mask]
# Branchless grad scatter like we did in the sync-free forward
in_range = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
local_idx = (labels_chunk - vocab_start).clamp(0, vocab_end - vocab_start - 1).to(torch.int64)
grad_logits.scatter_add_(1, local_idx.unsqueeze(1), (grad_chunk * in_range).unsqueeze(1))
grad_logits = grad_logits * inv_t_chunk
if needs_hidden:
+3 -3
View File
@@ -43,7 +43,7 @@ def format_log_message(
log_dir: Path,
trainer: bool = False,
orchestrator: bool = False,
evaluator: bool = False,
evals: bool = False,
inference: bool = False,
job_log: bool = False,
train_env_names: list[str] | None = None,
@@ -68,8 +68,8 @@ def format_log_message(
log_lines.append(f"{i2}{'All ranks:':<{col - 1}}tail -F {log_dir}/trainer/torchrun/*/*/*/*.log")
if orchestrator:
log_lines.append(f"{i1}{'Orchestrator:':<{col}}tail -F {log_dir}/orchestrator.log")
if evaluator:
log_lines.append(f"{i1}{'Evaluator:':<{col}}tail -F {log_dir}/evaluator.log")
if evals:
log_lines.append(f"{i1}{'Evals:':<{col}}tail -F {log_dir}/evals.log")
if inference:
log_lines.append(f"{i1}{'Inference:':<{col}}tail -F {log_dir}/inference.log")
if num_infer_nodes > 1:
+2
View File
@@ -7,6 +7,7 @@ from pydantic import BaseModel, Field, ValidationError
from pydantic_config import ConfigFileError
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.configs.evals import EvalsConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.rl import RLConfig
@@ -23,6 +24,7 @@ CONFIG_CLASSES = [
OrchestratorConfig,
InferenceConfig,
EnvServerConfig,
EvalsConfig,
]