Compare commits

...
Author SHA1 Message Date
Mika SenghaasandGitHub 7f811c01a8 chore: bump verifiers to latest main (#3572)
## Summary

- Bump the `deps/verifiers` submodule from `5a69fb4d` (`feat: stream
served episodes turn by turn (#2512)`) to `28f08939` (latest `main`).
- Commits this pulls in:
- [vf#2616](https://github.com/PrimeIntellect-ai/verifiers/pull/2616)
(`ff3b8dc5`): fix(v1): recover the routed-experts row dropped at each
turn boundary — a reused sampled prefix node keeps a placeholder final
routing row until a later turn's prefill forwards it; it is now
repaired.
- [vf#2618](https://github.com/PrimeIntellect-ai/verifiers/pull/2618)
(`28f08939`): fix(serve): stream repaired routing rows — served
multi-turn episodes had the worker's #2616 repair but the delta stream
never delivered it, so the client kept placeholder routing rows; indexed
`routing_repairs` now reach the client assembly.
- Together they keep `routed_experts` training data correct for
multi-turn MoE episodes under env servers (the router-replay /
routed-experts data path).
- `uv.lock` is unchanged: verifiers is an editable path dependency and
the new commits touch no dependency metadata.

## Verification

- `git -C deps/verifiers merge-base --is-ancestor 5a69fb4d 28f08939` —
the new pin descends from the old one.
- `uv lock --check` — passes.
- `uv run pytest deps/verifiers/tests/v1/test_graph.py
deps/verifiers/tests/v1/test_serve_delta.py -q` — 18 passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the routed-experts data path for multi-turn MoE under env
servers; wrong routing rows would corrupt training data, but the change
is an upstream bugfix with targeted tests.
> 
> **Overview**
> Updates the **`deps/verifiers`** submodule from `5a69fb4d` to
**`28f08939`** (latest `main`). No other repo files change—**`uv.lock`**
stays the same because verifiers is an editable path dependency.
> 
> The new pin pulls in two upstream fixes for **multi-turn MoE
`routed_experts` / router-replay** when using env servers: **v1 graph
repair** for a routing row that was dropped at turn boundaries when a
sampled prefix node was reused, and **serve streaming** so those
repaired rows are included in the delta stream instead of leaving
placeholder routing on the client.
> 
> Together this keeps training data aligned with what the worker
actually computed for served multi-turn episodes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0fb3ab40ec5b917c2d0d548ac022fe6b5d08fce8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 10:54:59 -07:00
Mika SenghaasandGitHub 2d6dc64efd fix: log periodic gauges through the monitors (#3565)
## Summary
- The `PeriodicLogger` printed its pipeline view to the console and
called `wandb.log` directly, so the `dispatcher/*`, `concurrency/*`,
`watcher/*`, and `event_loop_lag/*` gauges only ever reached W&B. The
file monitor (and with it the local dashboard's `metrics.jsonl`) and the
Prime monitor never saw them; with W&B disabled the gauges existed only
as console log text.
- The periodic payload now fans out through `monitors.log(payload,
step=None)` like the inference-metrics collector, so every registered
monitor receives it as a time-keyed row and stamps its own time axis.
All W&B-specific logic is gone from the orchestrator and the eval runner
(`eval/runner.py`, which replaced the old evals process in #3471): the
W&B monitor already defines the `_timestamp` axis lazily per key prefix,
so the eager `wandb.define_metric` pre-registration and its
`metric_keys`/`wandb_enabled` plumbing are removed (the now-unused
`DispatcherMetrics.drain_keys` helper goes with it).
- Clean-exit teardown now stops the `PeriodicLogger` before
`monitors.finalize()`, next to the inference collector — both write
through the monitors, and a tick after finalize would land on a finished
W&B / Prime run. The eval runner already drained its loggers first
(`drain()` before `finalize()`); the orchestrator now matches.
- Overview panels, mirrored in the W&B saved view
(`monitors/wandb/overview.py`) and the local dashboard
(`dashboard/static/app.js`), which the overview code keeps in sync: the
inflight panel gains `concurrency/max_inflight` so in-flight episodes
read against the adaptive cap, and the token-rate panels drop their
per-engine tail series (`generation_tokens_total:rate/min`,
`prompt_tokens_total:rate/max`).

## Verification
1-step reverse-text runs (`uv run rl @
configs/ci/integration/reverse-text/start.toml --max-steps 1`, W&B off,
file monitor on), before on `main` vs. after on this branch:

- **before**: `monitors/file/metrics.jsonl` has 13 rows and zero
`concurrency/*` / `dispatcher/*` keys — only
train/eval/inference/loss/perf keys.
- **after**: periodic time-keyed rows (`"step": null`, `"producer":
"orch"`) carrying all `concurrency/*` gauges (`max_inflight`,
`turnover`, `capacity`, `signal`, `growth_multiplier`), 12
`dispatcher/*` keys, 4 `watcher/*` keys, and 7 `event_loop_lag/*` keys.
- **local dashboard overview** (headless browser check against both run
dirs): after, the `dispatcher/inflight/{train,eval}` +
`concurrency/max_inflight` panel renders with data (all charts mounted,
no console errors); before, the panel is absent (no keys, no panel).
- **teardown ordering** (after the finalize-order fix): the last
`metrics.jsonl` write lands strictly before `monitors.finalize()`
(03:54:38.66 vs. the `Finalized metrics` log line at 03:54:39), zero
rows written at or after finalize, clean exit, no `Failed to log`
warnings.
- Re-verified after rebasing onto `main` (picked up the eval-CLI
consolidation and the concurrency-taper commit) and again after the
teardown-order fix — all green.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes observability plumbing and shutdown ordering for background
loggers; behavior is well-scoped but affects all runs’ metrics export
and clean-exit teardown.
> 
> **Overview**
> **Periodic pipeline metrics** (dispatcher, concurrency, watcher, event
loop lag) no longer go only to W&B via direct `wandb.log`.
`PeriodicLogger` now emits each tick through `monitors.log(payload,
step=None)`, so file monitor, dashboard `metrics.jsonl`, Prime, and W&B
all get the same time-keyed rows.
> 
> The orchestrator and eval runner drop `metric_keys`, `wandb_enabled`,
and eager `wandb.define_metric` pre-registration; unused
`DispatcherMetrics.drain_keys` is removed. On clean exit, the
orchestrator **stops `PeriodicLogger` before `monitors.finalize()`**,
matching inference metrics teardown so nothing writes after the run is
closed.
> 
> **Overview charts** (W&B overview + local dashboard) add
`concurrency/max_inflight` to the inflight panel and simplify token-rate
panels to fleet sum only (no per-engine min/max tails).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
be479ea13c728ab82bacdd9f0773fc70dc0a3b41. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 10:02:47 -07:00
07ebe34570 fix(rl): launch env servers in multi-node RL runs (#3568)
Multi-node RL runs currently launch no environment servers. The
orchestrator waits 600 seconds
for an address file that nobody writes, then times out, and the trainer
sits in the weight
broadcast until its own timeout.

The flat-to-nested refactor in #3471 replaced `format_log_message`'s two
flat `train_env_names` /
`eval_env_names` parameters with a single `env_names: dict[str,
list[str]]` and updated all four
call sites in `rl.py`. Two of them really are `format_log_message` calls
and were correct. The
other two are `template.render(...)` calls feeding

[`multi_node_rl.sbatch.j2:542-559`](https://github.com/PrimeIntellect-ai/prime-rl/blob/d5ed9fb7e4233c6f4914af2652c3bda69bddb0c7/src/prime_rl/templates/multi_node_rl.sbatch.j2#L542-L559),
which still reads the flat names:

```diff
# src/prime_rl/entrypoints/rl.py:534,574 in c394c2e1b, write_slurm_script
-            train_env_names=train_env_names,
-            eval_env_names=eval_env_names,
+            env_names={"train": train_env_names, "eval": eval_env_names},
```

```jinja
{# multi_node_rl.sbatch.j2:542,550, unchanged by this PR #}
{%- if train_env_names or eval_env_names %}
{%- for name in train_env_names %}
```

Under Jinja's default `Undefined`, a name that was never passed is
indistinguishable from an
empty list: `{% if train_env_names or eval_env_names %}` is false either
way and nothing raises.
The generated script was therefore identical to one for a run that
legitimately has no env
servers. This reverts the two render calls to flat kwargs and leaves the
three
`format_log_message` calls on the nested dict.

- The failure is silent: the generated sbatch and the per-source env
JSON both look correct, and
the first symptom is `TimeoutError: env server never published its
address ... within 600.0s`.
- Single-node and SFT are unaffected. Single-node goes through
`rl_local`, which spawns env
servers as subprocesses; `sft.py` already spreads its env names as
`**eval_vars`, the flat form
  `multi_node_sft.sbatch.j2` wants.

## Verification

**Render level.** The pre-fix script is 13 lines shorter, and those 13
lines are the entire
env-server block:

```sh
uv run rl @ examples/basic/reverse-text/rl.toml --deployment.type multi_node --deployment.num-train-nodes 1 --deployment.num-infer-nodes 1 --slurm.partition all --max-steps 2 --run.name envserver-check --no-dashboard --dry-run
grep -c "uv run env-server" $PRL_OUTPUT_DIR/envserver-check/launcher/rl.sbatch
```

Before: `0`. After: `2`, one for the train source and one for the eval
source. Diffing the two
generated scripts shows nothing else moved (comment block elided):

```diff
@@ -331,0 +332,13 @@
+    mkdir -p $LOG_DIR/envs/train
+    uv run env-server @ $CONFIG_DIR/envs/train/reverse-text.json \
+        > $LOG_DIR/envs/train/reverse-text.log 2>&1 &
+    mkdir -p $LOG_DIR/envs/eval
+    uv run env-server @ $CONFIG_DIR/envs/eval/reverse-text-eval.json \
+        > $LOG_DIR/envs/eval/reverse-text-eval.log 2>&1 &
```

**Runtime.** Before, from one of the failing multi-node runs, the
orchestrator polls for a file
no process will write and gives up after 600s:

```
TimeoutError: env server never published its address to
<run>/configs/attempt_1/resolved/envs/train/reverse-text.address within 600.0s
```

After, a 2-node reverse-text run on Qwen3-0.6B spawns the server, which
publishes its address
46s later, and training completes:

```
14:48:47  <run>/logs/attempt_1/envs/train/reverse-text.log created
14:49:33  EnvServerPool up: address=tcp://127.0.0.1:42101 workers=1/inf multiplex=128
15:01:56  SUCCESS Step 2 | 1.2s | Loss 0.0038 | Entropy 0.6078 | Grad. Norm 0.7942
```

That log file is the cleanest discriminator: the shell redirect on the
`uv run env-server` line
creates it, so before the fix it never exists at all.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 13:02:37 -04:00
8 changed files with 31 additions and 74 deletions
+1 -1
+3 -2
View File
@@ -406,8 +406,9 @@ const INFERENCE_PANELS = [
["inference/agg/num_requests_running/mean", "inference/agg/num_requests_running/min", "inference/agg/num_requests_running/max"],
["inference/agg/num_requests_waiting/mean", "inference/agg/num_requests_waiting/min", "inference/agg/num_requests_waiting/max"],
["inference/agg/prefix_cache_hit_rate/pooled", "inference/agg/prefix_cache_hit_rate/min"],
["inference/agg/generation_tokens_total:rate/sum", "inference/agg/generation_tokens_total:rate/min"],
["inference/agg/prompt_tokens_total:rate/sum", "inference/agg/prompt_tokens_total:rate/max"],
["inference/agg/generation_tokens_total:rate/sum"],
["inference/agg/prompt_tokens_total:rate/sum"],
["dispatcher/inflight/train", "dispatcher/inflight/eval", "concurrency/max_inflight"],
];
const TRAINER_KEY_RE = /^(perf|optim|loss|entropy|system|mismatch_kl|kl_ent_ratio|is_masked|masked_|unmasked_|max_vio|routing_|ref_kl|val)[/_]?/;
+4 -2
View File
@@ -531,7 +531,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
env_names={"train": train_env_names, "eval": eval_env_names},
train_env_names=train_env_names,
eval_env_names=eval_env_names,
**modelexpress_vars,
)
else:
@@ -571,7 +572,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
trainer_env_vars=trainer_env_vars,
orchestrator_env_vars=orchestrator_env_vars,
inference_env_vars=inference_env_vars,
env_names={"train": train_env_names, "eval": eval_env_names},
train_env_names=train_env_names,
eval_env_names=eval_env_names,
**modelexpress_vars,
)
+1 -8
View File
@@ -28,7 +28,7 @@ from prime_rl.orchestrator import live
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
@@ -79,7 +79,6 @@ class EvalRunner:
# 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.client.base_url}, model={config.model})")
self.clients = InferenceClient(config.client, model_name=config.model)
@@ -153,13 +152,7 @@ class EvalRunner:
self.periodic_logger = PeriodicLogger(
name="Eval",
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,
)
async def start(self) -> None:
+3 -3
View File
@@ -73,9 +73,9 @@ INFERENCE_PANELS = [
"inference/agg/num_requests_waiting/max",
],
["inference/agg/prefix_cache_hit_rate/pooled", "inference/agg/prefix_cache_hit_rate/min"],
["inference/agg/generation_tokens_total:rate/sum", "inference/agg/generation_tokens_total:rate/min"],
["inference/agg/prompt_tokens_total:rate/sum", "inference/agg/prompt_tokens_total:rate/max"],
["dispatcher/inflight/train", "dispatcher/inflight/eval"],
["inference/agg/generation_tokens_total:rate/sum"],
["inference/agg/prompt_tokens_total:rate/sum"],
["dispatcher/inflight/train", "dispatcher/inflight/eval", "concurrency/max_inflight"],
]
# SFT flavor: no rollout-based train sections — the training signal is the loss curve.
+2 -17
View File
@@ -92,8 +92,8 @@ class DispatcherMetrics:
def drained(self, *, train_envs: set[str], eval_envs: set[str]) -> dict[str, float]:
"""Return per-tick counters and clear them. Emits the full pre-
registered key set every tick (zero when no activity) so the wandb
time axis stays dense and ``define_metric`` lines up."""
registered key set every tick (zero when no activity) so the
time-keyed series stay dense on every monitor."""
out: dict[str, float] = {}
for kind in ("train", "eval"):
envs = train_envs if kind == "train" else eval_envs
@@ -112,21 +112,6 @@ class DispatcherMetrics:
self.errored_by_kind_env.clear()
return out
@staticmethod
def drain_keys(*, train_envs: set[str], eval_envs: set[str]) -> list[str]:
"""Full set of keys ``drained`` may emit; used by the periodic
logger for ``wandb.define_metric``."""
keys = [
"dispatcher/cancelled/train",
"dispatcher/cancelled/eval",
"dispatcher/errored/train",
"dispatcher/errored/eval",
]
for env in train_envs | eval_envs:
keys.append(f"dispatcher/cancelled/{env}")
keys.append(f"dispatcher/errored/{env}")
return keys
def _validate_episode_task(episode: vf.WireEpisode, task: vf.Task) -> None:
expected = (task.key, task.hash)
+7 -23
View File
@@ -11,7 +11,7 @@ and drives the pipeline. Components are single-purpose:
- ``TrainEpisodes`` / ``EvalEpisodes`` preserve episode boundaries and build per-step metrics.
- ``WeightWatcher`` advances ``Policy`` and notifies observers.
- ``PeriodicLogger`` polls the components on a shared interval for the
``_timestamp``-axis pipeline log.
pipeline log, a time-keyed row through the monitors.
Components don't reference the orchestrator. The orchestrator wires them
in ``setup()`` and drives them from ``main_loop()``.
@@ -41,7 +41,7 @@ from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient, setup_admin_plane
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
@@ -336,7 +336,6 @@ class Orchestrator:
)
log_interval = config.log.interval
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
self.concurrency = ConcurrencyController(config.concurrency, fallback_cost=config.seq_len)
self.dispatcher = Dispatcher(
@@ -398,24 +397,7 @@ class Orchestrator:
self.periodic_logger = PeriodicLogger(
name="Pipeline",
collect=self.collect_pipeline_view,
metric_keys=[
*list(self.dispatcher.gauges().keys()),
*list(self.concurrency.gauges().keys()),
*DispatcherMetrics.drain_keys(
train_envs={e.name for e in self.train_envs},
eval_envs={e.name for e in self.eval_envs} if self.eval_envs is not None else set(),
),
*list(self.watcher.gauges().keys()),
"event_loop_lag/min",
"event_loop_lag/mean",
"event_loop_lag/median",
"event_loop_lag/p90",
"event_loop_lag/p99",
"event_loop_lag/max",
"event_loop_lag/n",
],
interval=log_interval,
wandb_enabled=wandb_enabled,
)
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
@@ -457,10 +439,12 @@ class Orchestrator:
elapsed = format_time(time.perf_counter() - start_time)
if clean_exit:
get_logger().success(f"Orchestrator step loop done in {elapsed}")
# The collector logs to the W&B run, so it must stop before
# finalize marks the run finished
# The background loggers write through the monitors, so they must
# stop before finalize marks the run finished
if self.inference_metrics is not None:
await self.inference_metrics.stop()
if self.periodic_logger is not None:
await self.periodic_logger.stop()
# Finalize only on a clean exit — a crashed run must not be marked
# completed; the platform run's atexit hook marks it failed instead.
await monitors.finalize()
@@ -830,7 +814,7 @@ class Orchestrator:
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
"""Pipeline view for the orchestrator's ``PeriodicLogger``. Returns
``(console_body, wandb_payload)``. Per-env ``(env=N, …)``
``(console_body, payload)``. Per-env ``(env=N, …)``
breakdowns inline only when there's more than one train / eval env;
the eval halves drop entirely when nothing is accumulating."""
disp_gauges = self.dispatcher.gauges()
+10 -18
View File
@@ -1,16 +1,14 @@
"""PeriodicLogger: orchestrator's pipeline view, fires every ``interval``
seconds. ``collect()`` returns ``(console_body, wandb_payload)`` in one
call so drain-on-read counters fire exactly once per tick. Wandb writes
land on the ``_timestamp`` axis."""
seconds. ``collect()`` returns ``(console_body, payload)`` in one call so
drain-on-read counters fire exactly once per tick. The payload goes to every
registered monitor as a time-keyed row (``step=None``)."""
from __future__ import annotations
import asyncio
import time
from typing import Callable
import wandb
from prime_rl import monitors
from prime_rl.utils.async_utils import safe_cancel
from prime_rl.utils.logger import get_logger
@@ -21,21 +19,14 @@ class PeriodicLogger:
*,
name: str,
collect: Callable[[], tuple[str, dict[str, float]]],
metric_keys: list[str],
interval: float,
wandb_enabled: bool,
) -> None:
self.name = name
self.collect = collect
self.interval = interval
self.wandb_enabled = wandb_enabled
self.task: asyncio.Task | None = None
self.stopped = asyncio.Event()
if self.wandb_enabled:
for key in metric_keys:
wandb.define_metric(key, step_metric="_timestamp")
async def start(self) -> None:
self.task = asyncio.create_task(self.run(), name=f"{self.name}_periodic_logger")
@@ -46,16 +37,17 @@ class PeriodicLogger:
await asyncio.wait_for(self.stopped.wait(), timeout=self.interval)
except asyncio.TimeoutError:
pass
self.emit()
await self.emit()
except asyncio.CancelledError:
return
def emit(self) -> None:
async def emit(self) -> None:
body, payload = self.collect()
get_logger().info(body)
if self.wandb_enabled and payload:
payload["_timestamp"] = time.time()
wandb.log(payload)
if payload:
# Time-keyed row: the pipeline view is sampled on wall time, not
# the training step. Each monitor stamps its own time axis.
await monitors.log(payload, step=None)
async def stop(self) -> None:
self.stopped.set()