Compare commits

...
Author SHA1 Message Date
samsjaandGitHub 487d8a76d1 feat(examples): add 4-node and 2-node GLM-4.5-Air scaleswe budget variants (#3548)
## Summary

Follow-up to #3546: the two budget variants and docs updates from that
PR were pushed after it was merged, so they never landed on main. This
PR carries them.

Adds two budget variants of the GLM-4.5-Air `scaleswe` example that keep
the single-node sign-SGD trainer setup (full optimizer offload +
skip-optimizer checkpointing) from before the Muon switch:

- `swe-budget.toml` + `swe-4-node.toml`: 1 train + 3 infer replicas (the
topology `swe.toml` used before #3546), batch size 256
- `swe-budget.toml` + `swe-2-node.toml`: 1 train + 1 infer replica at
batch size 64 (4 groups of 16) — train a 100B+ MoE on only two nodes

The variants are overlays rather than full copies: the shared recipe
(sign-SGD trainer, router replay, GRPO linear length penalty,
deployment/ckpt/broadcast/inference settings) lives in
`swe-budget.toml`, and each variant file only carries the deltas —
topology, batch size, per-variant SLURM job name / sandbox cleanup label
/ W&B run name, and the train/eval sources with their matching runtime
labels. Launch them composed, left-to-right:

```
uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml
```

Router replay, `max_off_policy_steps`, and the length-penalty weights
are the same as `swe.toml`. Each variant keeps its own SLURM job name,
sandbox cleanup label, and W&B run name so they can run side by side.

## Changes

- **`swe-budget.toml`** (new): shared base of the budget variants — the
single-node sign-SGD trainer recipe (cp=4 ulysses, full optimizer
offload, GLM-5.1 memory stack) plus the shared settings.
- **`swe-4-node.toml`** / **`swe-2-node.toml`**: now thin overlays over
`swe-budget.toml` — `num_infer_replicas` 3 / 1, batch size 256 / 64,
per-variant identity, and the sources with their labels.
- **`tests/unit/test_configs.py`**: `test_load_configs` retries files
that no config class parses standalone as overlays over each sibling
TOML — the documented `@ base.toml @ overlay.toml` composition.
- **Example README**: the table lists the budget variants as
`swe-budget.toml + <variant>` compositions; the launch section shows the
composed command.
- **`docs/scaling.md`** / **`docs/configuration.md`**: link the two-node
config ("train a 100B+ MoE on only two nodes"); scaling.md notes it is
an overlay on the shared base.

## Validation

- `uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @
examples/advanced/glm-4.5-air/swe-4-node.toml --dry-run`
- `uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @
examples/advanced/glm-4.5-air/swe-2-node.toml --dry-run`
- Config-level checks against the installed config package: the base
parses standalone; the composed configs resolve to configs identical to
the pre-split standalone files (compared resolved `model_dump()`, only
the auto-generated run name differs); the overlays alone fail validation
as intended (fail fast instead of silently launching a default-config
run).
2026-09-17 13:45:25 -07:00
d05fe6de95 feat: split dashboard overview and metrics tabs (#3578)
## Summary
- The dashboard's `Metrics` tab is now two tabs for every run type.
**Overview** is the curated view: the W&B overview sections for training
runs (train, eval, stability, inference, performance) and the episode
pane for eval runs (progress bar, summary tiles, swarms, usage and
timing). **Metrics** is every key in `metrics.jsonl`, one pane per key,
with a regex filter, smoothing and collapse/expand. The Overview/All
toggle is gone; the tabs replace it.
- Eval runs load `metrics.jsonl` next to their episode series, so the
time-keyed `inference/`, `concurrency/` and `dispatcher/` rows the
runner samples during the epoch chart on the Metrics tab the same way
they do for RL runs. Before, an eval run had no way to reach its raw
metric keys at all.
- The Metrics tab groups keys by path instead of by stat family. `Flat`
makes one section per parent path (`dispatcher/cancelled` holds `eval`,
`gsm8k`, `train`; `dispatcher` holds `mode`), sorted so a parent
precedes its children. `Nested` walks the key segments as a tree of
sections (`dispatcher` holds the `mode` pane and the nested `cancelled`,
`errored`, `inflight`, `off_policy`, `queued` sections).
- A section's pane grid keeps the 12px rhythm before the sections nested
under it; previously the nested section header sat flush against the
panes above.
- The two tabs share one metric store and one chart registry: the open
tab owns the charts and re-renders on switch, each tab keeps its own
search, and the smoothing window is shared. The dashboard skill, README,
`docs/eval.md`, `docs/training.md` and the browser smoke test (which now
also exercises the Metrics tab) are updated to match.

**Eval Overview**

<img width="1608" height="1045" alt="Screenshot 2026-09-17 at 1 00
24 PM"
src="https://github.com/user-attachments/assets/bd54ffa2-d18c-4379-acfb-7e3cb8982dcd"
/>

**Eval Metrics**

<img width="1608" height="1045" alt="Screenshot 2026-09-17 at 1 00
49 PM"
src="https://github.com/user-attachments/assets/53eca142-b7de-47db-baee-cd6561bf2e9f"
/>

**Train Overview**

<img width="1608" height="1045" alt="Screenshot 2026-09-17 at 1 01
04 PM"
src="https://github.com/user-attachments/assets/3860a4e4-ff1a-4502-9df6-88fff2174ce3"
/>

**Train Metrics**

<img width="1608" height="1045" alt="Screenshot 2026-09-17 at 1 01
16 PM"
src="https://github.com/user-attachments/assets/5e0a23b7-91ef-42f4-ab55-85aeadb7ee59"
/>

## Verification
Headless Chromium against the dashboard served from this branch, no
console errors on either tab:

- `uv run rl @ configs/ci/integration/reverse-text/start.toml
--max-steps 5`: Overview renders 23 curated panes including the
inference section; Metrics lists 1135 keys, 209 `inference/` families
and all five `concurrency/` gauges.
- `uv run eval gsm8k -n 16 -r 2` against a local `uv run inference`
server with adaptive concurrency: Overview renders the episode pane (32
episodes, 7 tiles); Metrics lists 870 keys, 213 `inference/` families
and the five `concurrency/` gauges.
- Flat and nested section structure checked for the `dispatcher/` and
`concurrency/` keys of the eval run as listed above.
- `tests/integration/dashboard_smoke.py` passes on both run dirs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are confined to the local dashboard UI, static assets, docs,
and smoke tests; no server-side training or eval pipeline logic.
> 
> **Overview**
> The run dashboard replaces the single **Metrics** tab and its
Overview/All toggle with two tabs: **Overview** (default) for the
curated W&B-style layout—training sections or the eval episode pane—and
**Metrics** for every key in `metrics.jsonl`, with regex filter,
flat/nested path grouping, and shared smoothing.
> 
> Eval runs now stream **`metrics.jsonl` alongside the episode series**,
so time-keyed `inference/`, `concurrency/`, and similar rows appear on
Metrics instead of being unreachable. Chart rendering is refactored
around `CHART_VIEWS`: one metric store and chart registry, re-mounting
when switching tabs, per-tab search prefs, and eval-specific controls
moved to Overview.
> 
> Docs (`eval.md`, `training.md`, dashboard skill/README) and
**`dashboard_smoke.py`** are updated to expect six views and to exercise
both tabs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ce08f3f18f343a5c0b7b38585bb40a9409798117. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-17 13:09:50 -07:00
Cooper MillerandGitHub a563a03d61 chore: require prime-runs 0.1.3 (#3571)
Require `prime-runs[train]>=0.1.3` and update the lockfile from 0.1.2 to
0.1.3. FFT image builds use `uv sync --locked`, so the PyPI release
alone leaves them on the previous SDK and its dual-upload behavior.

With the new SDK, training episodes upload only to Prime Traces when the
account has access; accounts without access retain legacy samples. Run
lifecycle and metrics continue through Platform. Only the SDK
requirement and its locked artifact change; pinned submodules and other
resolved packages are preserved.

Validation: `uv lock --check` passed; TOML and the resolved 0.1.3
requirement were verified; all 288 published SDK tests passed against
the locked prime-traces 0.0.3 dependency. A GPU training run was not
performed.

Rollout: rebuild and promote the FFT image after merge.
PrimeIntellect-ai/platform#5452 separately handles duplicate list
entries and displaying native traces inside the full run page.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> No in-repo logic changes, but the locked SDK upgrade alters how
training episodes are uploaded once images are rebuilt—worth validating
in staging before wide rollout.
> 
> **Overview**
> Raises the **`prime-runs[train]`** floor from **>=0.1.1** to
**>=0.1.3** in `pyproject.toml` and refreshes **`uv.lock`** so resolved
**`prime-runs`** moves from **0.1.2** to **0.1.3** (PyPI artifact hashes
only; no other dependency churn in this diff).
> 
> This matters because FFT training images install with **`uv sync
--locked`**, so the lockfile must advance for builds to pick up the new
SDK—not just the PyPI release. **`PrimeTrainMonitor`**
(`src/prime_rl/monitors/prime.py`) still calls the same **`prime_runs`**
APIs; behavior shifts come from **0.1.3** (e.g. trace-aware episode
uploads vs legacy samples for accounts without Traces access, while run
lifecycle/metrics stay on Platform).
> 
> After merge, **rebuild and promote the FFT image** so production
training runs the locked **0.1.3** SDK.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
21c2f421dfbf883bb9ca7eda4ed0a8cf10776fd7. 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 11:09:42 -07:00
Mika SenghaasandGitHub de08c72769 feat(inference): sticky least-loaded routing (#3563)
## Summary

Makes `sticky_least_loaded` the default routing algorithm on
`vllm-router` (ported from upstream into our fork in
https://github.com/PrimeIntellect-ai/router/pull/55). New session are
routed to the engine with _least active sessions_, any requests in an
active sessions are sticky-routed to maximize prefix cache hits. So this
is a mix of least loaded and consistent hashing which should be strictly
better for RL workloads.

- pin vllm-router v0.2.1 release wheels for x86_64 and aarch64
- make sticky_least_loaded the default vllm-router policy while
preserving explicit policy overrides
- release rollout sessions on success, failure, and cancellation for
managed routed inference, retaining discarded retry trace IDs
- call /finish_session without capability probing or 404/405 caching;
log individual failures at debug level and continue future cleanup
- document the new default and lifecycle behavior

## Context

- Router implementation:
https://github.com/PrimeIntellect-ai/router/pull/55
- Router release:
https://github.com/PrimeIntellect-ai/router/releases/tag/v0.2.1
- Side-by-side experiment:
https://github.com/PrimeIntellect-ai/prime-rl/pull/3553

## Verification

We ran matched 100-step GLM-4.5-Air ScaleSWE jobs on six H200 nodes (2
trainer + 4 TP=8 inference replicas), changing only the vllm-router
policy: [sticky
least-loaded](https://wandb.ai/primeintellect/routing/runs/b44ce2f5354a416bb37788a4db9d12c3)
versus [consistent
hashing](https://wandb.ai/primeintellect/routing/runs/de4b5c72f95c4c5ebbc7e9614690af52).
They reached trainer step 100 in 8h46m and 8h44m respectively, with
nearly identical mean step time (309s vs. 308s).

<img width="1239" height="762" alt="Screenshot 2026-09-17 at 10 11
13 AM"
src="https://github.com/user-attachments/assets/a3204c40-49b0-41f0-b1ae-9d85391f893d"
/>

| Metric | Sticky least-loaded | Consistent hashing | Difference |
| --- | ---: | ---: | ---: |
| Decode throughput | 13.85k tokens/s | 13.11k tokens/s | +5.6% |
| Prefill throughput | 702.6k tokens/s | 665.0k tokens/s | +5.7% |
| Decode-token imbalance (CV) | 1.2% | 6.8% | 82% lower |
| Running-request imbalance (CV) | 5.1% | 23.9% | 79% lower |
| KV-usage imbalance (CV) | 8.2% | 25.1% | 67% lower |


Sticky processed about 6% more tokens in essentially the same wall time.
The higher useful throughput and markedly lower engine imbalance,
without an end-to-end regression, make it the better default.

## Validation

- uv sync --all-extras --all-packages
- uv lock --check
- uv run pytest tests/unit/orchestrator tests/unit/test_configs.py -q
(276 passed, 1 skipped)
- uv run ruff check .
- verified the installed vllm-router CLI exposes sticky_least_loaded
- 10 focused local cleanup checks: successful and failed episodes,
cancellation, overload/stale/superseded drops, shutdown, max steps,
cancellation during cleanup, and continued cleanup after a 404

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes default multi-replica routing and adds best-effort session
cleanup on the rollout hot path; failures are logged but could leave
stale router session state on older routers.
> 
> **Overview**
> Switches the default **vllm-router** policy from `consistent_hash` to
**`sticky_least_loaded`**, pins **vllm-router v0.2.1**, and documents
that new `X-Session-ID` sessions land on the least-loaded replica while
later turns stay sticky for KV reuse.
> 
> For managed deployments where `admin_base_url` bypasses the router for
engine admin, the orchestrator now **releases router sessions when
rollouts finish**: after each successful env episode it calls
**`/finish_session`** per trace id via the client-facing router URL,
probes support once, and disables cleanup on 404/405 so external routers
are unaffected. Explicit `[inference.router] policy` overrides still
work.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
571b09581344e4ee420044aa8392ec97f9a4b538. 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:55:15 -07:00
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
28 changed files with 588 additions and 311 deletions
+1 -1
+1 -1
View File
@@ -225,7 +225,7 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
**Advanced** (32–2048 GPUs, SLURM):
- [**Qwen3-30B-A3B**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-30b-a3b) — `Qwen3-30B-A3B` on math, SWE, and tool use.
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal.
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal; includes a variant that trains the 100B+ MoE on only two nodes.
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
+1 -1
View File
@@ -89,7 +89,7 @@ Monitors receive the run's metrics and episodes through one abstraction. The fil
The file monitor writes the run's metrics and trace stream under `output_dir / run.name / monitors/file/` and feeds the local [dashboard](training.md#dashboard). Env servers stream every rollout to the eval process as it happens: the trace's header when it is minted, then one delta per committed turn (the new messages and the model call behind them), per phase change (boot, setup, agent, finalize, scoring), and a preview of each model request's uncommitted messages, so a tool result shows the moment the model is asked about it rather than with the reply. The file monitor appends those deltas to `monitors/file/traces/live/<trace_id>.jsonl` and deletes the file when the episode lands in the finished trace stream, so that directory is exactly the live set and finished traces stay where they always were. The dashboard's traces tab shows live rollouts in the episode table itself: a pulsing dot in the `#` cell marks the row, a phase badge says where the rollout is (boot, setup, running, finalize, scoring), the `dispatched → arrived` column shows the dispatch time with the elapsed time in brackets, and the turn, token and branch counts grow as deltas land. The status filter toggles live and completed rows, and a live row opens in the trace viewer, which follows the rollout turn by turn (the transcript stays pinned to the newest turn until you scroll up; folded entries stay folded; the pending messages of the request in flight render dimmed with an `awaiting model` chip). The table and an open live trace poll once a second and transfer nothing while the rollout is unchanged. The progress line in `eval.log` counts the live rollouts by phase (`2 inflight episodes ... - boot 1 · running 1`). Read a live trace from a shell with `uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`. The same stream exists for RL runs, covering train and online-eval rollouts alike.
The dashboard's metrics tab reads the trace stream directly. It shows one env at a time; the filter menu picks the env and whether errored episodes join the distributions. A block bar has one cell per expected episode: landed episodes (errored ones in red; click one to open it), live rollouts as pulsing outlines (click one to follow it), and the rest empty, with the percentage beside it. The expected count is what the eval runner wrote to `monitors/file/plan.json` when it counted the epoch's tasks. Below the bar, a summary row gives the headline numbers: avg@k and pass@k, the error and truncation rates (yellow past 10%, red past 50%), mean turns and branches in one tile, mean episode time and tokens, and the total cost when the run has costs; hover a tile for its distribution. The env's own rewards and metrics follow, a beeswarm pane each, resizable like the training charts. The usage section is one pane splitting each episode's tokens into input and output, and the timing section is the same pane over the phases of a rollout (boot, setup, model, harness, finalize, scoring, and `other` for wall time no phase accounts for): an icicle bar shows the mean split, one strip per episode below shows the split per rollout, and a legend sits above. Hovering a phase highlights it across the pane; the strips show 40 episodes by default and all of them on `show all`. A metric every episode shares appears as a chip instead of a pane, and a metric with only a few distinct values, such as a binary reward, as a counted dot plot with the count and share of each value. Every dot is an episode (or a task): hover it for its value and click it to open the trace; hover the pane's background for the summary (min, p10, median, p90, max), with a faint boxplot behind the dots. Errored episodes stay out of the distributions until the filter includes them, where they read red.
The dashboard's overview tab reads the trace stream directly. It shows one env at a time; the filter menu picks the env and whether errored episodes join the distributions. A block bar has one cell per expected episode: landed episodes (errored ones in red; click one to open it), live rollouts as pulsing outlines (click one to follow it), and the rest empty, with the percentage beside it. The expected count is what the eval runner wrote to `monitors/file/plan.json` when it counted the epoch's tasks. Below the bar, a summary row gives the headline numbers: avg@k and pass@k, the error and truncation rates (yellow past 10%, red past 50%), mean turns and branches in one tile, mean episode time and tokens, and the total cost when the run has costs; hover a tile for its distribution. The env's own rewards and metrics follow, a beeswarm pane each, resizable like the training charts. The usage section is one pane splitting each episode's tokens into input and output, and the timing section is the same pane over the phases of a rollout (boot, setup, model, harness, finalize, scoring, and `other` for wall time no phase accounts for): an icicle bar shows the mean split, one strip per episode below shows the split per rollout, and a legend sits above. Hovering a phase highlights it across the pane; the strips show 40 episodes by default and all of them on `show all`. A metric every episode shares appears as a chip instead of a pane, and a metric with only a few distinct values, such as a binary reward, as a counted dot plot with the count and share of each value. Every dot is an episode (or a task): hover it for its value and click it to open the trace; hover the pane's background for the summary (min, p10, median, p90, max), with a faint boxplot behind the dots. Errored episodes stay out of the distributions until the filter includes them, where they read red. The metrics tab charts every key of the run's `metrics.jsonl`: the epoch's `eval/<env>/…` summaries and the time-keyed `inference/` and `concurrency/` rows the runner samples while the epoch is in flight.
### Prime
+4 -2
View File
@@ -190,8 +190,10 @@ Both backends support the 2 most important things:
- P/D disaggregation - handling the prefill and decode stages separately
### Routing policies
The 2 policies you might want to configure are:
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - it hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica.
The policies you might want to configure are:
- `sticky_least_loaded` - the default policy. A new `X-Session-ID` is assigned to the least-loaded replica, then every later turn in that rollout remains on the same replica for KV cache reuse. The orchestrator releases sessions when rollouts complete, fail, or are cancelled, including traces discarded during retries. Failed release requests are logged without disabling future cleanup.
- `consistent_hash` - hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica, preserving KV cache reuse without considering current load.
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
+1
View File
@@ -234,6 +234,7 @@ Full multi-node configs ship under [`examples/advanced/`](https://github.com/Pri
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/configs/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
- [`glm-4.5-air/swe-2-node.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-4.5-air/swe-2-node.toml) — train a 100B+ MoE on only two nodes: a single-node sign-SGD trainer (full optimizer offload) paired with one inference replica at batch size 64. An overlay on the shared `swe-budget.toml` base — launch with `uv run rl @ swe-budget.toml @ swe-2-node.toml`.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
+1 -1
View File
@@ -355,7 +355,7 @@ tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
### Dashboard
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with six views per run: an overview (the W&B overview sections, read from the file monitor's `metrics.jsonl`), metrics (every key in that file, one pane each, with a regex filter), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
+6 -4
View File
@@ -1,14 +1,16 @@
# GLM-4.5-Air
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0).
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0). The SWE configs also ship budget variants: `swe-4-node.toml` (1 train + 3 infer) and `swe-2-node.toml` — train a 100B+ MoE on only two nodes. Both are thin overlays on a shared `swe-budget.toml` base: the base holds the recipe, the overlay the topology, batch size, and per-run identity.
| Config | Trains on | Evals on | Topology |
|---|---|---|---|
| [`search.toml`](search.toml) | `openseeker` + `redsearcher` (search QA, `rlm` harness + `search` skill) | `browsecomp` (500 examples) | 2 train + 4 infer nodes |
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 2 train + 4 infer nodes |
| [`swe-budget.toml`](swe-budget.toml) + [`swe-4-node.toml`](swe-4-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
| [`swe-budget.toml`](swe-budget.toml) + [`swe-2-node.toml`](swe-2-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 1 infer node |
| [`terminal.toml`](terminal.toml) | `tmax` (per-task Docker image, `rlm` ipython harness) | `swebench-verified` + `terminal-bench-2` (avg@4) | 2 train + 4 infer nodes |
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8`. `search.toml` and `terminal.toml` train with Muon on 2 nodes; `swe.toml` fits the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer. Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8` (plus expert parallelism on `swe.toml`). `search.toml`, `swe.toml`, and `terminal.toml` train with Muon on 2 trainer nodes. The budget variants instead fit the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer; `swe-2-node.toml` cuts the batch size to 64 (4 groups of 16) to match the throughput of its single inference replica. They don't parse standalone: compose them left-to-right over `swe-budget.toml` (`uv run rl @ swe-budget.toml @ swe-2-node.toml`). Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
## Requirements
@@ -54,7 +56,7 @@ uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
--run.name glm45air-swe
```
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. For SWE on a smaller budget, compose a budget variant over its base: `uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml` trains the 100B+ MoE on only two nodes. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
## Monitor with the dashboard
@@ -0,0 +1,41 @@
# Budget variant of swe.toml: train a 100B+ MoE on only two nodes (1 train + 1 infer replica) with
# the single-node sign-SGD trainer. Overlay for swe-budget.toml — this file only carries the
# deltas, so compose the two (left-to-right merge, see docs/configuration.md "TOML Composition"):
#
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml
#
# The batch size is 64 (4 groups of 16), matching the rollout throughput of the single inference
# replica. The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the
# budget variants can run side by side.
[slurm]
job_name = "glm45air-swe-2-node"
# 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 "glm45air-swe-2-node" -y || true'
[deployment]
num_infer_replicas = 1
[monitors.wandb]
name = "glm45air-scaleswe-2-node"
[orchestrator]
batch_size = 64
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-2-node"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-2-node"]
env.agent.timeout.rollout = 3600
@@ -0,0 +1,42 @@
# Budget variant of swe.toml: the same recipe on four nodes (1 train + 3 infer replicas, the
# topology swe.toml used before the Muon switch) with the single-node sign-SGD trainer. Overlay for
# swe-budget.toml — this file only carries the deltas, so compose the two (left-to-right merge, see
# docs/configuration.md "TOML Composition"):
#
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-4-node.toml
#
# Batch size 256 (16 groups of 16) matches the rollout throughput of the three inference replicas.
# The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the budget
# variants can run side by side.
[slurm]
job_name = "glm45air-swe-4-node"
# 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 "glm45air-swe-4-node" -y || true'
[deployment]
num_infer_replicas = 3
[monitors.wandb]
name = "glm45air-scaleswe-4-node"
[orchestrator]
batch_size = 256
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-4-node"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-4-node"]
env.agent.timeout.rollout = 3600
@@ -0,0 +1,114 @@
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Shared base of the budget variants of swe.toml
# (`swe-4-node.toml`, `swe-2-node.toml`): the pre-Muon recipe with the single-node sign-SGD
# trainer, composed as `uv run rl @ swe-budget.toml @ <variant>.toml`. Router replay is enabled
# (trainer.enable_router_replay replays the routed-expert decisions returned by inference via
# enable_return_routed_experts) — 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. Each
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
#
# Inference serves the bf16 checkpoint as-is (no quantization). 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 (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
# skip-gather / skip-optimizer checkpointing. Concurrency is fully default: the controller derives
# its start from the measured KV budget and adapts from there.
#
# The variant overlays on top of this base set the inference replica count and batch size, the
# per-variant SLURM job name / sandbox cleanup label / W&B run name, and the train/eval sources
# with their matching runtime labels.
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]
partition = "all"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[monitors.wandb]
project = "swe-ablations"
[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_optimizer = true
[trainer.optim]
type = "sign_sgd"
# --- Orchestrator ---
[orchestrator]
group_size = 16
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"
# --- 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
enable_return_routed_experts = true
@@ -303,8 +303,8 @@ class VllmRouterConfig(BaseConfig):
type: Literal["vllm-router"] = "vllm-router"
policy: str = "consistent_hash"
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
policy: str = "sticky_least_loaded"
"""Routing policy. Defaults to session-affine least-loaded routing; alternatives include ``consistent_hash`` and ``round_robin``."""
class LlmdRouterConfig(BaseConfig):
+3 -3
View File
@@ -17,7 +17,7 @@ dependencies = [
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
"prime>=0.6.19",
"prime-runs[train]>=0.1.1",
"prime-runs[train]>=0.1.3",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
@@ -269,8 +269,8 @@ torchao = [
dion = { git = "https://github.com/samsja/dion.git", rev = "99e5f7e" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
+2 -1
View File
@@ -9,10 +9,11 @@ description: Find, start, use, and stop the local run dashboard for metrics, con
What is not obvious from the UI:
- Overview and Metrics read the same `monitors/file/metrics.jsonl`. **Overview** is the curated view (the sections of the W&B overview: train, eval, stability, inference, performance). **Metrics** is every key in the file, one pane per key, sectioned by parent path (`Flat`) or as a tree of sections along the key path (`Nested`), with a regex filter; time-keyed rows (`inference/`, `concurrency/`, `dispatcher/`) chart against wall time.
- Config and Logs default to `latest (attempt <n>)`; select an attempt to inspect an earlier launch. The Config view shows a copyable launch command.
- Trace viewer views: **Transcript**, **Timeline** (wall-clock Gantt of prefix branches), **Replay** (the branch as a terminal session; response text is paced evenly across the recorded model-call span and labelled inferred; default 8×; **Skip inference** collapses model calls but keeps tool delays; **T** toggles thinking, never advertise Ctrl+T) and **Semantic** (`semantic_parents` as a causal graph of model calls; width reflects peak agent concurrency; unplaceable fragments show as unlinked). Traces without semantic parents disable Semantic.
- Live rollouts appear in the traces table with a pulsing dot and a phase badge, and open in the viewer, which follows them (pinned to the newest turn until you scroll up; the request in flight's uncommitted messages render dimmed as `awaiting model`). They come from `monitors/file/traces/live/*.jsonl`, polled once a second.
- For an eval run the metrics tab shows one env at a time (filter → env, `include errors`): a block progress bar (one cell per expected episode, from `monitors/file/plan.json`), summary tiles (avg@k, pass@k, error and truncation rate coloured >10% yellow / >50% red, turns / branches, episode time, tokens, cost), env metrics as dot plots or beeswarms (hover a dot for its episode, click to open it; hover the background for the quantiles), and usage / timing composition panes (icicle of the mean split over per-episode strips; `other` is wall time no phase accounts for; hover a part to dim the rest; 40 strips by default, `show all` for every one).
- For an eval run the overview tab shows one env at a time (filter → env, `include errors`): a block progress bar (one cell per expected episode, from `monitors/file/plan.json`), summary tiles (avg@k, pass@k, error and truncation rate coloured >10% yellow / >50% red, turns / branches, episode time, tokens, cost), env metrics as dot plots or beeswarms (hover a dot for its episode, click to open it; hover the background for the quantiles), and usage / timing composition panes (icicle of the mean split over per-episode strips; `other` is wall time no phase accounts for; hover a part to dim the rest; 40 strips by default, `show all` for every one).
- `view on platform` in the top bar links to the run on the Prime platform when `--monitors.prime` was on (`monitors/prime/run.json`); an eval's evaluation opens at epoch start, so the link is live from the first episode.
- An eval reads `completed` once its stream is sealed by a clean exit; a crashed or interrupted one reads `stopped` after its files go quiet.
+3 -1
View File
@@ -74,7 +74,9 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
## `inference` — vLLM server
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly.
Router session cleanup runs on successful, failed, and cancelled episodes, including discarded retry traces. Cleanup failures are logged per session and do not disable subsequent releases.
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly. The default `sticky_least_loaded` policy keeps each rollout on one replica while assigning new sessions to the least-loaded replica; RL and SFT online eval automatically release completed sessions.
```bash
uv run inference --vllm.model Qwen/Qwen3-0.6B
+2 -2
View File
@@ -1,8 +1,8 @@
# Dashboard
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
directories (metrics, resolved configs, rollout traces, cited reports,
component logs) at
directories (a curated overview, every logged metric, resolved configs,
rollout traces, cited reports, component logs) at
http://localhost:7788. The trace viewer includes transcript, synchronized
agent timeline, and terminal replay views; timeline activities open the
corresponding transcript call. Needs the `dashboard` extra. Every instance also serves
+207 -168
View File
@@ -26,13 +26,13 @@ const state = {
runs: [],
run: null,
meta: null,
tab: "metrics",
tab: "overview",
live: true,
metrics: {
loaded: false, offset: 0, byKey: new Map(),
charts: [], renderedKeys: -1, timeKeys: new Set(), timeZero: null, maxStep: null,
collapsedSections: new Set(prefs.collapsedSections ?? []),
mode: prefs.metricsMode ?? "overview", search: prefs.metricsSearch ?? "",
searches: { overview: prefs.overviewSearch ?? "", metrics: prefs.metricsSearch ?? "" },
smooth: prefs.smooth ?? 1, paneMin: prefs.paneMin ?? 260, paneH: prefs.paneH ?? 150, includeErrors: prefs.includeErrors ?? false,
allLayout: prefs.allLayout ?? "flat",
paneOrder: prefs.paneOrder ?? {},
@@ -177,16 +177,15 @@ async function toggleCompare(name, on) {
renderMetricsBody();
}
/* eval runs have one env and no steps: the step bar, kind/subset toggles, chart
mode, and smoothing make no sense there */
/* eval runs have one env and no steps: the step bar, kind/subset toggles and
smoothing make no sense there, and the overview is the episode pane */
function applyRunTypeControls() {
const isEval = state.meta?.type === "eval";
$("#metrics-mode").hidden = isEval;
$("#metrics-filter-wrap").hidden = !isEval;
$("#metrics-search").hidden = isEval;
$("#metrics-collapse").hidden = isEval;
$("#metrics-expand").hidden = isEval;
$("#smooth-range").closest(".ctl").hidden = isEval;
$("#overview-filter-wrap").hidden = !isEval;
$("#overview-search").hidden = isEval;
$("#overview-collapse").hidden = isEval;
$("#overview-expand").hidden = isEval;
$("#overview-smooth").closest(".ctl").hidden = isEval;
$("#step-bar").hidden = isEval;
// an eval run has no steps to switch between, so it is stream-only
$("#trace-mode").hidden = isEval;
@@ -332,7 +331,7 @@ function renderOverview() {
["status", `<span class="badge st-${status}">${status}</span>`],
["type", `<span class="val">${esc((meta.type ?? "n/a").toUpperCase())}</span>`],
meta.type === "eval"
? ["episodes", `<span class="val">${step != null ? step.toLocaleString() : "n/a"}</span>`]
? ["episodes", `<span class="val">${state.metrics.evalCount.toLocaleString()}</span>`]
: ["step", `<span class="val">${stepText}</span>`],
["model", `<span class="val" title="${esc(meta.model ?? "")}">${esc(meta.model ?? "n/a")}</span>`],
...(meta.type === "eval"
@@ -372,9 +371,12 @@ async function activateTab(tab, force = false) {
setActive("#tabs", "tab", tab);
document.querySelectorAll("main > section").forEach((s) => (s.hidden = s.id !== `tab-${tab}`));
updateHash();
if (tab === "metrics") {
if (isChartTab(tab)) {
if (!state.metrics.loaded) await initMetrics();
else if (state.live) await fetchMetrics();
else {
renderMetricsBody();
if (state.live) await fetchMetrics();
}
}
if (tab === "config" && !state.config.loaded) await initConfig();
if (tab === "logs" && !state.logs.loaded) await initLogs();
@@ -390,6 +392,36 @@ async function activateTab(tab, force = false) {
/* ---------------------------------------------------------------- metrics */
/* the overview and metrics tabs read one metric store and share one chart
registry: the open tab owns the charts, so switching re-renders into its body.
The overview is the curated view (for an eval run, the episode pane); metrics
is every key in the file, sectioned by family */
const CHART_VIEWS = {
overview: { body: "#overview-body", status: "#overview-status", search: "#overview-search", mode: "overview" },
metrics: { body: "#metrics-body", status: "#metrics-status", search: "#metrics-search", mode: "all" },
};
function isChartTab(tab = state.tab) {
return tab in CHART_VIEWS;
}
function chartBodies() {
return Object.values(CHART_VIEWS).map((view) => $(view.body));
}
function chartView() {
return CHART_VIEWS[state.tab] ?? CHART_VIEWS.overview;
}
function metricsMode() {
return chartView().mode;
}
/* the eval overview is built from the episode series, not the metric rows */
function rowsChartHere() {
return isChartTab() && !(state.tab === "overview" && state.meta?.type === "eval");
}
const COMMON_METRICS = ["effective/num_turns/mean", "effective/num_total_tokens/mean", "effective/num_branches/mean"];
const COMMON_REGEXES = ["effective/[^/]+/is_truncated/mean", "all/[^/]+/has_error/mean"];
const STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"];
@@ -406,8 +438,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)[/_]?/;
@@ -461,46 +494,52 @@ function ingestInto(store, rows, meta) {
first charts paint immediately and a progress readout ticks up while the rest
loads, with the main thread yielding between chunks */
async function fetchMetrics() {
if (state.meta?.type === "eval") return fetchEvalSeries();
const m = state.metrics;
if (m.fetching) return 0;
m.fetching = true;
let total = 0;
let showedProgress = false;
try {
for (let first = true; ; first = false) {
const requestedOffset = m.offset;
const [data, compared] = await Promise.all([
api(`/api/runs/${encodeURIComponent(state.run)}/metrics?offset=${m.offset}`),
first ? fetchCompares() : false,
]);
if (state.metrics !== m) return total; // the run changed mid-load
m.offset = data.offset;
total += data.rows.length;
let touched = null;
if (data.rows.length) {
touched = ingestInto(m, data.rows, state.meta);
renderOverview();
}
if (data.rows.length || compared) {
if (m.byKey.size !== m.renderedKeys) renderMetricsBody();
else updateCharts(compared ? null : touched); // compares may touch any panel
}
// A writer can leave one incomplete JSONL record at EOF. Wait for the
// next poll instead of repeatedly requesting the same partial record.
if (data.offset >= (data.size ?? data.offset) || data.offset === requestedOffset) break;
showedProgress = true;
$("#metrics-status").textContent = `loading metrics · ${Math.round((data.offset / data.size) * 100)}%`;
}
if (showedProgress && m.mode === "overview") $("#metrics-status").textContent = "";
if (state.meta?.type === "eval") await fetchEvalSeries();
if (state.metrics !== m) return 0;
return await fetchMetricRows(m);
} finally {
m.fetching = false;
}
}
async function fetchMetricRows(m) {
let total = 0;
let showedProgress = false;
for (let first = true; ; first = false) {
const requestedOffset = m.offset;
const [data, compared] = await Promise.all([
api(`/api/runs/${encodeURIComponent(state.run)}/metrics?offset=${m.offset}`),
first ? fetchCompares() : false,
]);
if (state.metrics !== m) return total; // the run changed mid-load
m.offset = data.offset;
total += data.rows.length;
let touched = null;
if (data.rows.length) {
touched = ingestInto(m, data.rows, state.meta);
renderOverview();
}
if ((data.rows.length || compared) && rowsChartHere()) {
if (m.byKey.size !== m.renderedKeys) renderMetricsBody();
else updateCharts(compared ? null : touched); // compares may touch any panel
}
// A writer can leave one incomplete JSONL record at EOF. Wait for the
// next poll instead of repeatedly requesting the same partial record.
if (data.offset >= (data.size ?? data.offset) || data.offset === requestedOffset) break;
if (!rowsChartHere()) continue;
showedProgress = true;
$(chartView().status).textContent = `loading metrics · ${Math.round((data.offset / data.size) * 100)}%`;
}
if (showedProgress && metricsMode() === "overview") $(chartView().status).textContent = "";
return total;
}
/* eval runs have no metrics.jsonl and no step axis — their metrics view is a
grid of stat cards showing the running average over the episodes so far */
/* an eval run's overview reads the episode series: the running distributions
over the episodes so far */
async function fetchEvalSeries() {
const m = state.metrics;
const liveChanged = await loadLive({ render: state.tab === "traces" });
@@ -514,7 +553,7 @@ async function fetchEvalSeries() {
data = { unchanged: true };
}
if (data.unchanged) {
if (liveChanged && m.loaded && state.tab === "metrics") renderMetricsBody();
if (liveChanged && m.loaded && state.tab === "overview") renderMetricsBody();
return 0;
}
m.evalEtag = data.etag;
@@ -527,11 +566,10 @@ async function fetchEvalSeries() {
m.evalSeries[key] = existing;
}
m.evalCount = data.count;
m.maxStep = data.count; // the overview's episode count
const costs = (m.evalSeries.cost || []).filter((v) => v != null); // merged, not just the increment
m.evalCost = costs.length ? costs.reduce((a, b) => a + b, 0) : null;
renderOverview();
if (m.loaded) renderMetricsBody();
if (m.loaded && state.tab === "overview") renderMetricsBody();
return data.count;
}
@@ -556,8 +594,8 @@ function evalEnv() {
function renderEvalEnvs() {
const envs = evalEnvs();
const current = evalEnv();
$("#metrics-env-row").hidden = !envs.length;
$("#metrics-env").innerHTML = envs.map((env) => `<option value="${esc(env)}" ${env === current ? "selected" : ""}>${esc(env)}</option>`).join("");
$("#overview-env-row").hidden = !envs.length;
$("#overview-env").innerHTML = envs.map((env) => `<option value="${esc(env)}" ${env === current ? "selected" : ""}>${esc(env)}</option>`).join("");
syncDressedSelects();
}
@@ -615,7 +653,7 @@ function evalProgressHtml(env, idx, live) {
`<span class="ep-cell"></span>`.repeat(Math.max(0, EP_CELL_CAP - doneCells - liveCells));
}
// the toolbar line reads like the traces tab's
$("#metrics-status").textContent = [...(live.length ? [`${live.length} live`] : []), `${fmtCompact(done)} completed episode${done === 1 ? "" : "s"}`].join(" · ");
$("#overview-status").textContent = [...(live.length ? [`${live.length} live`] : []), `${fmtCompact(done)} completed episode${done === 1 ? "" : "s"}`].join(" · ");
return (
`<div class="eval-progress"><div class="ep-head"><span class="name">${esc(env)}</span></div>` +
`<div class="ep-row"><div class="ep-blocks">${cells || `<span class="ep-cell"></span>`}</div>` +
@@ -820,7 +858,7 @@ function swarmSvg(entry, W, H) {
/* swarms are drawn to their host's pixel size, so they redraw with the panes */
function drawSwarms() {
for (const card of document.querySelectorAll("#metrics-body .swarm-card")) {
for (const card of document.querySelectorAll("#overview-body .swarm-card")) {
const entry = swarmRegistry.get(card.dataset.key);
const host = card.querySelector(".swarm-host");
if (!entry || !host?.clientWidth) continue;
@@ -1016,8 +1054,8 @@ function tokensPaneHtml(idx) {
const TM_MAX_STRIPS = 40;
function drawTiming() {
drawComposition(document.querySelector("#metrics-body .timing-pane"), timingModel, { kind: "timing", fmt: fmtDuration, time: true, color: phaseColor });
drawComposition(document.querySelector("#metrics-body .tokens-pane"), tokensModel, { kind: "tokens", fmt: (v) => fmtCompact(Math.round(v)), time: false, color: (n) => TOKEN_COLORS[n] || "#3a3a3a" });
drawComposition(document.querySelector("#overview-body .timing-pane"), timingModel, { kind: "timing", fmt: fmtDuration, time: true, color: phaseColor });
drawComposition(document.querySelector("#overview-body .tokens-pane"), tokensModel, { kind: "tokens", fmt: (v) => fmtCompact(Math.round(v)), time: false, color: (n) => TOKEN_COLORS[n] || "#3a3a3a" });
}
/* an icicle of the mean composition above one strip per episode; every segment
@@ -1173,12 +1211,12 @@ function summaryTilesHtml(idx, all, scoreEntries) {
function renderEvalPane(body) {
const m = state.metrics;
const series = m.evalSeries || {};
const filter = makeFilter(m.search.trim());
const filter = makeFilter(m.searches.overview.trim());
renderEvalEnvs();
const env = evalEnv();
$("#metrics-status").textContent = "";
$("#metrics-errors").checked = !!m.includeErrors;
$("#metrics-filter-btn").classList.toggle("active", !!m.includeErrors);
$("#overview-status").textContent = "";
$("#overview-errors").checked = !!m.includeErrors;
$("#overview-filter-btn").classList.toggle("active", !!m.includeErrors);
swarmRegistry.clear();
if (!env) {
body.innerHTML = emptyState("no episodes yet", "metrics appear as episodes land");
@@ -1250,19 +1288,19 @@ function renderEvalPane(body) {
drawTiming();
}
$("#metrics-errors").addEventListener("change", (e) => {
$("#overview-errors").addEventListener("change", (e) => {
state.metrics.includeErrors = e.target.checked;
savePrefs();
renderMetricsBody();
});
$("#metrics-body").addEventListener("mousemove", (e) => {
$("#overview-body").addEventListener("mousemove", (e) => {
const tip = $("#swarm-tip");
const timed = e.target.closest("[data-tip]");
const pane = e.target.closest(".comp-pane");
const rowEl = e.target.closest("[data-row]");
const part = rowEl ? null : e.target.closest("[data-part]");
document.querySelectorAll("#metrics-body .comp-pane").forEach((p) => {
document.querySelectorAll("#overview-body .comp-pane").forEach((p) => {
if (p === pane && rowEl) highlightRow(p, rowEl.dataset.row);
else highlightPart(p, p === pane && part ? part.dataset.part : null);
});
@@ -1278,22 +1316,22 @@ $("#metrics-body").addEventListener("mousemove", (e) => {
tip.innerHTML = swarmTipHtml(entry, dot ? entry.points[+dot.dataset.i] : null);
}
tip.hidden = false;
const host = $("#tab-metrics").getBoundingClientRect();
const host = $("#tab-overview").getBoundingClientRect();
const left = Math.min(e.clientX - host.left + 12, host.width - tip.offsetWidth - 8);
tip.style.left = `${Math.max(4, left)}px`;
tip.style.top = `${e.clientY - host.top + 14}px`;
});
$("#metrics-body").addEventListener("mouseleave", () => {
$("#overview-body").addEventListener("mouseleave", () => {
$("#swarm-tip").hidden = true;
document.querySelectorAll("#metrics-body .comp-pane").forEach((p) => highlightPart(p, null));
document.querySelectorAll("#overview-body .comp-pane").forEach((p) => highlightPart(p, null));
});
$("#metrics-env").addEventListener("change", (e) => {
$("#overview-env").addEventListener("change", (e) => {
state.metrics.evalEnv = e.target.value;
renderMetricsBody();
});
$("#metrics-body").addEventListener("click", (e) => {
$("#overview-body").addEventListener("click", (e) => {
const strip = e.target.closest(".tm-strip-seg[data-line], .tm-row-hit[data-line]");
if (strip) {
openEpisode(+strip.dataset.line);
@@ -1804,7 +1842,7 @@ function panelTitle(panel, series, sectionName) {
}
if (sectionName && title.startsWith(`${sectionName}/`)) title = title.slice(sectionName.length + 1);
// overview: a lone mean is implied - all mode keeps the stat next to its /min//p10 siblings
if (state.metrics.mode === "overview" && title.endsWith("/mean")) title = title.slice(0, -"/mean".length);
if (metricsMode() === "overview" && title.endsWith("/mean")) title = title.slice(0, -"/mean".length);
return title;
}
@@ -1850,7 +1888,7 @@ function renderPanelCard(grid, panel, lazy = false) {
}
function paneOrderKey(sectionName) {
return `${state.metrics.mode}:${sectionName ?? ""}`;
return `${metricsMode()}:${sectionName ?? ""}`;
}
function persistPaneOrder(grid) {
@@ -1910,33 +1948,39 @@ function addSection(body, name, count, display = name) {
/* all-mode: fully recursive sections along family path segments (train → agg →
all → agent → …). Every logged key gets its own pane — stats are never
overlaid, so min/p10/median/... show as raw separate plots. */
function renderKeyTree(parent, name, families, depth) {
/* one section per path prefix: the keys right under it are its panes, the deeper
ones nest as sections of their own */
function renderKeyTree(parent, name, keys, depth) {
const display = depth === 1 ? name : name.split("/").pop();
const { div, grid } = addSection(parent, name, families.length, display);
const { div, grid } = addSection(parent, name, keys.length, display);
const children = new Map();
const leaves = [];
for (const f of families) {
const segments = f.family.split("/");
if (segments.length <= depth + 1) leaves.push(f);
for (const key of keys) {
const segments = key.split("/");
// a bare key (no path) is a pane of its own top-level section
if (segments.length <= depth + 1) renderPanelCard(grid, { metric: key }, true);
else {
const segment = segments[depth];
if (!children.has(segment)) children.set(segment, []);
children.get(segment).push(f);
children.get(segment).push(key);
}
}
for (const f of leaves) for (const key of f.keys) renderPanelCard(grid, { metric: key }, true);
if (grid.children.length) applyPaneOrder(grid);
else grid.remove();
for (const [segment, childFamilies] of children) renderKeyTree(div, `${name}/${segment}`, childFamilies, depth + 1);
for (const [segment, childKeys] of children) renderKeyTree(div, `${name}/${segment}`, childKeys, depth + 1);
}
function renderMetricsBody() {
const m = state.metrics;
for (const entry of m.charts) entry.u?.destroy();
m.charts = [];
if (!isChartTab()) {
m.renderedKeys = -1; // nothing on screen: the next chart tab renders afresh
return;
}
m.renderedKeys = m.byKey.size;
const body = $("#metrics-body");
body.innerHTML = "";
const view = chartView();
const body = $(view.body);
for (const other of chartBodies()) other.innerHTML = ""; // the other tab's panes lost their charts above
lazyObserver?.disconnect();
lazyObserver = new IntersectionObserver(
(entries) => {
@@ -1948,15 +1992,15 @@ function renderMetricsBody() {
},
{ root: body, rootMargin: "400px" }
);
if (state.meta?.type === "eval") return renderEvalPane(body);
activeFilter = makeFilter(state.metrics.search.trim());
if (state.tab === "overview" && state.meta?.type === "eval") return renderEvalPane(body);
activeFilter = makeFilter(m.searches[state.tab].trim());
if (!state.meta?.has_metrics && !m.byKey.size) {
body.innerHTML = emptyState("no metrics yet");
$("#metrics-status").textContent = "";
$(view.status).textContent = "";
return;
}
if (m.mode === "overview") {
$("#metrics-status").textContent = "";
if (view.mode === "overview") {
$(view.status).textContent = "";
for (const section of buildSections(state.meta)) {
const { div, grid } = addSection(body, section.name);
for (const panel of section.panels) {
@@ -1973,38 +2017,36 @@ function renderMetricsBody() {
body.innerHTML = emptyState("no keys match", "no overview panels match the filter");
return;
}
// all: one card per metric family - flat lists a section per family with a
// pane per stat, nested groups families recursively along path segments
const familyKeys = new Map();
let shown = 0;
for (const key of [...m.byKey.keys()].sort()) {
if (activeFilter && !activeFilter.test(key)) continue;
shown++;
const family = familyOf(key);
if (!familyKeys.has(family)) familyKeys.set(family, []);
familyKeys.get(family).push(key);
}
$("#metrics-status").textContent = activeFilter ? `${shown} / ${m.byKey.size} keys` : "";
if (!familyKeys.size) {
// all: one pane per key - flat lists a section per parent path, nested walks
// the path segments as a tree of sections
const keys = [...m.byKey.keys()].filter((key) => !activeFilter || activeFilter.test(key)).sort();
$(view.status).textContent = activeFilter ? `${keys.length} / ${m.byKey.size} keys` : "";
if (!keys.length) {
body.innerHTML = emptyState("no keys match", `0 of ${m.byKey.size} keys match the filter`);
return;
}
const bySegment = (keys, at) => {
const groups = new Map();
for (const key of keys) {
const segments = key.split("/");
const group = at(segments);
if (!groups.has(group)) groups.set(group, []);
groups.get(group).push(key);
}
return groups;
};
if (m.allLayout === "flat") {
for (const [family, keys] of familyKeys) {
const { div, grid } = addSection(body, family, keys.length);
for (const key of keys) renderPanelCard(grid, { metric: key }, true);
// a bare key with no path is its own section
const sections = [...bySegment(keys, (segments) => segments.slice(0, -1).join("/") || segments[0])].sort(([a], [b]) => a.localeCompare(b));
for (const [parent, group] of sections) {
const { div, grid } = addSection(body, parent, group.length);
for (const key of group) renderPanelCard(grid, { metric: key }, true);
if (!grid.children.length) div.remove();
else applyPaneOrder(grid);
}
return;
}
const groups = new Map();
for (const [family, keys] of familyKeys) {
const group = family.split("/")[0];
if (!groups.has(group)) groups.set(group, []);
groups.get(group).push({ family, keys });
}
for (const [group, families] of groups) renderKeyTree(body, group, families, 1);
for (const [group, groupKeys] of bySegment(keys, (segments) => segments[0])) renderKeyTree(body, group, groupKeys, 1);
}
async function initMetrics() {
@@ -6253,15 +6295,6 @@ function syncTraceFilterControls() {
document.querySelectorAll("#tabs button").forEach((b) => b.addEventListener("click", () => activateTab(b.dataset.tab)));
document.querySelectorAll("#metrics-mode button").forEach((b) =>
b.addEventListener("click", () => {
state.metrics.mode = b.dataset.mode;
setActive("#metrics-mode", "mode", b.dataset.mode);
$("#all-layout").hidden = b.dataset.mode !== "all";
renderMetricsBody();
savePrefs();
})
);
$("#config-format").addEventListener("click", (e) => {
const btn = e.target.closest("button[data-fmt]");
if (!btn || btn.disabled || btn.dataset.fmt === state.config.fmt) return;
@@ -6281,49 +6314,57 @@ $("#config-search").addEventListener(
savePrefs();
})
);
document.querySelectorAll("#all-layout button").forEach((b) =>
document.querySelectorAll("#metrics-layout button").forEach((b) =>
b.addEventListener("click", () => {
state.metrics.allLayout = b.dataset.layout;
setActive("#all-layout", "layout", b.dataset.layout);
setActive("#metrics-layout", "layout", b.dataset.layout);
renderMetricsBody();
savePrefs();
})
);
$("#metrics-search").addEventListener(
"input",
debounce(() => {
state.metrics.search = $("#metrics-search").value;
renderMetricsBody();
for (const [tab, view] of Object.entries(CHART_VIEWS)) {
$(view.search).addEventListener(
"input",
debounce(() => {
state.metrics.searches[tab] = $(view.search).value;
renderMetricsBody();
savePrefs();
}, 250)
);
$(`#${tab}-collapse`).addEventListener("click", () =>
document.querySelectorAll(`${view.body} details.section`).forEach((s) => (s.open = false))
);
$(`#${tab}-expand`).addEventListener("click", () =>
document.querySelectorAll(`${view.body} details.section`).forEach((s) => (s.open = true))
);
$(`#${tab}-smooth`).addEventListener("input", (e) => {
state.metrics.smooth = +e.target.value;
syncSmoothControls();
updateCharts();
savePrefs();
}, 250)
);
});
}
// remember collapsed sections across re-renders; charts created while hidden
// have zero width, so resize on expand ("toggle" doesn't bubble → capture)
$("#metrics-body").addEventListener(
"toggle",
(e) => {
const section = e.target;
if (!section.matches?.("details.section")) return;
if (section.open) resizeCharts();
// a search force-opens sections - don't let that overwrite the saved state
if (activeFilter) return;
if (section.open) state.metrics.collapsedSections.delete(section.dataset.name);
else state.metrics.collapsedSections.add(section.dataset.name);
savePrefs();
},
true
);
$("#metrics-collapse").addEventListener("click", () =>
document.querySelectorAll("#metrics-body details.section").forEach((s) => (s.open = false))
);
$("#metrics-expand").addEventListener("click", () =>
document.querySelectorAll("#metrics-body details.section").forEach((s) => (s.open = true))
);
for (const body of chartBodies())
body.addEventListener(
"toggle",
(e) => {
const section = e.target;
if (!section.matches?.("details.section")) return;
if (section.open) resizeCharts();
// a search force-opens sections - don't let that overwrite the saved state
if (activeFilter) return;
if (section.open) state.metrics.collapsedSections.delete(section.dataset.name);
else state.metrics.collapsedSections.add(section.dataset.name);
savePrefs();
},
true
);
// drag a pane header to reorder within its section (order persisted by title)
$("#metrics-body").addEventListener("dragover", (e) => {
for (const body of chartBodies()) body.addEventListener("dragover", (e) => {
if (!dragCard) return;
const grid = e.target.closest(".chart-grid");
if (!grid || grid !== dragCard.parentElement) return;
@@ -6336,7 +6377,7 @@ $("#metrics-body").addEventListener("dragover", (e) => {
});
/* wandb-style resize handles: resizing one pane resizes all of them */
$("#metrics-body").addEventListener("pointerdown", (e) => {
for (const body of chartBodies()) body.addEventListener("pointerdown", (e) => {
const grip = e.target.closest("[data-rz]");
if (!grip) return;
e.preventDefault();
@@ -6982,7 +7023,7 @@ $("#tm-meta").addEventListener("click", (e) => {
});
function resizeCharts() {
$("#metrics-body").style.setProperty("--pane-h", `${chartHeight()}px`);
for (const body of chartBodies()) body.style.setProperty("--pane-h", `${chartHeight()}px`);
drawSwarms();
drawTiming();
for (const entry of state.metrics.charts) {
@@ -7011,8 +7052,8 @@ function savePrefs() {
paneH: state.metrics.paneH,
includeErrors: state.metrics.includeErrors,
paneOrder: state.metrics.paneOrder,
metricsMode: state.metrics.mode,
metricsSearch: state.metrics.search,
overviewSearch: state.metrics.searches.overview,
metricsSearch: state.metrics.searches.metrics,
collapsedSections: [...state.metrics.collapsedSections],
traceErrorsOnly: state.traces.errorsOnly,
traceStatus: state.traces.status,
@@ -7033,16 +7074,17 @@ function savePrefs() {
}
function applyPaneSize() {
$("#metrics-body").style.setProperty("--pane-min", `${state.metrics.paneMin}px`);
for (const body of chartBodies()) body.style.setProperty("--pane-min", `${state.metrics.paneMin}px`);
resizeCharts();
}
$("#smooth-range").addEventListener("input", (e) => {
state.metrics.smooth = +e.target.value;
$("#smooth-val").textContent = state.metrics.smooth > 1 ? String(state.metrics.smooth) : "off";
updateCharts();
savePrefs();
});
/* one smoothing window, shown on both chart tabs */
function syncSmoothControls() {
for (const tab of Object.keys(CHART_VIEWS)) {
$(`#${tab}-smooth`).value = state.metrics.smooth;
$(`#${tab}-smooth-val`).textContent = state.metrics.smooth > 1 ? String(state.metrics.smooth) : "off";
}
}
let ticking = false;
async function pollDashboard() {
@@ -7060,7 +7102,7 @@ async function pollDashboard() {
}
renderOverview(); // keeps the duration field ticking
syncDressedSelects();
if (state.tab === "metrics" && state.metrics.loaded) await fetchMetrics();
if (isChartTab() && state.metrics.loaded) await fetchMetrics();
else if (state.tab === "logs" && state.logs.loaded) await pollLogs();
else if (state.tab === "traces" && state.traces.loaded) await refreshTraces();
else if (state.tab === "report" && state.report.loaded) await refreshReport();
@@ -7088,9 +7130,8 @@ document.addEventListener("visibilitychange", () => {
});
(async function init() {
$("#smooth-range").value = state.metrics.smooth;
$("#smooth-val").textContent = state.metrics.smooth > 1 ? String(state.metrics.smooth) : "off";
$("#metrics-search").value = state.metrics.search;
syncSmoothControls();
for (const [tab, view] of Object.entries(CHART_VIEWS)) $(view.search).value = state.metrics.searches[tab];
state.logs.level = LOG_LEVELS.some(([level]) => level === prefs.logLevel) ? prefs.logLevel : "DEBUG";
renderLogLevel();
$("#log-search").value = prefs.logSearch ?? "";
@@ -7098,16 +7139,14 @@ document.addEventListener("visibilitychange", () => {
const signal = prefs.tokenSignal ?? "";
$("#token-signal").value = $(`#token-signal option[value="${CSS.escape(signal)}"]`) ? signal : "";
$("#follow-toggle").checked = state.follow;
for (const sel of ["#run-select", "#trace-env", "#metrics-env", "#trace-sort", "#tm-env", "#tm-sort", "#config-attempt-select", "#attempt-select", "#token-signal", "#report-select"])
for (const sel of ["#run-select", "#trace-env", "#overview-env", "#trace-sort", "#tm-env", "#tm-sort", "#config-attempt-select", "#attempt-select", "#token-signal", "#report-select"])
dressSelect($(sel));
syncTraceFilterControls();
setActive("#metrics-mode", "mode", state.metrics.mode);
setActive("#all-layout", "layout", state.metrics.allLayout);
$("#all-layout").hidden = state.metrics.mode !== "all";
setActive("#metrics-layout", "layout", state.metrics.allLayout);
setActive("#log-view", "view", state.logs.view);
applyPaneSize();
const params = new URLSearchParams(location.hash.slice(1));
state.tab = params.get("tab") || "metrics";
state.tab = params.get("tab") || "overview";
state.report.wanted = params.get("report");
hadHashRun = !!params.get("run");
setActive("#tabs", "tab", state.tab);
@@ -7116,6 +7155,6 @@ document.addEventListener("visibilitychange", () => {
const wanted = params.get("run");
const run = state.runs.find((r) => r.name === wanted)?.name ?? state.runs[0]?.name;
if (run) await selectRun(run);
else $("#metrics-body").innerHTML = emptyState("no runs found", `nothing to show in ${state.outputDir ?? "the output directory"}`);
else $("#overview-body").innerHTML = emptyState("no runs found", `nothing to show in ${state.outputDir ?? "the output directory"}`);
connectViewEvents();
})();
+24 -15
View File
@@ -21,7 +21,8 @@
</div>
<nav id="tabs">
<button data-tab="config">Config</button>
<button data-tab="metrics" class="active">Metrics</button>
<button data-tab="overview" class="active">Overview</button>
<button data-tab="metrics">Metrics</button>
<button data-tab="traces">Traces</button>
<button data-tab="report">Report</button>
<button data-tab="logs">Logs</button>
@@ -38,30 +39,39 @@
<div id="run-overview"></div>
<main>
<section id="tab-metrics">
<section id="tab-overview">
<div class="controls">
<div id="metrics-filter-wrap" class="dd-wrap" hidden>
<button id="metrics-filter-btn" class="btn dd-btn" title="filter">
<div id="overview-filter-wrap" class="dd-wrap" hidden>
<button id="overview-filter-btn" class="btn dd-btn" title="filter">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
</button>
<div class="dd-menu dd-filters" id="metrics-filter-menu" hidden>
<div class="dd-menu dd-filters" id="overview-filter-menu" hidden>
<div class="dd-sec">filter</div>
<label class="dd-row" id="metrics-env-row"><span class="t-label">env</span>
<select id="metrics-env"></select>
<label class="dd-row" id="overview-env-row"><span class="t-label">env</span>
<select id="overview-env"></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="metrics-errors"><span class="dot"></span>include errors</label>
<label class="toggle dd-row"><input type="checkbox" id="overview-errors"><span class="dot"></span>include errors</label>
</div>
</div>
<div class="seg" id="metrics-mode">
<button data-mode="overview" class="active">Overview</button>
<button data-mode="all">All</button>
</div>
<input id="overview-search" class="search" type="search" placeholder="regex filter, e.g. reward or ^inference/">
<label class="ctl">smooth <input id="overview-smooth" type="range" min="1" max="50" value="1"><span id="overview-smooth-val">off</span></label>
<span id="overview-status" class="muted"></span>
<div class="spacer"></div>
<button id="overview-collapse" class="btn">collapse</button>
<button id="overview-expand" class="btn">expand</button>
</div>
<div id="overview-body"></div>
<div id="swarm-tip" hidden></div>
</section>
<section id="tab-metrics" hidden>
<div class="controls">
<input id="metrics-search" class="search" type="search" placeholder="regex filter, e.g. ^entropy/ or reward">
<label class="ctl">smooth <input id="smooth-range" type="range" min="1" max="50" value="1"><span id="smooth-val">off</span></label>
<label class="ctl">smooth <input id="metrics-smooth" type="range" min="1" max="50" value="1"><span id="metrics-smooth-val">off</span></label>
<span id="metrics-status" class="muted"></span>
<div class="spacer"></div>
<div class="seg" id="all-layout" hidden>
<div class="seg" id="metrics-layout">
<button data-layout="flat">Flat</button>
<button data-layout="nested">Nested</button>
</div>
@@ -69,7 +79,6 @@
<button id="metrics-expand" class="btn">expand</button>
</div>
<div id="metrics-body"></div>
<div id="swarm-tip" hidden></div>
</section>
<section id="tab-config" hidden>
+5 -3
View File
@@ -306,12 +306,14 @@ main > section { flex: 1; min-height: 0; display: flex; flex-direction: column;
/* --------------------------------------------------------------- metrics */
/* stable gutter: no layout shift when collapsing sections hides the scrollbar */
#metrics-body { flex: 1; overflow-y: auto; scrollbar-gutter: stable; min-height: 0; padding-right: 10px; }
#overview-body, #metrics-body { flex: 1; overflow-y: auto; scrollbar-gutter: stable; min-height: 0; padding-right: 10px; }
.chart-card.dragging { opacity: 0.45; }
/* one 12px rhythm everywhere: section-to-section, header-to-panes, pane-to-pane */
details.section { margin-bottom: 12px; }
/* nested sections (all-mode key tree) indent one step */
details.section details.section { margin-left: 14px; }
/* a section's own panes keep the rhythm before the sections nested under them */
details.section > .chart-grid:not(:last-child) { margin-bottom: 12px; }
details.section:not([open]) > summary { margin-bottom: 0; }
/* section headers are full-width bars so the clickable region is obvious */
details.section > summary {
@@ -360,7 +362,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
.ep-cell.live { border-color: var(--accent); background: rgba(182, 255, 60, 0.18); animation: live-pulse 1.6s ease-in-out infinite; cursor: pointer; }
/* distributions: a beeswarm per metric, a faint boxplot behind it, stats on hover */
#tab-metrics { position: relative; }
#tab-overview { position: relative; }
.swarm-card .chart-head { cursor: default; }
.swarm-host { height: var(--pane-h, 150px); margin-top: 6px; }
.swarm { display: block; }
@@ -528,7 +530,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
/* metrics regex filter (overview + all) */
#metrics-search, #config-search, #log-search { flex: 1; max-width: 460px; }
#overview-search, #metrics-search, #config-search, #log-search { flex: 1; max-width: 460px; }
/* wandb-style resize handles on every chart card: right edge = width, bottom
edge = height, corner = both. Resizing one pane resizes all of them. */
+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.
+27
View File
@@ -91,6 +91,13 @@ class InferenceClient:
)
self.eval_client = setup_client(client_config, client_type=eval_client_type)
self._scorer = PrefillScorer()
# Managed routed deployments set admin_base_url so engine admin traffic
# bypasses the client-facing router. External and frozen clients do not.
self._session_client = (
setup_admin_clients(client_config.model_copy(update={"admin_base_url": None}))[0]
if client_config.admin_base_url is not None
else None
)
self.model_name = model_name
async def score(self, token_ids: list[int]) -> list[float]:
@@ -100,6 +107,26 @@ class InferenceClient:
async def aclose(self) -> None:
await self._scorer.aclose()
if self._session_client is not None:
await self._session_client.aclose()
async def finish_sessions(self, session_ids: list[str]) -> None:
"""Release completed sessions when the client-facing router supports it."""
if self._session_client is None or not session_ids:
return
async def finish_session(session_id: str) -> None:
try:
await _admin_post(
self._session_client,
"/finish_session",
timeout_s=5.0,
params={"session_id": session_id},
)
except Exception as error:
get_logger().debug(f"Failed to release inference session {session_id}: {error!r}")
await asyncio.gather(*(finish_session(session_id) for session_id in session_ids))
class AdminPlane:
+25 -26
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)
@@ -593,7 +578,10 @@ class Dispatcher:
started_at=time.monotonic(),
)
session_ids: set[str] = set()
def on_delta(delta: dict) -> None:
session_ids.add(delta["trace"])
first = not meta.live
live.apply(meta, delta)
self.queue_live({"delta": delta, "dispatch": live.dispatch_info(meta)})
@@ -602,15 +590,26 @@ class Dispatcher:
if first and meta.live:
self.live_events.append(live.dispatched_event(meta))
task = asyncio.create_task(
env.run(
client=client,
model_name=model_name,
cache_salt=cache_salt,
task_data=group.task.data.model_dump(mode="json"),
on_delta=on_delta,
)
)
async def run_episode() -> vf.WireEpisode:
try:
episode = await env.run(
client=client,
model_name=model_name,
cache_salt=cache_salt,
task_data=group.task.data.model_dump(mode="json"),
on_delta=on_delta,
)
session_ids.update(trace.id for trace in episode.traces)
return episode
finally:
cleanup = asyncio.create_task(clients.finish_sessions(sorted(session_ids)))
try:
await asyncio.shield(cleanup)
except asyncio.CancelledError:
await cleanup
raise
task = asyncio.create_task(run_episode())
self.inflight[task] = meta
self.live_events.append(live.pending_event(meta))
return True
+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()
+10 -2
View File
@@ -60,8 +60,8 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
page.on("pageerror", lambda e: errors.append(f"page: {e}"))
base = f"http://127.0.0.1:{port}"
# metrics: the run resolves and the overview renders charts with data
page.goto(f"{base}/#run={run_name}&tab=metrics")
# overview: the run resolves and the curated view renders with data
page.goto(f"{base}/#run={run_name}&tab=overview")
page.wait_for_timeout(PAGE_SETTLE_MS)
status = page.locator("#run-overview .badge").first.inner_text()
assert status, "overview card did not render a status"
@@ -82,6 +82,14 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
with_data = page.evaluate("""() => [...document.querySelectorAll('.chart-card .u-wrap')].length""")
assert with_data >= 5, f"expected >=5 mounted charts, got {with_data}"
# metrics: every key in metrics.jsonl, one pane each, for every run type
page.click("#tabs [data-tab=metrics]")
page.wait_for_timeout(PAGE_SETTLE_MS)
panes = page.locator("#metrics-body .chart-card").count()
assert panes >= 5, f"expected >=5 metric panes, got {panes}"
mounted = page.evaluate("""() => document.querySelectorAll('#metrics-body .chart-card .u-wrap').length""")
assert mounted >= 1, f"expected mounted metric panes, got {mounted}"
# config: the default view renders (launch TOML on new runs), and the
# resolved concatenated document renders as a tree
page.click("#tabs [data-tab=config]")
+25 -8
View File
@@ -40,16 +40,33 @@ def get_config_files() -> list[Path]:
return config_files + example_files + k8s_files
def can_parse(config_cls: type, args: list[str]) -> bool:
"""Whether `cli` parses the given `@` config file args into `config_cls`."""
try:
cli(config_cls, args=args)
return True
except (ValidationError, ConfigFileError, SystemExit):
return False
@pytest.mark.parametrize("config_file", get_config_files(), ids=lambda x: x.as_posix())
def test_load_configs(config_file: Path):
"""Tests that all config files can be loaded by at least one config class."""
could_parse = []
for config_cls in CONFIG_CLASSES:
try:
cli(config_cls, args=["@", config_file.as_posix()])
could_parse.append(True)
except (ValidationError, ConfigFileError, SystemExit):
could_parse.append(False)
"""Tests that all config files can be loaded by at least one config class.
A file that no class parses standalone is an overlay — a checked-in config that only carries
the deltas over a shared base (e.g. the glm-4.5-air budget variants over
`swe-budget.toml`). Retry those composed with each sibling TOML as the base: the
documented `@ base.toml @ overlay.toml` left-to-right merge (docs/configuration.md,
"TOML Composition").
"""
could_parse = [can_parse(config_cls, ["@", config_file.as_posix()]) for config_cls in CONFIG_CLASSES]
if not any(could_parse):
sibling_bases = sorted(p for p in config_file.parent.glob("*.toml") if p != config_file)
could_parse = [
can_parse(config_cls, ["@", base.as_posix(), "@", config_file.as_posix()])
for base in sibling_bases
for config_cls in CONFIG_CLASSES
]
assert any(could_parse), f"No config class could be parsed from {config_file}"
Generated
+16 -16
View File
@@ -5058,8 +5058,8 @@ all = [
{ name = "torchvision", marker = "sys_platform == 'linux'" },
{ name = "vllm", version = "0.28.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm", version = "0.28.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.0", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.0", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
]
dashboard = [
{ name = "fastapi" },
@@ -5072,8 +5072,8 @@ disagg = [
{ name = "deep-gemm", version = "2.5.0+891d57b", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "nixl", marker = "sys_platform == 'linux'" },
{ name = "nixl-cu13", marker = "sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.0", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.0", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
]
dynamo = [
{ name = "ai-dynamo", marker = "sys_platform == 'linux'" },
@@ -5177,7 +5177,7 @@ requires-dist = [
{ name = "prime-rl", extras = ["gpu"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.1" },
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.3" },
{ name = "prometheus-client", specifier = ">=0.20.0" },
{ name = "psutil", specifier = ">=7.0.0" },
{ name = "pyarrow", specifier = ">=21.0.0" },
@@ -5206,9 +5206,9 @@ requires-dist = [
{ name = "vllm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.28.0" },
{ name = "vllm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" },
{ name = "vllm-router", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'disagg'" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "wandb", specifier = ">=0.26.1" },
{ name = "wandb-workspaces", specifier = ">=0.4.3" },
]
@@ -5251,15 +5251,15 @@ requires-dist = [
[[package]]
name = "prime-runs"
version = "0.1.2"
version = "0.1.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx" },
{ name = "prime-traces" },
]
sdist = { url = "https://files.pythonhosted.org/packages/db/ee/0e9cf800aa6b3db148b01d26e0d6957074027f52323b348ad35594e41d1c/prime_runs-0.1.2.tar.gz", hash = "sha256:2cd4775aa3176f95abf3def78ba257b6b0579ba2606d24307c88495e5b1bb6f1", size = 62099, upload-time = "2026-09-09T00:28:45.621Z" }
sdist = { url = "https://files.pythonhosted.org/packages/3f/ba/3d38aeafc0ef885eef7b99bbe26fe350b4248af8d3fa89d4ca8a249f0f04/prime_runs-0.1.3.tar.gz", hash = "sha256:181ab1c720ed9113abbf3719ba6863c9ee23c55309101c0b7f4021ff9dafbe20", size = 65541, upload-time = "2026-09-17T15:31:42.319Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/37/59/e48470b0b47d3fc261e31e13d1ed47177f0a71044234ae46b40b00063f1c/prime_runs-0.1.2-py3-none-any.whl", hash = "sha256:95ca0775317cf2733aa38a0a26b263174b992d5be63009a4cfeeff212924759b", size = 43333, upload-time = "2026-09-09T00:28:44.22Z" },
{ url = "https://files.pythonhosted.org/packages/6e/93/5fff685470a6cb12fc93192432951a081de70e271aef1cebc506fba4ccc5/prime_runs-0.1.3-py3-none-any.whl", hash = "sha256:86c3d5183ed5848854a194233b4a9451deabea56a9063771244c5c54c00d69df", size = 45087, upload-time = "2026-09-17T15:31:40.913Z" },
]
[package.optional-dependencies]
@@ -8298,8 +8298,8 @@ provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttens
[[package]]
name = "vllm-router"
version = "0.2.0"
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl" }
version = "0.2.1"
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" }
resolution-markers = [
"platform_machine == 'aarch64' and sys_platform == 'linux'",
]
@@ -8312,7 +8312,7 @@ dependencies = [
{ name = "uvicorn" },
]
wheels = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:07b4b18155231c926334a497db504767930fb81758049cbd9113c1e9f9c2ba69" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:0420aba42df1c970a78e1c4d4062eb00498e397f2dd506bade39eb915bf807b6" },
]
[package.metadata]
@@ -8331,8 +8331,8 @@ provides-extras = ["dev"]
[[package]]
name = "vllm-router"
version = "0.2.0"
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl" }
version = "0.2.1"
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" }
resolution-markers = [
"platform_machine == 'x86_64' and sys_platform == 'linux'",
]
@@ -8345,7 +8345,7 @@ dependencies = [
{ name = "uvicorn" },
]
wheels = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:bac193bedf10f9a0265fe4fdaae0f0418574cd1f15c45f27da1b4a2bae8c10b8" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:046591cac21424997600d30b500bbaa3c450601e8b2b4fad6db9d142d1c36a0e" },
]
[package.metadata]