Compare commits

...
Author SHA1 Message Date
07e6bec87a feat: log time/wait_for_policy for dispatch gate stalls (#2938)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: log time/wait_for_policy for dispatch gate stalls

The dispatch gate (`dispatch_allowed`) pauses the orchestrator when it
would run more than TARGET_LAG batches ahead of the trainer's policy
version, but that pause was invisible in metrics — the only signal was
two info log lines. When the trainer is the bottleneck this stall is
exactly what we want to quantify.

Accumulate the wall-clock the gate spends closed across pause/resume
cycles and log it as `time/wait_for_policy` alongside the other
orchestrator `time/*` metrics, resetting each shipped batch.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: drop redundant comment on wait_for_policy state

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat: add time/wait_for_policy to the W&B overview performance section

Show the orchestrator's dispatch-gate wait next to time/wait_for_batch
in the curated overview view.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 12:49:21 -07:00
9fede0ac78 feat: auto-create curated W&B overview view per project (#2933)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: auto-create curated W&B "overview" saved view per project

Creates an idempotent "overview" saved view (train / eval / stability /
performance sections) on the first run into a W&B project, so a new project
gets a usable overview without hand-picking panels from the thousands of
logged metrics.

- New src/prime_rl/utils/monitor/workspace.py builds the view via wandb-workspaces
- WandbMonitor creates it after wandb.init (run's primary process, online only,
  best-effort so a failure never breaks training; skips if it already exists)
- Per-env train/<env> and eval/<env> sections built from the orchestrator's
  resolved env names; single train env collapses to train/<env>, multiple add
  train/agg on top
- inference/* panels use the wall-clock x-axis (they are logged against
  _timestamp); every other panel uses `step`
- Config: WandbConfig.create_overview (default True; --wandb.no-create-overview)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat: add time/wait_for_batch to overview performance section

* feat: always create overview when wandb enabled (drop create_overview config)

* chore: rename overview env-name params to train_env_names/eval_env_names

* chore: make overview metric/layout constants public

* feat: version overview on env-set change; make helpers public, inline x_for

* refactor: fold overview view code into monitor/wandb.py

* docs: note deliberate metric volume + auto-created W&B overview view

* feat: unify train/eval overview metrics (reward vs avg@), all subset only

* chore: drop perf throughput/throughput_per_gpu/peak_memory from overview

* fix: isolate per-view load in overview reuse loop so one bad view doesn't abort

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 12:39:30 -07:00
7 changed files with 218 additions and 0 deletions
+2
View File
@@ -307,6 +307,8 @@ uv run rl @ rl.toml --wandb \
--no-trainer.wandb.log-extras.distributions
```
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, W&B mode **auto-creates an `overview` saved view** on the first run into a project — curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
### Platform Monitoring
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics, samples, and distributions to the platform dashboard. Bare flag uses defaults:
+1
View File
@@ -22,6 +22,7 @@ dependencies = [
"vllm>=0.24.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.4",
"pyzmq>=27.1.0",
+2
View File
@@ -34,6 +34,8 @@ Default cadence: **1 hour** (researcher can override). At each check-in:
**Notes**: anything unusual (errors, restarts, hangs). Omit if nothing notable.
```
In W&B, each project auto-gets an **"overview" saved view** (train / eval / stability / performance sections) on its first run — use it for a quick check instead of the auto-generated default workspace.
### Restarting a run
**Never restart unless the researcher explicitly asked.** Confirm the exact restart command and the conditions that warrant one.
+10
View File
@@ -165,6 +165,8 @@ class Orchestrator:
# Trigger timestamps so eval success logs can report epoch duration
self.eval_triggered_at = {}
self.consecutive_empty_batches = 0
self.gate_closed_at = None
self.wait_for_policy_time = 0.0
self.component_tasks = []
# Optional attributes — ``setup()`` populates them when the relevant
@@ -222,6 +224,8 @@ class Orchestrator:
tokenizer=self.tokenizer,
run_config=config,
keep_full_history=config.bench,
train_env_names=[env.resolved_name for env in config.train.env],
eval_env_names=[env.resolved_name for env in config.eval.env] if config.eval is not None else [],
)
if config.heartbeat is not None:
@@ -555,6 +559,7 @@ class Orchestrator:
"progress/total_tasks": self.progress.total_problems,
"time/step": step_time,
"time/save_ckpt": save_ckpt_time,
"time/wait_for_policy": self.wait_for_policy_time,
"step": step,
}
for env_name, env_pool in batch.rollouts.by_env().items():
@@ -566,6 +571,7 @@ class Orchestrator:
for name, count in self.train_sink.pre_filter_dropped_by_name.items():
metrics[f"pre_filters/all/{name}/rate"] = count / self.train_sink.pre_filter_seen
self.monitor.log(metrics, step=step)
self.wait_for_policy_time = 0.0
self.monitor.log_samples(effective.rollouts, step=step)
self.monitor.log_distributions(
distributions={
@@ -798,10 +804,14 @@ class Orchestrator:
get_logger().info(
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
)
self.gate_closed_at = time.perf_counter()
gate.clear()
else:
if not was_set:
get_logger().info("Resuming dispatcher")
if self.gate_closed_at is not None:
self.wait_for_policy_time += time.perf_counter() - self.gate_closed_at
self.gate_closed_at = None
gate.set()
async def on_version_pending(self, step: int) -> None:
+4
View File
@@ -38,6 +38,8 @@ def setup_monitor(
*,
prime_config: PrimeMonitorConfig | None = None,
keep_full_history: bool = True,
train_env_names: list[str] = [],
eval_env_names: list[str] = [],
# Backward compatibility: support old 'config' keyword argument
config: WandbWithExtrasConfig | None = None,
) -> Monitor:
@@ -65,6 +67,8 @@ def setup_monitor(
tokenizer=tokenizer,
run_config=run_config,
keep_full_history=keep_full_history,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
)
)
+184
View File
@@ -2,15 +2,20 @@ from __future__ import annotations
import json
import os
import re
import sys
import time
from collections.abc import Sequence
from pathlib import Path
from typing import TYPE_CHECKING, Any
import wandb
import wandb_workspaces.reports.v2 as wr
import wandb_workspaces.workspaces as ws
from transformers.tokenization_utils import PreTrainedTokenizer
from wandb.errors import CommError
from wandb.sdk.mailbox.mailbox_handle import ServerResponseError
from wandb_gql import gql
from prime_rl.configs.shared import WandbConfig, WandbWithExtrasConfig
from prime_rl.utils.config import BaseConfig
@@ -48,6 +53,8 @@ class WandbMonitor(Monitor):
tokenizer: PreTrainedTokenizer | None = None,
run_config: BaseConfig | None = None,
keep_full_history: bool = True,
train_env_names: list[str] = [],
eval_env_names: list[str] = [],
):
self.config = config
self.logger = get_logger()
@@ -82,11 +89,13 @@ class WandbMonitor(Monitor):
x_update_finish_state=primary,
)
self.logger.info(f"Using shared W&B mode ({label=}, {primary=})")
is_online = True
else:
run_id = None
primary = False
mode = os.environ.get("WANDB_MODE", "offline" if config.offline else "online")
settings = wandb.Settings(mode=mode)
is_online = mode == "online"
retryable_errors = (CommError, ServerResponseError) if shared_mode else (CommError,)
@@ -129,6 +138,22 @@ class WandbMonitor(Monitor):
wandb.define_metric("*", step_metric="step")
# Provision the curated "overview" saved view once per project (the run's primary process
# in shared mode, else the single master). Best-effort: a workspaces/API failure must never
# take down training.
if is_online and (primary if shared_mode else True):
try:
url = ensure_overview_view(
self.wandb.entity,
self.wandb.project,
train_envs=train_env_names,
eval_envs=eval_env_names,
)
if url:
self.logger.info(f"Created W&B overview view - {url}")
except Exception as e:
self.logger.warning(f"Failed to create W&B overview view - {e}")
# Optionally, initialize sample logging attributes
if config is not None and isinstance(config, WandbWithExtrasConfig) and config.log_extras:
if config.log_extras.samples:
@@ -262,3 +287,162 @@ class WandbMonitor(Monitor):
dir_path.mkdir(parents=True, exist_ok=True)
with open(dir_path / filename, "w") as f:
json.dump(wandb.summary._as_dict(), f)
# --- curated "overview" saved view -------------------------------------------------------------
# prime-rl logs many metrics; the default workspace auto-generates a panel per key, which buries the
# few that matter. These build a named saved view grouping the important metrics into sections, so a
# new project gets a usable overview without hand-picking panels. Panels are untitled — each shows
# its raw metric name.
OVERVIEW_NAME = "overview"
# Per-rollout metrics (under "<scope>/all/") shown for BOTH train and eval. Only the reward metric
# differs — train uses "reward/mean", eval uses "avg@k" — and each section builder prepends its own.
COMMON_METRICS = [
"has_error/mean",
"is_truncated/mean",
"num_total_tokens/mean",
"num_turns/mean",
"num_branches/mean",
]
STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"]
PERFORMANCE_METRICS = [
"perf/mfu",
"time/step",
"time/wait_for_batch",
"time/wait_for_policy",
"inference/agg/throughput",
"inference/agg/running_requests",
"inference/agg/waiting_requests",
"inference/agg/kv_cache_usage_mean",
"inference/agg/prefix_cache_hit_rate",
]
# Dense grid: more, smaller panels per row and enough rows that sections don't paginate.
COLUMNS = 4
ROWS = 6
def line_panels(metrics: Sequence[str], regexes: Sequence[str]) -> list[wr.LinePlot]:
# inference/* is logged against wall time (step_metric="_timestamp") → "WallTime" (== W&B's
# "_timestamp"); everything else on "step" (prime-rl's logged training step, not internal "Step").
# x is set per-panel because LinePlot defaults it to "Step", which overrides the workspace x_axis.
return [wr.LinePlot(x="WallTime" if m.startswith("inference/") else "step", y=[m]) for m in metrics] + [
wr.LinePlot(x="step", metric_regex=r) for r in regexes
]
def section(name: str, metrics: Sequence[str] = (), regexes: Sequence[str] = ()) -> ws.Section:
return ws.Section(
name=name,
is_open=True,
panels=line_panels(metrics, regexes),
layout_settings=ws.SectionLayoutSettings(columns=COLUMNS, rows=ROWS),
)
def train_section(name: str, scope: str) -> ws.Section:
return section(name, metrics=[f"{scope}/all/reward/mean"] + [f"{scope}/all/{m}" for m in COMMON_METRICS])
def eval_section(name: str, env_pattern: str) -> ws.Section:
# Same metrics as train, but eval's reward is "avg@k" (dynamic k → regex). Everything is a regex so
# one section can also serve any env (env_pattern=".*"). Only the "all" subset, like train.
return section(
name,
regexes=[f"eval/{env_pattern}/all/avg@.*"] + [f"eval/{env_pattern}/all/{m}" for m in COMMON_METRICS],
)
def build_sections(train_envs: Sequence[str] = (), eval_envs: Sequence[str] = ()) -> list[ws.Section]:
# With one env the aggregate == that env, so show only its section. With several, put the
# cross-env aggregate on top followed by a section per env.
if len(train_envs) == 1:
sections = [train_section(f"train/{train_envs[0]}", f"train/{train_envs[0]}")]
elif len(train_envs) > 1:
sections = [train_section("train/agg", "train/agg")]
sections += [train_section(f"train/{env}", f"train/{env}") for env in train_envs]
else:
# Env names unknown (e.g. SFT): fall back to the aggregate.
sections = [train_section("train", "train/agg")]
if eval_envs:
sections += [eval_section(f"eval/{env}", re.escape(env)) for env in eval_envs]
else:
# Env names unknown (e.g. SFT): one regex section matching any eval env.
sections.append(eval_section("eval", ".*"))
sections.append(section("stability", metrics=STABILITY_METRICS))
sections.append(section("performance", metrics=PERFORMANCE_METRICS))
return sections
def list_views(entity: str, project: str) -> list[tuple[str, str]]:
"""``(display_name, internal_name)`` for every saved view in the project."""
query = gql(
"""
query Views($entity: String!, $project: String!) {
project(name: $project, entityName: $entity) {
allViews(viewType: "project-view") { edges { node { name displayName } } }
}
}
"""
)
res = wandb.Api().client.execute(query, variable_values={"entity": entity, "project": project})
edges = ((res.get("project") or {}).get("allViews") or {}).get("edges") or []
return [(e["node"]["displayName"], e["node"]["name"]) for e in edges if e.get("node")]
def env_signature(train_envs: Sequence[str], eval_envs: Sequence[str]) -> tuple:
return (tuple(sorted(train_envs)), tuple(sorted(eval_envs)))
def view_env_signature(sections: Sequence[ws.Section]) -> tuple:
"""Reconstruct the ``(train, eval)`` env set a view was built for from its section names."""
train = sorted(s.name[len("train/") :] for s in sections if s.name.startswith("train/") and s.name != "train/agg")
evals = sorted(s.name[len("eval/") :] for s in sections if s.name.startswith("eval/"))
return (tuple(train), tuple(evals))
def next_overview_name(base: str, existing: Sequence[str]) -> str:
if base not in existing:
return base
prefix = f"{base}-v"
versions = [1] + [int(n[len(prefix) :]) for n in existing if n.startswith(prefix) and n[len(prefix) :].isdigit()]
return f"{base}-v{max(versions) + 1}"
def ensure_overview_view(
entity: str,
project: str,
name: str = OVERVIEW_NAME,
train_envs: Sequence[str] = (),
eval_envs: Sequence[str] = (),
) -> str | None:
"""Ensure an overview saved view exists for this run's env set. Reuses an existing overview built
for the same envs; when the env set is new, creates a fresh versioned view (``overview`` →
``overview-v2`` → …). Returns the URL of a newly created view, else None."""
target = env_signature(train_envs, eval_envs)
overviews = [(dn, iname) for dn, iname in list_views(entity, project) if dn == name or dn.startswith(f"{name}-v")]
for _, internal_name in overviews:
slug = internal_name.removeprefix("nw-").removesuffix("-v")
try:
existing = ws.Workspace.from_url(f"https://wandb.ai/{entity}/{project}?nw={slug}")
matches = view_env_signature(existing.sections) == target
except Exception as e:
# A single unreadable view must not abort reuse detection / versioning for the rest.
get_logger().warning(f"Could not inspect overview view {internal_name} - {e}")
continue
if matches:
return None
workspace = ws.Workspace(
entity=entity,
project=project,
name=next_overview_name(name, [dn for dn, _ in overviews]),
sections=build_sections(train_envs, eval_envs),
auto_generate_panels=False,
settings=ws.WorkspaceSettings(x_axis="step"),
)
workspace.save()
return workspace.url
Generated
+15
View File
@@ -4247,6 +4247,7 @@ dependencies = [
{ name = "vllm", version = "0.24.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
{ name = "vllm", version = "0.24.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
{ name = "wandb" },
{ name = "wandb-workspaces" },
]
[package.optional-dependencies]
@@ -4486,6 +4487,7 @@ requires-dist = [
{ name = "vllm", marker = "platform_machine == 'x86_64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "wandb", specifier = ">=0.26.1" },
{ name = "wandb-workspaces", specifier = ">=0.4.3" },
{ name = "wideseek-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/wideseek_v1" },
{ name = "wiki-search", marker = "extra == 'envs'", editable = "deps/verifiers/environments/wiki_search" },
{ name = "wiki-search-v1", marker = "extra == 'envs'", editable = "deps/verifiers/environments/wiki_search_v1" },
@@ -7127,6 +7129,19 @@ wheels = [
]
[[package]]
name = "wandb-workspaces"
version = "0.4.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "pydantic" },
{ name = "wandb" },
]
sdist = { url = "https://files.pythonhosted.org/packages/44/90/749e3af75f1bc2685711176f8f0fe6dae38d5b979e4dc160c30cd4373597/wandb_workspaces-0.4.3.tar.gz", hash = "sha256:2c551bc35cadda14ff0c7c3ac1d7bbbb1c95b8f0dbc662ec2c58f3d3d832f854", size = 234226, upload-time = "2026-06-10T22:27:17.22Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/c0/8f/0c1bc0b48733935031ef8956a1efb1436e3f4e1a3a402eece169a952672b/wandb_workspaces-0.4.3-py3-none-any.whl", hash = "sha256:4536dbc9d57d3aa59318e770b5c526c087f52b6b9488634b1d393163b9f6da2f", size = 109269, upload-time = "2026-06-10T22:27:15.509Z" },
]
[[package]]
name = "wasabi"
version = "1.1.3"