Compare commits

...
Author SHA1 Message Date
01994b8168 fix: misc dashboard improvs (#3374)
## Summary

- refresh live metrics and trace rows on the same five-second cadence
- better `no data yet` for unavailable overview data
- show episode and trace errors at the bottom of the trace viewer
- add the task key as `task ID` to the identity section of the trace
overview pane
- use `n/a` for missing value uniformly; some spots showed an en dash.
- allow filter from trace viewer

## Verification

### Overview empty state

<img width="1608" height="1045" alt="Screenshot 2026-08-24 at 3 54 20
PM"
src="https://github.com/user-attachments/assets/02e06087-5286-435e-9776-52ec9502f7f5"
/>

### Errors

<img width="1608" height="1045" alt="Screenshot 2026-08-24 at 3 52 29
PM"
src="https://github.com/user-attachments/assets/b39a28cc-c50d-467c-b7f7-39c354a5e008"
/>

### Task ID

<img width="318" height="151" alt="Screenshot 2026-08-24 at 3 52 42 PM"
src="https://github.com/user-attachments/assets/f12f50b5-685d-4ca5-8b80-5c89877cab43"
/>

### Checks

- `node --check src/prime_rl/dashboard/static/app.js`
- `git diff --check`
- dashboard browser smoke against `outputs/reverse-text-rl`
- live append browser repro for metrics, trace rows, and new trace steps
- fake inference URL eval and browser layout check with a full traceback
- headless browser render of a synthetic `ProviderError` episode:
collapsed and expanded traceback, `task ID` row, consistent `n/a`
placeholders, red-marked error rows in the sidebar

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Frontend-only dashboard static assets; no API or training-path
changes. Risk is limited to UI regressions in metrics/traces polling and
the trace modal.
> 
> **Overview**
> This PR tightens **live updates** and **trace UX** in the static
dashboard (`app.js`, `index.html`, `style.css`).
> 
> **Polling & loading:** Poll interval moves to **5s**; metrics and
traces refresh when switching tabs with live on, on tab visibility, and
when re-enabling live. Metrics streaming stops retrying the same offset
when a partial JSONL line sits at EOF; `fetching` guards avoid
overlapping metrics/trace loads.
> 
> **Traces:** Step selection **follows the latest preferred step** while
you’re on the tail (historical picks and an open modal stay put). Empty
trace/metrics states use shorter labels and the episode table keeps its
chrome with an in-table empty row to avoid layout shift. Overview panels
show **“no data yet”** for configured eval sections before data lands.
> 
> **Trace viewer:** Episode/trace **errors render as banners** at the
bottom of the message column (with expandable tracebacks); **task ID**
appears in the identity pane. The modal gets the same
**filter/sort/env/errors** controls as the traces tab, synced through
shared state. Error episodes are highlighted in the sidebar list.
> 
> **Polish:** Missing numeric/overview fields use **`n/a`** instead of
en dashes (empty eval env list still shows **–**). Run overview merges
the full run record from the runs list on refresh.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
239dc7797d996fb0b17badb9dd60b640474b431d. 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 <noreply@anthropic.com>
2026-08-24 16:11:11 -07:00
e6b5e4de5d feat: auto-started dashboard daemon (#3371)
## Summary

- Launchers (`rl`, `sft`) register their output dir in
`~/.cache/prime-rl/dashboard/dirs.json` and make sure one dashboard
serves it (`ensure_dashboard` in the new `entrypoints/dashboard.py`,
kept free of `dashboard`-extra imports). Every dashboard instance serves
its CLI dirs **plus** the registry, re-read live — a run in a new output
dir appears on the one live URL without a restart: one dashboard per
host per user.
- Discovery goes through `daemon.json` (pid + **actual** url), so it
survives port spillover — nothing ever probes port 7788. A live daemon's
URL is logged (`Dashboard running at <url>`); interactive sessions spawn
a detached daemon (own session — killing a run never takes it down) when
none is live (`Dashboard started at <url>`); non-tty launches (CI,
nohup) only register. A stale claim from a dead process is taken over on
the next start.
- `--isolated` is the escape hatch: serve only the given dirs, no
registry read/write, no discovery claim (launchers ignore the instance).
`dashboard: bool = True` on RL/SFT opts a run out via `--no-dashboard`.
- The daemon carries the process title `PRL::Dashboard` via the shared
`set_proc_title`. `psutil` is promoted from transitive to a core
dependency so `prime_rl.utils.process` imports in the slim GPU-free env.
- Launcher startup now ends with a `Dashboard · <url>` banner (blank
lines around, green url) as the last log, after `Launcher complete` (was
`Startup complete. Showing ... logs`). The launcher no longer tails
orchestrator/trainer logs into its terminal - the dashboard is the
monitoring surface.
- New `skills/dashboard/SKILL.md` teaches agents discovery, liveness
checks, and kill/restart commands; `monitor-run` and `start-run` skills
point at it.

Supersedes #3368, rebuilt on the (now merged) stack #3369 (PRL prefix) →
#3370 (GPU extra; the server is a normal package member, so no
setproctitle fallback and no duplicated cache-dir logic); targets
`main`.

## Verification

E2E on this box: daemon claims `daemon.json` with pid + url and shows
`PRL::Dashboard` in `ps`; `ensure_dashboard` from a second process
registers a fresh output dir and the live dashboard absorbs it (run
count grows without restart); a second instance spills to port 7789 and
does **not** steal the claim; `--isolated` serves only its dirs and
leaves the registry untouched; a pty-spawned launcher starts a detached
daemon that survives the launcher's exit; slim `uv sync --extra
dashboard` env (no torch/vllm) imports `entrypoints.dashboard`,
`dashboard.server`, and `set_proc_title`, and `dashboard --help` works;
`tests/unit/test_configs.py` passes (122).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are local dev/monitoring UX and read-only dashboard serving;
training paths are unchanged aside from optional subprocess spawn and
registry file writes.
> 
> **Overview**
> **RL and SFT launchers** now register each run’s `output_dir` in a
per-user registry and ensure a single local dashboard serves it. New
`dashboard: bool = True` (disable with `--no-dashboard`) drives
`ensure_dashboard` in `entrypoints/dashboard.py`, which reuses a live
daemon via `~/.cache/prime-rl/dashboard/daemon.json` or spawns a
detached process in interactive TTY sessions only.
> 
> The **dashboard server** merges CLI dirs with `dirs.json` (live
re-read), claims/releases daemon discovery, adds **`--isolated`** to opt
out of the registry, and moves sidecar cache under the shared dashboard
state dir. The **`dashboard` console script** now enters through
`entrypoints.dashboard.main`.
> 
> **Launcher UX** drops `tail -F` on orchestrator/trainer logs; startup
ends with **Launcher complete** and a **Dashboard · url** banner.
**`psutil`** is a direct dependency so process titles work without the
GPU stack. Agent skills/docs describe discovery, liveness, and
kill/restart.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
035e7ec4c1a2671db778a85a42147d332a8a73ed. 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 <noreply@anthropic.com>
2026-08-24 15:12:09 -07:00
a5853ce9ab feat: slim uv sync (#3370)
## Summary

- The CUDA/linux-only stack (torch+cu128 index, vllm, torchtitan,
mooncake-transfer-engine, ring-flash-attn, dion, tilelang,
flash-linear-attention, torchao, nvidia-ml-py, modelexpress) moves from
core dependencies into a **`gpu` extra** (linux-marked), and
`darwin/arm64` joins `tool.uv.environments` — a bare `uv sync` now
resolves and installs on a MacBook (slim: configs, monitors, dashboard,
CLI tooling). `uv sync --all-extras` — already the recommended install
on GPU machines — pulls everything exactly as before (`all` aggregates
`gpu` too).
- Every other GPU extra (`flash-attn-3`, `flash-attn-cute`, `disagg`,
`gpt-oss`, `quack`, `kernels`, the `mamba-ssm` group) gets linux markers
so the darwin lock split resolves; the torch cu128 index sources are
linux-scoped.
- CI (`cpu_tests`, benchmarks) and the docker entrypoint's
`PRIME_RL_REF` override sync move to `--all-extras`; `Dockerfile.cuda`
adds `--extra gpu`; the install skill documents the split.
- The dashboard's standalone PEP 723 `--script` form is removed: `uv
sync --extra dashboard && uv run dashboard` is now the dependency-free
path everywhere, and `server.py` becomes a normal package member — it
imports the new `CACHE_DIR` from `utils/pathing` instead of duplicating
the cache-dir logic.

## Breaking

- `uv sync` without extras no longer installs the training/inference
stack; use `uv sync --all-extras` (recommended) or `--extra gpu`.
Anything invoking `uv sync --extra flash-attn` alone must add `--extra
gpu`.
- `uv run --script src/prime_rl/dashboard/server.py` no longer works
(header removed); use `uv sync --extra dashboard && uv run dashboard`.

## Verification

On linux: bare `uv sync --extra dashboard` produces an env with no
torch/vllm from which `uv run dashboard` serves real runs end to end;
`uv sync --all-extras --all-packages` restores the full env (torch
2.11+cu128, vllm import, `entrypoints.rl` import OK);
`tests/unit/test_configs.py` (122 passed) and the dashboard browser
smoke pass. `uv lock` resolves all three environments including the new
darwin split.

#3369 (PRL prefix) is merged and this now targets `main`; the
dashboard-daemon PR (#3371) lands on top.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes the default dependency contract and Docker runtime `uv sync`
behavior; anyone on bare `uv sync` or old dashboard script paths will
miss GPU deps, and PRIME_RL_REF overrides now pull all extras (including
heavy disagg/quack) at pod startup.
> 
> **Overview**
> **Slim default install:** Core dependencies no longer pull the Linux
CUDA training stack (torch/cu128, vllm, torchtitan, mooncake,
ring-flash-attn, dion, tilelang, flash-linear-attention, torchao,
modelexpress, nvidia-ml-py). Those move behind a new **`gpu` optional
extra** (linux-marked). Other GPU extras (`flash-attn-3`, `disagg`,
`quack`, `kernels`, `mamba-ssm`, etc.) get linux markers;
**`darwin/arm64`** is added to `tool.uv.environments` so a bare `uv
sync` resolves on macOS. The **`all`** extra now includes
`prime-rl[gpu]`.
> 
> **Install paths updated:** CI (`cpu_tests`, benchmarks) and
**`Dockerfile.cuda`** sync with **`--all-extras`** / explicit **`--extra
gpu`** so Linux GPU images still get the full stack.
**`scripts/docker-entrypoint.sh`** on `PRIME_RL_REF` overrides switches
from a hand-picked extra list to **`uv sync --inexact --all-extras`**
(plus `mamba-ssm` group)—so override checkouts may install disagg/quack
at startup, not only flash-attn/gpt-oss.
> 
> **Dashboard:** The PEP 723 **`uv run --script`** standalone form is
removed from `server.py`; docs/skills point to **`uv sync --extra
dashboard && uv run dashboard`**. Dashboard sidecar cache uses shared
**`CACHE_DIR`** from `utils/pathing` (`home_dir()` fallback to temp).
> 
> **Breaking:** `uv sync` alone no longer installs training/inference
deps—use **`uv sync --all-extras`** (recommended on GPU Linux) or
**`--extra gpu`** (and add flash-attn etc. as before). **`uv run
--script src/prime_rl/dashboard/server.py`** no longer works.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
64562e87834dc6ef1eba7ab372b50f102088cb5f. 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 <noreply@anthropic.com>
2026-08-24 14:43:45 -07:00
Mika SenghaasandGitHub 38582b2bf1 chore: bump verifiers to 0.3.1 (#3372)
## Summary

- require the stable `verifiers[harbor]>=0.3.1` release instead of a
development build
- point the Verifiers submodule at the published `v0.3.1` tag

## Verification

- `uv lock --check`
- built `verifiers-0.3.1-py3-none-any.whl` and `verifiers-0.3.1.tar.gz`
from `deps/verifiers`
- verified the submodule commit has the exact `v0.3.1` tag

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dependency constraint only—switches from a dev pre-release to the
stable 0.3.1 minimum with no application code changes in this diff.
> 
> **Overview**
> Pins **`verifiers[harbor]`** to the stable **`>=0.3.1`** release
instead of the prior **`>=0.3.1.dev59`** development build in
`pyproject.toml`.
> 
> This moves dependency resolution off a pre-release dev tag onto the
published 0.3.1 line while keeping the same optional **`harbor`** extra
and existing editable **`deps/verifiers`** source configuration.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f399e80c03ad6e26533aa770df28e90c69517891. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 14:24:46 -07:00
a266325605 feat: rename proc-title prefix to PRL (#3369)
## Summary

- `PRIME_RL_PROC_PREFIX` becomes `PRL`, so every component's process
title reads `PRL::Trainer`, `PRL::Orchestrator`, `PRL::Inference`,
`PRL::EnvServer`, `PRL::Launcher`, ... — shorter to type and grep. The
`monitor-run` skill's process tree is updated.

## Breaking

- Process titles change from `PRIME-RL::<Name>` to `PRL::<Name>`;
anything matching the old prefix (`pgrep -f PRIME-RL`, dashboards, ops
scripts) must switch.

First PR of a 3-stack: PRL prefix → CPU-only `uv sync` (GPU deps behind
an extra) → dashboard daemon.

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 14:17:03 -07:00
Konstantin DunasandGitHub b9de4a0f7a fix(orchestrator): make dispatch failures explicit (#3364) 2026-08-24 22:23:30 +02:00
32 changed files with 1189 additions and 421 deletions
+1 -1
View File
@@ -170,7 +170,7 @@ jobs:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync
run: uv sync --all-extras
- name: Download all benchmark artifacts
uses: actions/download-artifact@v8
with:
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --extra flash-attn --all-packages --locked
run: uv sync --all-extras --all-packages --locked
- name: Run tests
env:
USERNAME_CI: CI_RUNNER
+2 -2
View File
@@ -96,7 +96,7 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# mount here: .git would bust the cache every commit.
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
@@ -132,7 +132,7 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
+1 -1
+1 -1
View File
@@ -329,7 +329,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 four views per run: metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved configs, a rollout trace viewer with a per-token advantage/logprob view, and merged component logs. 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. On a machine that should not resolve the training dependencies (e.g. a cluster head node), run it standalone: `uv run --script src/prime_rl/dashboard/server.py [output_dir ...]` — an isolated script environment with only the dashboard's own small dependencies.
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with four views per run: metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved configs, a rollout trace viewer with a per-token advantage/logprob view, and merged component logs. 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.
### Weights & Biases
@@ -299,6 +299,10 @@ class RLConfig(BaseConfig):
slurm: SlurmConfig | None = None
"""SLURM configuration. If None, runs locally."""
dashboard: bool = True
"""Make sure a local dashboard daemon serves this run's output dir (started on
demand in interactive sessions; an already-running daemon's URL is logged)."""
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
@@ -285,6 +285,10 @@ class SFTConfig(BaseConfig):
slurm: SlurmConfig | None = None
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
dashboard: bool = True
"""Make sure a local dashboard daemon serves this run's output dir (started on
demand in interactive sessions; an already-running daemon's URL is logged)."""
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
+35 -30
View File
@@ -13,38 +13,25 @@ dependencies = [
"loguru>=0.7.3",
"pyarrow>=21.0.0",
"numpy>=2.2.6",
"torch>=2.9.0",
"torchvision",
"torchaudio",
"torchdata>=0.11.0",
"transformers==5.6.2",
"vllm>=0.26.0",
"mooncake-transfer-engine>=0.3.10.post2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
"ring-flash-attn>=0.1.8",
"prime>=0.6.19",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
"openai>=1.106.1",
"orjson>=3.11.0",
"psutil>=7.0.0",
"rich>=14.0.0",
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.3.1.dev59",
"verifiers[harbor]>=0.3.1",
"renderers>=0.1.10",
"dion",
"tilelang>=0.1.8",
"flash-linear-attention",
"nvidia-ml-py>=12.575.51",
"pybase64>=1.4.2",
"orjson>=3.10",
"pandas>=2.0",
"msgspec>=0.18",
"torchao>=0.17.0",
"modelexpress==0.3.0",
]
[project.scripts]
@@ -55,12 +42,28 @@ trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
evals = "prime_rl.entrypoints.evals:main"
env-server = "prime_rl.entrypoints.env_server:main"
dashboard = "prime_rl.dashboard.server:main"
dashboard = "prime_rl.entrypoints.dashboard:main"
[project.entry-points."vllm.general_plugins"]
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
[project.optional-dependencies]
gpu = [
"torch>=2.9.0 ; sys_platform == 'linux'",
"torchvision ; sys_platform == 'linux'",
"torchaudio ; sys_platform == 'linux'",
"torchdata>=0.11.0 ; sys_platform == 'linux'",
"vllm>=0.26.0 ; sys_platform == 'linux'",
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
"torchtitan ; sys_platform == 'linux'",
"dion ; sys_platform == 'linux'",
"tilelang>=0.1.8 ; sys_platform == 'linux'",
"flash-linear-attention ; sys_platform == 'linux'",
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
"torchao>=0.17.0 ; sys_platform == 'linux'",
"modelexpress==0.3.0 ; sys_platform == 'linux'",
]
dashboard = [
"fastapi>=0.115",
"uvicorn>=0.30",
@@ -73,30 +76,31 @@ flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.22/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
]
flash-attn-3 = ["flash_attn_3"]
flash-attn-3 = ["flash_attn_3 ; sys_platform == 'linux'"]
flash-attn-cute = [
"flash-attn-4",
"flash-attn-4 ; sys_platform == 'linux'",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64' or platform_machine == 'aarch64'",
"deep-gemm",
"nixl",
"nixl-cu12 ; platform_machine == 'x86_64'",
"vllm-router",
"deep-ep ; sys_platform == 'linux'",
"deep-gemm ; sys_platform == 'linux'",
"nixl ; sys_platform == 'linux'",
"nixl-cu12 ; sys_platform == 'linux' and platform_machine == 'x86_64'",
"vllm-router ; sys_platform == 'linux'",
]
gpt-oss = [
"kernels",
"kernels ; sys_platform == 'linux'",
]
quack = [
"quack-kernels>=0.4.1",
"quack-kernels>=0.4.1 ; sys_platform == 'linux'",
]
# Prebuilt `prime-kernels` wheels from a release (see the `kernels` skill). Compiled for
# sm_100a; on other GPUs the package installs fine and reports its kernels unavailable.
kernels = [
"prime-kernels",
"prime-kernels ; sys_platform == 'linux'",
]
all = [
"prime-rl[gpu]",
"prime-rl[flash-attn]",
"prime-rl[disagg]",
"prime-rl[quack]",
@@ -106,7 +110,7 @@ all = [
[dependency-groups]
mamba-ssm = [
"mamba-ssm>=2.3.0",
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
]
dev = [
"ipykernel>=6.29.5",
@@ -129,6 +133,7 @@ no-build-isolation-package = ["flash-attn"]
environments = [
"sys_platform == 'linux' and platform_machine == 'x86_64'",
"sys_platform == 'linux' and platform_machine == 'aarch64'",
"sys_platform == 'darwin' and platform_machine == 'arm64'",
]
# Override torch's pinned cuDNN to fix Conv3d performance regression (torch 2.9 + cuDNN 9.8-9.14)
# See: https://github.com/pytorch/pytorch/issues/166122
@@ -216,9 +221,9 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
torch = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
torchvision = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
torchaudio = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
torchao = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
+4 -10
View File
@@ -53,16 +53,10 @@ if [ -n "$PRIME_RL_REF" ]; then
cp -a /app/.venv "$DEST/.venv"
fi
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
# Mirror the image's uv sync extras — explicit instead
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
# startup. --inexact keeps the seeded venv's pre-built wheels
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
# override's lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev --all-packages \
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
--extra gpt-oss \
--group mamba-ssm )
# --inexact keeps the seeded venv's pre-built wheels (flash-attn-3,
# deep-ep, mamba-ssm) in place; uv only rebuilds them if the override's
# lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev --all-packages --all-extras --group mamba-ssm )
export VIRTUAL_ENV="$DEST/.venv"
export PATH="$DEST/.venv/bin:$PATH"
cd "$DEST"
+53
View File
@@ -0,0 +1,53 @@
---
name: dashboard
description: Find, start, use, and stop the local run dashboard — the web UI for run output dirs (metrics, configs, traces, logs). Use when asked for the dashboard URL, when a run needs watching in the browser, or when a dashboard must be restarted or killed.
---
# Run dashboard
`uv sync --extra dashboard && uv run dashboard [output_dir ...]` (default
`outputs/`) serves a web UI at `http://localhost:7788`. It only reads run
dirs — safe against live runs — and installs anywhere (cluster head node,
laptop against a mounted outputs dir): GPU dependencies live behind the
`gpu` extra.
Every dashboard instance serves the dirs it was started with **plus** every dir
in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`, re-read
live). Launchers (`rl`, `sft`) register their output dir on every
start and, in interactive sessions, auto-start a dashboard only when none is
live — an already-running one absorbs the new dir automatically, whatever port
it is on. `--no-dashboard` opts a run out; non-interactive launches (CI, nohup)
register their dir but never spawn.
## Isolated mode
`--isolated` serves only the given dirs: no registry read or write, no
discovery claim, and launchers ignore the instance. Use it for focused views
(demos, debugging one run dir) or to keep a scratch dir out of the registry.
## Finding the live dashboard
The live port can differ from 7788 (a taken port bumps to the next free one),
so read the discovery file:
```bash
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
curl -sf $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/runs > /dev/null && echo live
ps aux | grep PRL::Dashboard # process title
```
Hand the researcher the `url` from `daemon.json`. Launcher logs also print it:
startup ends with a `Dashboard · <url>` banner. The auto-started instance logs
to `~/.cache/prime-rl/dashboard/daemon.log`.
## Stopping / restarting
```bash
kill $(jq -r .pid ~/.cache/prime-rl/dashboard/daemon.json) # the discovered instance
pkill -f PRL::Dashboard # every dashboard on the host
```
A clean exit releases `daemon.json`; a stale file from a dead process is taken
over by the next start. Killing a dashboard never affects runs (it only reads),
and killing a run never takes the dashboard down (it runs in its own session).
Restart by launching any run, or directly: `uv run dashboard`.
+1 -1
View File
@@ -22,7 +22,7 @@ git submodule update --init --recursive
## Sync
```bash
uv sync # core only
uv sync # slim
uv sync --group dev # + pytest, ruff, pre-commit
uv sync --all-extras # + extras (flash-attn, flash-attn-cute, …)
uv sync --all-extras --all-packages # + all env packages (needed to train on them)
+20 -8
View File
@@ -60,9 +60,21 @@ metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved con
files, a rollout trace viewer with a per-token advantage/logprob view, and merged
component logs. It only reads the run dirs — safe to run against a live run.
`--port`/`--host` pick the bind address; a taken port automatically bumps to the next
free one, so several dashboards run side by side without coordination. Without the
project's GPU deps (e.g. a head node), run it standalone:
`uv run --script src/prime_rl/dashboard/server.py [output_dir ...]`.
free one, so several dashboards run side by side without coordination. GPU deps live
behind the `gpu` extra, so `uv sync --extra dashboard && uv run dashboard` works
without the training stack (e.g. on a head node).
**Daemon (auto-start)**: launchers auto-start one dashboard per host per user and a
live one absorbs each new run's output dir automatically — see the `dashboard` skill
for discovery, kill/restart commands, and `--isolated`. The short version: the live
port can differ from 7788 (a taken port bumps), so read the discovery file:
```bash
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
ps aux | grep PRL::Dashboard # the daemon's process title
```
Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`.
### Logs
@@ -184,13 +196,13 @@ A few warnings are normal. Escalate when errors are persistent, growing, or hit
All processes use `setproctitle` so they're visible in `ps`/`htop`/`pstree`:
```
PRIME-RL::Launcher
├── PRIME-RL::Inference (vLLM server, GPU 0)
├── PRIME-RL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
PRL::Launcher
├── PRL::Inference (vLLM server, GPU 0)
├── PRL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
│ └── Verifiers::EnvWorker0..N
├── PRIME-RL::Orchestrator (CPU-only; connects to each env server)
├── PRL::Orchestrator (CPU-only; connects to each env server)
├── torchrun
│ └── PRIME-RL::Trainer (GPU 1+)
│ └── PRL::Trainer (GPU 1+)
└── tail trainer.log
```
+9
View File
@@ -139,3 +139,12 @@ env.agent.runtime.type = "subprocess"
- `packages/prime-rl-configs/src/prime_rl/configs/` — all config classes
- `configs/debug/` — minimal debug configs
- `examples/` — full example configs (e.g. `reverse-text/`)
## Dashboard
Interactive launches auto-start one shared dashboard daemon per user (process title
`PRL::Dashboard`) and end startup with a `Dashboard · <url>` banner. Relay
that URL to the researcher. Discovery: `~/.cache/prime-rl/dashboard/daemon.json` holds
the live `url` (the port can differ from 7788 when it was taken). `--no-dashboard`
opts a run out.
+8 -8
View File
@@ -2,19 +2,19 @@
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
directories (metrics, resolved configs, rollout traces, component logs) at
http://localhost:7788. Needs the `dashboard` extra.
http://localhost:7788. Needs the `dashboard` extra. Every instance also serves
the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
(one dashboard per host per user); `--isolated` serves only the given dirs and
skips the registry. See `skills/dashboard/SKILL.md` for discovery and
kill/restart commands.
To run it without resolving the project's GPU dependencies (a cluster head
node, a laptop against a mounted outputs dir), use the standalone script form —
it resolves only a handful of small wheels into an isolated script environment:
GPU dependencies live behind the `gpu` extra, so this works anywhere — a
cluster head node, a laptop against a mounted outputs dir:
```bash
uv run --script src/prime_rl/dashboard/server.py [output_dir ...]
uv sync --extra dashboard && uv run dashboard [output_dir ...]
```
The script needs its `static/` sibling directory, so copy this whole folder
when moving it to another machine.
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
The integration suite covers it end to end (`tests/integration/dashboard_smoke.py`
runs after every integration test).
+102 -22
View File
@@ -1,15 +1,3 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "fastapi>=0.115",
# "uvicorn>=0.30",
# "orjson>=3.10",
# "tokenizers>=0.20",
# "huggingface_hub>=0.25",
# "rich>=14.0",
# ]
# ///
"""Local dashboard for prime-rl runs: logs, metrics, and rollout traces.
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
@@ -24,6 +12,7 @@ Multiple output directories can be tracked at once.
import argparse
import hashlib
import os
import sys
import threading
import time
@@ -32,16 +21,16 @@ from pathlib import Path
import orjson
from prime_rl.entrypoints.dashboard import DAEMON_FILE, DIRS_FILE, STATE_DIR, registry_lock
from prime_rl.utils.process import set_proc_title
try:
import uvicorn
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
except ModuleNotFoundError as error: # the dashboard ships as an extra
raise SystemExit(
"the dashboard needs the 'dashboard' extra - install with `uv sync --extra dashboard` "
"(or run the standalone script: `uv run --script src/prime_rl/dashboard/server.py`)"
) from error
raise SystemExit("the dashboard needs the 'dashboard' extra - install with `uv sync --extra dashboard`") from error
STATIC_DIR = Path(__file__).parent / "static"
MASTER_LOGS = {"trainer.log", "orchestrator.log", "inference.log", "evals.log"}
@@ -89,10 +78,61 @@ def is_run_dir(path: Path) -> bool:
return any((path / marker).exists() for marker in ("configs", "logs", "metrics.jsonl", "rollouts"))
_dirs_file_state: tuple[float, list[Path]] = (0.0, [])
def registered_dirs() -> list[Path]:
"""Output dirs registered in dirs.json (by launchers and by every dashboard's
own CLI dirs), re-read when the file changes so a run in a new output dir
appears on the one live dashboard without a restart."""
global _dirs_file_state
try:
mtime = DIRS_FILE.stat().st_mtime
except OSError:
return []
if mtime != _dirs_file_state[0]:
try:
dirs = [Path(d) for d in orjson.loads(DIRS_FILE.read_bytes())]
except (OSError, ValueError):
dirs = []
_dirs_file_state = (mtime, dirs)
return _dirs_file_state[1]
def register_dirs(dirs: list[Path]) -> None:
"""Add dirs to the shared registry (idempotent, atomic)."""
with registry_lock():
try:
known = list(orjson.loads(DIRS_FILE.read_bytes()))
except (OSError, ValueError):
known = []
fresh = [str(d.resolve()) for d in dirs if str(d.resolve()) not in known]
if not fresh:
return
tmp = DIRS_FILE.with_suffix(".tmp")
tmp.write_bytes(orjson.dumps(known + fresh))
tmp.replace(DIRS_FILE)
isolated = False
def tracked_dirs() -> list[Path]:
"""One dashboard per user serves everything: the dirs it was started with
plus every dir any launcher (or other dashboard start) has registered.
--isolated opts out: only the CLI dirs, no registry."""
dirs = list(output_dirs)
if isolated:
return dirs
known = {d.resolve() for d in dirs}
dirs.extend(d for d in registered_dirs() if d.resolve() not in known and d.is_dir())
return dirs
def scan_runs() -> dict[str, Path]:
global _run_registry
by_name: dict[str, list[Path]] = {}
for base in output_dirs:
for base in tracked_dirs():
if not base.is_dir():
continue
for run_dir in sorted(base.iterdir()):
@@ -615,7 +655,7 @@ def episode_summaries(path: Path) -> list[dict]:
# Parsing a step's traces file for the table can mean reading gigabytes; the
# result is persisted outside the run dir (the dashboard never writes there),
# so a revisit — or a dashboard restart — skips the parse entirely.
SIDECAR_DIR = Path.home() / ".cache" / "prime-rl" / "dashboard"
SIDECAR_DIR = STATE_DIR
SIDECAR_WRITE_INTERVAL_S = 20.0
_sidecar_written: dict[Path, tuple[float, int]] = {} # path -> (last write time, count)
@@ -797,7 +837,7 @@ def render_status(url: str):
text.append(" · ", style="dim")
text.append(url + "\n", style="underline #B6FF3C")
runs = scan_runs()
for base in output_dirs:
for base in tracked_dirs():
text.append(f"\n {base.resolve()}/\n", style="dim")
names = sorted(name for name, run_dir in runs.items() if run_dir.parent == base) or ["(no runs yet)"]
for i, name in enumerate(names):
@@ -821,23 +861,61 @@ def free_port(host: str, start: int) -> int:
raise SystemExit(f"no free port in [{start}, {start + 100})")
def claim_daemon(url: str) -> bool:
"""Record this process as THE dashboard daemon (pid + actual url, port
spillover included) so launchers can find it instead of starting another."""
with registry_lock():
existing = read_json(DAEMON_FILE)
if existing.get("pid") and existing.get("pid") != os.getpid():
try:
os.kill(existing["pid"], 0)
print(f"another dashboard daemon is already running at {existing.get('url')}", file=sys.stderr)
return False
except OSError:
pass # stale file from a dead daemon
tmp = DAEMON_FILE.with_suffix(".tmp")
tmp.write_bytes(orjson.dumps({"pid": os.getpid(), "url": url, "started": time.time()}))
tmp.replace(DAEMON_FILE)
return True
def release_daemon() -> None:
with registry_lock():
if read_json(DAEMON_FILE).get("pid") == os.getpid():
DAEMON_FILE.unlink(missing_ok=True)
def main() -> None:
global output_dirs
global output_dirs, isolated
parser = argparse.ArgumentParser(description="prime-rl run dashboard")
parser.add_argument("output_dirs", nargs="*", default=[Path("outputs")], type=Path, metavar="output_dir")
parser.add_argument("--port", type=int, default=7788)
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument(
"--isolated",
action="store_true",
help="serve only the given dirs: don't join the per-user registry, don't remember "
"these dirs, and don't claim discovery (launchers will ignore this instance)",
)
args = parser.parse_args()
isolated = args.isolated
output_dirs = [d for d in args.output_dirs if d.is_dir()]
for missing in set(args.output_dirs) - set(output_dirs):
print(f"warning: output dir {missing} does not exist", file=sys.stderr)
if not output_dirs:
raise SystemExit("no existing output dir given")
if not isolated:
# this instance's dirs join the per-user registry, and it serves the union -
# one dashboard per host per user covers every run
register_dirs(output_dirs)
if not tracked_dirs():
raise SystemExit("no existing output dir given" + ("" if isolated else " (and none registered)"))
set_proc_title("Dashboard")
port = free_port(args.host, args.port)
if port != args.port:
print(f"port {args.port} is taken - serving on {port}", file=sys.stderr)
args.port = port
url = f"http://localhost:{args.port}"
# first non-isolated instance owns discovery; extras and --isolated still serve
claimed = False if isolated else claim_daemon(url)
live = None
stop = threading.Event()
if sys.stdout.isatty():
@@ -866,6 +944,8 @@ def main() -> None:
stop.set()
if live is not None:
live.stop()
if claimed:
release_daemon()
if __name__ == "__main__":
+170 -96
View File
@@ -12,7 +12,7 @@ const api = async (path) => {
/* accent-first line palette, then the prime-context chart palette */
const PALETTE = ["#b6ff3c", "#b7a6fa", "#78f8a5", "#fcdaa4", "#4a9eff", "#ff6b4a", "#bcbcbc"];
const SINGLE_SERIES = "#b6ff3c";
const POLL_MS = 3000;
const POLL_MS = 5000;
const prefs = JSON.parse(localStorage.getItem("prl-dash") || "{}");
const state = {
@@ -49,7 +49,7 @@ const state = {
};
function fmtNum(v) {
if (v == null || Number.isNaN(v)) return "–";
if (v == null || Number.isNaN(v)) return "n/a";
if (v === 0) return "0";
const abs = Math.abs(v);
if (abs >= 1e6 || abs < 1e-3) return v.toExponential(2);
@@ -57,10 +57,10 @@ function fmtNum(v) {
if (Number.isInteger(v)) return String(v);
return v.toPrecision(4).replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, "");
}
const fmtReward = (v) => (v == null || Number.isNaN(v) ? "–" : v.toFixed(3));
const fmtReward = (v) => (v == null || Number.isNaN(v) ? "n/a" : v.toFixed(3));
/* compact human counts that never overflow: 1.1K, 2.2M, 3.3B */
function fmtCompact(n) {
if (n == null || Number.isNaN(n)) return "–";
if (n == null || Number.isNaN(n)) return "n/a";
const abs = Math.abs(n);
if (abs >= 1e9) return `${+(n / 1e9).toFixed(abs >= 1e10 ? 0 : 1)}B`;
if (abs >= 1e6) return `${+(n / 1e6).toFixed(abs >= 1e7 ? 0 : 1)}M`;
@@ -68,7 +68,7 @@ function fmtCompact(n) {
return String(n);
}
function fmtCost(v) {
if (v == null || Number.isNaN(v)) return "–";
if (v == null || Number.isNaN(v)) return "n/a";
return `$${v >= 1 ? v.toFixed(2) : v.toFixed(4)}`;
}
@@ -120,7 +120,7 @@ async function loadRuns() {
syncDressedSelects();
const fresh = state.runs.find((r) => r.name === current);
if (fresh && state.meta) {
Object.assign(state.meta, { updated: fresh.updated, started: fresh.started, last_step: fresh.last_step });
Object.assign(state.meta, fresh);
renderOverview();
}
}
@@ -167,9 +167,8 @@ function applyRunTypeControls() {
$("#trace-subset").hidden = isEval;
$("#tm-step-prev").hidden = isEval;
$("#tm-step-next").hidden = isEval;
$("#tm-kind").hidden = isEval || state.meta?.type === "sft";
$("#tm-subset").hidden = isEval;
$(".tm-filterhead").hidden = isEval;
$("#tm-kind-row").hidden = isEval || state.meta?.type === "sft";
$("#tm-subset-row").hidden = isEval;
}
async function selectRun(name) {
@@ -181,14 +180,18 @@ async function selectRun(name) {
state.meta = state.runs.find((r) => r.name === name) ?? (await api(`/api/runs/${encodeURIComponent(name)}`));
state.metrics = {
...state.metrics,
loaded: false, offset: 0, byKey: new Map(), charts: [], renderedKeys: -1,
loaded: false, fetching: false, offset: 0, byKey: new Map(), charts: [], renderedKeys: -1,
timeKeys: new Set(), timeZero: null, maxStep: null,
evalEtag: null, evalCount: 0, evalCost: null,
};
if (state.meta?.type === "eval") fetchEvalSeries(); // populates the overview cost early
state.config = { loaded: false, files: [], file: null, fmt: state.config.fmt, cache: new Map() };
state.logs = { ...state.logs, loaded: false, attempt: "latest", files: [], paneFile: {}, maximized: null, buffers: new Map() };
state.traces = { ...state.traces, loaded: false, steps: [], step: null, env: "", episodes: [], etag: null, kind: "train", subset: state.traces.preferred };
state.traces = {
...state.traces,
loaded: false, fetching: false, steps: [], step: null, env: "", episodes: [], etag: null,
kind: "train", subset: state.traces.preferred,
};
applyRunTypeControls();
renderOverview();
renderCompareMenu();
@@ -197,7 +200,7 @@ async function selectRun(name) {
}
function fmtDuration(secs) {
if (secs == null || !isFinite(secs) || secs < 0) return "–";
if (secs == null || !isFinite(secs) || secs < 0) return "n/a";
const d = Math.floor(secs / 86400);
const h = Math.floor((secs % 86400) / 3600);
const m = Math.floor((secs % 3600) / 60);
@@ -211,7 +214,7 @@ function fmtDuration(secs) {
}
function fmtAgo(ts) {
if (!ts) return "–";
if (!ts) return "n/a";
const secs = Date.now() / 1000 - ts;
if (secs < 90) return "just now";
if (secs < 3600) return `${Math.round(secs / 60)} min ago`;
@@ -233,8 +236,8 @@ function runStatus(step) {
/* unbounded env lists: show the first two, fold the rest into "+N" (full list
in the tooltip) */
function envListField(envs) {
if (!envs?.length) return `<span class="val">–</span>`;
function envListField(envs, empty = "n/a") {
if (!envs?.length) return `<span class="val">${empty}</span>`;
const display = envs.length > 2 ? `${envs.slice(0, 2).join(", ")} +${envs.length - 2}` : envs.join(", ");
return `<span class="val" title="${esc(envs.join(", "))}">${esc(display)}</span>`;
}
@@ -250,7 +253,7 @@ function renderOverview() {
const step = currentStep();
const status = runStatus(step);
const durationEnd = status === "running" ? Date.now() / 1000 : meta.updated;
const duration = meta.started && durationEnd ? fmtDuration(durationEnd - meta.started) : "–";
const duration = meta.started && durationEnd ? fmtDuration(durationEnd - meta.started) : "n/a";
const field = ([label, value]) => `<div class="ov-field"><span class="lbl">${label}</span>${value}</div>`;
// rollout dirs can run one step past max_steps (the final ship drains late
// arrivals), so the headline caps at the configured horizon
@@ -258,18 +261,19 @@ function renderOverview() {
const stepText = `${shownStep != null ? shownStep.toLocaleString() : "–"}/${meta.max_steps ? meta.max_steps.toLocaleString() : "∞"}`;
const left = [
["status", `<span class="badge st-${status}">${status}</span>`],
["type", `<span class="val">${esc((meta.type ?? "–").toUpperCase())}</span>`],
["type", `<span class="val">${esc((meta.type ?? "n/a").toUpperCase())}</span>`],
meta.type === "eval"
? ["episodes", `<span class="val">${step != null ? step.toLocaleString() : "–"}</span>`]
? ["episodes", `<span class="val">${step != null ? step.toLocaleString() : "n/a"}</span>`]
: ["step", `<span class="val">${stepText}</span>`],
["model", `<span class="val" title="${esc(meta.model ?? "")}">${esc(meta.model ?? "–")}</span>`],
["model", `<span class="val" title="${esc(meta.model ?? "")}">${esc(meta.model ?? "n/a")}</span>`],
...(meta.type === "eval"
? [["env", `<span class="val" title="${esc(meta.env ?? "")}">${esc(meta.env ?? "–")}</span>`]]
? [["env", `<span class="val" title="${esc(meta.env ?? "")}">${esc(meta.env ?? "n/a")}</span>`]]
: [
meta.type === "sft"
? ["dataset", `<span class="val" title="${esc(meta.dataset ?? "")}">${esc(meta.dataset ?? "–")}</span>`]
? ["dataset", `<span class="val" title="${esc(meta.dataset ?? "")}">${esc(meta.dataset ?? "n/a")}</span>`]
: ["train envs", envListField(meta.train_envs)],
["eval envs", envListField(meta.eval_envs)],
// an empty eval env list is a known "none", not missing data
["eval envs", envListField(meta.eval_envs, "–")],
]),
];
const right = [
@@ -297,10 +301,16 @@ 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" && !state.metrics.loaded) await initMetrics();
if (tab === "metrics") {
if (!state.metrics.loaded) await initMetrics();
else if (state.live) await fetchMetrics();
}
if (tab === "config" && !state.config.loaded) await initConfig();
if (tab === "logs" && !state.logs.loaded) await initLogs();
if (tab === "traces" && !state.traces.loaded) await initTraces();
if (tab === "traces") {
if (!state.traces.loaded) await initTraces();
else if (state.live) await refreshTraces();
}
}
/* ---------------------------------------------------------------- metrics */
@@ -384,6 +394,7 @@ async function fetchMetrics() {
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,
@@ -400,7 +411,9 @@ async function fetchMetrics() {
if (m.byKey.size !== m.renderedKeys) renderMetricsBody();
else updateCharts(compared ? null : touched); // compares may touch any panel
}
if (data.offset >= (data.size ?? data.offset)) break;
// 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)}%`;
}
@@ -464,7 +477,7 @@ function renderEvalCards(body) {
);
}
const fmtVal = (key, v) => {
if (v == null) return "–";
if (v == null) return "n/a";
if (key === "cost") return fmtCost(v);
if (key.startsWith("timing/")) return fmtDuration(v);
if (key.endsWith("tokens")) return fmtCompact(Math.round(v));
@@ -1107,7 +1120,7 @@ function renderMetricsBody() {
if (state.meta?.type === "eval") return renderEvalCards(body);
activeFilter = makeFilter(state.metrics.search.trim());
if (!state.meta?.has_metrics && !m.byKey.size) {
body.innerHTML = emptyState("no metrics", "this run has no metrics.jsonl yet");
body.innerHTML = emptyState("no metrics yet");
$("#metrics-status").textContent = "";
return;
}
@@ -1121,7 +1134,7 @@ function renderMetricsBody() {
}
if (!grid.children.length) {
// a configured eval env stays visible before its first eval fires
if (section.configured && !activeFilter) grid.innerHTML = `<div class="chart-empty">no eval data yet</div>`;
if (section.configured && !activeFilter) grid.innerHTML = `<div class="chart-empty">no data yet</div>`;
else div.remove();
} else applyPaneOrder(grid);
}
@@ -1726,28 +1739,27 @@ async function initLogs() {
async function loadRollouts() {
const traces = state.traces;
const previousTarget = latestPreferredStep(traces.steps, traces.kind, traces.preferred);
const wasFollowing = traces.step == null || traces.step === previousTarget?.step;
const data = await api(`/api/runs/${encodeURIComponent(state.run)}/rollouts`);
traces.steps = data.steps;
if (traces.step == null && data.steps.length) {
// default to the newest step that already shipped the preferred subset —
// the newest step is usually in-flight with only "all" (no advantages yet)
const preferred = traces.preferred;
const newestFirst = [...data.steps].reverse();
const shipped =
newestFirst.find((s) => s.available[`${traces.kind}/${preferred}`]) ??
newestFirst.find((s) => Object.keys(s.available).some((k) => k.endsWith(`/${preferred}`)));
traces.step = (shipped ?? data.steps[data.steps.length - 1]).step;
adjustKindSubset();
} else if (traces.step != null) {
// the preferred subset may have shipped since the last poll (a live step's
// effective file lands late) — re-adjust and reload when it changes
const before = `${traces.kind}/${traces.subset}`;
adjustKindSubset();
if (`${traces.kind}/${traces.subset}` !== before) await loadEpisodes();
}
const target = latestPreferredStep(data.steps, traces.kind, traces.preferred);
// Follow new work while the user is on the latest preferred step. Keep a
// manually selected historical step stable, especially while its modal is open.
if (target && wasFollowing && $("#trace-modal").hidden) traces.step = target.step;
adjustKindSubset();
renderStepControl();
}
function latestPreferredStep(steps, kind, preferred) {
const newestFirst = [...steps].reverse();
return (
newestFirst.find((s) => s.available[`${kind}/${preferred}`]) ??
newestFirst.find((s) => Object.keys(s.available).some((key) => key.endsWith(`/${preferred}`))) ??
newestFirst[0]
);
}
function stepInfo(step) {
return state.traces.steps.find((s) => s.step === step);
}
@@ -1793,6 +1805,7 @@ function renderStepControl() {
` title="${title}${hasEval ? " · eval" : ""}"></span>`
);
}
if (!cells.length) cells.push(`<span class="sb-cell placeholder"></span>`);
const signature = cells.join("");
if (signature === traces.stepControlSignature) return;
traces.stepControlSignature = signature;
@@ -1803,7 +1816,7 @@ function renderStepControl() {
const hasEval = info && (info.available["eval/all"] || info.available["eval/effective"]);
$("#step-label").innerHTML =
traces.step == null
? ""
? `<span class="muted">no steps yet</span>`
: `step ${traces.step}${steps.length > 1 ? `<span class="muted">/${steps[steps.length - 1].step}</span>` : ""}` +
(hasEval ? ' <span class="eval-dot" title="eval rollouts"></span>' : "");
}
@@ -1817,19 +1830,18 @@ function selectStepByIndex(index) {
loadEpisodes();
}
// the table chrome stays in place; the message renders as a spanning row so
// arriving traces cause no layout shift
function showTraceEmpty(title, detail) {
$("#episode-table-wrap").hidden = true;
const el = $("#trace-empty");
el.hidden = false;
el.innerHTML = emptyState(title, detail);
$("#episode-table tbody").innerHTML = `<tr class="empty"><td colspan="10">${emptyState(title, detail)}</td></tr>`;
}
async function loadEpisodes() {
const traces = state.traces;
updateTraceFilterBtn();
syncTraceFilterControls();
if (traces.step == null) {
$("#trace-status").textContent = "";
showTraceEmpty("no traces", "this run has no saved traces yet");
showTraceEmpty("no traces yet");
return;
}
const qs = new URLSearchParams({ sort: traces.sort, order: traces.order, errors_only: traces.errorsOnly });
@@ -1851,13 +1863,12 @@ async function loadEpisodes() {
traces.etag = data.etag;
traces.etagKey = etagKey;
traces.episodes = data.episodes;
$("#trace-empty").hidden = true;
$("#episode-table-wrap").hidden = false;
const envSel = $("#trace-env");
const currentEnv = traces.env;
envSel.innerHTML =
`<option value="">all envs</option>` +
data.envs.map((e) => `<option value="${esc(e)}" ${e === currentEnv ? "selected" : ""}>${esc(e)}</option>`).join("");
for (const sel of ["#trace-env", "#tm-env"])
$(sel).innerHTML =
`<option value="">all envs</option>` +
data.envs.map((e) => `<option value="${esc(e)}" ${e === currentEnv ? "selected" : ""}>${esc(e)}</option>`).join("");
syncDressedSelects();
if (!data.total) {
$("#trace-status").textContent = "";
showTraceEmpty("no episodes", "nothing matches the current filters");
@@ -1914,9 +1925,20 @@ function renderEpisodeRows(reset = false) {
async function initTraces() {
state.traces.loaded = true;
await loadRollouts();
adjustKindSubset();
await loadEpisodes();
await refreshTraces();
}
async function refreshTraces() {
const traces = state.traces;
if (traces.fetching) return;
traces.fetching = true;
try {
await loadRollouts();
if (state.traces !== traces) return;
await loadEpisodes();
} finally {
traces.fetching = false;
}
}
/* ----------------------------------------------------------- episode view */
@@ -1946,7 +1968,7 @@ function filteredRollouts() {
function tmItemHtml(e) {
return (
`<div class="tm-item ${e.line === currentLine ? "active" : ""}" data-line="${e.line}">` +
`<div class="tm-item ${e.line === currentLine ? "active" : ""}${e.num_errors || !e.ok ? " err" : ""}" data-line="${e.line}">` +
`<span class="tm-num">#${e.line}</span><span class="tm-env muted" title="${esc(e.env ?? "")}">${esc(e.env ?? "")}</span>` +
`<span class="tm-reward ${rewardClass(e.reward)}">${fmtReward(e.reward)}</span></div>`
);
@@ -2185,11 +2207,40 @@ function reasoningBlock(content) {
let entriesObserver = null;
function renderMessages(trace, branches) {
function episodeErrors(ep, trace) {
return [...(ep.errors || []), ...(trace?.errors || [])];
}
function errorBannersHtml(errors) {
if (!errors.length) return "";
return (
`<div class="trace-errors">` +
errors
.map((error) => {
const record = error && typeof error === "object" ? error : { message: String(error) };
const type = record.type ?? "Error";
const message = record.message ?? "No error message";
const traceback = Array.isArray(record.traceback) ? record.traceback.join("") : record.traceback;
return (
`<section class="trace-error-banner">` +
`<div class="trace-error-message"><span class="trace-error-type">${esc(type)}</span> ${esc(message)}</div>` +
(traceback
? `<details class="trace-error-tb"><summary><span>traceback</span><span class="entry-chev">›</span></summary><pre>${esc(traceback)}</pre></details>`
: "") +
`</section>`
);
})
.join("") +
`</div>`
);
}
function renderMessages(ep, trace, branches) {
const container = $("#tm-messages");
entriesObserver?.disconnect();
const errorsHtml = errorBannersHtml(episodeErrors(ep, trace));
if (!trace) {
container.innerHTML = emptyState("no traces", "this episode carries no trace data");
container.innerHTML = emptyState("no traces", "this episode carries no trace data") + errorsHtml;
return;
}
const signal = $("#token-signal").value;
@@ -2235,7 +2286,8 @@ function renderMessages(trace, branches) {
let rendered = Math.min(path.length, CHUNK);
container.innerHTML =
path.slice(0, rendered).map(entryHtml).join("") +
(rendered < path.length ? `<div id="tm-more" class="chart-empty">scroll for ${path.length - rendered} more entries</div>` : "");
(rendered < path.length ? `<div id="tm-more" class="chart-empty">scroll for ${path.length - rendered} more entries</div>` : "") +
errorsHtml;
if (rendered < path.length) {
const sentinel = container.querySelector("#tm-more");
entriesObserver = new IntersectionObserver((hits) => {
@@ -2361,15 +2413,9 @@ function renderMeta(ep, trace, branches) {
parts.push(metaRow("episode ID", ep.id, true));
if (trace?.id) parts.push(metaRow("trace ID", trace.id, true));
if (ep.group?.id) parts.push(metaRow("group ID", ep.group.id, true));
if (ep.task?.key) parts.push(metaRow("task ID", ep.task.key, true));
if (trace?.agent?.runtime?.id) parts.push(metaRow("runtime ID", trace.agent.runtime.id, true));
const errors = [...(ep.errors || []), ...(trace?.errors || [])];
if (errors.length)
parts.push(
`<details class="meta-fold" open><summary>errors (${errors.length})</summary>` +
`<pre class="json">${esc(JSON.stringify(errors, null, 2))}</pre></details>`
);
$("#tm-meta").innerHTML = parts.join("");
}
@@ -2404,14 +2450,17 @@ function renderEpisode() {
: "";
$("#tm-tabs-row").hidden = traceTabs.hidden && branchTabs.hidden;
renderRolloutList();
renderMessages(trace, branches);
renderMessages(ep, trace, branches);
renderMeta(ep, trace, branches);
}
/* ---------------------------------------------------------------- wiring */
$("#run-select").addEventListener("change", (e) => selectRun(e.target.value));
$("#live-toggle").addEventListener("change", (e) => (state.live = e.target.checked));
$("#live-toggle").addEventListener("change", async (e) => {
state.live = e.target.checked;
if (state.live) await pollDashboard();
});
$("#compare-menu").addEventListener("change", (e) => {
const box = e.target.closest("[data-compare]");
if (box) toggleCompare(box.dataset.compare, box.checked);
@@ -2480,9 +2529,16 @@ function dressSelect(select) {
dressedSelects.add(select);
syncDressedSelects();
}
function updateTraceFilterBtn() {
/* the table and the trace viewer carry the same filter dropdown over one
shared state — a change in either view shows up in both */
function syncTraceFilterControls() {
const t = state.traces;
$("#trace-filter-btn").classList.toggle("active", !!(t.env || t.errorsOnly || t.sort !== "line"));
for (const sel of ["#trace-env", "#tm-env"]) $(sel).value = t.env;
for (const sel of ["#trace-sort", "#tm-sort"]) $(sel).value = `${t.sort}:${t.order}`;
for (const sel of ["#trace-errors", "#tm-errors"]) $(sel).checked = t.errorsOnly;
for (const sel of ["#trace-filter-btn", "#tm-filter-btn"])
$(sel).classList.toggle("active", !!(t.env || t.errorsOnly || t.sort !== "line"));
syncDressedSelects();
}
document.querySelectorAll("#tabs button").forEach((b) => b.addEventListener("click", () => activateTab(b.dataset.tab)));
@@ -2717,6 +2773,14 @@ async function setTraceSubset(subset, inModal = false) {
if (inModal) await reopenFirstEpisode();
}
/* filter changes keep the open viewer in sync: hold the current episode when
it survives the filter, land on the first one otherwise */
async function refreshModalList() {
if ($("#trace-modal").hidden) return;
if (filteredRollouts().some((e) => e.line === currentLine)) renderRolloutList();
else await reopenFirstEpisode();
}
/* after a filter change inside the viewer, land on the first episode of the
new subset (line numbers don't correspond across files) */
async function reopenFirstEpisode() {
@@ -2744,13 +2808,26 @@ for (const [sel, inModal] of [["#trace-subset", false], ["#tm-subset", true]])
setTraceSubset(b.dataset.subset, inModal);
})
);
$("#trace-env").addEventListener("change", (e) => { state.traces.env = e.target.value; loadEpisodes(); });
$("#trace-errors").addEventListener("change", (e) => { state.traces.errorsOnly = e.target.checked; loadEpisodes(); savePrefs(); });
$("#trace-sort").addEventListener("change", (e) => {
[state.traces.sort, state.traces.order] = e.target.value.split(":");
loadEpisodes();
savePrefs();
});
for (const sel of ["#trace-env", "#tm-env"])
$(sel).addEventListener("change", async (e) => {
state.traces.env = e.target.value;
await loadEpisodes();
await refreshModalList();
});
for (const sel of ["#trace-errors", "#tm-errors"])
$(sel).addEventListener("change", async (e) => {
state.traces.errorsOnly = e.target.checked;
await loadEpisodes();
savePrefs();
await refreshModalList();
});
for (const sel of ["#trace-sort", "#tm-sort"])
$(sel).addEventListener("change", async (e) => {
[state.traces.sort, state.traces.order] = e.target.value.split(":");
await loadEpisodes();
savePrefs();
await refreshModalList();
});
$("#episode-table").addEventListener("click", (e) => {
const row = e.target.closest("tr[data-line]");
if (row) openEpisode(+row.dataset.line);
@@ -2817,8 +2894,6 @@ $("#tm-list").addEventListener("click", (e) => {
const item = e.target.closest("[data-line]");
if (item) openEpisode(+item.dataset.line);
});
$("#tm-prev").addEventListener("click", () => stepRollout(-1));
$("#tm-next").addEventListener("click", () => stepRollout(1));
$("#tm-collapse").addEventListener("click", () =>
document.querySelectorAll("#tm-messages details.entry").forEach((d) => (d.open = false))
);
@@ -2885,12 +2960,10 @@ $("#smooth-range").addEventListener("input", (e) => {
savePrefs();
});
let tickCount = 0;
let ticking = false;
setInterval(async () => {
async function pollDashboard() {
if (!state.live || ticking) return;
ticking = true;
tickCount++;
try {
// keep the run list fresh so new runs register without a page refresh;
// it runs concurrently with the tab poll (they're independent requests)
@@ -2905,17 +2978,19 @@ setInterval(async () => {
syncDressedSelects();
if (state.tab === "metrics" && state.metrics.loaded) await fetchMetrics();
else if (state.tab === "logs" && state.logs.loaded) await pollLogs();
else if (state.tab === "traces" && state.traces.loaded) {
await loadRollouts();
if (tickCount % 5 === 0) await loadEpisodes();
}
else if (state.tab === "traces" && state.traces.loaded) await refreshTraces();
await runsRefresh;
} catch (err) {
console.warn("poll failed", err);
} finally {
ticking = false;
}
}, POLL_MS);
}
setInterval(pollDashboard, POLL_MS);
document.addEventListener("visibilitychange", () => {
if (!document.hidden) pollDashboard();
});
(async function init() {
$("#smooth-range").value = state.metrics.smooth;
@@ -2926,10 +3001,9 @@ setInterval(async () => {
$("#log-search").value = prefs.logSearch ?? "";
$("#config-search").value = prefs.configSearch ?? "";
$("#token-signal").value = prefs.tokenSignal ?? "";
for (const sel of ["#run-select", "#trace-env", "#trace-sort", "#attempt-select", "#token-signal"])
for (const sel of ["#run-select", "#trace-env", "#trace-sort", "#tm-env", "#tm-sort", "#attempt-select", "#token-signal"])
dressSelect($(sel));
$("#trace-sort").value = `${state.traces.sort}:${state.traces.order}`;
$("#trace-errors").checked = state.traces.errorsOnly;
syncTraceFilterControls();
setActive("#metrics-mode", "mode", state.metrics.mode);
setActive("#all-layout", "layout", state.metrics.allLayout);
$("#all-layout").hidden = state.metrics.mode !== "all";
+35 -15
View File
@@ -71,16 +71,6 @@
<span id="step-label" class="t-label"></span>
</div>
<div class="controls">
<div class="seg" id="trace-kind">
<button data-kind="train" class="active">Train</button>
<button data-kind="eval">Eval</button>
</div>
<div class="seg" id="trace-subset">
<button data-subset="all">All</button>
<button data-subset="effective" class="active">Effective</button>
</div>
<span id="trace-status" class="muted"></span>
<div class="spacer"></div>
<div id="trace-filter-wrap" class="dd-wrap">
<button id="trace-filter-btn" class="btn dd-btn" title="filter &amp; sort">
<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>
@@ -102,8 +92,16 @@
<label class="toggle"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<div class="seg" id="trace-kind">
<button data-kind="train" class="active">Train</button>
<button data-kind="eval">Eval</button>
</div>
<div class="seg" id="trace-subset">
<button data-subset="all">All</button>
<button data-subset="effective" class="active">Effective</button>
</div>
<span id="trace-status" class="muted"></span>
</div>
<div id="trace-empty" hidden></div>
<div id="episode-table-wrap">
<table id="episode-table">
<thead><tr>
@@ -147,11 +145,36 @@
<span id="tm-step-label"></span>
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
</div>
<div class="tm-head tm-filterhead">
<div class="tm-head tm-ctlrow">
<div id="tm-filter-wrap" class="dd-wrap">
<button id="tm-filter-btn" class="btn dd-btn" title="filter &amp; sort">
<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 id="tm-filter-menu" class="dd-menu" hidden>
<label class="t-label">env</label>
<select id="tm-env"><option value="">all envs</option></select>
<label class="t-label">sort</label>
<select id="tm-sort">
<option value="line:asc">order: arrival</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="advantage:desc">advantage ↓</option>
<option value="advantage:asc">advantage ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
<option value="group:asc">group</option>
</select>
<label class="toggle"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
</div>
</div>
</div>
<div class="tm-head tm-ctlrow" id="tm-kind-row">
<div class="seg" id="tm-kind">
<button data-kind="train">Train</button>
<button data-kind="eval">Eval</button>
</div>
</div>
<div class="tm-head tm-ctlrow" id="tm-subset-row">
<div class="seg" id="tm-subset">
<button data-subset="all">All</button>
<button data-subset="effective">Effective</button>
@@ -160,9 +183,6 @@
<div class="tm-head">
<span class="t-label">episodes</span>
<span id="tm-count" class="badge"></span>
<div class="spacer"></div>
<button id="tm-prev" class="btn tm-nav" title="previous episode">↑</button>
<button id="tm-next" class="btn tm-nav" title="next episode">↓</button>
</div>
<div id="tm-list"></div>
</aside>
+42 -3
View File
@@ -570,6 +570,8 @@ mark.hit {
#step-blocks { flex: 1; display: flex; gap: 2px; height: 16px; min-width: 0; margin-bottom: 4px; }
.sb-cell { position: relative; flex: 1; min-width: 0; background: var(--grey-2); border: 1px solid var(--hairline); cursor: pointer; }
.sb-cell:hover { border-color: var(--grey-6); }
.sb-cell.placeholder { cursor: default; }
.sb-cell.placeholder:hover { border-color: var(--hairline); }
.sb-cell.on { background: var(--accent); border-color: var(--accent); }
/* eval steps carry a small dot under the block (same mark as the step label) */
.sb-cell.eval::after {
@@ -613,6 +615,9 @@ mark.hit {
#episode-table td { padding: 5px 10px; border-bottom: 1px solid var(--hairline-faint); white-space: nowrap; }
#episode-table tbody tr { cursor: pointer; }
#episode-table tbody tr:hover { background: var(--grey-2); }
#episode-table tr.empty { cursor: default; }
#episode-table tr.empty:hover { background: none; }
#episode-table tr.empty td { border-bottom: 0; }
.r-pos { color: var(--positive); }
.r-neg { color: var(--negative); }
.r-zero { color: var(--grey-4); }
@@ -659,13 +664,14 @@ mark.hit {
.tm-item .tm-reward { flex-shrink: 0; }
.tm-item:hover { background: var(--grey-2); }
.tm-item.active { background: var(--grey-2); border-color: var(--grey-3); color: var(--grey-6); }
.tm-item.err { background: rgba(255, 69, 57, 0.08); border-color: var(--negative); }
.tm-item.err:hover, .tm-item.err.active { background: rgba(255, 69, 57, 0.16); }
.tm-item .tm-reward { margin-left: auto; }
.tm-nav { padding: 0 8px; height: 24px; }
.tm-stephead { justify-content: space-between; background: var(--grey-2); min-height: 40px; }
#step-label, #tm-step-label { white-space: nowrap; }
#tm-step-label { color: var(--grey-6); }
.tm-filterhead { gap: 8px; }
.tm-filterhead .seg button { height: 22px; padding: 0 9px; font-size: 10px; }
.tm-ctlrow { min-height: 0; padding: 8px 14px; }
#tm-step-label {
font-size: 11px;
letter-spacing: var(--track-caps);
@@ -678,10 +684,43 @@ mark.hit {
#tm-step-label .muted { text-transform: none; letter-spacing: var(--track-mono); }
#tm-main { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
#tm-messages { flex: 1; overflow-y: auto; padding: 14px 16px; }
#tm-messages { display: flex; flex: 1; flex-direction: column; overflow-y: auto; padding: 14px 16px; }
#tm-messages > * { flex-shrink: 0; }
#tm-right { border-left: 1px solid var(--hairline); overflow-y: auto; min-height: 0; }
#tm-meta { padding: 12px 14px; }
.trace-errors { margin-top: auto; padding-top: 12px; }
.trace-error-banner {
border: 1px solid var(--negative);
background: rgba(255, 69, 57, 0.08);
color: var(--grey-6);
}
.trace-error-banner + .trace-error-banner { margin-top: 8px; }
.trace-error-message { padding: 10px 12px; font-size: 12px; white-space: pre-wrap; word-break: break-word; }
.trace-error-type { font-weight: 500; color: var(--negative); }
.trace-error-tb > summary {
display: flex;
align-items: center;
gap: 10px;
padding: 6px 12px;
border-top: 1px solid rgba(255, 69, 57, 0.2);
color: var(--grey-4);
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.trace-error-tb > summary:hover { color: var(--grey-6); }
.trace-error-tb[open] .entry-chev { transform: rotate(90deg); }
.trace-error-tb > pre {
margin: 0;
padding: 10px 12px;
border-top: 1px solid rgba(255, 69, 57, 0.2);
color: var(--grey-5);
font: 400 11px/1.5 var(--font-mono);
white-space: pre-wrap;
word-break: break-word;
}
/* numbered collapsible message entries */
details.entry { border: 1px solid var(--hairline); margin-bottom: 8px; }
details.entry > summary {
+127
View File
@@ -0,0 +1,127 @@
"""Launcher-side dashboard auto-start.
Every launcher registers its output dir in a shared registry and makes sure one
dashboard is running: every dashboard instance serves its own dirs plus the
registry (re-read live), so each new run shows up on one URL - one dashboard
per host per user. If a live daemon already exists, its URL is reused instead
of starting another. Discovery goes through
``~/.cache/prime-rl/dashboard/daemon.json`` (pid + actual url), which survives
port spillover. The daemon also carries the process title ``PRL::Dashboard``.
Kept free of ``dashboard``-extra imports on purpose: the launcher must work
without the extra (then it registers the dir and points at the missing extra
instead of spawning). ``main`` is the ``dashboard`` console script, delegating
to the actual server.
"""
import fcntl
import importlib.util
import json
import os
import shutil
import subprocess
import sys
import time
import urllib.request
from contextlib import contextmanager
from pathlib import Path
from prime_rl.utils.pathing import CACHE_DIR
STATE_DIR = CACHE_DIR / "dashboard"
DAEMON_FILE = STATE_DIR / "daemon.json"
DIRS_FILE = STATE_DIR / "dirs.json"
DAEMON_LOG = STATE_DIR / "daemon.log"
SPAWN_TIMEOUT_S = 10.0
@contextmanager
def registry_lock():
"""Serialize read-modify-write cycles on the shared registry files: concurrent
launchers (or dashboard starts) must not drop each other's entries."""
STATE_DIR.mkdir(parents=True, exist_ok=True)
with open(STATE_DIR / ".lock", "w") as lock_file:
fcntl.flock(lock_file, fcntl.LOCK_EX)
yield
def register_output_dir(output_dir: Path) -> None:
"""Add the dir to the daemon's registry (idempotent, atomic)."""
with registry_lock():
try:
dirs = json.loads(DIRS_FILE.read_text())
except (OSError, ValueError):
dirs = []
entry = str(output_dir.resolve())
if entry in dirs:
return
dirs.append(entry)
tmp = DIRS_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(dirs))
tmp.replace(DIRS_FILE)
def find_daemon(timeout: float = 1.0) -> dict | None:
"""The live daemon's record ({pid, url, ...}), or None."""
try:
info = json.loads(DAEMON_FILE.read_text())
os.kill(info["pid"], 0)
except (OSError, ValueError, KeyError, TypeError):
return None
try:
with urllib.request.urlopen(f"{info['url']}/api/runs", timeout=timeout):
return info
except OSError:
return None
def ensure_dashboard(output_dir: Path, logger) -> str | None:
"""Register the run's output dir and make sure one dashboard daemon serves it.
Returns the dashboard URL (log it with ``log_dashboard_url``), or None when no
daemon could be found or started (missing extra, non-interactive session, or
startup failure).
"""
# The dir may not exist yet on a first run: create it up front, because the
# daemon only serves registered dirs that exist (and refuses to start with none).
output_dir.mkdir(parents=True, exist_ok=True)
register_output_dir(output_dir)
daemon = find_daemon()
if daemon is not None:
return daemon["url"]
if not sys.stdout.isatty():
logger.warning("Non-interactive session - not auto-starting a dashboard (the output dir stays registered)")
return None
# The console script exists even without the extra, so check the actual imports.
if importlib.util.find_spec("fastapi") is None or importlib.util.find_spec("uvicorn") is None:
logger.warning("Dashboard extra not installed - install with `uv sync --extra dashboard`")
return None
binary = shutil.which("dashboard")
if binary is None:
logger.warning("Dashboard entry point not found - install with `uv sync --extra dashboard`")
return None
with open(DAEMON_LOG, "ab") as log_file:
process = subprocess.Popen([binary], stdout=log_file, stderr=log_file, start_new_session=True)
deadline = time.monotonic() + SPAWN_TIMEOUT_S
while time.monotonic() < deadline:
daemon = find_daemon()
if daemon is not None:
return daemon["url"]
if process.poll() is not None:
break
time.sleep(0.25)
logger.warning(f"Dashboard daemon did not come up - see {DAEMON_LOG}")
return None
def log_dashboard_url(logger, url: str | None) -> None:
"""Banner pointing at the dashboard - meant as the launcher's last startup log."""
if url is None:
return
logger.opt(raw=True, colors=True).info(f"\n <b>Dashboard</b> · <green><u>{url}</u></green>\n\n")
def main() -> None:
from prime_rl.dashboard.server import main as server_main
server_main()
+8 -8
View File
@@ -14,6 +14,7 @@ from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
from prime_rl.entrypoints.inference import vllm_overrides_fragment
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import get_logger, setup_logger
@@ -129,6 +130,8 @@ def rl_local(config: RLConfig):
logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs from deployment config
gpu_offset = 0
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
@@ -367,14 +370,8 @@ def rl_local(config: RLConfig):
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Monitor all processes for failures
logger.success("Startup complete. Showing orchestrator logs...")
tail_process = Popen(
f"tail -F '{log_dir / 'orchestrator.log'}'",
shell=True,
)
processes.append(tail_process)
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Check for errors from monitor threads
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
@@ -604,6 +601,8 @@ def rl_slurm(config: RLConfig):
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
@@ -611,6 +610,7 @@ def rl_slurm(config: RLConfig):
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
log_dashboard_url(logger, dashboard_url)
def rl(config: RLConfig):
+8 -6
View File
@@ -12,6 +12,7 @@ from prime_rl.configs.evals import EvalsConfig, OnlineConfig
from prime_rl.configs.orchestrator import EvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.shared import LogConfig
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
from prime_rl.utils.config import cli, dump_resolved_config, find_package_resource
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import (
@@ -322,6 +323,8 @@ def sft_slurm(config: SFTConfig):
logger.success(f"Dry run complete. To submit manually:\n\n{submit}{note}\n\n{log_message}")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
submitted_job_ids: list[str] = []
for path in script_paths:
# --parsable prints ``<job_id>[;<cluster>]`` — the human-readable format varies
@@ -346,6 +349,7 @@ def sft_slurm(config: SFTConfig):
logger.success(f"Submitted batch job {job_id}")
logger.success(log_message)
log_dashboard_url(logger, dashboard_url)
def sft_local(config: SFTConfig):
@@ -368,6 +372,8 @@ def sft_local(config: SFTConfig):
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
log_dir = create_attempt_log_dir(config.run_dir)
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
@@ -506,12 +512,8 @@ def sft_local(config: SFTConfig):
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(
f"tail -F '{log_dir / 'trainer.log'}' | sed -u 's/^\\[[a-zA-Z]*[0-9]*\\]://'",
shell=True,
)
processes.append(tail_process)
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Wait for the trainer (and the evals process, which drains its final evals after
# the trainer's last checkpoint) while surfacing any process failure.
+21 -8
View File
@@ -40,12 +40,13 @@ from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.metrics import dispatch_failure_metrics
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.types import EvalBatch, Policy
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.config import dump_resolved_config
@@ -375,10 +376,15 @@ class Evals:
# An env with no examples emits no episodes, so its epoch can never finalize.
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
while pending:
episode = await self.dispatcher.out_q.get()
step = eval_work(episode).step
await monitors.log([episode], step, "eval", "all")
eval_batch = self.eval_sink.add(episode)
item = await self.dispatcher.out_q.get()
if isinstance(item, GroupCancellation):
raise RuntimeError("Eval dispatcher emitted a group cancellation")
if isinstance(item, DispatchFailure):
eval_batch = self.eval_sink.fail(item)
else:
step = eval_work(item).step
await monitors.log([item], step, "eval", "all")
eval_batch = self.eval_sink.add(item)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
pending.discard(eval_batch.env_name)
@@ -386,17 +392,24 @@ class Evals:
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
if not batch.episodes:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no episodes returned, skipping log")
if not batch.episodes and not batch.failures:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
return
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
if batch.episodes.effective:
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
episodes = batch.episodes
effective = episodes.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", episodes), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
total_attempts = len(episodes) + len(batch.failures)
metrics |= dispatch_failure_metrics(
batch.failures,
prefix=f"eval/{batch.env_name}/all",
total_attempts=total_attempts,
)
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
+1
View File
@@ -33,6 +33,7 @@ OVERVIEW_NAME = "overview"
# agent. Only the score metric differs — train scores with "reward/mean", eval with "avg@k" (its k
# dynamic, so also a regex) — and each section builder prepends its own.
COMMON_METRICS = [
"all/dispatch_failure/mean",
"effective/num_total_tokens/mean",
"effective/num_turns/mean",
"effective/num_branches/mean",
+41 -37
View File
@@ -6,10 +6,10 @@
burst-capped so a raised (or drained) cap never lands all its prefills at
once.
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
- Emit-everything invariant: every dispatched episode eventually reaches
``out_q`` exactly once — as a native episode, or covered by its group's
single ``GroupCancellation`` message when the group is dropped. Failures
remain episode errors; sinks decide drop / partial-train policy.
- Every dispatched attempt reaches ``out_q`` exactly once: as the native
episode returned by the environment, as a ``DispatchFailure`` when no
episode was produced, or under the group's ``GroupCancellation`` when the
orchestrator abandons it.
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
schedule next. Transitions are level-triggered (driven by the eval
source's emptiness), so in-flight episodes of the opposite kind drain
@@ -44,6 +44,7 @@ from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.train_source import TrainSource
from prime_rl.orchestrator.types import (
CancelReason,
DispatchFailure,
DispatchResult,
GroupCancellation,
GroupState,
@@ -121,15 +122,6 @@ class DispatcherMetrics:
return keys
def _trace_task(task: vf.Task) -> vf.TraceTask:
return vf.TraceTask(
type=type(task).__name__,
data=task.data,
key=task.key,
hash=task.hash,
)
def _validate_episode_task(episode: vf.WireEpisode, task: vf.Task) -> None:
expected = (task.key, task.hash)
actual = (episode.task.key, episode.task.hash)
@@ -202,7 +194,8 @@ class Dispatcher:
# Bounded so the dispatcher backpressures on a slow sink (unbounded
# when no hard ceiling is configured — the dynamic cap still bounds
# in-flight work). One entry per episode — the sinks count episodes,
# never loose traces — plus one ``GroupCancellation`` per dropped group.
# never loose traces — plus terminal dispatcher events for attempts
# that produced no episode.
maxsize = max(8, max_inflight_ceiling) if max_inflight_ceiling is not None else 0
self.out_q: asyncio.Queue[DispatchResult] = asyncio.Queue(maxsize=maxsize)
@@ -353,7 +346,7 @@ class Dispatcher:
timeout=0.5, # wake periodically to re-check fill (mode flips)
)
for task in done:
await self.handle_completed_episode(task)
await self.handle_completed_request(task)
except asyncio.CancelledError:
return
@@ -558,34 +551,40 @@ class Dispatcher:
if refund_admission:
self.admissions_in_window = max(0, self.admissions_in_window - 1)
async def handle_completed_episode(self, task: asyncio.Task) -> None:
"""Emit every dispatched episode exactly once to ``out_q``."""
async def handle_completed_request(self, task: asyncio.Task) -> None:
"""Emit the terminal result of one dispatched environment request."""
meta = self.inflight.pop(task, None)
if meta is None:
return # already handled by drop_group / cancel_inflight_episodes
self.release(refund_admission=True)
group = self.groups.get(meta.group_id)
is_synth_exception = False
try:
episode: vf.WireEpisode = task.result()
except asyncio.CancelledError:
return
except Exception as exc:
get_logger().warning(f"Episode task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
episode = vf.WireEpisode(
env=vf.EnvInfo(id=meta.env_name),
task=_trace_task(meta.task),
ok=False,
errors=[
vf.Error(
get_logger().warning(f"Environment request failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
policy_version = self.complete_group_member(meta, group)
await self.out_q.put(
DispatchFailure(
kind=meta.kind,
env_name=meta.env_name,
group_id=str(meta.group_id),
step=meta.step,
policy_version=policy_version,
task_type=type(meta.task).__name__,
task_key=meta.task.key,
task_hash=meta.task.hash,
error=vf.Error(
type=type(exc).__name__,
message=str(exc),
traceback="".join(traceback.format_exception(exc)),
)
],
),
)
)
is_synth_exception = True
return
if not episode.traces and episode.ok:
episode.ok = False
@@ -601,19 +600,29 @@ class Dispatcher:
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
if trace.has_error:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if not is_synth_exception and trace.last_error is not None:
if trace.last_error is not None:
get_logger().warning(
f"Trace failed in group {meta.group_id} ({meta.env_name}) — "
f"{trace.last_error.type}: {trace.last_error.message}"
)
if not episode.ok and not episode.traces:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if not is_synth_exception and self.on_episode_complete is not None and meta.started_at > 0:
if self.on_episode_complete is not None and meta.started_at > 0:
self.on_episode_complete(
meta.env_name, meta.kind, episode.num_total_tokens, time.monotonic() - meta.started_at
)
await self.emit_episode(meta, group, episode)
def complete_group_member(self, meta: InflightEpisode, group: GroupState | None) -> int:
"""Advance group accounting and return the attempt's pinned policy version."""
policy_version = meta.policy_version
if group is not None:
policy_version = group.policy_version_at_start
group.emitted += 1
if group.emitted >= group.target_episodes:
self.groups.pop(meta.group_id, None)
return policy_version
async def emit_episode(
self,
meta: InflightEpisode,
@@ -622,12 +631,7 @@ class Dispatcher:
) -> None:
"""Stamp one completed episode with its dispatch provenance and emit it."""
_validate_episode_task(episode, meta.task)
policy_version = meta.policy_version
if group is not None:
policy_version = group.policy_version_at_start
group.emitted += 1
if group.emitted >= group.target_episodes:
self.groups.pop(meta.group_id, None)
policy_version = self.complete_group_member(meta, group)
episode.env.name = meta.env_name
episode.group = vf.GroupInfo(id=str(meta.group_id))
@@ -654,7 +658,7 @@ class Dispatcher:
# Sync claim phase: pop matching tasks from ``self.inflight`` and
# release their permits in one non-yielding sweep. After this loop
# the dropped tasks are no longer reachable from ``self.inflight``,
# so ``handle_completed_episode``'s existing None-guard makes the
# so ``handle_completed_request``'s existing None-guard makes the
# subsequent async emit phase race-free.
claimed: list[tuple[asyncio.Task, InflightEpisode]] = []
for task, meta in list(self.inflight.items()):
+55 -17
View File
@@ -8,7 +8,7 @@ import verifiers.v1 as vf
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.metrics import EvalEpisodes
from prime_rl.orchestrator.types import EvalBatch
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, eval_work
from prime_rl.utils.logger import get_logger
@@ -19,7 +19,9 @@ class EvalSink:
def __init__(self, *, eval_envs: EvalEnvs) -> None:
self.eval_envs = eval_envs
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
self.pending_group_failures: dict[str, list[DispatchFailure]] = defaultdict(list)
self.pending_batches: dict[tuple[str, int], list[vf.Episode]] = defaultdict(list)
self.pending_batch_failures: dict[tuple[str, int], list[DispatchFailure]] = defaultdict(list)
def add(self, episode: vf.Episode) -> EvalBatch | None:
env_name = episode_env_name(episode)
@@ -28,12 +30,32 @@ class EvalSink:
bkey = (env_name, eval_step)
group = self.pending_groups[group_id]
group.append(episode)
if len(group) >= self.group_size_for(env_name):
if self._group_size(group_id) >= self.group_size_for(env_name):
self.process_group(group_id)
if len(self.pending_batches[bkey]) >= self.batch_size_for(env_name):
if self._batch_size(bkey) >= self.batch_size_for(env_name):
return self.process_batch(bkey)
return None
def fail(self, failure: DispatchFailure) -> EvalBatch | None:
"""Count a request failure toward its group and eval epoch without
manufacturing a verifier episode."""
if failure.kind != "eval":
raise ValueError(f"EvalSink cannot process a {failure.kind} dispatch failure")
group_id = failure.group_id
bkey = (failure.env_name, failure.step)
self.pending_group_failures[group_id].append(failure)
if self._group_size(group_id) >= self.group_size_for(failure.env_name):
self.process_group(group_id)
if self._batch_size(bkey) >= self.batch_size_for(failure.env_name):
return self.process_batch(bkey)
return None
def _group_size(self, group_id: str) -> int:
return len(self.pending_groups[group_id]) + len(self.pending_group_failures[group_id])
def _batch_size(self, key: tuple[str, int]) -> int:
return len(self.pending_batches[key]) + len(self.pending_batch_failures[key])
def group_size_for(self, env_name: str) -> int:
return self.eval_envs.get(env_name).config.group_size
@@ -42,15 +64,23 @@ class EvalSink:
return len(env.examples) * env.config.group_size
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
batch_counts = {key: len(runs) for key, runs in self.pending_batches.items()}
keys = set(self.pending_batches) | set(self.pending_batch_failures)
batch_counts = {key: self._batch_size(key) for key in keys}
buffered: dict[tuple[str, int], int] = {}
for group in self.pending_groups.values():
if not group:
group_ids = set(self.pending_groups) | set(self.pending_group_failures)
for group_id in group_ids:
group = self.pending_groups[group_id]
failures = self.pending_group_failures[group_id]
if not group and not failures:
continue
episode = group[0]
eval_step = eval_work(episode).step
key = (episode_env_name(episode), eval_step)
buffered[key] = buffered.get(key, 0) + len(group)
if group:
env_name = episode_env_name(group[0])
eval_step = eval_work(group[0]).step
else:
env_name = failures[0].env_name
eval_step = failures[0].step
key = (env_name, eval_step)
buffered[key] = buffered.get(key, 0) + len(group) + len(failures)
return [
(
env_name,
@@ -64,12 +94,18 @@ class EvalSink:
def process_group(self, group_id: str) -> None:
group = self.pending_groups.pop(group_id, [])
if not group:
failures = self.pending_group_failures.pop(group_id, [])
if not group and not failures:
return
episode = group[0]
env_name = episode_env_name(episode)
eval_step = eval_work(episode).step
self.pending_batches[(env_name, eval_step)].extend(group)
if group:
env_name = episode_env_name(group[0])
eval_step = eval_work(group[0]).step
else:
env_name = failures[0].env_name
eval_step = failures[0].step
key = (env_name, eval_step)
self.pending_batches[key].extend(group)
self.pending_batch_failures[key].extend(failures)
traces = [trace for episode in group for trace in episode.traces]
survivors = [trace for trace in traces if not trace.has_error]
@@ -79,15 +115,17 @@ class EvalSink:
task_idx = next((trace.task.data.idx for trace in traces), None)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} "
f"eval_step={eval_step} | episodes={len(group)} traces={len(traces)} "
f"(errored={num_errored}) | reward={avg_reward:.4f}"
f"eval_step={eval_step} | episodes={len(group)} dispatch_failures={len(failures)} "
f"traces={len(traces)} (errored={num_errored + len(failures)}) | reward={avg_reward:.4f}"
)
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
env_name, step = key
episodes = self.pending_batches.pop(key, [])
failures = self.pending_batch_failures.pop(key, [])
return EvalBatch(
env_name=env_name,
step=step,
episodes=EvalEpisodes(episodes, group_size=self.group_size_for(env_name)),
failures=failures,
)
+15 -2
View File
@@ -9,11 +9,25 @@ from typing import Any, Literal
import verifiers.v1 as vf
from prime_rl.orchestrator.algo.routing import is_trainable, scalar_advantage
from prime_rl.orchestrator.types import DispatchFailure
from prime_rl.orchestrator.utils import compute_pass_metrics, episode_env_name, episode_group_id
Subset = Literal["all", "effective"]
def dispatch_failure_metrics(failures: list[DispatchFailure], *, prefix: str, total_attempts: int) -> dict[str, float]:
"""Metrics for requests that failed outside the verifier episode boundary."""
if total_attempts == 0:
return {}
out = {f"{prefix}/dispatch_failure/mean": len(failures) / total_attempts}
error_types = [failure.error.type for failure in failures]
out |= {
f"{prefix}/dispatch_failure/{error_type}": float(error_types.count(error_type))
for error_type in sorted(set(error_types))
}
return out
@dataclass(frozen=True)
class TraceRecord:
"""A trace joined with its episode and training selection state.
@@ -317,8 +331,7 @@ class EpisodeMetrics:
def cancelled(self) -> Stat:
"""Per-episode pipeline-cancellation rate — same denominator as
``has_error``. Read from the id-set, not the trace records, so
trace-less episodes (synthetic error episodes inside a voided group)
still count."""
trace-less episodes still count."""
return Stat([float(episode.id in self.cancelled_ids) for episode in self.episodes])
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
+63 -13
View File
@@ -45,7 +45,7 @@ from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.metrics import TrainEpisodes
from prime_rl.orchestrator.metrics import TrainEpisodes, dispatch_failure_metrics
from prime_rl.orchestrator.packing import BatchPacker
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
@@ -55,6 +55,7 @@ from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.train_sink import TrainSink
from prime_rl.orchestrator.train_source import TrainSource
from prime_rl.orchestrator.types import (
DispatchFailure,
EvalBatch,
GroupCancellation,
Policy,
@@ -524,9 +525,13 @@ class Orchestrator:
await self.wait_for_version(self.final_version, reason="before shutdown")
async def main_loop(self) -> None:
"""Consume completed episodes and ``GroupCancellation`` events from the
dispatcher and route them to the train / eval sink. The sinks return a
finalized batch (or ``None``); we just dispatch on the result."""
"""Consume dispatcher results and route them to the train / eval sink.
Native episodes are persisted as verifier artifacts. Dispatch failures
and group cancellations remain internal accounting events.
The sinks return a finalized batch (or ``None``); we just dispatch on
the result."""
while not self.stopped.is_set():
self._raise_if_component_stopped()
if self.draining and self.dispatcher.is_idle:
@@ -546,6 +551,17 @@ class Orchestrator:
if train_batch is not None and not self.draining and not self.stopped.is_set():
await self.finalize_train_batch(train_batch)
continue
if isinstance(item, DispatchFailure):
if item.kind == "eval":
assert self.eval_sink is not None
eval_batch = self.eval_sink.fail(item)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
else:
train_batch = await self.train_sink.fail(item)
if train_batch is not None and not self.draining and not self.stopped.is_set():
await self.finalize_train_batch(train_batch)
continue
episode = item
# Every completed rollout — errored, rejected, or never batched — lands in the
@@ -669,6 +685,20 @@ class Orchestrator:
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
for env_name, env_pool in pool.by_env().items():
metrics |= env_pool.metrics.to_wandb(prefix=f"train/{env_name}", subset=subset)
total_attempts = len(batch.episodes) + len(batch.failures)
metrics |= dispatch_failure_metrics(batch.failures, prefix="train/agg/all", total_attempts=total_attempts)
failures_by_env: dict[str, list[DispatchFailure]] = {}
for failure in batch.failures:
failures_by_env.setdefault(failure.env_name, []).append(failure)
episodes_by_env = batch.episodes.by_env()
for env_name in set(episodes_by_env) | set(failures_by_env):
env_failures = failures_by_env.get(env_name, [])
env_attempts = len(episodes_by_env.get(env_name, TrainEpisodes())) + len(env_failures)
metrics |= dispatch_failure_metrics(
env_failures,
prefix=f"train/{env_name}/all",
total_attempts=env_attempts,
)
# Progress / timing / env-share accounting (assembled here, not in the metrics
# objects). ``num_tokens`` is over the full arrival window; the input/output breakdown is over
@@ -678,7 +708,9 @@ class Orchestrator:
num_input = sum(record.trace.num_input_tokens for record in effective.records)
num_output = sum(record.trace.num_output_tokens for record in effective.records)
num_rollouts = batch.episodes.num_traces
num_unique_examples = len({episode_group_id(episode) for episode in batch.episodes})
group_ids = {episode_group_id(episode) for episode in batch.episodes}
group_ids.update(failure.group_id for failure in batch.failures)
num_unique_examples = len(group_ids)
metrics |= {
"progress/tokens": num_tokens,
"progress/input_tokens": num_input,
@@ -839,10 +871,10 @@ class Orchestrator:
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
Every quality metric (Reward, Trainable, Turns, Branches, Max Off-Policy, Truncation) is
computed over exactly the traces shipped to the trainer this step (``batch.cohort``).
``Error``, ``Cancelled``, and ``Ratio`` are rates over the step's full arrival window —
``Error``, ``Dispatch Failure``, ``Cancelled``, and ``Ratio`` describe the step's full arrival window —
over the shipped set they are 0/0/share-of-shipped by construction, so the window is the
only scope where they carry signal (and they stay disjoint: a cancellation is a pipeline
decision, not a rollout failure)."""
decision, an episode error came from the environment, and a dispatch failure produced no episode)."""
episodes = batch.episodes
effective = batch.cohort.effective
eff = effective.metrics
@@ -851,13 +883,16 @@ class Orchestrator:
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
trainable_rate = (n_trainable / n_effective) if n_effective else 0.0
max_off_policy_steps = max((episode_staleness(episode, step)[0] for episode in effective), default=0)
num_attempts = len(episodes) + len(batch.failures)
dispatch_failure_rate = len(batch.failures) / num_attempts if num_attempts else 0.0
head = (
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
f"Trainable {n_trainable}/{n_effective} ({trainable_rate:.1%}) | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max_off_policy_steps} | "
f"Error {episodes.metrics.has_error.mean():.1%} | Cancelled {episodes.metrics.cancelled.mean():.1%} | "
f"Error {episodes.metrics.has_error.mean():.1%} | Dispatch Failure {dispatch_failure_rate:.1%} | "
f"Cancelled {episodes.metrics.cancelled.mean():.1%} | "
f"Truncation {eff.is_truncated.mean():.1%}"
)
if len(self.train_envs) <= 1:
@@ -866,7 +901,10 @@ class Orchestrator:
window_by_env = episodes.by_env()
shipped_by_env = effective.by_env()
env_names = sorted(set(window_by_env) | set(shipped_by_env))
failures_by_env: dict[str, list[DispatchFailure]] = {}
for failure in batch.failures:
failures_by_env.setdefault(failure.env_name, []).append(failure)
env_names = sorted(set(window_by_env) | set(shipped_by_env) | set(failures_by_env))
name_width = max((len(name) for name in env_names), default=0)
lines = [head]
for env_name in env_names:
@@ -874,29 +912,35 @@ class Orchestrator:
env_eff_pool = shipped_by_env.get(env_name, TrainEpisodes())
env_eff = env_eff_pool.metrics
ratio = (pool.num_traces / n_generated) if n_generated else 0.0
env_failures = failures_by_env.get(env_name, [])
env_attempts = len(pool) + len(env_failures)
env_failure_rate = len(env_failures) / env_attempts if env_attempts else 0.0
lines.append(
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_eff.reward.mean():.4f} | "
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max((episode_staleness(episode, step)[0] for episode in env_eff_pool), default=0)} | "
f"Error {pool.metrics.has_error.mean():.1%} | Cancelled {pool.metrics.cancelled.mean():.1%} | "
f"Error {pool.metrics.has_error.mean():.1%} | Dispatch Failure {env_failure_rate:.1%} | "
f"Cancelled {pool.metrics.cancelled.mean():.1%} | "
f"Truncation {env_eff.is_truncated.mean():.1%}"
)
get_logger().success("\n\t\t ".join(lines))
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors."""
if not batch.episodes:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no episodes returned, skipping log")
if not batch.episodes and not batch.failures:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
return
# The non-errored subset is logged on epoch completion (multiple eval envs share the
# step's trace file — each epoch appends its cohort once, and every record carries
# ``env_name``); the full returned cohort already streamed into ``all`` on arrival.
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
if batch.episodes.effective:
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
policy_spans = [eval_work(episode).policy for episode in batch.episodes]
if any(span is None for span in policy_spans):
raise ValueError(f"Eval {batch.env_name} step {batch.step} is missing policy provenance")
policy_versions = {span.start for span in policy_spans if span is not None}
policy_versions.update(failure.policy_version for failure in batch.failures)
policy_version = min(policy_versions)
if len(policy_versions) > 1:
get_logger().warning(
@@ -909,6 +953,12 @@ class Orchestrator:
metrics: dict[str, float] = {}
for subset, pool in (("all", episodes), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
total_attempts = len(episodes) + len(batch.failures)
metrics |= dispatch_failure_metrics(
batch.failures,
prefix=f"eval/{batch.env_name}/all",
total_attempts=total_attempts,
)
metrics[f"eval/{batch.env_name}/policy_version"] = float(policy_version)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
+38 -14
View File
@@ -1,10 +1,10 @@
"""Training-side episode, group, and batch assembly.
``add()`` takes one completed episode and ``cancel()`` a dropped group's
``GroupCancellation``; both return ``TrainBatch | None``. Before every readiness
check the sink sweeps ``pending_batch`` for traces past ``max_off_policy_steps`` —
this sweep, not the dispatcher's in-flight cancel, is what guarantees nothing
stale ships."""
``add()`` takes one completed episode, ``fail()`` a request that produced no
episode, and ``cancel()`` a dropped group's ``GroupCancellation``. Before every
readiness check the sink sweeps ``pending_batch`` for traces past
``max_off_policy_steps`` — this sweep, not the dispatcher's in-flight cancel,
is what guarantees nothing stale ships."""
from __future__ import annotations
@@ -20,7 +20,7 @@ from prime_rl.orchestrator.algo.routing import stamp_loss_routing
from prime_rl.orchestrator.envs import TrainEnvs
from prime_rl.orchestrator.metrics import TrainEpisodes
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.orchestrator.types import GroupCancellation, Progress, TrainBatch
from prime_rl.orchestrator.types import DispatchFailure, GroupCancellation, Progress, TrainBatch
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, min_fresh_version, train_work
from prime_rl.transports.batch import TrainingSample
from prime_rl.utils.logger import get_logger
@@ -87,7 +87,9 @@ class TrainSink:
self.on_result = on_result
self.pending_episodes = TrainEpisodes()
self.pending_failures: list[DispatchFailure] = []
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
self.pending_group_failures: dict[str, list[DispatchFailure]] = defaultdict(list)
# A dropped group's terminal marker; its ``count`` fills in for the
# episodes the group will never deliver.
self.pending_group_cancellations: dict[str, GroupCancellation] = {}
@@ -113,7 +115,9 @@ class TrainSink:
return self.pending_tokens, self.token_batch_size, "tokens"
def buffered_count(self) -> int:
return sum(len(group) for group in self.pending_groups.values())
episodes = sum(len(group) for group in self.pending_groups.values())
failures = sum(len(group) for group in self.pending_group_failures.values())
return episodes + failures
def pending_batch_by_env(self) -> dict[str, int]:
counts: dict[str, int] = defaultdict(int)
@@ -145,10 +149,22 @@ class TrainSink:
await self.process_group(cancellation.group_id)
return self._maybe_batch()
async def fail(self, failure: DispatchFailure) -> TrainBatch | None:
"""Count a request failure toward its group without presenting it as
an episode to the algorithm or curriculum."""
if failure.kind != "train":
raise ValueError(f"TrainSink cannot process a {failure.kind} dispatch failure")
self.pending_group_failures[failure.group_id].append(failure)
if not self._group_complete(failure.group_id, failure.env_name):
return None
await self.process_group(failure.group_id)
return self._maybe_batch()
def _group_complete(self, group_id: str, env_name: str) -> bool:
cancellation = self.pending_group_cancellations.get(group_id)
cancelled = cancellation.count if cancellation is not None else 0
return len(self.pending_groups[group_id]) + cancelled >= self.group_size_for(env_name)
failed = len(self.pending_group_failures[group_id])
return len(self.pending_groups[group_id]) + failed + cancelled >= self.group_size_for(env_name)
def _maybe_batch(self) -> TrainBatch | None:
"""Sweep stale queued traces, then cut a batch if the survivors still
@@ -209,18 +225,24 @@ class TrainSink:
async def process_group(self, group_id: str) -> None:
group = self.pending_groups.pop(group_id, [])
failures = self.pending_group_failures.pop(group_id, [])
cancellation = self.pending_group_cancellations.pop(group_id, None)
if not group and cancellation is None:
if not group and not failures and cancellation is None:
return
env_name = episode_env_name(group[0]) if group else cancellation.env_name
env_name = (
episode_env_name(group[0]) if group else (failures[0].env_name if failures else cancellation.env_name)
)
env = self.train_envs.get(env_name)
traces = [trace for episode in group for trace in episode.traces]
task_idx = next((trace.task.data.idx for trace in traces), None)
num_errored = sum(trace.has_error for trace in traces) + sum(
not episode.ok for episode in group if not episode.traces
num_errored = (
sum(trace.has_error for trace in traces)
+ sum(not episode.ok for episode in group if not episode.traces)
+ len(failures)
)
n_owed = len(group) + (cancellation.count if cancellation is not None else 0)
n_owed = len(group) + len(failures) + (cancellation.count if cancellation is not None else 0)
self.pending_failures.extend(failures)
# A stale drop voids the whole group: every member shares the dispatch
# version, so the arrived episodes are exactly as stale as the
@@ -367,6 +389,8 @@ class TrainSink:
cohort = TrainEpisodes(cohort_episodes, sampled_trace_ids=shipped_ids)
episodes = self.pending_episodes
failures = self.pending_failures
if samples:
self.pending_episodes = TrainEpisodes()
return TrainBatch(episodes=episodes, cohort=cohort, samples=samples)
self.pending_failures = []
return TrainBatch(episodes=episodes, cohort=cohort, samples=samples, failures=failures)
+24 -4
View File
@@ -52,7 +52,22 @@ class GroupCancellation:
reason: CancelReason
DispatchResult: TypeAlias = vf.WireEpisode | GroupCancellation
@dataclass(frozen=True)
class DispatchFailure:
"""An environment request that failed before producing an episode."""
kind: WorkKind
env_name: str
group_id: str
step: int
policy_version: int
task_type: str
task_key: str
task_hash: str
error: vf.Error
DispatchResult: TypeAlias = vf.WireEpisode | DispatchFailure | GroupCancellation
@dataclass(frozen=True)
@@ -96,21 +111,26 @@ class GroupState:
@dataclass
class TrainBatch:
"""Observation and shipped-cohort reports plus the trainer payload."""
"""Returned episodes, dispatch failures, shipped cohort, and trainer payload."""
episodes: TrainEpisodes
cohort: TrainEpisodes
samples: list[TrainingSample]
failures: list[DispatchFailure]
@dataclass
class EvalBatch:
"""One env's eval epoch. ``episodes`` is the full returned cohort (errored included); its
``.effective`` / ``.metrics`` views drive logging."""
"""One env's eval epoch.
``episodes`` is the full returned cohort (errored included), while
``failures`` accounts for requests that returned no verifier artifact.
"""
env_name: str
step: int
episodes: EvalEpisodes
failures: list[DispatchFailure]
class VersionObserver(Protocol):
+13
View File
@@ -1,6 +1,7 @@
import asyncio
import os
import shutil
import tempfile
import time
from pathlib import Path
@@ -90,6 +91,18 @@ def format_log_message(
return "Logs:\n" + "\n".join(log_lines)
def home_dir() -> Path:
"""Best-effort home directory; fall back to the temp dir so import never fails."""
try:
return Path.home()
except RuntimeError:
return Path(tempfile.gettempdir())
CACHE_DIR = home_dir() / ".cache" / "prime-rl"
"""User-scoped cache root."""
def get_config_dir(output_dir: Path) -> Path:
"""Resolved per-component config dumps (JSON). The launch TOML copy lives one
level up, at `configs/<entrypoint>.toml`."""
+1 -1
View File
@@ -10,7 +10,7 @@ import setproctitle
from prime_rl.utils.logger import get_logger
PRIME_RL_PROC_PREFIX = "PRIME-RL"
PRIME_RL_PROC_PREFIX = "PRL"
# Applied to every launched component (trainer, orchestrator, inference).
Generated
+281 -112
View File
File diff suppressed because it is too large Load Diff