Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be5855cfe3 | ||
|
|
43365ec52f | ||
|
|
ab5de8fff4 | ||
|
|
97d32d947f | ||
|
|
6b3364d1a8 | ||
|
|
544bd6205a |
@@ -31,6 +31,7 @@ Namespaces are one honking great idea -- let's do more of those!
|
||||
## Running code
|
||||
|
||||
- **Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
|
||||
- **Tools vs entrypoints**: standalone scripts in `tools/` use plain argparse with positional args; `[project.scripts]` entrypoints use pydantic-config (`@ file.toml` + dotted CLI overrides).
|
||||
- **Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
|
||||
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
|
||||
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
|
||||
|
||||
+19
-3
@@ -263,8 +263,8 @@ Checkpointing is split across processes because the orchestrator and trainer can
|
||||
|
||||
| Process | What's saved | Where |
|
||||
|---|---|---|
|
||||
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_N/trainer/` |
|
||||
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_N/orchestrator/` |
|
||||
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_{n}/trainer/` |
|
||||
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_{n}/orchestrator/` |
|
||||
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
|
||||
|
||||
### Enabling Checkpoints
|
||||
@@ -297,6 +297,20 @@ uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
|
||||
--resume.dir outputs/my-run/checkpoints/step_10
|
||||
```
|
||||
|
||||
### Exporting Checkpoints
|
||||
|
||||
Trainer checkpoints are DCP-sharded; export them to HF-format safetensors with `tools/convert_dcp_to_bf16.py`. The script reads the model config from the run's resolved config and writes sharded safetensors plus config/tokenizer assets to `<ckpt_dir>/weights` (or a second positional arg). It exports full fine-tunes only — LoRA checkpoints are rejected.
|
||||
|
||||
```bash
|
||||
# single process (1 GPU)
|
||||
uv run python tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
|
||||
|
||||
# multi-rank for faster gathers and models that don't fit one GPU
|
||||
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
|
||||
```
|
||||
|
||||
The exported directory loads directly into `uv run inference --vllm.model <dir>` or any HF consumer. Quantize it to blockwise FP8 (DeepSeek/GLM format, loads natively in vLLM) with `tools/convert_bf16_to_fp8.py <dir>`, or go straight from the checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (each rank quantizes its gathered slice, writes only `<ckpt_dir>/weights-FP8` — no intermediate bf16 export); dequantize an fp8-only release (e.g. GLM-5-FP8) for training with `tools/convert_fp8_to_bf16.py <dir>`.
|
||||
|
||||
## Observability
|
||||
|
||||
### Log Files
|
||||
@@ -329,7 +343,9 @@ tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
|
||||
|
||||
### Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with four views per run: metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved configs, a rollout trace viewer with a per-token advantage/logprob view, and merged component logs. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved configs, a rollout trace viewer with a per-token advantage/logprob view, merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
|
||||
|
||||
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
|
||||
|
||||
### Weights & Biases
|
||||
|
||||
|
||||
@@ -471,9 +471,6 @@ class RLConfig(BaseConfig):
|
||||
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
|
||||
"have no disk artifact to load from."
|
||||
)
|
||||
# The final version v{max_steps} is broadcast iff something consumes it:
|
||||
# training never samples from it, but a configured final eval measures it.
|
||||
broadcast_final = self.orchestrator.eval is not None
|
||||
if self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
inference_world_size = (
|
||||
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
|
||||
@@ -485,7 +482,6 @@ class RLConfig(BaseConfig):
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
broadcast_final=broadcast_final,
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
transport_config = dict(
|
||||
@@ -501,10 +497,10 @@ class RLConfig(BaseConfig):
|
||||
self.orchestrator.weight_broadcast = orchestrator_config_type(**common_config, **transport_config)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig(
|
||||
timeout=self.weight_broadcast.timeout, broadcast_final=broadcast_final
|
||||
timeout=self.weight_broadcast.timeout
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig(
|
||||
timeout=self.weight_broadcast.timeout, broadcast_final=broadcast_final
|
||||
timeout=self.weight_broadcast.timeout
|
||||
)
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
|
||||
@@ -42,12 +42,6 @@ class BaseWeightBroadcastConfig(BaseConfig):
|
||||
"""Timeout in seconds for the broadcast handshake and transfer. The trainer
|
||||
fails the run when no consumer acknowledges an offered version in time."""
|
||||
|
||||
broadcast_final: bool = True
|
||||
"""Internal - stamped by the RL/SFT launcher, never set by users: whether the
|
||||
trainer broadcasts the final version v{max_steps}. True iff something consumes
|
||||
it (a configured final eval) - training itself never samples from the final
|
||||
version."""
|
||||
|
||||
|
||||
class RunConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "prime-rl"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
description = "Async RL Training at Scale"
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
|
||||
@@ -47,6 +47,8 @@ def _qwen3_5_moe_vlm_config():
|
||||
tc.num_attention_heads = 4
|
||||
tc.num_key_value_heads = 2
|
||||
tc.head_dim = 64
|
||||
# mrope_section must sum to rotary_dim // 2 for the shrunken head_dim
|
||||
tc.rope_parameters["mrope_section"] = [3, 3, 2]
|
||||
tc.moe_intermediate_size = 128
|
||||
tc.shared_expert_intermediate_size = 128
|
||||
tc.num_experts = 4
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: dashboard
|
||||
description: Find, start, use, and stop the local run dashboard — the web UI for run output dirs (metrics, configs, traces, logs). Use when asked for the dashboard URL, when a run needs watching in the browser, or when a dashboard must be restarted or killed.
|
||||
description: Find, start, use, and stop the local run dashboard for metrics, configs, traces, logs, and reports. Use when asked for its URL, to watch or inspect a run, to control the open dashboard, or to create a cited dashboard report explicitly requested by the user.
|
||||
---
|
||||
|
||||
# Run dashboard
|
||||
@@ -51,3 +51,76 @@ A clean exit releases `daemon.json`; a stale file from a dead process is taken
|
||||
over by the next start. Killing a dashboard never affects runs (it only reads),
|
||||
and killing a run never takes the dashboard down (it runs in its own session).
|
||||
Restart by launching any run, or directly: `uv run dashboard`.
|
||||
|
||||
## Point the open dashboard
|
||||
|
||||
Use `POST /api/view` to show relevant run data in every connected dashboard
|
||||
tab:
|
||||
|
||||
```bash
|
||||
curl -sS -X POST $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/view \
|
||||
-H 'content-type: application/json' -d '{
|
||||
"run": "demo-rl", "tab": "traces",
|
||||
"step": 0, "kind": "train", "subset": "effective",
|
||||
"episode": "ep-s00-reverse-text-0",
|
||||
"highlight": [{"node": 3, "quote": "hint: reverse the words", "reason": "tool result the policy conditioned on"}]
|
||||
}'
|
||||
```
|
||||
|
||||
`run` is required; other fields are optional and leave unspecified UI state
|
||||
unchanged. For trace evidence, supply `step`, `kind`, and `subset` together and
|
||||
address the episode by stable `id`. Use optional `trace` and `branch` indices
|
||||
for multi-agent traces and `highlight` entries shaped as `{node, quote,
|
||||
reason, field?}`. On `409`, tell the user to open the returned `url`; the stored
|
||||
command applies when the tab connects.
|
||||
|
||||
## Write a report only when asked
|
||||
|
||||
Create a report only when the user explicitly asks for one. Otherwise answer
|
||||
normally; use `/api/view` when showing trace evidence would help.
|
||||
|
||||
Write requested reports to `<run>/reports/<slug>.md`, then POST `{"run": ...,
|
||||
"tab": "report", "report": "<slug>"}`. Use Markdown with a frontmatter
|
||||
`title` and one-line JSON citation definitions:
|
||||
|
||||
```markdown
|
||||
---
|
||||
title: Why does reward dip at step 4?
|
||||
---
|
||||
|
||||
The dip is provider errors, not policy regression [^err].
|
||||
|
||||
[^err]: {"step": 4, "kind": "train", "subset": "all", "episode": "ep-...", "node": 0, "quote": "engine overloaded", "note": "The failed call that emptied this step's batch."}
|
||||
```
|
||||
|
||||
The frontmatter `title` is rendered as the report H1; do not repeat it with a
|
||||
Markdown `#` heading. The inline renderer supports only HTTP(S) and anchor
|
||||
links. Relative Markdown links render as literal text, so identify local source
|
||||
files with inline code paths or link to a supported HTTP endpoint.
|
||||
|
||||
Each citation requires `step`, `kind`, `subset`, `episode`, `quote`, and `note`.
|
||||
Use the top-level rollout record `id` returned by the dashboard episode-list
|
||||
API—not a nested `traces[*].id`, and never `line`. Copy a short, distinctive
|
||||
quote exactly; matching is case-sensitive and whitespace-insensitive. Keep
|
||||
`note` to 1–2 sentences explaining why the quote supports the claim.
|
||||
|
||||
Cite major empirical, comparative, and diagnostic conclusions, but not routine
|
||||
explanation. Use exact trace citations for trajectory-level claims. For
|
||||
aggregate statistics, identify the run and source file; do not imply that one
|
||||
example trajectory proves the aggregate.
|
||||
|
||||
Use adjacent markers (`[^a] [^b]`) only when one claim genuinely depends on
|
||||
distinct passages, such as a comparison or corroboration. Use one citation
|
||||
when one passage is sufficient.
|
||||
|
||||
Optional fields are `run`, `trace`, `branch`, `node`, `field`, `prefix`, and
|
||||
`suffix`. Use `field: "content"` or `"reasoning"` only to disambiguate message
|
||||
parts. Use verbatim adjacent `prefix`/`suffix` only when a quote repeats.
|
||||
Ambiguous or mismatched citations remain broken and do not navigate.
|
||||
|
||||
Use Markdown; raw HTML is escaped.
|
||||
|
||||
Before handoff, reload the report and verify through the dashboard API that
|
||||
every referenced citation resolves uniquely to its episode, node, and quote.
|
||||
Confirm zero broken citations, one rendered title, and no unsupported relative
|
||||
links.
|
||||
|
||||
@@ -50,7 +50,7 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
|
||||
|
||||
- `{run_dir}/configs/` — the launch TOML copied verbatim (`rl.toml`/`sft.toml`), plus `resolved/` with the per-component resolved configs, written as JSON so explicit None settings round-trip.
|
||||
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
|
||||
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved episodes (see Episodes below).
|
||||
- `{run_dir}/rollouts/step_{n}/{train,eval}/` — saved episodes (see Episodes below).
|
||||
|
||||
### Dashboard
|
||||
|
||||
@@ -162,8 +162,8 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
|
||||
### Episodes
|
||||
|
||||
```
|
||||
{run_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per episode as it completes
|
||||
{run_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
{run_dir}/rollouts/step_{n}/{train,eval}/all/traces.jsonl # appended per episode as it completes
|
||||
{run_dir}/rollouts/step_{n}/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
```
|
||||
|
||||
JSONL files of native `vf.Episode` records (training tensors excluded), one line per episode.
|
||||
@@ -182,7 +182,7 @@ jq '.traces[].rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.ok | not) | {id, env: .env.id, errors}' {run_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
```
|
||||
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
|
||||
|
||||
### Common failure modes
|
||||
|
||||
|
||||
@@ -127,6 +127,10 @@ env.agent.runtime.type = "subprocess"
|
||||
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
|
||||
|
||||
## Exporting checkpoints
|
||||
|
||||
Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`). Convert to HF safetensors with `uv run python tools/convert_dcp_to_bf16.py <run_dir>/checkpoints/step_{n}` (writes `<ckpt_dir>/weights`, serveable via `uv run inference --vllm.model <dir>`; model config auto-read from the run’s `configs/resolved/trainer.json`/`sft.json`; multi-rank via `torchrun --nproc-per-node N`; full fine-tunes only, LoRA rejected). Quantize a bf16 HF dir to blockwise FP8 with `tools/convert_bf16_to_fp8.py <dir>` (vLLM-native format), or straight from a checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (rank-parallel, writes only `<ckpt_dir>/weights-FP8`, no bf16 on disk); dequantize fp8-only releases with `tools/convert_fp8_to_bf16.py <dir>`. Caveat: on SM120 GPUs (RTX PRO 6000) vLLM 0.26 picks `CutlassFp8BlockScaledMMKernel` for blockwise-fp8 checkpoints and it silently degrades outputs — serve with `VLLM_DISABLED_KERNELS=CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel` to fall back to the Triton kernel.
|
||||
|
||||
## Summary
|
||||
|
||||
| Command | Purpose | Typical use |
|
||||
@@ -150,4 +154,3 @@ Interactive launches auto-start one shared dashboard daemon per user (process ti
|
||||
that URL to the researcher. Discovery: `~/.cache/prime-rl/dashboard/daemon.json` holds
|
||||
the live `url` (the port can differ from 7788 when it was taken). `--no-dashboard`
|
||||
opts a run out.
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
# Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
|
||||
directories (metrics, resolved configs, rollout traces, component logs) at
|
||||
directories (metrics, resolved configs, rollout traces, cited reports,
|
||||
component logs) at
|
||||
http://localhost:7788. Needs the `dashboard` extra. Every instance also serves
|
||||
the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
|
||||
(one dashboard per host per user); `--isolated` serves only the given dirs and
|
||||
skips the registry. See `skills/dashboard/SKILL.md` for discovery and
|
||||
kill/restart commands.
|
||||
skips the registry. See `skills/dashboard/SKILL.md` for discovery,
|
||||
kill/restart commands, and the local view-command/report contract.
|
||||
|
||||
GPU dependencies live behind the `gpu` extra, so this works anywhere — a
|
||||
cluster head node, a laptop against a mounted outputs dir:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Local dashboard for prime-rl runs: logs, metrics, and rollout traces.
|
||||
"""Local dashboard for prime-rl runs: logs, metrics, rollout traces, and reports.
|
||||
|
||||
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.
|
||||
|
||||
@@ -11,6 +11,7 @@ Multiple output directories can be tracked at once.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import hashlib
|
||||
import os
|
||||
import sys
|
||||
@@ -28,7 +29,7 @@ from prime_rl.utils.process import set_proc_title
|
||||
try:
|
||||
import uvicorn
|
||||
from fastapi import FastAPI, HTTPException, Query
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
except ModuleNotFoundError as error: # the dashboard ships as an extra
|
||||
raise SystemExit("the dashboard needs the 'dashboard' extra - install with `uv sync --extra dashboard`") from error
|
||||
@@ -65,7 +66,7 @@ def _lru_put(cache: OrderedDict, key, value) -> None:
|
||||
|
||||
|
||||
# Append-only file caches keyed by absolute path: line-start offsets and per-episode summaries.
|
||||
_offsets_cache: OrderedDict[Path, tuple[int, list[int]]] = OrderedDict()
|
||||
_offsets_cache: OrderedDict[Path, tuple[int, bytes, list[int]]] = OrderedDict()
|
||||
_summaries_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
|
||||
_tokenizer_cache: dict[str, object] = {}
|
||||
_piece_cache: dict[tuple[str, int], str] = {}
|
||||
@@ -429,6 +430,49 @@ def read_config(run: str, file: str) -> dict:
|
||||
return {"file": file, "content": path.read_text()}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------- reports
|
||||
|
||||
|
||||
def report_title(path: Path) -> str | None:
|
||||
"""`title:` from the frontmatter block, scanning only the first bytes of the file."""
|
||||
try:
|
||||
with path.open("r", errors="replace") as f:
|
||||
head = f.read(4096)
|
||||
except OSError:
|
||||
return None
|
||||
if not head.startswith("---"):
|
||||
return None
|
||||
for line in head.splitlines()[1:]:
|
||||
if line.strip() == "---":
|
||||
break
|
||||
key, _, value = line.partition(":")
|
||||
if key.strip() == "title":
|
||||
return value.strip().strip("\"'") or None
|
||||
return None
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/reports")
|
||||
def list_reports(run: str) -> dict:
|
||||
"""Markdown reports under <run>/reports/, newest first."""
|
||||
reports_dir = get_run_dir(run) / "reports"
|
||||
rows = []
|
||||
for path in reports_dir.glob("*.md") if reports_dir.is_dir() else []:
|
||||
try:
|
||||
stat = path.stat()
|
||||
except OSError:
|
||||
continue
|
||||
rows.append({"file": path.name, "title": report_title(path), "mtime": stat.st_mtime, "size": stat.st_size})
|
||||
rows.sort(key=lambda r: r["mtime"], reverse=True)
|
||||
return {"reports": rows}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/report")
|
||||
def read_report(run: str, file: str) -> dict:
|
||||
path = safe_child(get_run_dir(run) / "reports", file, suffix=".md")
|
||||
stat = path.stat()
|
||||
return {"file": file, "text": path.read_text(errors="replace"), "mtime": stat.st_mtime, "size": stat.st_size}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------- metrics
|
||||
|
||||
|
||||
@@ -511,9 +555,13 @@ def rollout_steps(run_dir: Path) -> list[dict]:
|
||||
def line_offsets(path: Path) -> list[int]:
|
||||
size = path.stat().st_size
|
||||
with _lock:
|
||||
cached_size, offsets = _lru_get(_offsets_cache, path) or (0, [])
|
||||
if cached_size > size: # rewritten (e.g. resume cleanup): rebuild
|
||||
cached_size, offsets = 0, []
|
||||
cached_size, checkpoint, offsets = _lru_get(_offsets_cache, path) or (0, b"", [])
|
||||
if cached_size > size or (cached_size and file_checkpoint(path, cached_size) != checkpoint):
|
||||
# The bytes immediately before the old EOF changed: this is a rewrite,
|
||||
# not an append. Invalidate offsets and their derived summaries together.
|
||||
cached_size, checkpoint, offsets = 0, b"", []
|
||||
_summaries_cache.pop(path, None)
|
||||
_sidecar_written.pop(path, None)
|
||||
if cached_size == size:
|
||||
return offsets
|
||||
# re-scan from the last recorded line (it may have been partial) into a local
|
||||
@@ -529,14 +577,21 @@ def line_offsets(path: Path) -> list[int]:
|
||||
if line.strip():
|
||||
found.append(pos)
|
||||
pos += len(line)
|
||||
scanned_size = f.tell()
|
||||
with _lock:
|
||||
cached_size, current = _lru_get(_offsets_cache, path) or (0, offsets)
|
||||
if cached_size > size:
|
||||
current = []
|
||||
cached_size, checkpoint, current = _lru_get(_offsets_cache, path) or (0, b"", offsets)
|
||||
current_matches = not cached_size or file_checkpoint(path, cached_size) == checkpoint
|
||||
if cached_size > scanned_size and current_matches:
|
||||
return current # a concurrent reader already scanned farther
|
||||
if not current_matches:
|
||||
cached_size, current = 0, []
|
||||
_summaries_cache.pop(path, None)
|
||||
_sidecar_written.pop(path, None)
|
||||
for offset in found:
|
||||
if not current or offset > current[-1]:
|
||||
current.append(offset)
|
||||
_lru_put(_offsets_cache, path, (max(size, cached_size), current))
|
||||
cached_size = max(scanned_size, cached_size)
|
||||
_lru_put(_offsets_cache, path, (cached_size, file_checkpoint(path, cached_size), current))
|
||||
return current
|
||||
|
||||
|
||||
@@ -648,7 +703,7 @@ def episode_summaries(path: Path) -> list[dict]:
|
||||
summaries.append({"line": line_no, "id": None, "error": "unparseable"})
|
||||
with _lock:
|
||||
_lru_put(_summaries_cache, path, (len(offsets), summaries))
|
||||
write_sidecar(path, offsets, summaries)
|
||||
write_sidecar(path, summaries)
|
||||
return summaries
|
||||
|
||||
|
||||
@@ -666,25 +721,46 @@ def sidecar_path(path: Path) -> Path:
|
||||
return SIDECAR_DIR / f"{digest}.json"
|
||||
|
||||
|
||||
def file_checkpoint(path: Path, end: int) -> bytes:
|
||||
"""Bytes immediately before a previously observed EOF.
|
||||
|
||||
Appends preserve this window; rewrites and truncate-then-regrow resumes do
|
||||
not. Checking 64 bytes stays constant-time even for multi-gigabyte traces.
|
||||
"""
|
||||
with path.open("rb") as f:
|
||||
start = max(0, end - 64)
|
||||
f.seek(start)
|
||||
return f.read(end - start)
|
||||
|
||||
|
||||
def load_sidecar(path: Path) -> list[dict] | None:
|
||||
data = read_json(sidecar_path(path))
|
||||
try:
|
||||
if data.get("path") != str(path.resolve()) or path.stat().st_size < data["size"]:
|
||||
return None # different file, or rewritten smaller (relaunch)
|
||||
if (
|
||||
data.get("path") != str(path.resolve())
|
||||
or path.stat().st_size < data["size"]
|
||||
or data.get("checkpoint") != file_checkpoint(path, data["size"]).hex()
|
||||
):
|
||||
return None
|
||||
return data["summaries"]
|
||||
except (KeyError, OSError):
|
||||
return None
|
||||
|
||||
|
||||
def write_sidecar(path: Path, offsets: list[int], summaries: list[dict]) -> None:
|
||||
def write_sidecar(path: Path, summaries: list[dict]) -> None:
|
||||
now = time.monotonic()
|
||||
last_time, last_count = _sidecar_written.get(path, (0.0, -1))
|
||||
if len(summaries) == last_count or now - last_time < SIDECAR_WRITE_INTERVAL_S:
|
||||
return
|
||||
_sidecar_written[path] = (now, len(summaries))
|
||||
SIDECAR_DIR.mkdir(parents=True, exist_ok=True)
|
||||
consumed = offsets[len(summaries) - 1] if summaries else 0
|
||||
payload = {"path": str(path.resolve()), "size": consumed, "summaries": summaries}
|
||||
size = path.stat().st_size
|
||||
payload = {
|
||||
"path": str(path.resolve()),
|
||||
"size": size,
|
||||
"checkpoint": file_checkpoint(path, size).hex(),
|
||||
"summaries": summaries,
|
||||
}
|
||||
target = sidecar_path(path)
|
||||
tmp = target.with_suffix(".tmp")
|
||||
tmp.write_bytes(orjson.dumps(payload))
|
||||
@@ -716,7 +792,8 @@ def list_episodes(
|
||||
step: int,
|
||||
kind: str,
|
||||
subset: str,
|
||||
limit: int = Query(default=5000, le=5000),
|
||||
limit: int = Query(default=5000, ge=1, le=5000),
|
||||
episode: str | None = None,
|
||||
env: str | None = None,
|
||||
errors_only: bool = False,
|
||||
sort: str = "line",
|
||||
@@ -729,6 +806,8 @@ def list_episodes(
|
||||
return unchanged
|
||||
summaries = episode_summaries(path)
|
||||
envs = sorted({s["env"] for s in summaries if s.get("env")})
|
||||
if episode is not None:
|
||||
summaries = [s for s in summaries if s.get("id") == episode]
|
||||
if env:
|
||||
summaries = [s for s in summaries if s.get("env") == env]
|
||||
if errors_only:
|
||||
@@ -846,6 +925,15 @@ def episode_series(run: str, step: int, kind: str, subset: str, etag: str | None
|
||||
return {"etag": current_etag, "count": len(summaries), "after": max(0, after), "series": series}
|
||||
|
||||
|
||||
def read_episode_at(path: Path, line: int) -> dict:
|
||||
offsets = line_offsets(path)
|
||||
if not 0 <= line < len(offsets):
|
||||
raise HTTPException(404, "episode line out of range")
|
||||
with path.open("rb") as f:
|
||||
f.seek(offsets[line])
|
||||
return orjson.loads(f.readline())
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/{line}")
|
||||
def get_episode(
|
||||
run: str,
|
||||
@@ -857,12 +945,7 @@ def get_episode(
|
||||
rendered: bool = False,
|
||||
) -> dict:
|
||||
path = traces_path(run, step, kind, subset)
|
||||
offsets = line_offsets(path)
|
||||
if not 0 <= line < len(offsets):
|
||||
raise HTTPException(404, "episode line out of range")
|
||||
with path.open("rb") as f:
|
||||
f.seek(offsets[line])
|
||||
rec = orjson.loads(f.readline())
|
||||
rec = read_episode_at(path, line)
|
||||
if not tokens and not rendered:
|
||||
return rec
|
||||
fallback_model = model_name(main_config(get_run_dir(run))[1])
|
||||
@@ -878,6 +961,192 @@ def get_episode(
|
||||
return rec
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- view command
|
||||
#
|
||||
# The agent-facing control plane: a local agent that already knows the on-disk
|
||||
# address of what it wants shown POSTs that address here, and every connected
|
||||
# browser tab navigates there. One-way fan-out over SSE — no WebSocket dependency,
|
||||
# and the browser's EventSource reconnects on its own. The dashboard stays a
|
||||
# filesystem reader: commands carry addresses and short highlight anchors, never
|
||||
# report or episode payloads.
|
||||
|
||||
VIEW_TABS = {"metrics", "config", "traces", "logs", "report"}
|
||||
VIEW_KEYS = {"run", "tab", "step", "kind", "subset", "episode", "line", "trace", "branch", "report", "highlight"}
|
||||
HIGHLIGHT_KEYS = {"node", "quote", "prefix", "suffix", "reason", "field"}
|
||||
|
||||
_view_command: dict | None = None
|
||||
_view_seq = 0
|
||||
_view_clients: set["asyncio.Queue"] = set()
|
||||
_view_url = "" # actual serve url, stamped by main() for the 409 body
|
||||
MAX_VIEW_QUEUE = 32
|
||||
|
||||
|
||||
def normalize_view_int(obj: dict, key: str, minimum: int) -> int | None:
|
||||
value = obj.get(key)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
raise HTTPException(400, f"{key} must be an integer")
|
||||
try:
|
||||
normalized = int(value)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(400, f"{key} must be an integer") from None
|
||||
if isinstance(value, float) and not value.is_integer():
|
||||
raise HTTPException(400, f"{key} must be an integer")
|
||||
if normalized < minimum:
|
||||
raise HTTPException(400, f"{key} must be >= {minimum}")
|
||||
obj[key] = normalized
|
||||
return normalized
|
||||
|
||||
|
||||
def validate_view_command(cmd: dict) -> dict:
|
||||
"""Check the command against the filesystem so the agent cannot point at nothing.
|
||||
Returns the command with an episode id resolved to its line number."""
|
||||
unknown = set(cmd) - VIEW_KEYS
|
||||
if unknown:
|
||||
raise HTTPException(400, f"unknown fields: {sorted(unknown)} (known: {sorted(VIEW_KEYS)})")
|
||||
run = cmd.get("run")
|
||||
if not isinstance(run, str) or not run:
|
||||
raise HTTPException(400, "run must be a non-empty string")
|
||||
run_dir = get_run_dir(run)
|
||||
tab = cmd.get("tab")
|
||||
if tab is not None and tab not in VIEW_TABS:
|
||||
raise HTTPException(400, f"tab must be one of {sorted(VIEW_TABS)}")
|
||||
report = cmd.get("report")
|
||||
if report is not None:
|
||||
if not isinstance(report, str) or not report:
|
||||
raise HTTPException(400, "report must be a non-empty string")
|
||||
name = report if report.endswith(".md") else f"{report}.md"
|
||||
safe_child(run_dir / "reports", name, suffix=".md")
|
||||
cmd["report"] = name
|
||||
|
||||
step = normalize_view_int(cmd, "step", 0)
|
||||
line = normalize_view_int(cmd, "line", 0)
|
||||
trace_index = normalize_view_int(cmd, "trace", 0)
|
||||
branch_index = normalize_view_int(cmd, "branch", -1)
|
||||
episode = cmd.get("episode")
|
||||
if episode is not None and (not isinstance(episode, str) or not episode):
|
||||
raise HTTPException(400, "episode must be a non-empty string")
|
||||
|
||||
kind, subset = cmd.get("kind"), cmd.get("subset")
|
||||
address = (step, kind, subset)
|
||||
if any(value is not None for value in address) and not all(value is not None for value in address):
|
||||
raise HTTPException(400, "trace addressing needs step, kind, and subset together")
|
||||
path = traces_path(run, step, kind, subset) if all(value is not None for value in address) else None
|
||||
|
||||
needs_episode = episode is not None or line is not None
|
||||
if needs_episode and path is None:
|
||||
raise HTTPException(400, "episode addressing needs step, kind, and subset")
|
||||
if any(value is not None for value in (trace_index, branch_index)) or cmd.get("highlight") is not None:
|
||||
if not needs_episode:
|
||||
raise HTTPException(400, "trace, branch, and highlight need an episode or line")
|
||||
|
||||
rec = None
|
||||
if episode is not None:
|
||||
matches = [s["line"] for s in episode_summaries(path) if s.get("id") == episode]
|
||||
if not matches:
|
||||
raise HTTPException(404, f"episode id {episode!r} not found in {kind}/{subset} at step {step}")
|
||||
if len(matches) > 1:
|
||||
raise HTTPException(409, f"episode id {episode!r} is not unique in {kind}/{subset} at step {step}")
|
||||
line = cmd["line"] = matches[0]
|
||||
if line is not None:
|
||||
rec = read_episode_at(path, line)
|
||||
|
||||
selected_trace = None
|
||||
if rec is not None and (trace_index is not None or branch_index is not None or cmd.get("highlight") is not None):
|
||||
traces = rec.get("traces") or []
|
||||
trace_index = trace_index or 0
|
||||
if not 0 <= trace_index < len(traces):
|
||||
raise HTTPException(404, f"trace {trace_index} not found in episode")
|
||||
selected_trace = traces[trace_index]
|
||||
if branch_index is not None:
|
||||
nodes = selected_trace.get("nodes") or []
|
||||
parents = {node.get("parent") for node in nodes if "parent" in node}
|
||||
branches = [i for i in range(len(nodes)) if i not in parents]
|
||||
if branch_index != -1 and not 0 <= branch_index < len(branches):
|
||||
raise HTTPException(404, f"branch {branch_index} not found in trace {trace_index}")
|
||||
|
||||
highlight = cmd.get("highlight")
|
||||
if highlight is not None:
|
||||
if not isinstance(highlight, list) or not all(isinstance(h, dict) for h in highlight):
|
||||
raise HTTPException(400, "highlight must be a list of objects")
|
||||
if len(highlight) > 50:
|
||||
raise HTTPException(400, "highlight may contain at most 50 entries")
|
||||
nodes = selected_trace.get("nodes") or []
|
||||
for h in highlight:
|
||||
unknown = set(h) - HIGHLIGHT_KEYS
|
||||
if unknown:
|
||||
raise HTTPException(
|
||||
400, f"unknown highlight fields: {sorted(unknown)} (known: {sorted(HIGHLIGHT_KEYS)})"
|
||||
)
|
||||
node = normalize_view_int(h, "node", 0)
|
||||
if node is None or node >= len(nodes):
|
||||
raise HTTPException(404, f"highlight node {node} not found in trace {trace_index}")
|
||||
quote = h.get("quote")
|
||||
if not isinstance(quote, str) or not quote.strip():
|
||||
raise HTTPException(400, "highlight quote must be a non-empty string")
|
||||
for key in ("prefix", "suffix", "reason"):
|
||||
if key in h and not isinstance(h[key], str):
|
||||
raise HTTPException(400, f"highlight {key} must be a string")
|
||||
if h.get("field") not in (None, "content", "reasoning"):
|
||||
raise HTTPException(400, "highlight field must be content|reasoning")
|
||||
return cmd
|
||||
|
||||
|
||||
def _view_event(cmd: dict) -> str:
|
||||
return f"data: {orjson.dumps(cmd).decode()}\n\n"
|
||||
|
||||
|
||||
@app.post("/api/view")
|
||||
async def post_view(cmd: dict) -> dict:
|
||||
global _view_command, _view_seq
|
||||
# validation walks the filesystem (and may summarize a traces file on first
|
||||
# touch) — keep it off the event loop so open SSE streams never stall
|
||||
cmd = await asyncio.to_thread(validate_view_command, cmd)
|
||||
_view_seq += 1
|
||||
cmd["seq"] = _view_seq
|
||||
cmd["ts"] = time.time()
|
||||
_view_command = cmd
|
||||
for queue in _view_clients:
|
||||
if queue.full():
|
||||
queue.get_nowait()
|
||||
queue.put_nowait(cmd)
|
||||
if not _view_clients:
|
||||
# stored for late-joining tabs, but the agent must not pretend it pointed
|
||||
# at something a human saw
|
||||
raise HTTPException(
|
||||
409, {"error": "no dashboard tab is connected", "url": _view_url, "stored": True, "seq": _view_seq}
|
||||
)
|
||||
return {"ok": True, "seq": _view_seq, "clients": len(_view_clients), "line": cmd.get("line")}
|
||||
|
||||
|
||||
@app.get("/api/view/events")
|
||||
async def view_events() -> "StreamingResponse":
|
||||
queue: asyncio.Queue = asyncio.Queue(maxsize=MAX_VIEW_QUEUE)
|
||||
|
||||
async def stream():
|
||||
_view_clients.add(queue)
|
||||
try:
|
||||
yield "retry: 2000\n\n"
|
||||
if _view_command is not None:
|
||||
# catch-up for a late tab: flagged so the client can decide whether
|
||||
# a stored command is still worth replaying
|
||||
yield _view_event({**_view_command, "replay": True})
|
||||
while True:
|
||||
try:
|
||||
yield _view_event(await asyncio.wait_for(queue.get(), timeout=15))
|
||||
except asyncio.TimeoutError:
|
||||
yield ": ping\n\n" # flushes dead connections out of the client count
|
||||
finally:
|
||||
_view_clients.discard(queue)
|
||||
|
||||
return StreamingResponse(
|
||||
stream(),
|
||||
media_type="text/event-stream",
|
||||
headers={"cache-control": "no-cache", "x-accel-buffering": "no"},
|
||||
)
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------- static
|
||||
|
||||
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
||||
@@ -913,6 +1182,9 @@ def free_port(host: str, start: int) -> int:
|
||||
|
||||
for port in range(start, start + 100):
|
||||
with socket.socket() as sock:
|
||||
# match uvicorn's own listener: without SO_REUSEADDR a just-killed
|
||||
# dashboard's TIME_WAIT sockets push restarts onto the next port
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
try:
|
||||
sock.bind((host, port))
|
||||
except OSError:
|
||||
@@ -946,7 +1218,7 @@ def release_daemon() -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
global output_dirs, isolated
|
||||
global output_dirs, isolated, _view_url
|
||||
parser = argparse.ArgumentParser(description="prime-rl run dashboard")
|
||||
parser.add_argument("output_dirs", nargs="*", default=[default_output_dir()], type=Path, metavar="output_dir")
|
||||
parser.add_argument("--port", type=int, default=7788)
|
||||
@@ -974,6 +1246,7 @@ def main() -> None:
|
||||
print(f"port {args.port} is taken - serving on {port}", file=sys.stderr)
|
||||
args.port = port
|
||||
url = f"http://localhost:{args.port}"
|
||||
_view_url = url
|
||||
# first non-isolated instance owns discovery; extras and --isolated still serve
|
||||
claimed = False if isolated else claim_daemon(url)
|
||||
live = None
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* prime-rl dashboard frontend: metrics (wandb-overview replica), merged logs, trace viewer.
|
||||
/* prime-rl dashboard frontend: metrics, configs, merged logs, traces, and cited reports.
|
||||
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. */
|
||||
|
||||
const $ = (sel) => document.querySelector(sel);
|
||||
@@ -47,6 +47,8 @@ const state = {
|
||||
order: (prefs.traceSort ?? "line:asc").split(":")[1],
|
||||
viewMode: prefs.tokenSignal === "rendered" ? "rendered" : (prefs.traceViewMode ?? "messages"),
|
||||
},
|
||||
report: { loaded: false, files: [], file: null, wanted: null, text: null, mtime: null, citations: {}, order: [], verify: new Map() },
|
||||
follow: prefs.follow ?? true,
|
||||
};
|
||||
|
||||
function fmtNum(v) {
|
||||
@@ -172,7 +174,7 @@ function applyRunTypeControls() {
|
||||
$("#tm-subset-row").hidden = isEval;
|
||||
}
|
||||
|
||||
async function selectRun(name) {
|
||||
async function selectRun(name, deferTab = false) {
|
||||
if (!name) return;
|
||||
state.run = name;
|
||||
state.compare = { runs: [], data: new Map() };
|
||||
@@ -193,11 +195,15 @@ async function selectRun(name) {
|
||||
loaded: false, fetching: false, steps: [], step: null, env: "", episodes: [], etag: null,
|
||||
kind: "train", subset: state.traces.preferred,
|
||||
};
|
||||
state.report = {
|
||||
...state.report,
|
||||
loaded: false, files: [], file: null, text: null, mtime: null, citations: {}, order: [], verify: new Map(),
|
||||
};
|
||||
applyRunTypeControls();
|
||||
renderOverview();
|
||||
renderCompareMenu();
|
||||
updateHash();
|
||||
await activateTab(state.tab, true);
|
||||
if (!deferTab) await activateTab(state.tab, true);
|
||||
}
|
||||
|
||||
function fmtDuration(secs) {
|
||||
@@ -293,7 +299,9 @@ function renderOverview() {
|
||||
}
|
||||
|
||||
function updateHash() {
|
||||
location.hash = `#run=${encodeURIComponent(state.run || "")}&tab=${state.tab}`;
|
||||
const parts = [`run=${encodeURIComponent(state.run || "")}`, `tab=${state.tab}`];
|
||||
if (state.tab === "report" && state.report.file) parts.push(`report=${encodeURIComponent(state.report.file)}`);
|
||||
location.hash = `#${parts.join("&")}`;
|
||||
}
|
||||
|
||||
async function activateTab(tab, force = false) {
|
||||
@@ -312,6 +320,10 @@ async function activateTab(tab, force = false) {
|
||||
if (!state.traces.loaded) await initTraces();
|
||||
else if (state.live) await refreshTraces();
|
||||
}
|
||||
if (tab === "report") {
|
||||
if (!state.report.loaded) await initReport();
|
||||
else if (state.live) await refreshReport();
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- metrics */
|
||||
@@ -2081,7 +2093,7 @@ async function ensureTokens() {
|
||||
currentEpisode = episode;
|
||||
}
|
||||
|
||||
async function openEpisode(line) {
|
||||
async function openEpisode(line, target = {}) {
|
||||
const requestVersion = ++episodeOpenVersion;
|
||||
episodeEnrichmentVersion++;
|
||||
$("#trace-modal").hidden = false;
|
||||
@@ -2099,8 +2111,8 @@ async function openEpisode(line) {
|
||||
episode._hasTokens = withTokens;
|
||||
episode._hasRendered = withRendered;
|
||||
currentEpisode = episode;
|
||||
currentTraceIdx = 0;
|
||||
currentBranchIdx = 0;
|
||||
currentTraceIdx = target.trace ?? 0;
|
||||
currentBranchIdx = target.branch ?? 0;
|
||||
renderEpisode();
|
||||
await ensureTokens();
|
||||
if (line === currentLine && requestVersion === episodeOpenVersion) renderEpisode();
|
||||
@@ -2111,8 +2123,10 @@ function closeDrawer() {
|
||||
episodeEnrichmentVersion++;
|
||||
$("#trace-modal").hidden = true;
|
||||
$("#drawer-backdrop").hidden = true;
|
||||
$("#tm-back").hidden = true;
|
||||
currentEpisode = null;
|
||||
currentLine = null;
|
||||
pendingHighlight = null;
|
||||
}
|
||||
|
||||
function traceBranches(trace) {
|
||||
@@ -2148,6 +2162,10 @@ function messageText(message) {
|
||||
return content == null ? "" : JSON.stringify(content);
|
||||
}
|
||||
|
||||
function reasoningText(content) {
|
||||
return typeof content === "string" ? content : content == null ? "" : JSON.stringify(content, null, 2);
|
||||
}
|
||||
|
||||
/* logprobs may cover only masked positions; map token index -> logprob index */
|
||||
function alignedSignal(node, values) {
|
||||
const n = (node.token_ids || []).length;
|
||||
@@ -2218,12 +2236,15 @@ function toolCallHtml(toolCall) {
|
||||
return `<div class="tool-call">${esc(name)}(${esc(args)})</div>`;
|
||||
}
|
||||
|
||||
function reasoningBlock(content) {
|
||||
const text = typeof content === "string" ? content : JSON.stringify(content, null, 2);
|
||||
function reasoningBlock(content, marks = null) {
|
||||
const text = reasoningText(content);
|
||||
// a highlight whose quote lives in the reasoning marks it and opens the block
|
||||
const marked = (marks || []).some((h) => h.quote && findQuote(text, h.quote, h.prefix, h.suffix));
|
||||
return (
|
||||
`<details class="sub"><summary><span class="sub-name">Reasoning</span>` +
|
||||
`<details class="sub"${marked ? " open" : ""}><summary><span class="sub-name">Reasoning</span>` +
|
||||
`<span class="entry-preview">${preview(text, 140)}</span>` +
|
||||
`<span class="entry-chev">›</span></summary><div class="entry-body">${esc(text)}</div></details>`
|
||||
`<span class="entry-chev">›</span></summary>` +
|
||||
`<div class="entry-body">${marked ? quoteMarkedHtml(text, marks) : esc(text)}</div></details>`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2367,10 +2388,27 @@ function renderMessages(ep, trace, branches) {
|
||||
for (const node of trace.nodes || [])
|
||||
for (const a of node.advantages || []) maxAbsAdv = Math.max(maxAbsAdv, Math.abs(a));
|
||||
const callsByNode = new Map((trace.calls || []).map((c) => [c.node, c]));
|
||||
// agent highlights (sticky until the next view command or drawer close)
|
||||
const hl =
|
||||
pendingHighlight &&
|
||||
pendingHighlight.run === state.run &&
|
||||
pendingHighlight.step === state.traces.step &&
|
||||
pendingHighlight.kind === state.traces.kind &&
|
||||
pendingHighlight.subset === state.traces.subset &&
|
||||
pendingHighlight.line === currentLine &&
|
||||
pendingHighlight.trace === currentTraceIdx
|
||||
? pendingHighlight
|
||||
: null;
|
||||
const hlByNode = new Map();
|
||||
for (const h of hl?.highlights || []) {
|
||||
if (!hlByNode.has(h.node)) hlByNode.set(h.node, []);
|
||||
hlByNode.get(h.node).push(h);
|
||||
}
|
||||
const entryHtml = (idx, i) => {
|
||||
const node = trace.nodes[idx];
|
||||
const role = node.message?.role ?? "?";
|
||||
const call = callsByNode.get(idx);
|
||||
const marks = hlByNode.get(idx) || [];
|
||||
const chips = [];
|
||||
if (concatenated && node.parent != null && node.parent !== idx - 1) chips.push(`↳ branches from ${node.parent + 1}`);
|
||||
if (node.sampled) chips.push("sampled");
|
||||
@@ -2378,13 +2416,22 @@ function renderMessages(ep, trace, branches) {
|
||||
if (call?.usage) chips.push(`${call.usage.prompt_tokens ?? "?"}→${call.usage.completion_tokens ?? "?"} tok`);
|
||||
else if (node.token_ids?.length) chips.push(`${node.token_ids.length} tok`);
|
||||
const text = messageText(node.message);
|
||||
const body = signal && node.token_ids?.length ? renderTokenNode(node, signal, maxAbsAdv) : esc(text);
|
||||
const subs = [];
|
||||
const contentMarks = marks.filter((h) => !h.field || h.field === "content");
|
||||
const contentMarked = contentMarks.some((h) => h.quote && findQuote(text, h.quote, h.prefix, h.suffix));
|
||||
const reasoningMarks = marks.filter((h) => !h.field || h.field === "reasoning");
|
||||
const reasoning = node.message?.reasoning_content ?? node.message?.reasoning;
|
||||
if (reasoning) subs.push(reasoningBlock(reasoning));
|
||||
const reasoningMarked = reasoningMarks.some(
|
||||
(h) => h.quote && findQuote(reasoningText(reasoning), h.quote, h.prefix, h.suffix)
|
||||
);
|
||||
const marked = contentMarked || reasoningMarked;
|
||||
const body = contentMarked
|
||||
? quoteMarkedHtml(text, contentMarks)
|
||||
: signal && node.token_ids?.length ? renderTokenNode(node, signal, maxAbsAdv) : esc(text);
|
||||
const subs = [];
|
||||
if (reasoning) subs.push(reasoningBlock(reasoning, reasoningMarks));
|
||||
const toolCalls = (node.message?.tool_calls || []).map(toolCallHtml);
|
||||
const messageHtml =
|
||||
`<details class="entry ${esc(role)}"${role === "system" ? "" : " open"}>` +
|
||||
`<details class="entry ${esc(role)}${marked ? " hl-entry" : ""}"${role === "system" && !marked ? "" : " open"}>` +
|
||||
`<summary><span class="entry-num">${String(i + 1).padStart(2, "0")}</span>` +
|
||||
`<span class="entry-role">${esc(role)}</span>` +
|
||||
`<span class="entry-preview">${preview(text, 180)}</span>` +
|
||||
@@ -2398,14 +2445,28 @@ function renderMessages(ep, trace, branches) {
|
||||
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
|
||||
// hundreds of turns paints the first screen immediately; a highlight past the
|
||||
// first chunk forces enough entries into the DOM to scroll to
|
||||
const CHUNK = 30;
|
||||
let rendered = Math.min(path.length, CHUNK);
|
||||
const lastMark = Math.max(-1, ...[...hlByNode.keys()].map((n) => path.indexOf(n)));
|
||||
let rendered = Math.min(path.length, Math.max(CHUNK, lastMark + 3));
|
||||
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>` : "") +
|
||||
errorsHtml;
|
||||
if (hl && !hl.scrolled) {
|
||||
const first = container.querySelector(".hl-entry");
|
||||
// consume the one-shot flag only when the scroll lands: openEpisode renders
|
||||
// twice (enrichment re-render), which detaches the first render's node
|
||||
// before its scheduled scroll fires
|
||||
if (first)
|
||||
requestAnimationFrame(() => {
|
||||
if (!first.isConnected) return;
|
||||
hl.scrolled = true;
|
||||
first.scrollIntoView({ block: "start", behavior: "smooth" });
|
||||
});
|
||||
}
|
||||
if (rendered < path.length) {
|
||||
const sentinel = container.querySelector("#tm-more");
|
||||
entriesObserver = new IntersectionObserver((hits) => {
|
||||
@@ -2573,6 +2634,584 @@ function renderEpisode() {
|
||||
renderMeta(ep, trace, branches);
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- report */
|
||||
/* Markdown from <run>/reports/*.md. Prose is free; claims are
|
||||
addressed: [^id] markers reference JSON citation lines, each one a trace
|
||||
address plus a verbatim quote the frontend re-checks against the files. */
|
||||
|
||||
async function initReport() {
|
||||
state.report.loaded = true;
|
||||
await refreshReport();
|
||||
}
|
||||
|
||||
async function refreshReport() {
|
||||
const rep = state.report;
|
||||
const data = await api(`/api/runs/${encodeURIComponent(state.run)}/reports`);
|
||||
if (state.report !== rep) return;
|
||||
rep.files = data.reports;
|
||||
if (!rep.files.length) {
|
||||
rep.file = null;
|
||||
rep.text = null;
|
||||
renderReportSelect();
|
||||
$("#report-verify").textContent = "";
|
||||
$("#report-status").textContent = "";
|
||||
$("#report-body").innerHTML = emptyState("no reports yet", "markdown files in <run>/reports/ appear here");
|
||||
return;
|
||||
}
|
||||
const wanted = rep.wanted && rep.files.find((f) => f.file === rep.wanted)?.file;
|
||||
rep.wanted = null;
|
||||
const target = wanted || (rep.file && rep.files.find((f) => f.file === rep.file)?.file) || rep.files[0].file;
|
||||
const entry = rep.files.find((f) => f.file === target);
|
||||
const changed = target !== rep.file || entry.mtime !== rep.mtime;
|
||||
rep.file = target;
|
||||
renderReportSelect();
|
||||
if (changed) await loadReport();
|
||||
}
|
||||
|
||||
async function loadReport() {
|
||||
const rep = state.report;
|
||||
const file = rep.file;
|
||||
const data = await api(`/api/runs/${encodeURIComponent(state.run)}/report?file=${encodeURIComponent(file)}`);
|
||||
if (state.report !== rep || rep.file !== file) return;
|
||||
rep.text = data.text;
|
||||
rep.mtime = data.mtime;
|
||||
renderReport();
|
||||
if (state.tab === "report") updateHash();
|
||||
}
|
||||
|
||||
function renderReportSelect() {
|
||||
const rep = state.report;
|
||||
const sel = $("#report-select");
|
||||
sel.disabled = !rep.files.length;
|
||||
sel.innerHTML = rep.files.length
|
||||
? rep.files
|
||||
.map((f) => `<option value="${esc(f.file)}" ${f.file === rep.file ? "selected" : ""}>${esc(f.title || f.file)}</option>`)
|
||||
.join("")
|
||||
: `<option>no reports</option>`;
|
||||
syncDressedSelects();
|
||||
}
|
||||
|
||||
function renderReport() {
|
||||
const rep = state.report;
|
||||
const { title, body, citations } = parseReport(rep.text || "");
|
||||
rep.citations = citations;
|
||||
rep.verify = new Map();
|
||||
rep.lookup = { summaries: new Map(), episodes: new Map() };
|
||||
const ctx = { citations, order: [] };
|
||||
const html = mdToHtml(body, ctx);
|
||||
rep.order = ctx.order;
|
||||
$("#report-body").innerHTML =
|
||||
(title ? `<h1 class="report-title">${esc(title)}</h1>` : "") +
|
||||
(html || emptyState("empty report", "this report has no content yet"));
|
||||
const entry = rep.files.find((f) => f.file === rep.file);
|
||||
$("#report-status").textContent = entry ? `${rep.file} · ${fmtAgo(entry.mtime)}` : (rep.file ?? "");
|
||||
$("#report-verify").textContent = rep.order.length ? "verifying citations…" : "";
|
||||
verifyCitations();
|
||||
}
|
||||
|
||||
/* frontmatter title + [^id]: {json} citation definitions, stripped from the body */
|
||||
function parseReport(text) {
|
||||
let title = null;
|
||||
let body = text;
|
||||
const fm = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
|
||||
if (fm) {
|
||||
body = text.slice(fm[0].length);
|
||||
const t = /^title:\s*(.+)$/m.exec(fm[1]);
|
||||
if (t) title = t[1].trim().replace(/^["']|["']$/g, "");
|
||||
}
|
||||
const citations = {};
|
||||
body = body.replace(/^\[\^([\w-]+)\]:[ \t]*(\{.*\})[ \t]*$/gm, (_, id, json) => {
|
||||
try {
|
||||
citations[id] = JSON.parse(json);
|
||||
} catch {
|
||||
citations[id] = { _invalid: json };
|
||||
}
|
||||
return "";
|
||||
});
|
||||
return { title, body, citations };
|
||||
}
|
||||
|
||||
/* markdown subset renderer (headings, lists, tables, fences, quotes, inline
|
||||
marks) over fully escaped text — reports never inject markup */
|
||||
function mdToHtml(src, ctx) {
|
||||
const lines = src.split("\n");
|
||||
const out = [];
|
||||
let para = [];
|
||||
const flush = () => {
|
||||
if (para.length) out.push(`<p>${renderInline(para.join(" "), ctx)}</p>`);
|
||||
para = [];
|
||||
};
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
const fence = /^(```|~~~)\s*(\S*)\s*$/.exec(line);
|
||||
if (fence) {
|
||||
flush();
|
||||
const buf = [];
|
||||
for (i++; i < lines.length && !lines[i].startsWith(fence[1]); i++) buf.push(lines[i]);
|
||||
out.push(`<pre class="md-code"${fence[2] ? ` data-lang="${esc(fence[2])}"` : ""}><code>${esc(buf.join("\n"))}</code></pre>`);
|
||||
continue;
|
||||
}
|
||||
const heading = /^(#{1,6})\s+(.*)$/.exec(line);
|
||||
if (heading) {
|
||||
flush();
|
||||
const level = heading[1].length;
|
||||
out.push(`<h${level}>${renderInline(heading[2], ctx)}</h${level}>`);
|
||||
continue;
|
||||
}
|
||||
if (/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(line) && !para.length) {
|
||||
out.push("<hr>");
|
||||
continue;
|
||||
}
|
||||
if (/^\s*>/.test(line)) {
|
||||
flush();
|
||||
const buf = [];
|
||||
for (; i < lines.length && /^\s*>/.test(lines[i]); i++) buf.push(lines[i].replace(/^\s*>\s?/, ""));
|
||||
i--;
|
||||
out.push(`<blockquote>${mdToHtml(buf.join("\n"), ctx)}</blockquote>`);
|
||||
continue;
|
||||
}
|
||||
if (line.includes("|") && /^\s*\|?[\s:|-]+\|?\s*$/.test(lines[i + 1] || "") && (lines[i + 1] || "").includes("-")) {
|
||||
flush();
|
||||
const cells = (row) => row.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim());
|
||||
const head = cells(line);
|
||||
const rows = [];
|
||||
for (i += 2; i < lines.length && lines[i].includes("|"); i++) rows.push(cells(lines[i]));
|
||||
i--;
|
||||
out.push(
|
||||
`<div class="md-table-wrap"><table class="md-table"><thead><tr>` +
|
||||
head.map((h) => `<th>${renderInline(h, ctx)}</th>`).join("") +
|
||||
`</tr></thead><tbody>` +
|
||||
rows.map((r) => `<tr>${head.map((_, j) => `<td>${renderInline(r[j] ?? "", ctx)}</td>`).join("")}</tr>`).join("") +
|
||||
`</tbody></table></div>`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const li = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(line);
|
||||
if (li) {
|
||||
flush();
|
||||
const ordered = /\d/.test(li[2][0]);
|
||||
const items = [];
|
||||
for (; i < lines.length; i++) {
|
||||
const m = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(lines[i]);
|
||||
if (!m) {
|
||||
// indented continuation lines fold into the previous item
|
||||
if (/^\s{2,}\S/.test(lines[i]) && items.length) {
|
||||
items[items.length - 1].text += " " + lines[i].trim();
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (m[1].length >= 2 && items.length) (items[items.length - 1].subs ??= []).push(m[3]);
|
||||
else items.push({ text: m[3] });
|
||||
}
|
||||
i--;
|
||||
const tag = ordered ? "ol" : "ul";
|
||||
out.push(
|
||||
`<${tag}>` +
|
||||
items
|
||||
.map(
|
||||
(it) =>
|
||||
`<li>${renderInline(it.text, ctx)}` +
|
||||
(it.subs ? `<ul>${it.subs.map((s) => `<li>${renderInline(s, ctx)}</li>`).join("")}</ul>` : "") +
|
||||
`</li>`
|
||||
)
|
||||
.join("") +
|
||||
`</${tag}>`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (!line.trim()) {
|
||||
flush();
|
||||
continue;
|
||||
}
|
||||
para.push(line.trim());
|
||||
}
|
||||
flush();
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
function renderInline(text, ctx) {
|
||||
let s = esc(text);
|
||||
const codes = [];
|
||||
s = s.replace(/`([^`]+)`/g, (_, c) => {
|
||||
codes.push(c);
|
||||
return `\x00${codes.length - 1}\x00`;
|
||||
});
|
||||
s = s.replace(/\[\^([\w-]+)\]/g, (_, id) => citeChipHtml(id, ctx));
|
||||
s = s.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+|#[^)\s]*)\)/g, `<a href="$2" target="_blank" rel="noopener">$1</a>`);
|
||||
s = s.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
|
||||
s = s.replace(/(^|[\s(])\*([^*\n]+)\*/g, "$1<em>$2</em>");
|
||||
s = s.replace(/(^|[\s(])_([^_\n]+)_/g, "$1<em>$2</em>");
|
||||
s = s.replace(/\x00(\d+)\x00/g, (_, i) => `<code>${codes[+i]}</code>`);
|
||||
return s;
|
||||
}
|
||||
|
||||
function citeChipHtml(id, ctx) {
|
||||
let n = ctx.order.indexOf(id) + 1;
|
||||
if (!n) n = ctx.order.push(id);
|
||||
if (!ctx.citations[id])
|
||||
return `<sup class="cite-chip missing" data-cite="${esc(id)}" title="[^${esc(id)}] has no citation definition">?</sup>`;
|
||||
return `<sup class="cite-chip" data-cite="${esc(id)}" title="citation ${esc(id)}">${n}</sup>`;
|
||||
}
|
||||
|
||||
/* Whitespace-insensitive exact quote search; returns [start, end) ranges in
|
||||
the original text so highlights survive reflowed whitespace. When the quote
|
||||
repeats inside the text, optional prefix/suffix (verbatim adjacent text) pick
|
||||
the right occurrence. */
|
||||
function findQuotes(text, quote, prefix = "", suffix = "") {
|
||||
const map = [];
|
||||
let normed = "";
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ws = /\s/.test(text[i]);
|
||||
if (ws && (!normed || normed.endsWith(" "))) continue;
|
||||
normed += ws ? " " : text[i];
|
||||
map.push(i);
|
||||
}
|
||||
const norm = (s) => String(s ?? "").replace(/\s+/g, " ").trim();
|
||||
const q = norm(quote);
|
||||
if (!q) return [];
|
||||
const pre = norm(prefix);
|
||||
const post = norm(suffix);
|
||||
const ranges = [];
|
||||
for (let at = normed.indexOf(q); at >= 0; at = normed.indexOf(q, at + 1)) {
|
||||
if (pre && !normed.slice(0, at).trimEnd().endsWith(pre)) continue;
|
||||
if (post && !normed.slice(at + q.length).trimStart().startsWith(post)) continue;
|
||||
ranges.push([map[at], map[at + q.length - 1] + 1]);
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
|
||||
const findQuote = (...args) => findQuotes(...args)[0] || null;
|
||||
|
||||
function quoteMarkedHtml(text, marks) {
|
||||
const ranges = [];
|
||||
for (const h of marks) {
|
||||
const r = h.quote ? findQuote(text, h.quote, h.prefix, h.suffix) : null;
|
||||
if (r) ranges.push([...r, h.reason]);
|
||||
}
|
||||
if (!ranges.length) return esc(text);
|
||||
ranges.sort((a, b) => a[0] - b[0]);
|
||||
const merged = [];
|
||||
for (const r of ranges) {
|
||||
const last = merged[merged.length - 1];
|
||||
if (last && r[0] <= last[1]) last[1] = Math.max(last[1], r[1]);
|
||||
else merged.push([...r]);
|
||||
}
|
||||
let out = "";
|
||||
let pos = 0;
|
||||
for (const [s, e, tip] of merged) {
|
||||
out += esc(text.slice(pos, s)) + `<mark class="hl-quote"${tip ? ` data-tip="${esc(tip)}"` : ""}>${esc(text.slice(s, e))}</mark>`;
|
||||
pos = e;
|
||||
}
|
||||
return out + esc(text.slice(pos));
|
||||
}
|
||||
|
||||
/* Citation resolution uses the same read endpoints as the trace viewer. Lookup
|
||||
promises live only for the current report render: duplicate references share
|
||||
work, while a changed report or rewritten trace never inherits stale evidence. */
|
||||
const CITATION_KEYS = new Set([
|
||||
"run", "step", "kind", "subset", "episode", "trace", "branch",
|
||||
"node", "field", "quote", "prefix", "suffix", "note",
|
||||
]);
|
||||
|
||||
async function resolveCitation(c, cache) {
|
||||
if (!c) return { matched: false, reason: "missing citation definition" };
|
||||
if (typeof c !== "object" || c._invalid) return { matched: false, reason: "invalid citation JSON" };
|
||||
const unknown = Object.keys(c).filter((key) => !CITATION_KEYS.has(key));
|
||||
if (unknown.length) return { matched: false, reason: `unknown fields: ${unknown.join(", ")}` };
|
||||
const run = c.run || state.run;
|
||||
if (typeof run !== "string" || !run) return { matched: false, reason: "citation needs a run" };
|
||||
if (!Number.isInteger(c.step) || !["train", "eval"].includes(c.kind) || !["all", "effective"].includes(c.subset))
|
||||
return { matched: false, reason: "citation needs a valid step, kind, and subset" };
|
||||
for (const key of ["trace", "node"])
|
||||
if (c[key] != null && (!Number.isInteger(c[key]) || c[key] < 0)) return { matched: false, reason: `${key} must be a non-negative integer` };
|
||||
if (c.branch != null && (!Number.isInteger(c.branch) || c.branch < -1))
|
||||
return { matched: false, reason: "branch must be an integer >= -1" };
|
||||
if (c.field != null && !["content", "reasoning"].includes(c.field))
|
||||
return { matched: false, reason: "field must be content or reasoning" };
|
||||
if (typeof c.episode !== "string" || !c.episode) return { matched: false, reason: "citation needs an episode id" };
|
||||
if (typeof c.quote !== "string" || !c.quote.trim()) return { matched: false, reason: "citation needs a verbatim quote" };
|
||||
if (typeof c.note !== "string" || !c.note.trim()) return { matched: false, reason: "citation needs a note" };
|
||||
for (const key of ["prefix", "suffix"])
|
||||
if (c[key] != null && typeof c[key] !== "string") return { matched: false, reason: `${key} must be a string` };
|
||||
const base = `/api/runs/${encodeURIComponent(run)}/rollouts/${c.step}/${c.kind}/${c.subset}`;
|
||||
const summaryKey = `${base}?episode=${encodeURIComponent(c.episode)}&limit=2`;
|
||||
if (!cache.summaries.has(summaryKey))
|
||||
cache.summaries.set(
|
||||
summaryKey,
|
||||
api(summaryKey).catch((err) => {
|
||||
cache.summaries.delete(summaryKey);
|
||||
throw err;
|
||||
})
|
||||
);
|
||||
const list = await cache.summaries.get(summaryKey);
|
||||
if (!list.total) return { matched: false, reason: `episode ${c.episode} not found` };
|
||||
if (list.total > 1) return { matched: false, reason: `episode ${c.episode} is not unique` };
|
||||
const line = list.episodes[0].line;
|
||||
const epKey = `${base}/${line}`;
|
||||
if (!cache.episodes.has(epKey))
|
||||
cache.episodes.set(
|
||||
epKey,
|
||||
api(epKey).catch((err) => {
|
||||
cache.episodes.delete(epKey);
|
||||
throw err;
|
||||
})
|
||||
);
|
||||
const ep = await cache.episodes.get(epKey);
|
||||
const trace = (ep.traces || [])[c.trace ?? 0];
|
||||
if (!trace) return { matched: false, reason: "trace not found", line };
|
||||
let nodes = c.node != null ? [[c.node, (trace.nodes || [])[c.node]]] : (trace.nodes || []).map((n, i) => [i, n]);
|
||||
nodes = nodes.filter(([, n]) => n);
|
||||
if (c.branch != null && c.branch !== -1) {
|
||||
const branch = traceBranches(trace)[c.branch];
|
||||
if (!branch) return { matched: false, reason: "branch not found", line };
|
||||
nodes = nodes.filter(([i]) => branch.includes(i));
|
||||
}
|
||||
if (!nodes.length) return { matched: false, reason: `node ${c.node} not found`, line };
|
||||
const matches = [];
|
||||
for (const [i, node] of nodes) {
|
||||
const fields = [
|
||||
["content", messageText(node.message)],
|
||||
["reasoning", reasoningText(node.message?.reasoning_content ?? node.message?.reasoning)],
|
||||
].filter(([field]) => !c.field || c.field === field);
|
||||
for (const [field, text] of fields) {
|
||||
for (const _ of findQuotes(text, c.quote, c.prefix, c.suffix)) matches.push({ nodeIdx: i, field });
|
||||
}
|
||||
}
|
||||
if (!matches.length)
|
||||
return { matched: false, reason: c.node != null ? "quote not found in node" : "quote not found in any node", line };
|
||||
if (matches.length > 1) return { matched: false, reason: "quote is ambiguous — add node and prefix or suffix", line };
|
||||
return { matched: true, line, ...matches[0] };
|
||||
}
|
||||
|
||||
function paintCitation(id, res) {
|
||||
document.querySelectorAll(`.cite-chip[data-cite="${CSS.escape(id)}"]`).forEach((el) => {
|
||||
el.classList.toggle("ok", !!res.matched);
|
||||
el.classList.toggle("bad", !res.matched);
|
||||
el.title = res.matched ? "quote verified against the trace" : `⚠ ${res.reason || "quote not found"}`;
|
||||
});
|
||||
}
|
||||
|
||||
async function verifyCitations() {
|
||||
const rep = state.report;
|
||||
const citations = rep.citations;
|
||||
const cache = rep.lookup;
|
||||
const ids = rep.order;
|
||||
if (!ids.length) return;
|
||||
let verified = 0;
|
||||
let broken = 0;
|
||||
for (const id of ids) {
|
||||
let res;
|
||||
try {
|
||||
res = await resolveCitation(citations[id], cache);
|
||||
} catch (err) {
|
||||
res = { matched: false, reason: String(err) };
|
||||
}
|
||||
if (state.report !== rep || rep.lookup !== cache) return;
|
||||
rep.verify.set(id, res);
|
||||
if (res.matched) verified++;
|
||||
else broken++;
|
||||
paintCitation(id, res);
|
||||
$("#report-verify").textContent = `${verified}/${ids.length} verified${broken ? ` · ${broken} broken` : ""}`;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ citation click */
|
||||
/* a chip is a link: clicking jumps straight to the trace with the quote
|
||||
highlighted; the citation's note surfaces on hover over the mark */
|
||||
|
||||
async function openCitation(id) {
|
||||
const c = state.report.citations[id];
|
||||
const rep = state.report;
|
||||
const cache = rep.lookup;
|
||||
let res = rep.verify.get(id);
|
||||
if (!res) {
|
||||
try {
|
||||
res = await resolveCitation(c, cache);
|
||||
} catch (err) {
|
||||
res = { matched: false, reason: String(err) };
|
||||
}
|
||||
if (state.report !== rep || rep.lookup !== cache) return;
|
||||
rep.verify.set(id, res);
|
||||
paintCitation(id, res);
|
||||
}
|
||||
if (!res.matched) return toastMsg(`[^${esc(id)}] is broken: ${esc(res.reason || "quote not found")}`);
|
||||
await applyViewCommand({
|
||||
run: c.run || state.run,
|
||||
tab: "traces",
|
||||
step: c.step,
|
||||
kind: c.kind,
|
||||
subset: c.subset,
|
||||
episode: c.episode,
|
||||
line: res.line,
|
||||
trace: c.trace,
|
||||
branch: c.branch ?? -1,
|
||||
highlight: [{ node: res.nodeIdx, field: res.field, quote: c.quote, prefix: c.prefix, suffix: c.suffix, reason: c.note }],
|
||||
});
|
||||
$("#tm-back").hidden = $("#trace-modal").hidden; // way back to the report
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------- view command */
|
||||
/* SSE from /api/view/events: a local agent POSTs an on-disk address, every
|
||||
connected tab navigates there through the same functions clicks use. */
|
||||
|
||||
let pendingHighlight = null;
|
||||
let lastViewSeq = 0;
|
||||
let hadHashRun = false;
|
||||
let applyingView = false;
|
||||
const viewCommandQueue = [];
|
||||
let viewDrain = Promise.resolve();
|
||||
const MAX_PENDING_VIEW_COMMANDS = 32;
|
||||
|
||||
function primeTraceCommand(cmd) {
|
||||
const traces = state.traces;
|
||||
if (cmd.step != null) traces.step = cmd.step;
|
||||
if (cmd.kind) traces.kind = cmd.kind;
|
||||
if (cmd.subset) {
|
||||
traces.subset = cmd.subset;
|
||||
traces.preferred = cmd.subset;
|
||||
}
|
||||
traces.env = "";
|
||||
traces.errorsOnly = false;
|
||||
if (cmd.highlight?.length) traces.viewMode = "messages";
|
||||
pendingHighlight = null;
|
||||
}
|
||||
|
||||
async function applyOneViewCommand(cmd) {
|
||||
let runChanged = false;
|
||||
if (cmd.run && cmd.run !== state.run) {
|
||||
if (!state.runs.some((r) => r.name === cmd.run)) await loadRuns();
|
||||
if (!state.runs.some((r) => r.name === cmd.run)) return toastMsg(`unknown run ${esc(cmd.run)}`);
|
||||
await selectRun(cmd.run, true);
|
||||
runChanged = true;
|
||||
}
|
||||
if (cmd.report) {
|
||||
state.report.wanted = cmd.report;
|
||||
state.report.loaded = false;
|
||||
}
|
||||
const traceCommand = ["step", "kind", "subset", "episode", "line", "trace", "branch", "highlight"].some(
|
||||
(key) => cmd[key] != null
|
||||
);
|
||||
if (traceCommand) primeTraceCommand(cmd); // target the requested file before the traces tab initializes
|
||||
if (cmd.tab && (cmd.tab !== state.tab || cmd.report || runChanged)) await activateTab(cmd.tab, true);
|
||||
else if (cmd.report && state.tab === "report") await initReport();
|
||||
else if (runChanged) await activateTab(state.tab, true);
|
||||
if (traceCommand) await applyTraceCommand(cmd);
|
||||
}
|
||||
|
||||
async function drainViewCommands() {
|
||||
while (viewCommandQueue.length) {
|
||||
const cmd = viewCommandQueue.shift();
|
||||
try {
|
||||
await applyOneViewCommand(cmd);
|
||||
} catch (err) {
|
||||
console.warn("view command failed", err);
|
||||
}
|
||||
}
|
||||
applyingView = false;
|
||||
}
|
||||
|
||||
function applyViewCommand(cmd) {
|
||||
viewCommandQueue.push(cmd);
|
||||
if (viewCommandQueue.length > MAX_PENDING_VIEW_COMMANDS) viewCommandQueue.shift();
|
||||
if (!applyingView) {
|
||||
applyingView = true;
|
||||
viewDrain = drainViewCommands();
|
||||
}
|
||||
return viewDrain;
|
||||
}
|
||||
|
||||
async function applyTraceCommand(cmd) {
|
||||
const traces = state.traces;
|
||||
if (!traces.loaded) await initTraces();
|
||||
adjustKindSubset();
|
||||
renderStepControl();
|
||||
await loadEpisodes();
|
||||
if (cmd.line == null && cmd.episode == null) return;
|
||||
const episodes = traces.episodes || [];
|
||||
const target = cmd.episode != null ? episodes.find((e) => e.id === cmd.episode) : episodes.find((e) => e.line === cmd.line);
|
||||
const line = target?.line ?? cmd.line;
|
||||
if (line == null) return toastMsg(`episode ${esc(cmd.episode ?? "?")} not found at this address`);
|
||||
pendingHighlight = {
|
||||
run: state.run,
|
||||
step: traces.step,
|
||||
kind: traces.kind,
|
||||
subset: traces.subset,
|
||||
line,
|
||||
trace: cmd.trace ?? 0,
|
||||
highlights: (cmd.highlight || []).filter((h) => h && h.node != null),
|
||||
scrolled: false,
|
||||
};
|
||||
await openEpisode(line, { trace: cmd.trace, branch: cmd.branch });
|
||||
}
|
||||
|
||||
let toastEl = null;
|
||||
let toastTimer = 0;
|
||||
|
||||
function toastMsg(html, ms = 6000) {
|
||||
if (!toastEl) {
|
||||
toastEl = document.createElement("div");
|
||||
toastEl.id = "view-toast";
|
||||
toastEl.hidden = true;
|
||||
document.body.appendChild(toastEl);
|
||||
toastEl.addEventListener("click", (e) => {
|
||||
if (e.target.closest(".toast-dismiss")) toastEl.hidden = true;
|
||||
const go = e.target.closest("[data-cmd]");
|
||||
if (go) {
|
||||
toastEl.hidden = true;
|
||||
applyViewCommand(JSON.parse(go.dataset.cmd));
|
||||
}
|
||||
});
|
||||
}
|
||||
toastEl.innerHTML = html;
|
||||
toastEl.hidden = false;
|
||||
clearTimeout(toastTimer);
|
||||
if (ms) toastTimer = setTimeout(() => (toastEl.hidden = true), ms);
|
||||
}
|
||||
|
||||
function showViewToast(cmd) {
|
||||
const label = [cmd.run, cmd.tab, cmd.step != null ? `step ${cmd.step}` : null, cmd.episode ?? cmd.report]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
toastMsg(
|
||||
`<span class="t-label">agent</span><span class="toast-text">${esc(label)}</span>` +
|
||||
`<button class="btn" data-cmd="${esc(JSON.stringify(cmd))}">go</button><button class="btn toast-dismiss">✕</button>`,
|
||||
30000
|
||||
);
|
||||
}
|
||||
|
||||
function connectViewEvents() {
|
||||
const source = new EventSource("/api/view/events");
|
||||
source.onmessage = (e) => {
|
||||
let cmd;
|
||||
try {
|
||||
cmd = JSON.parse(e.data);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!cmd || (cmd.seq && cmd.seq <= lastViewSeq)) return;
|
||||
if (cmd.seq) lastViewSeq = cmd.seq;
|
||||
// a stored command replays on connect: apply it only to a fresh bare tab —
|
||||
// a deep link or reload states its own target, and stale pointers stay dead
|
||||
if (cmd.replay && (hadHashRun || Date.now() / 1000 - (cmd.ts || 0) > 900)) return;
|
||||
if (!state.follow) return showViewToast(cmd);
|
||||
applyViewCommand(cmd);
|
||||
};
|
||||
}
|
||||
|
||||
$("#follow-toggle").addEventListener("change", (e) => {
|
||||
state.follow = e.target.checked;
|
||||
savePrefs();
|
||||
});
|
||||
$("#report-select").addEventListener("change", async (e) => {
|
||||
state.report.file = e.target.value;
|
||||
await loadReport();
|
||||
});
|
||||
$("#report-body").addEventListener("click", (e) => {
|
||||
const chip = e.target.closest(".cite-chip");
|
||||
if (chip) openCitation(chip.dataset.cite);
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------- wiring */
|
||||
|
||||
$("#run-select").addEventListener("change", (e) => selectRun(e.target.value));
|
||||
@@ -2968,6 +3607,10 @@ $("#episode-table-wrap").addEventListener(
|
||||
);
|
||||
$("#tm-list").addEventListener("scroll", rafThrottle(renderRolloutWindow));
|
||||
$("#drawer-close").addEventListener("click", closeDrawer);
|
||||
$("#tm-back").addEventListener("click", () => {
|
||||
closeDrawer();
|
||||
activateTab("report");
|
||||
});
|
||||
$("#drawer-backdrop").addEventListener("click", closeDrawer);
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape") return closeDrawer();
|
||||
@@ -2985,16 +3628,17 @@ tokTip.className = "tok-tip";
|
||||
tokTip.hidden = true;
|
||||
document.body.appendChild(tokTip);
|
||||
$("#tm-messages").addEventListener("mouseover", (e) => {
|
||||
const tok = e.target.closest(".tok[data-tip]");
|
||||
const tok = e.target.closest("[data-tip]");
|
||||
if (!tok) return;
|
||||
tokTip.textContent = tok.dataset.tip;
|
||||
tokTip.classList.toggle("note", tok.matches("mark.hl-quote")); // citation notes wrap
|
||||
tokTip.hidden = false;
|
||||
const rect = tok.getBoundingClientRect();
|
||||
tokTip.style.left = `${Math.min(rect.left, window.innerWidth - tokTip.offsetWidth - 12)}px`;
|
||||
tokTip.style.top = `${rect.top - tokTip.offsetHeight - 6}px`;
|
||||
});
|
||||
$("#tm-messages").addEventListener("mouseout", (e) => {
|
||||
if (e.target.closest(".tok[data-tip]")) tokTip.hidden = true;
|
||||
if (e.target.closest("[data-tip]")) tokTip.hidden = true;
|
||||
});
|
||||
$("#token-signal").addEventListener("change", async () => {
|
||||
await ensureTokens();
|
||||
@@ -3096,6 +3740,7 @@ function savePrefs() {
|
||||
logSearch: $("#log-search").value,
|
||||
configSearch: $("#config-search").value,
|
||||
tokenSignal: $("#token-signal").value,
|
||||
follow: state.follow,
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -3131,6 +3776,7 @@ async function pollDashboard() {
|
||||
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 refreshTraces();
|
||||
else if (state.tab === "report" && state.report.loaded) await refreshReport();
|
||||
await runsRefresh;
|
||||
} catch (err) {
|
||||
console.warn("poll failed", err);
|
||||
@@ -3153,7 +3799,8 @@ document.addEventListener("visibilitychange", () => {
|
||||
$("#log-search").value = prefs.logSearch ?? "";
|
||||
$("#config-search").value = prefs.configSearch ?? "";
|
||||
$("#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"])
|
||||
$("#follow-toggle").checked = state.follow;
|
||||
for (const sel of ["#run-select", "#trace-env", "#trace-sort", "#tm-env", "#tm-sort", "#attempt-select", "#token-signal", "#report-select"])
|
||||
dressSelect($(sel));
|
||||
syncTraceFilterControls();
|
||||
setActive("#metrics-mode", "mode", state.metrics.mode);
|
||||
@@ -3163,6 +3810,8 @@ document.addEventListener("visibilitychange", () => {
|
||||
applyPaneSize();
|
||||
const params = new URLSearchParams(location.hash.slice(1));
|
||||
state.tab = params.get("tab") || "metrics";
|
||||
state.report.wanted = params.get("report");
|
||||
hadHashRun = !!params.get("run");
|
||||
setActive("#tabs", "tab", state.tab);
|
||||
document.querySelectorAll("main > section").forEach((s) => (s.hidden = s.id !== `tab-${state.tab}`));
|
||||
await loadRuns();
|
||||
@@ -3170,4 +3819,5 @@ document.addEventListener("visibilitychange", () => {
|
||||
const run = state.runs.find((r) => r.name === wanted)?.name ?? state.runs[0]?.name;
|
||||
if (run) await selectRun(run);
|
||||
else $("#metrics-body").innerHTML = emptyState("no runs found", `nothing to show in ${state.outputDir ?? "the output directory"}`);
|
||||
connectViewEvents();
|
||||
})();
|
||||
|
||||
@@ -23,8 +23,10 @@
|
||||
<button data-tab="config">Config</button>
|
||||
<button data-tab="metrics" class="active">Metrics</button>
|
||||
<button data-tab="traces">Traces</button>
|
||||
<button data-tab="report">Report</button>
|
||||
<button data-tab="logs">Logs</button>
|
||||
</nav>
|
||||
<label class="toggle" title="apply agent view commands as they arrive"><input type="checkbox" id="follow-toggle" checked><span class="dot"></span>follow</label>
|
||||
<label class="toggle" title="poll for updates"><input type="checkbox" id="live-toggle" checked><span class="dot"></span>live</label>
|
||||
</header>
|
||||
|
||||
@@ -113,6 +115,17 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="tab-report" hidden>
|
||||
<div class="controls">
|
||||
<label class="t-label">report</label>
|
||||
<select id="report-select"></select>
|
||||
<span id="report-verify" class="muted"></span>
|
||||
<div class="spacer"></div>
|
||||
<span id="report-status" class="muted"></span>
|
||||
</div>
|
||||
<div id="report-wrap"><article id="report-body"></article></div>
|
||||
</section>
|
||||
|
||||
<section id="tab-logs" hidden>
|
||||
<div class="controls">
|
||||
<label class="t-label">attempt</label>
|
||||
@@ -189,6 +202,7 @@
|
||||
<section id="tm-main">
|
||||
<div class="tm-head">
|
||||
<span class="tm-title">Trace Viewer</span>
|
||||
<button id="tm-back" class="btn" hidden title="back to the report">← report</button>
|
||||
<div class="spacer"></div>
|
||||
<div class="seg" id="trace-view-mode">
|
||||
<button data-mode="messages" class="active">Messages</button>
|
||||
|
||||
@@ -877,3 +877,114 @@ pre.json { background: var(--grey-2); border: 1px solid var(--hairline); padding
|
||||
::-webkit-scrollbar-thumb { background: var(--grey-3); }
|
||||
::-webkit-scrollbar-thumb:hover { background: var(--grey-4); }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
/* ---------------------------------------------------------------- report */
|
||||
/* two toggles share the topbar: only the first one pushes right */
|
||||
#topbar .toggle + .toggle { margin-left: 0; }
|
||||
|
||||
#report-wrap { flex: 1; min-height: 0; overflow-y: auto; }
|
||||
#report-body {
|
||||
max-width: 820px;
|
||||
margin: 0 auto;
|
||||
padding: 8px 0 80px;
|
||||
font-size: 13px;
|
||||
line-height: 1.7;
|
||||
color: var(--grey-5);
|
||||
}
|
||||
#report-body h1, #report-body h2, #report-body h3, #report-body h4, #report-body h5, #report-body h6 {
|
||||
color: var(--grey-6);
|
||||
font-weight: 400;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
margin: 28px 0 10px;
|
||||
}
|
||||
#report-body h1 { font-size: 16px; }
|
||||
#report-body h2 { font-size: 13px; border-bottom: 1px solid var(--hairline); padding-bottom: 6px; }
|
||||
#report-body h3, #report-body h4, #report-body h5, #report-body h6 { font-size: 11px; color: var(--grey-5); }
|
||||
#report-body .report-title { margin-top: 8px; }
|
||||
#report-body p { margin: 10px 0; }
|
||||
#report-body hr { border: none; border-top: 1px solid var(--hairline); margin: 20px 0; }
|
||||
#report-body ul, #report-body ol { margin: 10px 0; padding-left: 22px; }
|
||||
#report-body li { margin: 4px 0; }
|
||||
#report-body blockquote {
|
||||
margin: 12px 0;
|
||||
padding: 2px 14px;
|
||||
border-left: 2px solid var(--grey-3);
|
||||
color: var(--grey-4);
|
||||
}
|
||||
#report-body code { background: var(--grey-2); padding: 1px 5px; font-size: 12px; color: var(--grey-6); }
|
||||
#report-body .md-code {
|
||||
background: var(--grey-2);
|
||||
border: 1px solid var(--hairline);
|
||||
padding: 12px 14px;
|
||||
overflow-x: auto;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
margin: 12px 0;
|
||||
}
|
||||
#report-body .md-code code { background: none; padding: 0; color: var(--grey-5); }
|
||||
#report-body a { color: var(--infra); text-decoration: none; }
|
||||
#report-body a:hover { text-decoration: underline; }
|
||||
#report-body strong { color: var(--grey-6); font-weight: 600; }
|
||||
.md-table-wrap { overflow-x: auto; margin: 12px 0; }
|
||||
.md-table { border-collapse: collapse; font-size: 12px; width: 100%; }
|
||||
.md-table th, .md-table td { border: 1px solid var(--hairline); padding: 6px 10px; text-align: left; }
|
||||
.md-table th {
|
||||
color: var(--grey-4);
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
/* citation chips: numbered, colored by verification against the trace files */
|
||||
.cite-chip {
|
||||
display: inline-block;
|
||||
min-width: 16px;
|
||||
padding: 0 4px;
|
||||
margin: 0 1px;
|
||||
text-align: center;
|
||||
font-size: 10px;
|
||||
line-height: 15px;
|
||||
border: 1px solid var(--grey-3);
|
||||
color: var(--grey-5);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
vertical-align: super;
|
||||
}
|
||||
.cite-chip:hover { border-color: var(--grey-6); color: var(--grey-6); }
|
||||
.cite-chip.ok { border-color: rgba(182, 255, 60, 0.5); color: var(--accent); }
|
||||
.cite-chip.bad, .cite-chip.missing { border-color: rgba(255, 69, 57, 0.6); color: var(--negative); }
|
||||
|
||||
/* agent highlights inside the trace viewer; the citation note rides the mark
|
||||
as a hover tooltip */
|
||||
mark.hl-quote {
|
||||
background: rgba(182, 255, 60, 0.22);
|
||||
color: var(--grey-6);
|
||||
outline: 1px solid rgba(182, 255, 60, 0.45);
|
||||
}
|
||||
mark.hl-quote[data-tip] { cursor: help; }
|
||||
.tok-tip.note { max-width: 420px; white-space: normal; }
|
||||
details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pulse 1.6s ease-out 2; }
|
||||
@keyframes hl-pulse {
|
||||
0% { box-shadow: 0 0 0 0 rgba(182, 255, 60, 0.45); }
|
||||
70% { box-shadow: 0 0 0 6px rgba(182, 255, 60, 0); }
|
||||
100% { box-shadow: 0 0 0 0 rgba(182, 255, 60, 0); }
|
||||
}
|
||||
|
||||
/* agent view-command toast (shown when follow is off, or on errors) */
|
||||
#view-toast {
|
||||
position: fixed;
|
||||
right: 16px;
|
||||
bottom: 16px;
|
||||
z-index: 70;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
padding: 10px 12px;
|
||||
max-width: 60vw;
|
||||
font-size: 12px;
|
||||
}
|
||||
#view-toast .toast-text { color: var(--grey-6); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
@@ -210,6 +210,8 @@ class Dispatcher:
|
||||
# *why* — the orchestrator toggles this based on step / policy lead.
|
||||
self.dispatch_allowed = asyncio.Event()
|
||||
self.dispatch_allowed.set()
|
||||
self.policy_update_pending = False
|
||||
self.scheduling_lock = asyncio.Lock()
|
||||
|
||||
self.stopped = asyncio.Event()
|
||||
self.task: asyncio.Task | None = None
|
||||
@@ -371,6 +373,12 @@ class Dispatcher:
|
||||
the resulting aborts are processed while the engine is still stepping —
|
||||
otherwise the orphaned KV transfers crash the decode engine on resume
|
||||
(see ``WeightWatcher.apply_policy_update``)."""
|
||||
self.policy_update_pending = True
|
||||
# Wait for a scheduling call that started before the pending update.
|
||||
# No rollout can cross the inference weight swap after this barrier.
|
||||
async with self.scheduling_lock:
|
||||
pass
|
||||
|
||||
if self.train_envs is None or self.progress is None:
|
||||
return
|
||||
min_version = min_fresh_version(self.progress.step, self.max_off_policy_steps)
|
||||
@@ -392,7 +400,8 @@ class Dispatcher:
|
||||
)
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""No-op: the dispatcher drains in ``on_version_pending`` (pre-pause)."""
|
||||
"""Resume rollout scheduling after inference applies the new policy."""
|
||||
self.policy_update_pending = False
|
||||
|
||||
async def fill_inflight(self) -> None:
|
||||
"""Schedule new rollouts up to ``max_inflight``, honoring
|
||||
@@ -401,28 +410,33 @@ class Dispatcher:
|
||||
respects it. When ``PREFER_EVAL``'s source exhausts we flip back to
|
||||
``PREFER_TRAIN`` so the eval tail drains alongside fresh train."""
|
||||
while True:
|
||||
if self.policy_update_pending:
|
||||
return
|
||||
if self.available_permits <= 0 or self.admission_budget() <= 0:
|
||||
return
|
||||
|
||||
if self.mode == DispatcherMode.PREFER_EVAL:
|
||||
# PREFER_EVAL is only entered when the orchestrator triggers
|
||||
# eval, which requires ``eval_source`` to be configured
|
||||
assert self.eval_source is not None
|
||||
if not self.eval_has_work:
|
||||
# Eval source + all eval groups fully dispatched. Flip
|
||||
# to PREFER_TRAIN so any remaining permits go to train
|
||||
# while the in-flight eval tail completes naturally
|
||||
self.switch_mode(DispatcherMode.PREFER_TRAIN, reason="the eval queue drained")
|
||||
continue
|
||||
scheduled = await self.try_schedule("eval")
|
||||
if not scheduled:
|
||||
return
|
||||
else: # PREFER_TRAIN — respects the orchestrator's dispatch gate
|
||||
if not self.dispatch_allowed.is_set():
|
||||
return
|
||||
scheduled = await self.try_schedule("train")
|
||||
if not scheduled:
|
||||
async with self.scheduling_lock:
|
||||
if self.policy_update_pending:
|
||||
return
|
||||
if self.mode == DispatcherMode.PREFER_EVAL:
|
||||
# PREFER_EVAL is only entered when the orchestrator triggers
|
||||
# eval, which requires ``eval_source`` to be configured
|
||||
assert self.eval_source is not None
|
||||
if not self.eval_has_work:
|
||||
# Eval source + all eval groups fully dispatched. Flip
|
||||
# to PREFER_TRAIN so any remaining permits go to train
|
||||
# while the in-flight eval tail completes naturally
|
||||
self.switch_mode(DispatcherMode.PREFER_TRAIN, reason="the eval queue drained")
|
||||
continue
|
||||
scheduled = await self.try_schedule("eval")
|
||||
if not scheduled:
|
||||
return
|
||||
else: # PREFER_TRAIN — respects the orchestrator's dispatch gate
|
||||
if not self.dispatch_allowed.is_set():
|
||||
return
|
||||
scheduled = await self.try_schedule("train")
|
||||
if not scheduled:
|
||||
return
|
||||
|
||||
def switch_mode(self, new_mode: DispatcherMode, *, reason: str) -> None:
|
||||
if new_mode == self.mode:
|
||||
|
||||
@@ -179,6 +179,13 @@ class Envs(Generic[EnvT]):
|
||||
async def start(self) -> None:
|
||||
"""Connect to all env servers in parallel — every address is known up front,
|
||||
so there's nothing to serialize on."""
|
||||
# When several env.start()s load_dataset() concurrently, datasets' parallel arrow read
|
||||
# (tqdm thread_map) races in ensure_lock's `del tqdm_class._lock` and crashes with
|
||||
# `AttributeError: type object 'tqdm' has no attribute '_lock'`. Pre-seed the lock so it
|
||||
# isn't created-and-deleted per call.
|
||||
from datasets.utils import tqdm as hf_tqdm
|
||||
|
||||
hf_tqdm.set_lock(hf_tqdm.get_lock())
|
||||
await asyncio.gather(*(env.start() for env in self))
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""EvalSource: trigger-driven, finite-per-epoch pull of eval examples.
|
||||
|
||||
The orchestrator pokes ``trigger(step)`` after each ship + once at
|
||||
startup; the dispatcher pulls via ``next_task()`` until
|
||||
The policy watcher calls ``trigger(step)`` after each applied policy,
|
||||
including startup. The dispatcher pulls via ``next_task()`` until
|
||||
``bool(source) == False``. Constructed only when eval is configured."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,8 +37,8 @@ class EvalSource:
|
||||
|
||||
self.queue: deque[TaskRequest] = deque()
|
||||
|
||||
# On resume we skip the startup eval; on fresh start the first
|
||||
# trigger fires every env (subject to ``skip_first_step``)
|
||||
# A fresh run evaluates the base policy. Resumed runs apply interval
|
||||
# rules to the loaded checkpoint and later policies.
|
||||
self.first_trigger = not is_resumed
|
||||
|
||||
def trigger(self, step: int, *, force: bool = False) -> list[str]:
|
||||
|
||||
@@ -78,11 +78,7 @@ from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, s
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_broadcast_dir
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
final_broadcast_version,
|
||||
resolve_latest_ckpt_step,
|
||||
)
|
||||
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
|
||||
|
||||
monkey_patch_oai_iterable_types()
|
||||
monkey_patch_chat_completion_logprobs()
|
||||
@@ -166,9 +162,10 @@ class Orchestrator:
|
||||
self.eval_triggered_at = {}
|
||||
self.consecutive_empty_batches = 0
|
||||
self.gate_closed_at = None
|
||||
# Pulsed by the version hooks so a held ship can re-check ``policy.version``
|
||||
# Pulsed after inference applies a policy so held work can re-check it.
|
||||
self.version_advanced = asyncio.Event()
|
||||
self.wait_for_policy_time = 0.0
|
||||
self.eval_triggered_steps: set[int] = set()
|
||||
self.component_tasks = []
|
||||
|
||||
# Always assigned by ``setup()``; None-initialized so teardown can run
|
||||
@@ -320,14 +317,9 @@ class Orchestrator:
|
||||
# scratch). The startup broadcast is always coming, so wait for it rather
|
||||
# than failing immediately when it is not there yet.
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
|
||||
t0 = time.perf_counter()
|
||||
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
)
|
||||
await self.receiver.sync_startup(sync_version, timeout=wait_timeout)
|
||||
self.policy.version = sync_version
|
||||
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
self.eval_source: EvalSource | None = (
|
||||
EvalSource(
|
||||
@@ -390,9 +382,12 @@ class Orchestrator:
|
||||
self.watcher = WeightWatcher(
|
||||
self.receiver,
|
||||
policy=self.policy,
|
||||
observers=[self.dispatcher, self],
|
||||
ckpt_step=self.policy.version,
|
||||
observers=[self.dispatcher],
|
||||
ckpt_step=sync_version,
|
||||
)
|
||||
if self.eval_source is not None:
|
||||
self.watcher.on_update(self.trigger_eval)
|
||||
self.watcher.on_update(self.on_policy_update)
|
||||
# Single periodic logger for the whole pipeline. It's the only
|
||||
# consumer of ``dispatcher.metrics.drained()`` (which clears on read)
|
||||
self.lag_monitor = EventLoopLagMonitor()
|
||||
@@ -419,6 +414,11 @@ class Orchestrator:
|
||||
wandb_enabled=wandb_enabled,
|
||||
)
|
||||
|
||||
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
|
||||
t0 = time.perf_counter()
|
||||
await self.watcher.sync_startup(sync_version, timeout=wait_timeout)
|
||||
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Run the orchestrator until shutdown. Drives setup, spawns the
|
||||
background tasks, runs the main loop in this task, then cleans up."""
|
||||
@@ -438,14 +438,6 @@ class Orchestrator:
|
||||
asyncio.create_task(self.watcher.start(), name="watcher"),
|
||||
]
|
||||
|
||||
# Base-model eval (policy v0) — fires before any train rollouts, logged at the first
|
||||
# step, unless ``eval.skip_first_step=True``. On resume, defaults to assuming a clean
|
||||
# exit (evals already completed); set ``eval.retrigger_on_resume=True`` to also re-fire
|
||||
# interval-aligned evals at the checkpoint step (e.g. after a crash).
|
||||
if config.eval is not None and config.eval.retrigger_on_resume and self.resume_step is not None:
|
||||
self.maybe_trigger_eval(self.resume_step)
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
|
||||
# Anchor step-time clock so the first step measures startup → first batch
|
||||
self.last_batch_at = time.perf_counter()
|
||||
|
||||
@@ -484,18 +476,11 @@ class Orchestrator:
|
||||
get_logger().warning("Orchestrator cleanup complete (forced)")
|
||||
trim_process_memory()
|
||||
|
||||
@property
|
||||
def final_version(self) -> int | None:
|
||||
"""Newest policy version the trainer will ever broadcast."""
|
||||
if self.config.max_steps is None:
|
||||
return None
|
||||
return final_broadcast_version(self.config.max_steps, self.config.weight_broadcast.broadcast_final)
|
||||
|
||||
async def wait_for_version(self, version: int, reason: str) -> None:
|
||||
"""Bounded wait until the watcher has applied v{version}."""
|
||||
if self.policy.version >= version:
|
||||
return
|
||||
get_logger().info(f"Waiting for the trainer to broadcast v{version} {reason}")
|
||||
get_logger().info(f"Waiting for inference to apply policy v{version} {reason}")
|
||||
|
||||
async def wait() -> None:
|
||||
while self.policy.version < version:
|
||||
@@ -514,15 +499,15 @@ class Orchestrator:
|
||||
try:
|
||||
await asyncio.wait_for(wait(), timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
get_logger().warning(f"Trainer did not broadcast v{version} within {timeout}s — proceeding anyway")
|
||||
get_logger().warning(f"Inference did not apply policy v{version} within {timeout}s — proceeding anyway")
|
||||
|
||||
async def wait_for_final_broadcast(self) -> None:
|
||||
"""Stay alive for the trainer's last broadcast. Every broadcast is a
|
||||
blocking rendezvous — tearing down the watcher before it would strand
|
||||
the trainer inside the handshake."""
|
||||
if self.final_version is None:
|
||||
if self.config.max_steps is None:
|
||||
return
|
||||
await self.wait_for_version(self.final_version, reason="before shutdown")
|
||||
await self.wait_for_version(self.config.max_steps, reason="before shutdown")
|
||||
|
||||
async def main_loop(self) -> None:
|
||||
"""Consume dispatcher results and route them to the train / eval sink.
|
||||
@@ -644,16 +629,16 @@ class Orchestrator:
|
||||
f"({n_trainable / effective.num_traces:.1%}) — consider reviewing task difficulty"
|
||||
)
|
||||
|
||||
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
|
||||
# Ship batch ``step`` only once inference has applied v{step-1-TARGET_LAG}.
|
||||
# Without this, fast envs fill batches from buffered rollouts and the
|
||||
# orchestrator races arbitrarily far ahead of the trainer. Always
|
||||
# satisfiable: the trainer broadcasts every version except v{max_steps},
|
||||
# and ``wait_for_final_broadcast`` keeps the watcher alive through the
|
||||
# last rendezvous after the pipeline drains.
|
||||
# satisfiable: the trainer broadcasts every version, and
|
||||
# ``wait_for_final_broadcast`` keeps the watcher alive through the last
|
||||
# rendezvous after the pipeline drains.
|
||||
required_version = step - 1 - TARGET_LAG
|
||||
if self.policy.version < required_version:
|
||||
get_logger().info(
|
||||
f"Holding batch {step} until the trainer publishes policy v{required_version} "
|
||||
f"Holding batch {step} until inference applies policy v{required_version} "
|
||||
f"(currently v{self.policy.version})"
|
||||
)
|
||||
hold_start = time.perf_counter()
|
||||
@@ -757,14 +742,8 @@ class Orchestrator:
|
||||
|
||||
self.log_train_batch(batch, step=step, step_time=step_time)
|
||||
|
||||
# The final eval must measure the final weights: hold until the
|
||||
# trainer's last broadcast (v{max_steps} when evals consume it) has
|
||||
# been applied before triggering it. Satisfiable — the trainer
|
||||
# broadcasts right after consuming the batch this call just shipped.
|
||||
if config.eval is not None and config.max_steps is not None and step >= config.max_steps:
|
||||
assert self.final_version is not None
|
||||
await self.wait_for_version(self.final_version, reason="for the final eval")
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
if config.max_steps is not None and step >= config.max_steps:
|
||||
await self.wait_for_version(step, reason="before shutdown")
|
||||
# Drain right after shipping the final batch. Waiting for a further
|
||||
# batch to fill would burn inference on data that can never train —
|
||||
# and with a tight ``max_off_policy_steps`` it never fills at all (the
|
||||
@@ -784,14 +763,18 @@ class Orchestrator:
|
||||
f"train episode(s); any in-flight evals will complete)"
|
||||
)
|
||||
|
||||
def maybe_trigger_eval(self, step: int) -> None:
|
||||
async def trigger_eval(self, step: int) -> None:
|
||||
"""Fire eligible eval epochs and flip to ``PREFER_EVAL`` if anything
|
||||
fires. No-op when eval is not configured."""
|
||||
if self.eval_source is None:
|
||||
if self.eval_source is None or step in self.eval_triggered_steps:
|
||||
return
|
||||
fired = self.eval_source.trigger(step)
|
||||
if self.resume_step == step and self.config.eval is not None and not self.config.eval.retrigger_on_resume:
|
||||
return
|
||||
is_final = self.config.max_steps is not None and step >= self.config.max_steps
|
||||
fired = self.eval_source.trigger(step, force=is_final)
|
||||
if not fired:
|
||||
return
|
||||
self.eval_triggered_steps.add(step)
|
||||
reason = f"eval was triggered at step {step}"
|
||||
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=reason)
|
||||
now = time.perf_counter()
|
||||
@@ -942,10 +925,6 @@ class Orchestrator:
|
||||
policy_versions = {span.start for span in policy_spans if span is not None}
|
||||
policy_versions.update(failure.policy_version for failure in batch.failures)
|
||||
policy_version = min(policy_versions)
|
||||
if len(policy_versions) > 1:
|
||||
get_logger().warning(
|
||||
f"Eval {batch.env_name} step {batch.step} had mixed policy versions: {sorted(policy_versions)}"
|
||||
)
|
||||
# Episode metrics over {all,effective} (eval batches are per-env, so no `agg` axis).
|
||||
# ``effective`` = non-errored; pass@k / pass^k only over the effective set.
|
||||
episodes = batch.episodes
|
||||
@@ -969,7 +948,7 @@ class Orchestrator:
|
||||
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
|
||||
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"Evaluated {batch.env_name} | "
|
||||
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
@@ -1006,7 +985,7 @@ class Orchestrator:
|
||||
if lead > TARGET_LAG:
|
||||
if was_set:
|
||||
get_logger().info(
|
||||
f"Pausing dispatcher until the trainer publishes policy v{self.progress.step - 1 - TARGET_LAG} "
|
||||
f"Pausing dispatcher until inference applies policy v{self.progress.step - 1 - TARGET_LAG} "
|
||||
f"(currently v{self.policy.version})"
|
||||
)
|
||||
self.gate_closed_at = time.perf_counter()
|
||||
@@ -1019,15 +998,10 @@ class Orchestrator:
|
||||
self.gate_closed_at = None
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook, fired at publish confirmation (pre-apply):
|
||||
``policy.version`` already carries the new version, so wake a held ship."""
|
||||
self.version_advanced.set()
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook: the weight update completed;
|
||||
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
|
||||
async def on_policy_update(self, _step: int) -> None:
|
||||
"""Refresh policy-dependent state after inference applies new weights."""
|
||||
self.update_dispatch_gate()
|
||||
self.version_advanced.set()
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Bounded best-effort teardown of all components. Has a global
|
||||
|
||||
@@ -6,6 +6,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable
|
||||
|
||||
from prime_rl.orchestrator.types import Policy, VersionObserver
|
||||
from prime_rl.transports.weights import WeightReceiver
|
||||
@@ -38,6 +39,19 @@ class WeightWatcher:
|
||||
self.task: asyncio.Task | None = None
|
||||
self.update_lock = asyncio.Lock()
|
||||
self.stopped = asyncio.Event()
|
||||
self.update_hooks: list[Callable[[int], Awaitable[None]]] = []
|
||||
|
||||
def on_update(self, hook: Callable[[int], Awaitable[None]]) -> None:
|
||||
"""Register an async hook that runs after inference applies new weights."""
|
||||
self.update_hooks.append(hook)
|
||||
|
||||
async def sync_startup(self, step: int, timeout: float) -> None:
|
||||
"""Apply the startup policy and notify the registered update hooks."""
|
||||
async with self.update_lock:
|
||||
await self.receiver.sync_startup(step, timeout)
|
||||
self.ckpt_step = step
|
||||
self.policy.version = step
|
||||
await self._notify_update(step)
|
||||
|
||||
async def start(self) -> None:
|
||||
self.task = asyncio.current_task()
|
||||
@@ -72,12 +86,9 @@ class WeightWatcher:
|
||||
await self.receiver.wait_published(next_step, cancelled=self.stopped.is_set)
|
||||
self.last_wait_for_ckpt_time = time.perf_counter() - t0
|
||||
|
||||
# Publish confirmed: the policy version advances here, before the
|
||||
# apply — inference pauses during the update, so nothing can generate
|
||||
# under the new number from the old weights, and a ship held on this
|
||||
# version releases without waiting out the inference weight reload.
|
||||
# Record the published version before notifying pending observers.
|
||||
# ``policy.version`` advances only after inference applies it.
|
||||
self.ckpt_step = next_step
|
||||
self.policy.version = next_step
|
||||
|
||||
# Drain stale rollouts BEFORE pausing the inference engines.
|
||||
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
|
||||
@@ -102,17 +113,22 @@ class WeightWatcher:
|
||||
await self.receiver.receive(next_step)
|
||||
self.last_update_weights_time = time.perf_counter() - t1
|
||||
self.update_count += 1
|
||||
self.policy.version = next_step
|
||||
get_logger().debug(
|
||||
f"Updated inference weights to policy v{next_step} in {format_time(self.last_update_weights_time)}"
|
||||
)
|
||||
|
||||
for observer in self.observers:
|
||||
try:
|
||||
await observer.on_new_version(next_step)
|
||||
except Exception as exc:
|
||||
get_logger().warning(
|
||||
f"Observer {type(observer).__name__}.on_new_version({next_step}) raised: {exc!r}"
|
||||
)
|
||||
await self._notify_update(next_step)
|
||||
|
||||
async def _notify_update(self, step: int) -> None:
|
||||
for observer in self.observers:
|
||||
try:
|
||||
await observer.on_new_version(step)
|
||||
except Exception as exc:
|
||||
get_logger().warning(f"Observer {type(observer).__name__}.on_new_version({step}) raised: {exc!r}")
|
||||
|
||||
for hook in self.update_hooks:
|
||||
await hook(step)
|
||||
|
||||
def gauges(self) -> dict[str, float]:
|
||||
return {
|
||||
|
||||
@@ -67,7 +67,7 @@ from prime_rl.utils.metrics_server import HealthServer, MetricsServer
|
||||
from prime_rl import monitors
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.utils import clean_exit, final_broadcast_version, resolve_latest_ckpt_step
|
||||
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
|
||||
from ring_flash_attn import substitute_hf_flash_attn
|
||||
|
||||
|
||||
@@ -590,31 +590,23 @@ def train(config: TrainerConfig):
|
||||
current_lr = optimizer.param_groups[0]["lr"]
|
||||
forward_backward_time = time.perf_counter() - forward_backward_start_time
|
||||
|
||||
# Broadcast the model just produced (policy v{progress.step}) so the orchestrator can
|
||||
# sample its next step from it. Every broadcast is a handshake with the consumer, so
|
||||
# versions past the last consumed one are skipped (``final_broadcast_version``:
|
||||
# training never samples v{max_steps}, but a configured final eval measures it).
|
||||
# Broadcast the model just produced (policy v{progress.step}). The final
|
||||
# broadcast keeps inference synchronized with the completed trainer.
|
||||
if weight_sender is None:
|
||||
broadcast_weights_time = 0
|
||||
else:
|
||||
broadcast_unused = config.max_steps is not None and progress.step > final_broadcast_version(
|
||||
config.max_steps, config.weight_broadcast.broadcast_final
|
||||
)
|
||||
if not broadcast_unused:
|
||||
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. 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
|
||||
else:
|
||||
broadcast_weights_time = 0
|
||||
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. 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
|
||||
|
||||
# Checkpoint the step we just finished (model = policy v{progress.step}).
|
||||
if (
|
||||
|
||||
@@ -236,17 +236,17 @@ def validate_run_dir(
|
||||
|
||||
|
||||
def clean_future_steps(output_dir: Path, resume_step: int) -> None:
|
||||
"""Remove stale rollouts, broadcasts, and traces past ``resume_step``.
|
||||
"""Remove stale rollouts past ``resume_step`` and broadcasts from it onward.
|
||||
|
||||
Pass ``resume_step=-1`` to wipe every step directory (fresh runs).
|
||||
"""
|
||||
dirs = [
|
||||
get_rollout_dir(output_dir),
|
||||
get_broadcast_dir(output_dir),
|
||||
cleanup_rules = [
|
||||
(get_rollout_dir(output_dir), lambda step: step > resume_step),
|
||||
(get_broadcast_dir(output_dir), lambda step: step >= resume_step),
|
||||
]
|
||||
|
||||
for directory in dirs:
|
||||
steps_to_delete = [step for step in get_all_ckpt_steps(directory) if step > resume_step]
|
||||
for directory, should_delete in cleanup_rules:
|
||||
steps_to_delete = [step for step in get_all_ckpt_steps(directory) if should_delete(step)]
|
||||
if not steps_to_delete:
|
||||
continue
|
||||
get_logger().info(
|
||||
|
||||
@@ -163,13 +163,6 @@ def get_free_port() -> int:
|
||||
return port
|
||||
|
||||
|
||||
def final_broadcast_version(max_steps: int, broadcast_final: bool) -> int:
|
||||
"""Newest policy version the trainer will ever broadcast: v{max_steps} when
|
||||
something consumes it (a configured final eval), else v{max_steps - 1} -
|
||||
training never samples from the final version."""
|
||||
return max_steps if broadcast_final else max_steps - 1
|
||||
|
||||
|
||||
@contextmanager
|
||||
def default_dtype(dtype):
|
||||
prev = torch.get_default_dtype()
|
||||
|
||||
@@ -2,14 +2,18 @@ from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.utils.weights import load_state_dict
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.integration.dashboard_smoke import make_dashboard_test
|
||||
from tests.utils import (
|
||||
check_avg_mismatch_kl_in_range,
|
||||
check_hf_load,
|
||||
check_no_error,
|
||||
check_reward_goes_up,
|
||||
check_reward_in_range,
|
||||
convert_checkpoint,
|
||||
strip_escape_codes,
|
||||
)
|
||||
|
||||
@@ -129,4 +133,24 @@ def test_reward_in_range_resume(rl_resume_process: ProcessResult, test_no_error_
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.6)
|
||||
|
||||
|
||||
def test_convert_final_checkpoint(rl_resume_process: ProcessResult, run_dir: Path, tmp_path: Path):
|
||||
"""The final DCP checkpoint converts to bf16 and fp8 (direct == chained), and the exports reload in HF."""
|
||||
assert rl_resume_process.returncode == 0
|
||||
step_dir = run_dir / "checkpoints" / "step_20"
|
||||
convert_checkpoint("dcp_to_bf16", step_dir)
|
||||
convert_checkpoint("dcp_to_fp8", step_dir)
|
||||
check_hf_load(step_dir / "weights")
|
||||
|
||||
# Quantizing the bf16 export reproduces the direct dcp->fp8 export byte-for-byte.
|
||||
convert_checkpoint("bf16_to_fp8", step_dir / "weights", tmp_path / "fp8-chained")
|
||||
direct = load_state_dict(step_dir / "weights-FP8")
|
||||
chained = load_state_dict(tmp_path / "fp8-chained")
|
||||
assert set(direct) == set(chained)
|
||||
for key in direct:
|
||||
assert torch.equal(direct[key].view(torch.uint8), chained[key].view(torch.uint8)), key
|
||||
|
||||
convert_checkpoint("fp8_to_bf16", step_dir / "weights-FP8", tmp_path / "dequant")
|
||||
check_hf_load(tmp_path / "dequant")
|
||||
|
||||
|
||||
test_dashboard = make_dashboard_test("rl_process", RUN_NAME)
|
||||
|
||||
@@ -7,7 +7,7 @@ from torch.distributed.checkpoint.format_utils import dcp_to_torch_save
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.integration.dashboard_smoke import make_dashboard_test
|
||||
from tests.utils import check_loss_goes_down, strip_escape_codes
|
||||
from tests.utils import check_hf_load, check_loss_goes_down, convert_checkpoint, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
|
||||
|
||||
@@ -173,4 +173,15 @@ def test_full_offload_model_only_resume_preserves_weights(
|
||||
)
|
||||
|
||||
|
||||
def test_convert_final_checkpoint(sft_resume_process: ProcessResult, run_dir: Path, tmp_path: Path):
|
||||
"""The final DCP checkpoint converts to bf16 and fp8, and the exports reload in HF."""
|
||||
assert sft_resume_process.returncode == 0
|
||||
step_dir = run_dir / "checkpoints" / "step_10"
|
||||
convert_checkpoint("dcp_to_bf16", step_dir)
|
||||
convert_checkpoint("dcp_to_fp8", step_dir)
|
||||
check_hf_load(step_dir / "weights")
|
||||
convert_checkpoint("fp8_to_bf16", step_dir / "weights-FP8", tmp_path / "dequant")
|
||||
check_hf_load(tmp_path / "dequant")
|
||||
|
||||
|
||||
test_dashboard = make_dashboard_test("sft_process", RUN_NAME)
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import pytest
|
||||
|
||||
from prime_rl.utils.pathing import validate_run_dir
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
get_broadcast_dir,
|
||||
get_rollout_dir,
|
||||
get_step_path,
|
||||
validate_run_dir,
|
||||
)
|
||||
|
||||
|
||||
def test_nonexistent_dir_passes(tmp_path):
|
||||
@@ -88,3 +94,20 @@ def test_clean_outside_output_dir_raises(tmp_path):
|
||||
with pytest.raises(ValueError, match="remain under output_dir"):
|
||||
validate_run_dir(escaped, output_dir=tmp_path / "outputs", resuming=False, clean=True)
|
||||
assert escaped.exists()
|
||||
|
||||
|
||||
def test_clean_future_steps_rebuilds_resume_broadcast(tmp_path):
|
||||
rollout_dir = get_rollout_dir(tmp_path)
|
||||
broadcast_dir = get_broadcast_dir(tmp_path)
|
||||
for parent in (rollout_dir, broadcast_dir):
|
||||
for step in (1, 2, 3):
|
||||
get_step_path(parent, step).mkdir(parents=True)
|
||||
|
||||
clean_future_steps(tmp_path, resume_step=2)
|
||||
|
||||
assert get_step_path(rollout_dir, 1).exists()
|
||||
assert get_step_path(rollout_dir, 2).exists()
|
||||
assert not get_step_path(rollout_dir, 3).exists()
|
||||
assert get_step_path(broadcast_dir, 1).exists()
|
||||
assert not get_step_path(broadcast_dir, 2).exists()
|
||||
assert not get_step_path(broadcast_dir, 3).exists()
|
||||
|
||||
+21
-1
@@ -108,7 +108,7 @@ def check_loss_goes_down(lines: list[str]):
|
||||
|
||||
|
||||
def check_final_eval_reward_above(lines: list[str], env_name: str, min_threshold: float):
|
||||
"""Assert the LAST `Evaluated {env_name} (Step N) | ... | Reward X.XXXX`
|
||||
"""Assert the last `Evaluated {env_name} | ... | Reward X.XXXX`
|
||||
line reports a reward above ``min_threshold``.
|
||||
|
||||
Robust for short distill smokes: until the policy converges, eval reward is
|
||||
@@ -223,3 +223,23 @@ def check_mismatch_kl_in_range(
|
||||
min_threshold=min_threshold,
|
||||
max_threshold=max_threshold,
|
||||
)
|
||||
|
||||
|
||||
def convert_checkpoint(converter: str, *args: Path) -> None:
|
||||
"""Run ``tools/convert_<converter>.py`` on a checkpoint."""
|
||||
import subprocess
|
||||
|
||||
cmd = ["uv", "run", "python", f"tools/convert_{converter}.py", *[str(arg) for arg in args]]
|
||||
subprocess.run(cmd, check=True, timeout=600)
|
||||
|
||||
|
||||
def check_hf_load(weights_dir: Path) -> None:
|
||||
"""Helper to assert that an exported checkpoint loads as an HF model with no missing/unexpected tensors"""
|
||||
import torch
|
||||
from transformers import AutoModelForCausalLM
|
||||
|
||||
model, loading_info = AutoModelForCausalLM.from_pretrained(weights_dir, output_loading_info=True)
|
||||
assert not loading_info["missing_keys"], f"missing keys: {loading_info['missing_keys'][:5]}"
|
||||
assert not loading_info["unexpected_keys"], f"unexpected keys: {loading_info['unexpected_keys'][:5]}"
|
||||
assert not loading_info["mismatched_keys"], f"mismatched keys: {loading_info['mismatched_keys'][:5]}"
|
||||
assert all(torch.isfinite(param).all() for param in model.parameters())
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Quantize a bf16 HF safetensors checkpoint to blockwise FP8 (DeepSeek/GLM format).
|
||||
|
||||
2D linear weights are quantized to e4m3 with per-128x128-block fp32 scales
|
||||
stored under ``<name>.weight_scale_inv``; norms, embeddings, lm_head, router
|
||||
gates and other sensitive modules stay in the source dtype. The output dir gets
|
||||
the quantized shards, a rewritten index, all non-weight assets, and a
|
||||
``quantization_config`` block in ``config.json`` that vLLM loads natively.
|
||||
|
||||
Usage (from the prime-rl repo):
|
||||
uv run python tools/convert_bf16_to_fp8.py <model_dir> [output_dir] [--block-size 128]
|
||||
|
||||
Writes to ``<model_dir>-FP8`` by default.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from safetensors import safe_open
|
||||
from safetensors.torch import save_file
|
||||
|
||||
from prime_rl.trainer.models.fp8 import quantize_to_fp8_blockwise
|
||||
|
||||
# Module-name substrings that stay unquantized: norms, embeddings, output head,
|
||||
# MoE router gates, GatedDeltaNet low-rank projections, MTP/indexer projections,
|
||||
# vision tower. Mirrors the trainer's _DEFAULT_FP8_IGNORE_PATTERNS
|
||||
# (configs/trainer.py), adapted to HF checkpoint names.
|
||||
SKIP_SUBSTRINGS = (
|
||||
"norm",
|
||||
"embed",
|
||||
"lm_head",
|
||||
"shared_expert_gate",
|
||||
"in_proj_a",
|
||||
"in_proj_b",
|
||||
"eh_proj",
|
||||
"weights_proj",
|
||||
"visual.",
|
||||
"router",
|
||||
)
|
||||
|
||||
|
||||
def should_quantize(name: str, tensor: torch.Tensor) -> bool:
|
||||
return (
|
||||
name.endswith(".weight")
|
||||
and tensor.ndim == 2
|
||||
and tensor.is_floating_point()
|
||||
and tensor.element_size() > 1
|
||||
and not name.endswith(".gate.weight")
|
||||
and not any(substring in name for substring in SKIP_SUBSTRINGS)
|
||||
)
|
||||
|
||||
|
||||
def quantize_state_dict(
|
||||
tensors: dict[str, torch.Tensor], block_size: int, device: str
|
||||
) -> tuple[dict[str, torch.Tensor], list[str]]:
|
||||
"""Quantize the quantizable tensors of one CPU state-dict slice; returns (out, modules kept in bf16).
|
||||
|
||||
Tensors move to ``device`` one at a time (and are popped from the input as they
|
||||
are consumed), so peak device memory stays near the largest single weight.
|
||||
"""
|
||||
out: dict[str, torch.Tensor] = {}
|
||||
modules_to_not_convert: list[str] = []
|
||||
for name in list(tensors):
|
||||
tensor = tensors.pop(name)
|
||||
if should_quantize(name, tensor):
|
||||
quantized, scales = quantize_to_fp8_blockwise(tensor.to(device), block_size)
|
||||
out[name] = quantized.cpu()
|
||||
out[name + "_scale_inv"] = scales.cpu()
|
||||
else:
|
||||
if name.endswith(".weight") and tensor.ndim == 2 and tensor.is_floating_point():
|
||||
modules_to_not_convert.append(name.removesuffix(".weight"))
|
||||
if name.endswith(".weight") and tensor.ndim > 2 and tensor.numel() > 1_000_000:
|
||||
print(f"Warning: leaving large {tensor.ndim}D tensor unquantized: {name} {tuple(tensor.shape)}")
|
||||
out[name] = tensor.cpu()
|
||||
return out, modules_to_not_convert
|
||||
|
||||
|
||||
def quantization_config(modules_to_not_convert: list[str], block_size: int) -> dict:
|
||||
return {
|
||||
"quant_method": "fp8",
|
||||
"fmt": "e4m3",
|
||||
"activation_scheme": "dynamic",
|
||||
"weight_block_size": [block_size, block_size],
|
||||
"modules_to_not_convert": sorted(set(modules_to_not_convert)),
|
||||
}
|
||||
|
||||
|
||||
def list_shards(model_dir: Path) -> list[str]:
|
||||
index_path = model_dir / "model.safetensors.index.json"
|
||||
if index_path.exists():
|
||||
weight_map = json.loads(index_path.read_text())["weight_map"]
|
||||
return sorted(set(weight_map.values()))
|
||||
if (model_dir / "model.safetensors").exists():
|
||||
return ["model.safetensors"]
|
||||
raise FileNotFoundError(f"No safetensors checkpoint found in {model_dir}")
|
||||
|
||||
|
||||
def convert(input_dir: Path, output_dir: Path | None = None, block_size: int = 128) -> Path:
|
||||
input_dir = input_dir.resolve()
|
||||
output_dir = output_dir or input_dir.with_name(input_dir.name + "-FP8")
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
|
||||
weight_map: dict[str, str] = {}
|
||||
total_size = 0
|
||||
modules_to_not_convert: list[str] = []
|
||||
num_quantized = 0
|
||||
|
||||
for shard_name in list_shards(input_dir):
|
||||
# Shards land in host memory; quantize_state_dict streams them through the
|
||||
# device tensor-by-tensor so a whole shard never sits on the GPU at once.
|
||||
with safe_open(input_dir / shard_name, framework="pt", device="cpu") as f:
|
||||
tensors = {name: f.get_tensor(name) for name in f.keys()}
|
||||
out_shard, shard_modules = quantize_state_dict(tensors, block_size, device)
|
||||
modules_to_not_convert.extend(shard_modules)
|
||||
num_quantized += sum(1 for name in out_shard if name.endswith("_scale_inv"))
|
||||
for name, tensor in out_shard.items():
|
||||
weight_map[name] = shard_name
|
||||
total_size += tensor.nbytes
|
||||
save_file(out_shard, output_dir / shard_name, metadata={"format": "pt"})
|
||||
print(f"Quantized {shard_name} ({num_quantized} tensors so far)")
|
||||
|
||||
if num_quantized == 0:
|
||||
raise ValueError(f"No quantizable weights found in {input_dir} - is this a bf16 checkpoint?")
|
||||
|
||||
index = {"metadata": {"total_size": total_size}, "weight_map": weight_map}
|
||||
(output_dir / "model.safetensors.index.json").write_text(json.dumps(index, indent=2, sort_keys=True) + "\n")
|
||||
|
||||
for path in input_dir.iterdir():
|
||||
if path.is_file() and path.suffix != ".safetensors" and path.name != "model.safetensors.index.json":
|
||||
shutil.copyfile(path, output_dir / path.name)
|
||||
|
||||
config_path = input_dir / "config.json"
|
||||
config = json.loads(config_path.read_text())
|
||||
config["quantization_config"] = quantization_config(modules_to_not_convert, block_size)
|
||||
(output_dir / "config.json").write_text(json.dumps(config, indent=2) + "\n")
|
||||
print(f"Done: {num_quantized} weights quantized -> {output_dir}")
|
||||
return output_dir
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("input_dir", type=Path, help="HF safetensors model dir (bf16/fp16/fp32)")
|
||||
parser.add_argument("output_dir", type=Path, nargs="?", default=None, help="default: <input_dir>-FP8")
|
||||
parser.add_argument("--block-size", type=int, default=128)
|
||||
args = parser.parse_args()
|
||||
convert(args.input_dir, args.output_dir, args.block_size)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Convert a DCP trainer checkpoint into bf16 HF-format weights offline.
|
||||
|
||||
The trainer saves only DCP checkpoints; every HF export goes through this
|
||||
script. It mirrors the trainer's broadcast save path: build the model, DCP-load
|
||||
the checkpoint's model state, gather rank-parallel, convert to HF format, and
|
||||
write sharded safetensors plus config/tokenizer assets.
|
||||
|
||||
The model and tokenizer configs are read from the run's resolved config
|
||||
(``<run>/configs/resolved/trainer.json`` or ``sft.json``). LoRA checkpoints are not
|
||||
supported — the script exports full fine-tunes only.
|
||||
|
||||
Usage (from the prime-rl repo; more ranks = faster gathers and writes, and
|
||||
models too big for one GPU need enough ranks to shard across):
|
||||
uv run python tools/convert_dcp_to_bf16.py <run>/checkpoints/step_{n} [output_dir]
|
||||
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_bf16.py \
|
||||
<run>/checkpoints/step_{n} [output_dir]
|
||||
|
||||
Writes to ``<ckpt_dir>/weights`` by default.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch.distributed.checkpoint import FileSystemReader
|
||||
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
|
||||
|
||||
from prime_rl.configs.trainer import ModelConfig, TokenizerConfig
|
||||
from prime_rl.trainer.ckpt import AppState
|
||||
from prime_rl.trainer.model import setup_model, setup_processor, setup_tokenizer
|
||||
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
|
||||
from prime_rl.trainer.utils import setup_torch_distributed
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_config_dir
|
||||
from prime_rl.utils.weights import (
|
||||
convert_state_dict_to_hf,
|
||||
gather_weights_parallel,
|
||||
save_state_dict_parallel,
|
||||
)
|
||||
|
||||
# Training kernels and parallelism settings do not apply to an offline export.
|
||||
# Resolve parallelism for the converter's world size and use portable kernels.
|
||||
CONVERSION_OVERRIDES = {
|
||||
"compile": None,
|
||||
"ac": None,
|
||||
"dp_replicate": 1,
|
||||
"cp": 1,
|
||||
"ep": "auto",
|
||||
"ep_comm_backend": "torch",
|
||||
"attn": "flash_attention_2",
|
||||
"moe_fused_kernel": False,
|
||||
}
|
||||
|
||||
RUN_CONFIG_NAMES = ("trainer.json", "sft.json")
|
||||
|
||||
|
||||
def resolve_dcp_dir(ckpt_dir: Path) -> Path:
|
||||
"""The DCP checkpoint id for a step dir (``step_{n}``) or its ``trainer`` subdir."""
|
||||
if (ckpt_dir / "trainer" / ".metadata").exists():
|
||||
return ckpt_dir / "trainer"
|
||||
if (ckpt_dir / ".metadata").exists():
|
||||
return ckpt_dir
|
||||
raise FileNotFoundError(f"No DCP checkpoint found at {ckpt_dir} (expected {ckpt_dir}/trainer/.metadata)")
|
||||
|
||||
|
||||
def resolve_run_configs(step_dir: Path) -> tuple[ModelConfig, TokenizerConfig]:
|
||||
"""Model/tokenizer configs from the run's resolved config."""
|
||||
logger = get_logger()
|
||||
config_dir = get_config_dir(step_dir.parent.parent)
|
||||
for name in RUN_CONFIG_NAMES:
|
||||
path = config_dir / name
|
||||
if path.exists():
|
||||
logger.info(f"Reading model config from {path}")
|
||||
run_config = json.loads(path.read_text())
|
||||
break
|
||||
else:
|
||||
raise FileNotFoundError(
|
||||
f"No resolved run config ({' or '.join(RUN_CONFIG_NAMES)}) found under {config_dir} "
|
||||
"- the checkpoint must live in its run directory"
|
||||
)
|
||||
|
||||
model = ModelConfig(**run_config["model"])
|
||||
tokenizer = TokenizerConfig(**run_config["tokenizer"])
|
||||
return model.model_copy(update=CONVERSION_OVERRIDES), tokenizer
|
||||
|
||||
|
||||
def check_not_lora(model_config: ModelConfig, dcp_dir: Path) -> None:
|
||||
if model_config.lora is not None:
|
||||
raise ValueError("LoRA checkpoints are not supported - dcp_to_bf16 exports full fine-tunes only")
|
||||
metadata = FileSystemReader(dcp_dir).read_metadata()
|
||||
lora_keys = [k for k in metadata.state_dict_metadata if "lora_A" in k or "lora_B" in k or ".base_layer." in k]
|
||||
if lora_keys:
|
||||
raise ValueError(
|
||||
f"Checkpoint contains LoRA keys (e.g. {lora_keys[0]}) - dcp_to_bf16 exports full fine-tunes only"
|
||||
)
|
||||
|
||||
|
||||
def setup_single_process_env() -> None:
|
||||
"""Default the torchrun env vars so the script also runs under plain ``python``."""
|
||||
if "RANK" in os.environ:
|
||||
return
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("localhost", 0))
|
||||
free_port = sock.getsockname()[1]
|
||||
os.environ["MASTER_ADDR"] = "localhost"
|
||||
os.environ["MASTER_PORT"] = str(free_port)
|
||||
os.environ["RANK"] = "0"
|
||||
os.environ["WORLD_SIZE"] = "1"
|
||||
os.environ["LOCAL_RANK"] = "0"
|
||||
os.environ["LOCAL_WORLD_SIZE"] = "1"
|
||||
|
||||
|
||||
def save_model_assets(model, model_config: ModelConfig, tokenizer_config: TokenizerConfig, output_dir: Path) -> None:
|
||||
"""Save model config, generation config, processor and tokenizer next to the weights."""
|
||||
model.config.save_pretrained(output_dir)
|
||||
if model.generation_config:
|
||||
# training sets use_cache=False which can conflict with cache_implementation —
|
||||
# save with use_cache=True without mutating the model's config
|
||||
gen_config = deepcopy(model.generation_config)
|
||||
gen_config.use_cache = True
|
||||
gen_config.save_pretrained(output_dir)
|
||||
# Processor first: it saves its own (unmodified) tokenizer, which the configured
|
||||
# tokenizer (pad token, custom chat template) must override.
|
||||
processor = setup_processor(model_config)
|
||||
if processor is not None:
|
||||
processor.save_pretrained(output_dir)
|
||||
if tokenizer_config.name is None:
|
||||
tokenizer_config = tokenizer_config.model_copy(update={"name": model_config.name})
|
||||
setup_tokenizer(tokenizer_config).save_pretrained(output_dir)
|
||||
# Local trust_remote_code models localize auto_map to plain module names, so the
|
||||
# custom code files must travel with the weights.
|
||||
source_dir = Path(model_config.name)
|
||||
if source_dir.is_dir():
|
||||
for path in source_dir.glob("*.py"):
|
||||
shutil.copyfile(path, output_dir / path.name)
|
||||
|
||||
|
||||
def load_and_convert(ckpt_dir: Path):
|
||||
"""DCP-load a checkpoint and gather it as a rank-partial HF-format bf16 state dict.
|
||||
|
||||
Returns ``(model, model_config, tokenizer_config, state_dict, step_dir)``.
|
||||
"""
|
||||
logger = setup_logger("info")
|
||||
|
||||
dcp_dir = resolve_dcp_dir(ckpt_dir)
|
||||
step_dir = dcp_dir.parent
|
||||
model_config, tokenizer_config = resolve_run_configs(step_dir)
|
||||
check_not_lora(model_config, dcp_dir)
|
||||
|
||||
setup_single_process_env()
|
||||
setup_torch_distributed()
|
||||
|
||||
resolve_ep(model_config)
|
||||
parallel_dims = get_parallel_dims(model_config)
|
||||
model = setup_model(model_config, parallel_dims, loading_from_checkpoint_later=True)
|
||||
|
||||
logger.info(f"Loading DCP checkpoint from {dcp_dir}")
|
||||
dcp_load(state_dict={"app": AppState(model, [], None, None)}, checkpoint_id=dcp_dir)
|
||||
|
||||
logger.info("Gathering and converting weights")
|
||||
state_dict = gather_weights_parallel(model, dtype=torch.bfloat16)
|
||||
if getattr(model.config, "tie_word_embeddings", False):
|
||||
for key in getattr(model, "_tied_weights_keys", []):
|
||||
state_dict.pop(key, None)
|
||||
state_dict = convert_state_dict_to_hf(model, state_dict)
|
||||
return model, model_config, tokenizer_config, state_dict, step_dir
|
||||
|
||||
|
||||
def convert(ckpt_dir: Path, output_dir: Path | None = None) -> Path:
|
||||
logger = get_logger()
|
||||
model, model_config, tokenizer_config, state_dict, step_dir = load_and_convert(ckpt_dir)
|
||||
output_dir = output_dir if output_dir is not None else step_dir / "weights"
|
||||
|
||||
logger.info(f"Writing HF weights to {output_dir}")
|
||||
save_state_dict_parallel(state_dict, output_dir)
|
||||
if get_world().is_master:
|
||||
save_model_assets(model, model_config, tokenizer_config, output_dir)
|
||||
logger.info(f"Done: {output_dir}")
|
||||
return output_dir
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument(
|
||||
"ckpt_dir", type=Path, help="the DCP checkpoint (<run>/checkpoints/step_{n} or .../step_{n}/trainer)"
|
||||
)
|
||||
parser.add_argument("output_dir", type=Path, nargs="?", default=None, help="default: <ckpt_dir>/weights")
|
||||
args = parser.parse_args()
|
||||
convert(args.ckpt_dir, args.output_dir)
|
||||
dist.destroy_process_group()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Convert a DCP trainer checkpoint into blockwise-FP8 HF weights.
|
||||
|
||||
Same gather as ``dcp_to_bf16``, but each rank quantizes its slice on GPU and
|
||||
only the fp8 shards are written — no intermediate bf16 export on disk.
|
||||
|
||||
Usage (from the prime-rl repo; more ranks = faster gathers, quantization and writes):
|
||||
uv run python tools/convert_dcp_to_fp8.py <run>/checkpoints/step_{n} [output_dir]
|
||||
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_fp8.py \
|
||||
<run>/checkpoints/step_{n} [output_dir]
|
||||
|
||||
Writes to ``<ckpt_dir>/weights-FP8`` by default.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from convert_bf16_to_fp8 import quantization_config, quantize_state_dict
|
||||
from convert_dcp_to_bf16 import load_and_convert, save_model_assets
|
||||
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.weights import save_state_dict_parallel
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument(
|
||||
"ckpt_dir", type=Path, help="the DCP checkpoint (<run>/checkpoints/step_{n} or .../step_{n}/trainer)"
|
||||
)
|
||||
parser.add_argument("output_dir", type=Path, nargs="?", default=None, help="default: <ckpt_dir>/weights-FP8")
|
||||
parser.add_argument("--block-size", type=int, default=128)
|
||||
args = parser.parse_args()
|
||||
|
||||
model, model_config, tokenizer_config, state_dict, step_dir = load_and_convert(args.ckpt_dir)
|
||||
output_dir = args.output_dir if args.output_dir is not None else step_dir / "weights-FP8"
|
||||
logger = get_logger()
|
||||
world = get_world()
|
||||
|
||||
logger.info("Quantizing weights to blockwise fp8")
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
state_dict, modules_to_not_convert = quantize_state_dict(state_dict, args.block_size, device)
|
||||
|
||||
logger.info(f"Writing fp8 weights to {output_dir}")
|
||||
save_state_dict_parallel(state_dict, output_dir)
|
||||
|
||||
all_modules: list[list[str] | None] = [None] * world.world_size
|
||||
dist.all_gather_object(all_modules, modules_to_not_convert)
|
||||
dist.destroy_process_group()
|
||||
|
||||
if world.is_master:
|
||||
save_model_assets(model, model_config, tokenizer_config, output_dir)
|
||||
config_path = output_dir / "config.json"
|
||||
config = json.loads(config_path.read_text())
|
||||
config["quantization_config"] = quantization_config(
|
||||
[module for modules in all_modules for module in modules or []], args.block_size
|
||||
)
|
||||
config_path.write_text(json.dumps(config, indent=2) + "\n")
|
||||
logger.info(f"Done: {output_dir}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Dequantize a blockwise-FP8 HF checkpoint (DeepSeek/GLM format) to bf16.
|
||||
|
||||
The inverse of ``tools/convert_bf16_to_fp8.py``, and works on official fp8-only
|
||||
releases (e.g. GLM-5-FP8): every e4m3 tensor is multiplied by its
|
||||
``<name>_scale_inv`` per-block scales and stored as bf16, scale tensors are
|
||||
dropped, and ``quantization_config`` is stripped from ``config.json``.
|
||||
|
||||
Usage (from the prime-rl repo):
|
||||
uv run python tools/convert_fp8_to_bf16.py <model_dir> [output_dir]
|
||||
|
||||
Writes to ``<model_dir>-BF16`` by default.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from safetensors import safe_open
|
||||
from safetensors.torch import save_file
|
||||
|
||||
|
||||
def dequantize_blockwise(weight: torch.Tensor, scales: torch.Tensor, block_size: tuple[int, int]) -> torch.Tensor:
|
||||
rows, cols = weight.shape
|
||||
block_rows, block_cols = block_size
|
||||
expanded = scales.repeat_interleave(block_rows, dim=0)[:rows].repeat_interleave(block_cols, dim=1)[:, :cols]
|
||||
return (weight.to(torch.float32) * expanded).to(torch.bfloat16)
|
||||
|
||||
|
||||
def list_shards(model_dir: Path) -> list[str]:
|
||||
index_path = model_dir / "model.safetensors.index.json"
|
||||
if index_path.exists():
|
||||
weight_map = json.loads(index_path.read_text())["weight_map"]
|
||||
return sorted(set(weight_map.values()))
|
||||
if (model_dir / "model.safetensors").exists():
|
||||
return ["model.safetensors"]
|
||||
raise FileNotFoundError(f"No safetensors checkpoint found in {model_dir}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("input_dir", type=Path, help="HF safetensors model dir with blockwise-fp8 weights")
|
||||
parser.add_argument("output_dir", type=Path, nargs="?", default=None, help="default: <input_dir>-BF16")
|
||||
args = parser.parse_args()
|
||||
|
||||
input_dir = args.input_dir.resolve()
|
||||
output_dir = args.output_dir or input_dir.with_name(input_dir.name + "-BF16")
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
|
||||
config = json.loads((input_dir / "config.json").read_text())
|
||||
quantization_config = config.pop("quantization_config", {})
|
||||
if quantization_config.get("scale_fmt") == "ue8m0":
|
||||
raise ValueError("ue8m0 scales are not supported - only plain float weight_scale_inv checkpoints")
|
||||
block_size = tuple(quantization_config.get("weight_block_size", [128, 128]))
|
||||
|
||||
index_path = input_dir / "model.safetensors.index.json"
|
||||
scale_to_shard = json.loads(index_path.read_text())["weight_map"] if index_path.exists() else {}
|
||||
|
||||
# Scales can live in a different shard than their weight; cache the most
|
||||
# recently opened shards to avoid re-reading them per tensor.
|
||||
shard_cache: dict[str, dict[str, torch.Tensor]] = {}
|
||||
|
||||
def get_scales(name: str, current_shard: str) -> torch.Tensor:
|
||||
shard_name = scale_to_shard.get(name, current_shard)
|
||||
if shard_name not in shard_cache:
|
||||
with safe_open(input_dir / shard_name, framework="pt", device=device) as f:
|
||||
shard_cache[shard_name] = {key: f.get_tensor(key) for key in f.keys()}
|
||||
while len(shard_cache) > 2:
|
||||
shard_cache.pop(next(iter(shard_cache)))
|
||||
if name not in shard_cache[shard_name]:
|
||||
raise KeyError(f"Missing {name} for fp8 tensor {name.removesuffix('_scale_inv')}")
|
||||
return shard_cache[shard_name][name]
|
||||
|
||||
weight_map: dict[str, str] = {}
|
||||
total_size = 0
|
||||
num_dequantized = 0
|
||||
|
||||
for shard_name in list_shards(input_dir):
|
||||
out_shard: dict[str, torch.Tensor] = {}
|
||||
with safe_open(input_dir / shard_name, framework="pt", device=device) as f:
|
||||
for name in f.keys():
|
||||
if name.endswith("_scale_inv"):
|
||||
continue
|
||||
tensor = f.get_tensor(name)
|
||||
if tensor.element_size() == 1:
|
||||
scales = get_scales(name + "_scale_inv", shard_name)
|
||||
out_shard[name] = dequantize_blockwise(tensor, scales, block_size).cpu()
|
||||
num_dequantized += 1
|
||||
else:
|
||||
out_shard[name] = tensor.cpu()
|
||||
for name, tensor in out_shard.items():
|
||||
weight_map[name] = shard_name
|
||||
total_size += tensor.nbytes
|
||||
save_file(out_shard, output_dir / shard_name, metadata={"format": "pt"})
|
||||
print(f"Dequantized {shard_name} ({num_dequantized} tensors so far)")
|
||||
|
||||
if num_dequantized == 0:
|
||||
raise ValueError(f"No fp8 weights found in {input_dir} - is this an fp8 checkpoint?")
|
||||
|
||||
index = {"metadata": {"total_size": total_size}, "weight_map": weight_map}
|
||||
(output_dir / "model.safetensors.index.json").write_text(json.dumps(index, indent=2, sort_keys=True) + "\n")
|
||||
|
||||
for path in input_dir.iterdir():
|
||||
if (
|
||||
path.is_file()
|
||||
and path.suffix != ".safetensors"
|
||||
and path.name not in ("model.safetensors.index.json", "config.json")
|
||||
):
|
||||
shutil.copyfile(path, output_dir / path.name)
|
||||
(output_dir / "config.json").write_text(json.dumps(config, indent=2) + "\n")
|
||||
print(f"Done: {num_dequantized} weights dequantized -> {output_dir}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user