Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3460245d63 | ||
|
|
3758321f08 | ||
|
|
01dc127b1a | ||
|
|
663b53bbc2 | ||
|
|
f96a46f090 | ||
|
|
01994b8168 |
+3
-1
@@ -194,9 +194,11 @@ Launch:
|
||||
|
||||
```bash
|
||||
uv run rl @ base_rl.toml @ my_slurm.toml # submits via sbatch
|
||||
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script + resolved config, exits
|
||||
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes launcher/rl.sbatch + resolved config, exits
|
||||
```
|
||||
|
||||
Every SLURM entrypoint stores its generated scripts and coordination files under `<run_dir>/launcher/`. SLURM stdout and stderr go to `launcher/logs/`. Local launches do not create `launcher/`.
|
||||
|
||||
### `[deployment]` Block
|
||||
|
||||
`[deployment]` is a discriminated union picked by `type` — `single_node` or `multi_node` for RL/SFT, with an extra disaggregated variant for inference. RL multi-node:
|
||||
|
||||
+1
-1
@@ -77,7 +77,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
|
||||
| Knob | What it does |
|
||||
|---|---|
|
||||
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). |
|
||||
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). Defaults to `$PRL_OUTPUT_DIR` if set, else `outputs`. |
|
||||
| `--run.name <name>` | Run name, also the run directory name under `<output_dir>` (override the directory separately via `--run.dir`). Auto-generated as `<envs>--<model>--<short-id>` when unset, so every launch gets a fresh, readable run directory. Set an explicit name for a predictable path — required to resume the run later. |
|
||||
| `--clean` | Wipe the run directory before starting. Useful when re-running a named run during iteration. |
|
||||
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
from pathlib import Path
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import SerializeAsAny, model_validator
|
||||
from pydantic import Field, SerializeAsAny, model_validator
|
||||
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
|
||||
class EnvServerConfig(BaseConfig):
|
||||
@@ -20,8 +20,8 @@ class EnvServerConfig(BaseConfig):
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
|
||||
@@ -6,7 +6,7 @@ from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, LogConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
|
||||
class EvalsEvalConfig(EvalConfig):
|
||||
@@ -86,9 +86,9 @@ class EvalsConfig(BaseConfig):
|
||||
"""Weight transport for online evals. The ``sft`` launcher fills this from its
|
||||
resolved trainer transport. None uses filesystem reloads."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — rollout traces and logs are written as
|
||||
subdirectories. Shared with the trainer for online evals."""
|
||||
subdirectories. Shared with the trainer for online evals. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from pydantic import ConfigDict, Field, model_validator
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
from prime_rl.configs.shared import EnvVars, LogConfig, SlurmConfig
|
||||
from prime_rl.utils.config import find_package_resource
|
||||
from prime_rl.utils.config import default_output_dir, find_package_resource
|
||||
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
|
||||
|
||||
# TODO: Set thinking/ solution budget
|
||||
@@ -471,8 +471,8 @@ class InferenceConfig(BaseConfig):
|
||||
slurm: SlurmConfig | None = None
|
||||
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory for SLURM logs and generated scripts."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory for SLURM logs and generated scripts. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
@@ -22,7 +22,7 @@ from prime_rl.configs.shared import (
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import TokenizerConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
|
||||
class LoRAConfig(BaseConfig):
|
||||
@@ -491,8 +491,8 @@ class OrchestratorConfig(BaseConfig):
|
||||
rollout_transport: TransportConfig = ZMQTransportConfig()
|
||||
"""Transport used to ship rollouts from orchestrator to trainer."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
tasks_per_minute: int | None = Field(None, ge=1)
|
||||
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
|
||||
|
||||
@@ -41,7 +41,7 @@ from prime_rl.configs.trainer import (
|
||||
TokenizerConfig,
|
||||
TrainerConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
|
||||
from prime_rl.utils.validation import (
|
||||
propagate_shared_fields,
|
||||
validate_shared_ckpt_config,
|
||||
@@ -243,8 +243,8 @@ class RLConfig(BaseConfig):
|
||||
run: RunConfig = Field(default_factory=RunConfig)
|
||||
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory that groups related runs. Each run writes its artifacts to ``output_dir / run.name``."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory that groups related runs. Each run writes its artifacts to ``output_dir / run.name``. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
clean: bool = False
|
||||
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
|
||||
|
||||
@@ -33,7 +33,7 @@ from prime_rl.configs.trainer import (
|
||||
WeightBroadcastConfig,
|
||||
validate_scheduler,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
|
||||
|
||||
|
||||
class BaseDataConfig(BaseConfig):
|
||||
@@ -233,8 +233,8 @@ class SFTConfig(BaseConfig):
|
||||
run: RunConfig = Field(default_factory=RunConfig)
|
||||
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
clean: bool = False
|
||||
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
|
||||
|
||||
@@ -16,7 +16,7 @@ from prime_rl.configs.shared import (
|
||||
TransportConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
# -- Shared trainer configs (used by both SFT and RL trainers) --
|
||||
|
||||
@@ -619,8 +619,8 @@ class TrainerConfig(BaseConfig):
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
matmul_precision: Literal["highest", "high", "medium"] = "high"
|
||||
"""Precision for float32 matrix multiplications. ``highest`` is full FP32 (required on ROCm/AMD GPUs to avoid catastrophic precision loss in softmax over large vocabularies). ``high`` enables TF32 on NVIDIA GPUs for a speedup with minor precision tradeoff. See ``torch.set_float32_matmul_precision``."""
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -6,6 +7,11 @@ from pydantic_config import BaseConfig as BaseConfig # noqa: F401
|
||||
from pydantic_config import cli # noqa: F401
|
||||
|
||||
|
||||
def default_output_dir() -> Path:
|
||||
"""Default output directory: ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
return Path(os.environ.get("PRL_OUTPUT_DIR", "outputs"))
|
||||
|
||||
|
||||
def dump_resolved_config(config: BaseModel, exclude: set[str] | None = None) -> dict:
|
||||
"""Dump a resolved config for a machine-written JSON artifact.
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ uv run rl --model @ model.toml --data @ data.toml # nes
|
||||
uv run rl @ base.toml --trainer @ trainer.toml --trainer.lr 1e-3 # mixed
|
||||
```
|
||||
|
||||
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base.
|
||||
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base. `output_dir` has one extra fallback: CLI > config files > `$PRL_OUTPUT_DIR` > `"outputs"`.
|
||||
|
||||
Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max_model_len`).
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ description: Find, start, use, and stop the local run dashboard — the web UI f
|
||||
# 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
|
||||
`outputs/`, or `$PRL_OUTPUT_DIR` if set) 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.
|
||||
|
||||
@@ -54,7 +54,7 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
|
||||
|
||||
### Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`; several dirs can be tracked at
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR` if set; several dirs can be tracked at
|
||||
once) 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 config
|
||||
files, a rollout trace viewer with a per-token advantage/logprob view, and merged
|
||||
@@ -93,6 +93,8 @@ Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`
|
||||
└── envs/{train,eval}/{env_name}.log # one log file per env
|
||||
```
|
||||
|
||||
SLURM batch logs are under `{run_dir}/launcher/logs/*job_*.log`.
|
||||
|
||||
Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough. Drop into per-node or per-rank logs only when debugging. All logs are loguru with `HH:mm:ss LEVEL message`; levels: `DEBUG`, `INFO`, `SUCCESS`, `WARNING`, `ERROR`.
|
||||
|
||||
Scan for problems:
|
||||
|
||||
@@ -7,6 +7,8 @@ description: How to launch prime-rl training runs — the `rl`, `sft`, `inferenc
|
||||
|
||||
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
|
||||
|
||||
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory.
|
||||
|
||||
## Run directories
|
||||
|
||||
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, broadcasts, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
|
||||
@@ -43,6 +45,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
|
||||
- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
|
||||
- SLURM: single- and multi-node
|
||||
- Multi-node SLURM stops after `.trainer.done` for trainer-only fake-data runs. Runs with inference stop after both `.trainer.done` and `.orchestrator.done`.
|
||||
- Environment packages: before launching a config with a non-core verifier env id,
|
||||
verify the package imports under `uv run` (for example
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
|
||||
|
||||
@@ -15,6 +15,14 @@ cluster head node, a laptop against a mounted outputs dir:
|
||||
uv sync --extra dashboard && uv run dashboard [output_dir ...]
|
||||
```
|
||||
|
||||
The trace viewer's **Messages** mode keeps structured `message.content` and
|
||||
`trace.tools` visibly separate. **Rendered** decodes each selected branch's
|
||||
recorded post-renderer `token_ids` as one sequence, retaining special tokens;
|
||||
it never reconstructs a chat template. The recorded IDs remain the source of
|
||||
truth, and the viewer reports when IDs, the renderer model, or its tokenizer
|
||||
are unavailable. Text, advantage, logprob, mask, and content signals apply to
|
||||
both views; Rendered with Text uses the exact full-sequence decode.
|
||||
|
||||
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).
|
||||
|
||||
@@ -22,6 +22,7 @@ from pathlib import Path
|
||||
import orjson
|
||||
|
||||
from prime_rl.entrypoints.dashboard import DAEMON_FILE, DIRS_FILE, STATE_DIR, registry_lock
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
try:
|
||||
@@ -37,7 +38,7 @@ MASTER_LOGS = {"trainer.log", "orchestrator.log", "inference.log", "evals.log"}
|
||||
MAX_LOG_CHUNK = 2_000_000
|
||||
|
||||
app = FastAPI()
|
||||
output_dirs: list[Path] = [Path("outputs")]
|
||||
output_dirs: list[Path] = [default_output_dir()]
|
||||
|
||||
# run id -> run dir, rebuilt on every /api/runs poll; ids are the run name,
|
||||
# qualified with the output dir's basename when two dirs hold the same name
|
||||
@@ -766,6 +767,56 @@ def decode_pieces(model: str, ids: list[int]) -> list[str] | None:
|
||||
return pieces
|
||||
|
||||
|
||||
def trace_node_paths(trace: dict) -> list[list[int]]:
|
||||
"""Root-to-leaf node indexes in the same order as the trace viewer."""
|
||||
nodes = trace.get("nodes") or []
|
||||
has_child = {node.get("parent") for node in nodes if isinstance(node, dict) and isinstance(node.get("parent"), int)}
|
||||
paths = []
|
||||
for leaf in (index for index in range(len(nodes)) if index not in has_child):
|
||||
path = []
|
||||
seen = set()
|
||||
index = leaf
|
||||
while isinstance(index, int) and 0 <= index < len(nodes) and index not in seen:
|
||||
seen.add(index)
|
||||
path.append(index)
|
||||
parent = nodes[index].get("parent") if isinstance(nodes[index], dict) else None
|
||||
index = parent if isinstance(parent, int) else None
|
||||
paths.append(list(reversed(path)))
|
||||
return paths
|
||||
|
||||
|
||||
def rendered_token_text(trace: dict, model: str | None) -> dict:
|
||||
"""Decode recorded post-renderer IDs as full branch sequences."""
|
||||
nodes = trace.get("nodes") or []
|
||||
paths = trace_node_paths(trace)
|
||||
if not any(isinstance(node, dict) and node.get("token_ids") for node in nodes):
|
||||
return {"status": "missing_token_ids", "model": model, "paths": []}
|
||||
if not model:
|
||||
return {"status": "missing_model", "model": None, "paths": []}
|
||||
tokenizer = get_tokenizer(model)
|
||||
if tokenizer is None:
|
||||
return {"status": "tokenizer_unavailable", "model": model, "paths": []}
|
||||
|
||||
def decode_path(path: list[int]) -> dict:
|
||||
ids = [token_id for index in path for token_id in (nodes[index].get("token_ids") or [])]
|
||||
try:
|
||||
text = tokenizer.decode(ids, skip_special_tokens=False)
|
||||
except Exception:
|
||||
text = None
|
||||
return {"nodes": path, "token_count": len(ids), "text": text}
|
||||
|
||||
rendered_paths = [decode_path(path) for path in paths]
|
||||
all_nodes = list(range(len(nodes)))
|
||||
all_nodes_rendered = decode_path(all_nodes)
|
||||
status = "ok" if all(path["text"] is not None for path in rendered_paths + [all_nodes_rendered]) else "decode_error"
|
||||
return {
|
||||
"status": status,
|
||||
"model": model,
|
||||
"paths": rendered_paths,
|
||||
"all_nodes": all_nodes_rendered,
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/series")
|
||||
def episode_series(run: str, step: int, kind: str, subset: str, etag: str | None = None, after: int = 0) -> dict:
|
||||
"""Per-episode series over a traces file (x = episode order): reward, shape, and the
|
||||
@@ -796,7 +847,15 @@ def episode_series(run: str, step: int, kind: str, subset: str, etag: str | None
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/{line}")
|
||||
def get_episode(run: str, step: int, kind: str, subset: str, line: int, tokens: bool = False) -> dict:
|
||||
def get_episode(
|
||||
run: str,
|
||||
step: int,
|
||||
kind: str,
|
||||
subset: str,
|
||||
line: int,
|
||||
tokens: bool = False,
|
||||
rendered: bool = False,
|
||||
) -> dict:
|
||||
path = traces_path(run, step, kind, subset)
|
||||
offsets = line_offsets(path)
|
||||
if not 0 <= line < len(offsets):
|
||||
@@ -804,17 +863,18 @@ def get_episode(run: str, step: int, kind: str, subset: str, line: int, tokens:
|
||||
with path.open("rb") as f:
|
||||
f.seek(offsets[line])
|
||||
rec = orjson.loads(f.readline())
|
||||
if not tokens:
|
||||
if not tokens and not rendered:
|
||||
return rec
|
||||
fallback_model = model_name(main_config(get_run_dir(run))[1])
|
||||
for trace in rec.get("traces") or []:
|
||||
client = ((trace.get("agent") or {}).get("config") or {}).get("client") or {}
|
||||
model = client.get("renderer_model_name") or fallback_model
|
||||
if not model:
|
||||
continue
|
||||
for node in trace.get("nodes") or []:
|
||||
if node.get("token_ids"):
|
||||
node["token_strs"] = decode_pieces(model, node["token_ids"])
|
||||
if tokens and model:
|
||||
for node in trace.get("nodes") or []:
|
||||
if node.get("token_ids"):
|
||||
node["token_strs"] = decode_pieces(model, node["token_ids"])
|
||||
if rendered:
|
||||
trace["rendered_tokens"] = rendered_token_text(trace, model)
|
||||
return rec
|
||||
|
||||
|
||||
@@ -888,7 +948,7 @@ def release_daemon() -> None:
|
||||
def main() -> None:
|
||||
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("output_dirs", nargs="*", default=[default_output_dir()], 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(
|
||||
|
||||
@@ -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 = {
|
||||
@@ -45,11 +45,12 @@ const state = {
|
||||
errorsOnly: prefs.traceErrorsOnly ?? false,
|
||||
sort: (prefs.traceSort ?? "line:asc").split(":")[0],
|
||||
order: (prefs.traceSort ?? "line:asc").split(":")[1],
|
||||
viewMode: prefs.tokenSignal === "rendered" ? "rendered" : (prefs.traceViewMode ?? "messages"),
|
||||
},
|
||||
};
|
||||
|
||||
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 +58,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 +69,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 +121,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 +168,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 +181,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 +201,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 +215,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 +237,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 +254,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 +262,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 +302,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 +395,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 +412,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 +478,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 +1121,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 +1135,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 +1740,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 +1806,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 +1817,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 +1831,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 +1864,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 +1926,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 */
|
||||
@@ -1925,6 +1948,8 @@ let currentEpisode = null;
|
||||
let currentLine = null;
|
||||
let currentTraceIdx = 0;
|
||||
let currentBranchIdx = 0;
|
||||
let episodeOpenVersion = 0;
|
||||
let episodeEnrichmentVersion = 0;
|
||||
|
||||
const COPY_SVG =
|
||||
`<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">` +
|
||||
@@ -1946,7 +1971,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>`
|
||||
);
|
||||
@@ -2029,42 +2054,61 @@ async function modalStep(delta) {
|
||||
}
|
||||
}
|
||||
|
||||
function fetchEpisode(line, withTokens) {
|
||||
function fetchEpisode(line, withTokens, withRendered = false) {
|
||||
const traces = state.traces;
|
||||
const qs = withTokens ? "?tokens=true" : "";
|
||||
const params = new URLSearchParams();
|
||||
if (withTokens) params.set("tokens", "true");
|
||||
if (withRendered) params.set("rendered", "true");
|
||||
const qs = params.size ? `?${params}` : "";
|
||||
return api(`/api/runs/${encodeURIComponent(state.run)}/rollouts/${traces.step}/${traces.kind}/${traces.subset}/${line}${qs}`);
|
||||
}
|
||||
|
||||
/* token strings multiply the payload of a big episode, so they are fetched only
|
||||
while a token signal is selected — the plain view ships the raw record */
|
||||
for token signals or the rendered-token view — the plain view ships the raw record */
|
||||
async function ensureTokens() {
|
||||
if (!currentEpisode || currentEpisode._hasTokens || !$("#token-signal").value) return;
|
||||
if (!currentEpisode) return;
|
||||
const wantsPieces = !!$("#token-signal").value;
|
||||
const wantsRendered = state.traces.viewMode === "rendered";
|
||||
if ((!wantsPieces || currentEpisode._hasTokens) && (!wantsRendered || currentEpisode._hasRendered)) return;
|
||||
const line = currentLine;
|
||||
const episode = await fetchEpisode(line, true);
|
||||
if (line !== currentLine) return;
|
||||
episode._hasTokens = true;
|
||||
const withTokens = wantsPieces || !!currentEpisode._hasTokens;
|
||||
const withRendered = wantsRendered || !!currentEpisode._hasRendered;
|
||||
const requestVersion = ++episodeEnrichmentVersion;
|
||||
const episode = await fetchEpisode(line, withTokens, withRendered);
|
||||
if (line !== currentLine || requestVersion !== episodeEnrichmentVersion) return;
|
||||
episode._hasTokens = withTokens;
|
||||
episode._hasRendered = withRendered;
|
||||
currentEpisode = episode;
|
||||
}
|
||||
|
||||
async function openEpisode(line) {
|
||||
const requestVersion = ++episodeOpenVersion;
|
||||
episodeEnrichmentVersion++;
|
||||
$("#trace-modal").hidden = false;
|
||||
$("#drawer-backdrop").hidden = false;
|
||||
currentLine = line;
|
||||
currentEpisode = null;
|
||||
renderModalStep();
|
||||
renderRolloutList();
|
||||
$("#tm-messages").innerHTML = `<div class="chart-empty">loading episode…</div>`;
|
||||
$("#tm-meta").innerHTML = "";
|
||||
const withTokens = !!$("#token-signal").value;
|
||||
const episode = await fetchEpisode(line, withTokens);
|
||||
if (line !== currentLine) return; // user already moved to another rollout
|
||||
const withRendered = state.traces.viewMode === "rendered";
|
||||
const episode = await fetchEpisode(line, withTokens, withRendered);
|
||||
if (line !== currentLine || requestVersion !== episodeOpenVersion) return;
|
||||
episode._hasTokens = withTokens;
|
||||
episode._hasRendered = withRendered;
|
||||
currentEpisode = episode;
|
||||
currentTraceIdx = 0;
|
||||
currentBranchIdx = 0;
|
||||
renderEpisode();
|
||||
await ensureTokens();
|
||||
if (line === currentLine && requestVersion === episodeOpenVersion) renderEpisode();
|
||||
}
|
||||
|
||||
function closeDrawer() {
|
||||
episodeOpenVersion++;
|
||||
episodeEnrichmentVersion++;
|
||||
$("#trace-modal").hidden = true;
|
||||
$("#drawer-backdrop").hidden = true;
|
||||
currentEpisode = null;
|
||||
@@ -2123,7 +2167,7 @@ function renderTokenNode(node, signal, maxAbsAdv) {
|
||||
const logprobAt = alignedSignal(node, node.logprobs);
|
||||
const advantageAt = alignedSignal(node, node.advantages);
|
||||
const spans = ids.map((id, i) => {
|
||||
const text = strs ? strs[i] : ` ${id} `;
|
||||
const text = strs?.[i] ?? ` ${id} `;
|
||||
const logprob = logprobAt(i), advantage = advantageAt(i);
|
||||
let bg = "";
|
||||
if (signal === "advantage" && advantage != null && maxAbsAdv > 0) {
|
||||
@@ -2183,18 +2227,142 @@ function reasoningBlock(content) {
|
||||
);
|
||||
}
|
||||
|
||||
function normalizedTools(tools) {
|
||||
if (tools == null) return [];
|
||||
return Array.isArray(tools) ? tools : [tools];
|
||||
}
|
||||
|
||||
function toolParts(tool, index) {
|
||||
if (!tool || typeof tool !== "object" || Array.isArray(tool))
|
||||
return { name: `tool ${index + 1}`, description: "Malformed tool definition", parameters: tool };
|
||||
const value = tool.function && typeof tool.function === "object" ? tool.function : tool;
|
||||
return {
|
||||
name: typeof value.name === "string" && value.name ? value.name : `tool ${index + 1}`,
|
||||
description: typeof value.description === "string" ? value.description : "No description recorded.",
|
||||
parameters: value.parameters ?? value.input_schema ?? value.schema ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function toolDefinitionsHtml(trace) {
|
||||
const tools = normalizedTools(trace.tools);
|
||||
if (!tools.length) return "";
|
||||
const names = tools.map((tool, i) => toolParts(tool, i).name);
|
||||
const body = tools.map((tool, i) => {
|
||||
const parts = toolParts(tool, i);
|
||||
const schema = parts.parameters == null ? "No parameters/schema recorded." :
|
||||
typeof parts.parameters === "string" ? parts.parameters : JSON.stringify(parts.parameters, null, 2);
|
||||
return (
|
||||
`<details class="tool-definition"><summary><span class="tool-def-name">${esc(parts.name)}</span>` +
|
||||
`<span class="entry-preview">${preview(parts.description, 140)}</span>` +
|
||||
`<button class="icon-btn" data-copy-tool="${i}" title="copy full tool definition">${COPY_SVG}</button>` +
|
||||
`<span class="entry-chev">›</span></summary>` +
|
||||
`<div class="tool-description">${esc(parts.description)}</div>` +
|
||||
`<div class="schema-head"><span>Parameters / JSON schema</span>` +
|
||||
`<button class="icon-btn" data-copy-schema="${i}" title="copy parameters/schema">${COPY_SVG}</button></div>` +
|
||||
`<pre class="tool-schema">${esc(schema)}</pre></details>`
|
||||
);
|
||||
}).join("");
|
||||
return (
|
||||
`<details class="tool-definitions"><summary><span class="context-label">Tool definitions</span>` +
|
||||
`<span class="chip">${tools.length} tool${tools.length === 1 ? "" : "s"}</span>` +
|
||||
`<span class="entry-preview">${esc(names.join(", "))}</span>` +
|
||||
`<button class="icon-btn" data-copy-tools title="copy all tool definitions">${COPY_SVG}</button>` +
|
||||
`<span class="entry-chev">›</span></summary>` +
|
||||
body + `</details>`
|
||||
);
|
||||
}
|
||||
|
||||
function renderedTokensHtml(trace, branches) {
|
||||
const rendered = trace.rendered_tokens;
|
||||
const errors = errorBannersHtml(episodeErrors(currentEpisode, trace));
|
||||
if (!rendered) return emptyState("rendered text not loaded", "select this view again to load recorded token IDs") + errors;
|
||||
const signal = $("#token-signal").value;
|
||||
const path = currentPath(trace, branches);
|
||||
const tokenCount = path.reduce((count, index) => count + (trace.nodes[index]?.token_ids?.length || 0), 0);
|
||||
const unavailable = {
|
||||
missing_token_ids: ["no recorded token IDs", "This trace cannot provide post-renderer text because its nodes have no token_ids."],
|
||||
missing_model: ["tokenizer model unavailable", "Neither renderer_model_name nor the run model was recorded."],
|
||||
tokenizer_unavailable: ["tokenizer unavailable", `Could not load the recorded renderer tokenizer${rendered.model ? ` (${rendered.model})` : ""}. Token IDs remain authoritative.`],
|
||||
decode_error: ["recorded tokens could not be decoded", "The tokenizer was found, but it could not decode this recorded sequence."],
|
||||
};
|
||||
const selected = currentBranchIdx === -1 ? rendered.all_nodes : rendered.paths?.[currentBranchIdx];
|
||||
if (signal && tokenCount) {
|
||||
let maxAbsAdv = 0;
|
||||
for (const node of trace.nodes || [])
|
||||
for (const advantage of node.advantages || []) maxAbsAdv = Math.max(maxAbsAdv, Math.abs(advantage));
|
||||
const body = path.map((index) => renderTokenNode(trace.nodes[index], signal, maxAbsAdv)).join("");
|
||||
return (
|
||||
`<details class="rendered-transcript" open><summary><span class="context-label">Rendered tokens/text</span>` +
|
||||
`<span class="chip">${fmtCompact(tokenCount)} tokens</span>` +
|
||||
(selected?.text != null ? `<span class="entry-preview">${preview(selected.text, 180)}</span>` : `<span class="entry-preview"></span>`) +
|
||||
(selected?.text != null ? `<button class="icon-btn" data-copy-rendered="text" title="copy decoded text">${COPY_SVG}</button>` : "") +
|
||||
`<button class="icon-btn" data-copy-rendered="ids" title="copy authoritative token IDs">IDs</button>` +
|
||||
`<span class="entry-chev">›</span></summary>` +
|
||||
`<pre class="rendered-text">${body}</pre></details>` + errors
|
||||
);
|
||||
}
|
||||
if (selected?.text == null) {
|
||||
const [title, detail] = unavailable[rendered.status] ?? ["rendered text unavailable", "The recorded token sequence could not be decoded."];
|
||||
return emptyState(title, detail) + errors;
|
||||
}
|
||||
return (
|
||||
`<details class="rendered-transcript" open><summary><span class="context-label">Rendered tokens/text</span>` +
|
||||
`<span class="chip">${fmtCompact(selected.token_count)} tokens</span>` +
|
||||
`<span class="entry-preview">${preview(selected.text, 180)}</span>` +
|
||||
`<button class="icon-btn" data-copy-rendered="text" title="copy decoded text">${COPY_SVG}</button>` +
|
||||
`<button class="icon-btn" data-copy-rendered="ids" title="copy authoritative token IDs">IDs</button>` +
|
||||
`<span class="entry-chev">›</span></summary>` +
|
||||
`<pre class="rendered-text">${esc(selected.text)}</pre></details>` + errors
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
if (state.traces.viewMode === "rendered") {
|
||||
container.innerHTML = renderedTokensHtml(trace, branches);
|
||||
return;
|
||||
}
|
||||
const signal = $("#token-signal").value;
|
||||
const path = currentPath(trace, branches);
|
||||
const concatenated = currentBranchIdx === -1;
|
||||
const toolsHtml = toolDefinitionsHtml(trace);
|
||||
const systemPosition = path.findIndex((idx) => trace.nodes[idx]?.message?.role === "system");
|
||||
let maxAbsAdv = 0;
|
||||
for (const node of trace.nodes || [])
|
||||
for (const a of node.advantages || []) maxAbsAdv = Math.max(maxAbsAdv, Math.abs(a));
|
||||
@@ -2215,7 +2383,7 @@ function renderMessages(trace, branches) {
|
||||
const reasoning = node.message?.reasoning_content ?? node.message?.reasoning;
|
||||
if (reasoning) subs.push(reasoningBlock(reasoning));
|
||||
const toolCalls = (node.message?.tool_calls || []).map(toolCallHtml);
|
||||
return (
|
||||
const messageHtml =
|
||||
`<details class="entry ${esc(role)}"${role === "system" ? "" : " open"}>` +
|
||||
`<summary><span class="entry-num">${String(i + 1).padStart(2, "0")}</span>` +
|
||||
`<span class="entry-role">${esc(role)}</span>` +
|
||||
@@ -2226,16 +2394,18 @@ function renderMessages(trace, branches) {
|
||||
subs.join("") +
|
||||
(body ? `<div class="entry-body">${body}</div>` : "") +
|
||||
toolCalls.join("") +
|
||||
`</details>`
|
||||
);
|
||||
`</details>`;
|
||||
return messageHtml + (i === systemPosition ? toolsHtml : "");
|
||||
};
|
||||
// long traces render in chunks as the reader scrolls — a 1MB episode with
|
||||
// hundreds of turns paints the first screen immediately
|
||||
const CHUNK = 30;
|
||||
let rendered = Math.min(path.length, CHUNK);
|
||||
container.innerHTML =
|
||||
(systemPosition === -1 ? toolsHtml : "") +
|
||||
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 +2531,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("");
|
||||
}
|
||||
|
||||
@@ -2403,15 +2567,19 @@ function renderEpisode() {
|
||||
`<button data-branch="-1" class="${currentBranchIdx === -1 ? "active" : ""}" title="all branches concatenated top to bottom">all</button>`
|
||||
: "";
|
||||
$("#tm-tabs-row").hidden = traceTabs.hidden && branchTabs.hidden;
|
||||
setActive("#trace-view-mode", "mode", state.traces.viewMode);
|
||||
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 +2648,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 +2892,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 +2927,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);
|
||||
@@ -2805,6 +3001,15 @@ $("#token-signal").addEventListener("change", async () => {
|
||||
renderEpisode();
|
||||
savePrefs();
|
||||
});
|
||||
$("#trace-view-mode").addEventListener("click", async (e) => {
|
||||
const btn = e.target.closest("[data-mode]");
|
||||
if (!btn || btn.dataset.mode === state.traces.viewMode) return;
|
||||
state.traces.viewMode = btn.dataset.mode;
|
||||
setActive("#trace-view-mode", "mode", state.traces.viewMode);
|
||||
await ensureTokens();
|
||||
renderEpisode();
|
||||
savePrefs();
|
||||
});
|
||||
$("#tm-trace-tabs").addEventListener("click", (e) => {
|
||||
const btn = e.target.closest("[data-trace]");
|
||||
if (btn) { currentTraceIdx = +btn.dataset.trace; currentBranchIdx = 0; renderEpisode(); }
|
||||
@@ -2817,21 +3022,42 @@ $("#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))
|
||||
document.querySelectorAll("#tm-messages details").forEach((d) => (d.open = false))
|
||||
);
|
||||
$("#tm-expand").addEventListener("click", () =>
|
||||
document.querySelectorAll("#tm-messages details").forEach((d) => (d.open = true))
|
||||
);
|
||||
$("#tm-messages").addEventListener("click", (e) => {
|
||||
const btn = e.target.closest("[data-copy]");
|
||||
const btn = e.target.closest("[data-copy], [data-copy-tool], [data-copy-schema], [data-copy-tools], [data-copy-rendered]");
|
||||
if (!btn) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const node = currentEpisode?.traces?.[currentTraceIdx]?.nodes?.[+btn.dataset.copy];
|
||||
if (node) copyText(messageText(node.message), btn);
|
||||
const trace = currentEpisode?.traces?.[currentTraceIdx];
|
||||
if (!trace) return;
|
||||
if (btn.dataset.copy != null) {
|
||||
const node = trace.nodes?.[+btn.dataset.copy];
|
||||
if (node) copyText(messageText(node.message), btn);
|
||||
return;
|
||||
}
|
||||
const tools = normalizedTools(trace.tools);
|
||||
if (btn.hasAttribute("data-copy-tools")) return copyText(JSON.stringify(tools, null, 2), btn);
|
||||
if (btn.dataset.copyTool != null) return copyText(JSON.stringify(tools[+btn.dataset.copyTool], null, 2), btn);
|
||||
if (btn.dataset.copySchema != null) {
|
||||
const schema = toolParts(tools[+btn.dataset.copySchema], +btn.dataset.copySchema).parameters;
|
||||
return copyText(typeof schema === "string" ? schema : JSON.stringify(schema, null, 2), btn);
|
||||
}
|
||||
if (btn.dataset.copyRendered) {
|
||||
const rendered = trace.rendered_tokens;
|
||||
const selected = currentBranchIdx === -1 ? rendered?.all_nodes : rendered?.paths?.[currentBranchIdx];
|
||||
if (btn.dataset.copyRendered === "text") {
|
||||
if (selected?.text != null) copyText(selected.text, btn);
|
||||
return;
|
||||
}
|
||||
const path = currentPath(trace, traceBranches(trace));
|
||||
const ids = path.flatMap((index) => trace.nodes?.[index]?.token_ids || []);
|
||||
return copyText(JSON.stringify(ids), btn);
|
||||
}
|
||||
});
|
||||
$("#tm-meta").addEventListener("click", (e) => {
|
||||
const btn = e.target.closest("[data-copytext]");
|
||||
@@ -2863,6 +3089,7 @@ function savePrefs() {
|
||||
collapsedSections: [...state.metrics.collapsedSections],
|
||||
traceErrorsOnly: state.traces.errorsOnly,
|
||||
traceSort: `${state.traces.sort}:${state.traces.order}`,
|
||||
traceViewMode: state.traces.viewMode,
|
||||
logView: state.logs.view,
|
||||
logComponents: state.logs.components ? [...state.logs.components] : null,
|
||||
logLevel: state.logs.level,
|
||||
@@ -2885,12 +3112,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 +3130,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;
|
||||
@@ -2925,11 +3152,10 @@ setInterval(async () => {
|
||||
renderLogLevel();
|
||||
$("#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"])
|
||||
$("#token-signal").value = prefs.tokenSignal === "rendered" ? "" : (prefs.tokenSignal ?? "");
|
||||
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";
|
||||
|
||||
@@ -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 & 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 & 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>
|
||||
@@ -170,12 +190,16 @@
|
||||
<div class="tm-head">
|
||||
<span class="tm-title">Trace Viewer</span>
|
||||
<div class="spacer"></div>
|
||||
<select id="token-signal">
|
||||
<option value="">text view</option>
|
||||
<option value="advantage">tokens: advantage</option>
|
||||
<option value="logprob">tokens: logprob</option>
|
||||
<option value="mask">tokens: mask</option>
|
||||
<option value="is_content">tokens: is_content</option>
|
||||
<div class="seg" id="trace-view-mode">
|
||||
<button data-mode="messages" class="active">Messages</button>
|
||||
<button data-mode="rendered">Rendered</button>
|
||||
</div>
|
||||
<select id="token-signal" title="Choose the token signal for either view. Text is uncolored; other options color recorded tokens by advantage, log probability, training mask, or message-content membership.">
|
||||
<option value="">Text</option>
|
||||
<option value="advantage">Advantage</option>
|
||||
<option value="logprob">Logprob</option>
|
||||
<option value="mask">Mask</option>
|
||||
<option value="is_content">Content</option>
|
||||
</select>
|
||||
<button id="tm-collapse" class="btn">collapse</button>
|
||||
<button id="tm-expand" class="btn">expand</button>
|
||||
|
||||
@@ -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 {
|
||||
@@ -749,6 +788,43 @@ details.sub > summary {
|
||||
details.sub .sub-name { font-weight: 500; color: var(--grey-6); }
|
||||
details.sub > .entry-body { border-top: 1px solid var(--hairline); }
|
||||
|
||||
/* tool definitions are model context, but deliberately sit outside numbered messages */
|
||||
details.tool-definitions, details.rendered-transcript {
|
||||
border: 1px solid var(--grey-3);
|
||||
margin-bottom: 12px;
|
||||
background: rgba(183, 166, 250, 0.025);
|
||||
}
|
||||
details.tool-definitions > summary, details.rendered-transcript > summary,
|
||||
details.tool-definition > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
padding: 7px 12px;
|
||||
background: var(--grey-2);
|
||||
}
|
||||
details.tool-definitions[open] > summary, details.rendered-transcript[open] > summary,
|
||||
details.tool-definition[open] > summary { border-bottom: 1px solid var(--hairline); }
|
||||
details.tool-definitions[open] > summary .entry-chev,
|
||||
details.rendered-transcript[open] > summary .entry-chev,
|
||||
details.tool-definition[open] > summary .entry-chev { transform: rotate(90deg); }
|
||||
.context-label, .tool-def-name { color: var(--chart-2); font-size: 10px; font-weight: 500; letter-spacing: var(--track-caps); text-transform: uppercase; }
|
||||
details.tool-definition { margin: 8px 12px; border: 1px solid var(--hairline); }
|
||||
.tool-description { padding: 10px 12px; color: var(--grey-5); font-size: 12px; white-space: pre-wrap; word-break: break-word; }
|
||||
.schema-head { display: flex; align-items: center; padding: 6px 12px; border-top: 1px solid var(--hairline); color: var(--grey-4); font-size: 10px; letter-spacing: var(--track-caps); text-transform: uppercase; }
|
||||
.schema-head .icon-btn { margin-left: auto; }
|
||||
.tool-schema, .rendered-text {
|
||||
margin: 0;
|
||||
padding: 12px 14px;
|
||||
overflow: auto;
|
||||
color: var(--grey-5);
|
||||
font: 400 11px/1.55 var(--font-mono);
|
||||
tab-size: 2;
|
||||
}
|
||||
.tool-schema { max-height: 380px; border-top: 1px solid var(--hairline); white-space: pre; }
|
||||
.rendered-text { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
#trace-view-mode button { white-space: nowrap; }
|
||||
|
||||
/* right pane: overview metadata */
|
||||
.tm-reward-big { color: var(--positive); }
|
||||
.tm-reward-big.neg { color: var(--negative); }
|
||||
|
||||
@@ -10,7 +10,13 @@ from typing import Any
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, latest_log_dir
|
||||
from prime_rl.utils.pathing import (
|
||||
format_log_message,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
latest_log_dir,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
@@ -71,6 +77,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.output_dir,
|
||||
launcher_log_dir=get_launcher_log_dir(config.output_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
dp_per_node=dp_per_node,
|
||||
num_nodes=getattr(config.deployment, "num_nodes", 1),
|
||||
@@ -116,6 +123,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
script = template.render(**template_vars)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.output_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -131,7 +139,7 @@ def inference_slurm(config: InferenceConfig):
|
||||
config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
script_path = config.output_dir / INFERENCE_SBATCH
|
||||
script_path = get_launcher_dir(config.output_dir) / INFERENCE_SBATCH
|
||||
write_slurm_script(config, config_path, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ from prime_rl.utils.pathing import (
|
||||
format_log_message,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
latest_log_dir,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
@@ -373,8 +375,9 @@ def rl_local(config: RLConfig):
|
||||
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()):
|
||||
# Trainer and orchestrator completion is the successful stop condition.
|
||||
completion_events = (stop_events["trainer"], stop_events["orchestrator"])
|
||||
while not all(event.is_set() for event in completion_events):
|
||||
if error_queue:
|
||||
error = error_queue[0]
|
||||
logger.error(f"Error: {error}")
|
||||
@@ -461,6 +464,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_dir / RL_CONFIG,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
elif config.inference is not None and config.inference.deployment.type == "disaggregated":
|
||||
@@ -472,6 +477,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
|
||||
nodes_per_infer_replica=infer_deploy.num_nodes,
|
||||
@@ -513,6 +520,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir, # TODO: should prob have each subconfig path separately
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.total_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
|
||||
@@ -545,6 +554,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -593,7 +603,7 @@ def rl_slurm(config: RLConfig):
|
||||
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
|
||||
)
|
||||
|
||||
script_path = config.run_dir / RL_SBATCH
|
||||
script_path = get_launcher_dir(config.run_dir) / RL_SBATCH
|
||||
write_slurm_script(config, config_dir, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@ from prime_rl.utils.pathing import (
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
get_log_dir,
|
||||
latest_log_dir,
|
||||
resolve_latest_ckpt_step,
|
||||
@@ -163,6 +165,8 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
else:
|
||||
@@ -170,6 +174,8 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
num_nodes=config.deployment.num_train_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
@@ -184,6 +190,7 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -218,6 +225,8 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
|
||||
**config.slurm.template_vars,
|
||||
config_dir=config_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router=config.inference.router,
|
||||
@@ -235,6 +244,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -270,7 +280,8 @@ def sft_slurm(config: SFTConfig):
|
||||
if decoupled_eval and config.monitors.wandb is not None:
|
||||
prl_run_id = os.environ["PRL_RUN_ID"]
|
||||
|
||||
script_path = config.run_dir / SFT_SBATCH
|
||||
launcher_dir = get_launcher_dir(config.run_dir)
|
||||
script_path = launcher_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, script_path, prl_run_id)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
@@ -282,7 +293,7 @@ def sft_slurm(config: SFTConfig):
|
||||
if decoupled_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(f"Wrote eval subconfigs to {config_dir}")
|
||||
eval_script_path = config.run_dir / EVAL_SBATCH
|
||||
eval_script_path = launcher_dir / EVAL_SBATCH
|
||||
write_eval_slurm_script(config, config_dir, eval_script_path, prl_run_id)
|
||||
logger.info(f"Wrote eval SLURM script to {eval_script_path}")
|
||||
script_paths = [script_path, eval_script_path]
|
||||
|
||||
@@ -42,6 +42,9 @@ class WandbMonitor(Monitor):
|
||||
self.logger.debug(f"Found WANDB_ARGS in environment variables {wandb_args}")
|
||||
sys.argv = json.loads(wandb_args)
|
||||
|
||||
# W&B advertises Weave on every init when it sees openai/verifiers imported.
|
||||
os.environ.setdefault("WANDB_DISABLE_WEAVE", "1")
|
||||
|
||||
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
|
||||
# requires a server connection and can't work offline.
|
||||
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1" and os.environ.get("WANDB_MODE") not in (
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately on any failed command so a crash anywhere releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately on any failed command so a crash anywhere releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
@@ -58,6 +58,7 @@ export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parall
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
@@ -67,6 +68,16 @@ ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
|
||||
# Clean exits do not trigger srun --kill-on-bad-exit. Each terminal component
|
||||
# publishes its successful exit through the shared launcher directory. Every node
|
||||
# uses the same completion condition before it tears down support processes.
|
||||
export TRAINER_DONE=$LAUNCHER_DIR/.trainer.done
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
export ORCHESTRATOR_DONE=$LAUNCHER_DIR/.orchestrator.done
|
||||
{% endif -%}
|
||||
mkdir -p "$LAUNCHER_DIR"
|
||||
rm -f "$TRAINER_DONE"{% if num_infer_nodes > 0 %} "$ORCHESTRATOR_DONE"{% endif %}
|
||||
|
||||
export PRL_RUN_ID=${PRL_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")}
|
||||
export PRL_RUN_NAME={{ run_name }}
|
||||
export WANDB_RUN_ID=$PRL_RUN_ID
|
||||
@@ -400,21 +411,28 @@ else
|
||||
|
||||
echo $HOSTNAMES_STR | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
|
||||
WANDB_SHARED_LABEL=trainer uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.json \
|
||||
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log &
|
||||
(
|
||||
WANDB_SHARED_LABEL=trainer uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.json \
|
||||
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ] && [ "$TRAIN_NODE_RANK" -eq 0 ]; then
|
||||
touch "$TRAINER_DONE" || exit $?
|
||||
fi
|
||||
exit "$COMPONENT_CODE"
|
||||
) &
|
||||
{% if num_infer_nodes > 0 %} fi{% endif %}
|
||||
{% if num_infer_nodes > 0 %}
|
||||
# Launch the orchestrator on the node ORCH_ADDR points at (see the ORCH_PROCID
|
||||
@@ -450,19 +468,41 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $LOG_DIR/orchestrator.log &
|
||||
(
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $LOG_DIR/orchestrator.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ]; then
|
||||
touch "$ORCHESTRATOR_DONE" || exit $?
|
||||
fi
|
||||
exit "$COMPONENT_CODE"
|
||||
) &
|
||||
fi
|
||||
{% endif %}
|
||||
|
||||
# Wait for the first background job to exit and propagate its exit code. This
|
||||
# turns background process crashes (router, orchestrator) into task failures
|
||||
# that --kill-on-bad-exit=1 can broadcast to the other nodes so the whole job
|
||||
# tears down instead of leaving zombies holding the allocation.
|
||||
wait -n
|
||||
EXIT_CODE=$?
|
||||
# Every node watches the terminal components for successful completion.
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
# Inference runs stop after both the trainer and orchestrator finish.
|
||||
( until [ -f "$TRAINER_DONE" ] && [ -f "$ORCHESTRATOR_DONE" ]; do sleep 10; done ) &
|
||||
{% else -%}
|
||||
# Trainer-only runs stop when the trainer finishes.
|
||||
( until [ -f "$TRAINER_DONE" ]; do sleep 10; done ) &
|
||||
{% endif -%}
|
||||
COMPLETION_PID=$!
|
||||
|
||||
# A clean component exit is not enough to stop the run. Keep waiting for the
|
||||
# shared completion condition. Propagate any failure through
|
||||
# --kill-on-bad-exit=1 so every node tears down.
|
||||
while true; do
|
||||
wait -n -p FINISHED_PID
|
||||
EXIT_CODE=$?
|
||||
if [ "$EXIT_CODE" -ne 0 ] || [ "${FINISHED_PID:-}" = "$COMPLETION_PID" ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
REMAINING_PIDS=$(jobs -p)
|
||||
{%- if cleanup_grace_period %}
|
||||
# Cross-node teardown is driven by `srun --kill-on-bad-exit=1`, which reaps peer
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately on any failed command so a crash on any node releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
@@ -33,6 +33,7 @@ export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_PATH={{ config_path }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
@@ -65,7 +66,7 @@ echo "MASTER_PORT=${MASTER_PORT}"
|
||||
{% if use_nccl_broadcast %}
|
||||
# The eval job has a separate allocation. Publish the trainer's NCCL host through
|
||||
# the shared run directory under this job ID.
|
||||
printf '%s\n' "$MASTER_ADDR" > "$OUTPUT_DIR/.sft_nccl_host_$SLURM_JOB_ID"
|
||||
printf '%s\n' "$MASTER_ADDR" > "$LAUNCHER_DIR/.sft_nccl_host_$SLURM_JOB_ID"
|
||||
{% endif %}
|
||||
|
||||
# Install environment
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/eval_job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/eval_job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/eval_job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/eval_job_%j.log
|
||||
|
||||
# Online-eval job for a decoupled SFT run: the inference pool (one vLLM engine per
|
||||
# DP rank behind a single router) plus the evals process and its env servers. The trainer
|
||||
@@ -42,6 +42,7 @@ export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export CONFIG_PATH=$CONFIG_DIR/inference.json
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Move a previous job's inference logs aside instead of deleting them: rm of log
|
||||
# files another job's processes still hold open can wedge in the NFS client and
|
||||
# hang the whole job before srun even runs.
|
||||
@@ -50,10 +51,9 @@ mkdir -p $OUTPUT_DIR/logs/inference
|
||||
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
|
||||
# A clean evals exit cannot trip srun --kill-on-bad-exit (which only propagates
|
||||
# failures), so node 0 publishes completion through this job-scoped sentinel and the
|
||||
# other nodes watch for it to release their engines. Stale sentinels from other job
|
||||
# IDs are inert, so only this job's own path needs clearing.
|
||||
export EVAL_DONE=$OUTPUT_DIR/.eval_done_$SLURM_JOB_ID
|
||||
# failures), so node 0 publishes completion through this sentinel and the other nodes
|
||||
# watch for it to release their engines.
|
||||
export EVAL_DONE=$LAUNCHER_DIR/.eval.done
|
||||
rm -f "$EVAL_DONE"
|
||||
{% if prl_run_id %}
|
||||
# Trainer (separate SLURM job) and evals log to a single shared W&B run whose id
|
||||
@@ -72,7 +72,7 @@ export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
export HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
{% if use_nccl_broadcast %}
|
||||
: "${TRAIN_JOB_ID:?TRAIN_JOB_ID is required for NCCL weight broadcast}"
|
||||
TRAIN_HOST_FILE="$OUTPUT_DIR/.sft_nccl_host_$TRAIN_JOB_ID"
|
||||
TRAIN_HOST_FILE="$LAUNCHER_DIR/.sft_nccl_host_$TRAIN_JOB_ID"
|
||||
until [ -s "$TRAIN_HOST_FILE" ]; do sleep 1; done
|
||||
export TRAIN_HOST=$(<"$TRAIN_HOST_FILE")
|
||||
rm -f "$TRAIN_HOST_FILE"
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
{%- if exclude %}
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately if any setup command or the launcher fails so the SLURM job
|
||||
# releases its allocation instead of holding nodes after a crash.
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
{%- if exclude %}
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately if any setup command or the launcher fails so the SLURM job
|
||||
# releases its allocation instead of holding nodes after a crash.
|
||||
|
||||
@@ -604,7 +604,12 @@ def train(config: TrainerConfig):
|
||||
broadcast_weights_start_time = time.perf_counter()
|
||||
# The per-layer gather + fp8 conversion peaks ~50 GiB above the
|
||||
# resident weights; release cached blocks (incl. offload-stream
|
||||
# pools) so the broadcast gets the full headroom.
|
||||
# pools) so the broadcast gets the full headroom. Drain all
|
||||
# pending work first: empty_cache returns blocks to the driver,
|
||||
# so a still-running kernel holding a cached block (e.g. the
|
||||
# optimizer step's tail) faults with an illegal memory access
|
||||
# once its block is freed under it.
|
||||
torch.cuda.synchronize()
|
||||
torch.cuda.empty_cache()
|
||||
weight_sender.broadcast(model, step=progress.step)
|
||||
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
|
||||
|
||||
@@ -61,7 +61,7 @@ def format_log_message(
|
||||
|
||||
log_lines: list[str] = []
|
||||
if job_log:
|
||||
log_lines.append(f"{i1}{'Job:':<{col}}tail -F {log_dir.parent.parent}/job_*.log")
|
||||
log_lines.append(f"{i1}{'Job:':<{col}}tail -F {get_launcher_log_dir(log_dir.parent.parent)}/*job_*.log")
|
||||
if trainer:
|
||||
log_lines.append(f"{i1}{'Trainer:':<{col}}tail -F {log_dir}/trainer.log")
|
||||
if num_train_nodes > 1:
|
||||
@@ -129,6 +129,14 @@ def write_launch_toml(run_dir: Path, name: str) -> None:
|
||||
(config_dir / f"{name}.toml").write_text("\n".join(texts))
|
||||
|
||||
|
||||
def get_launcher_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "launcher"
|
||||
|
||||
|
||||
def get_launcher_log_dir(output_dir: Path) -> Path:
|
||||
return get_launcher_dir(output_dir) / "logs"
|
||||
|
||||
|
||||
def get_ckpt_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "checkpoints"
|
||||
|
||||
@@ -174,10 +182,9 @@ def has_checkpoints(output_dir: Path) -> bool:
|
||||
return ckpt_dir.exists() and any(ckpt_dir.iterdir())
|
||||
|
||||
|
||||
# Launcher artifacts that may exist in a run directory before training starts: resolved
|
||||
# configs and the SLURM script/job log (a submitted job re-invokes the entrypoint inside
|
||||
# the run directory). Everything else is treated as artifacts of a previous run.
|
||||
LAUNCHER_ARTIFACTS = ("configs", "rl.sbatch", "sft.sbatch", "job_*.log")
|
||||
# Launcher artifacts may exist before training starts. Everything else is treated as
|
||||
# artifacts of a previous run.
|
||||
LAUNCHER_ARTIFACTS = ("configs", "launcher")
|
||||
|
||||
|
||||
def has_run_artifacts(run_dir: Path) -> bool:
|
||||
|
||||
@@ -19,8 +19,12 @@ def test_dir_with_launcher_artifacts_passes(tmp_path):
|
||||
run_dir.mkdir()
|
||||
(run_dir / "configs").mkdir()
|
||||
(run_dir / "configs" / "trainer.toml").touch()
|
||||
(run_dir / "rl.sbatch").touch()
|
||||
(run_dir / "job_1234.log").touch()
|
||||
(run_dir / "launcher").mkdir()
|
||||
(run_dir / "launcher" / "rl.sbatch").touch()
|
||||
(run_dir / "launcher" / ".trainer.done").touch()
|
||||
(run_dir / "launcher" / ".orchestrator.done").touch()
|
||||
(run_dir / "launcher" / "logs").mkdir()
|
||||
(run_dir / "launcher" / "logs" / "job_1234.log").touch()
|
||||
validate_run_dir(run_dir, output_dir=tmp_path, resuming=False, clean=False)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user