Compare commits

...
Author SHA1 Message Date
e3fdadedc5 feat: trainer trace annotations + dashboard overlays (#3444)
## Summary

Every rollout episode is written to disk exactly once, as an
arrival-ordered stream, and everything learned about it afterwards is an
append-only annotation folded back on read. The trainer's recomputed
per-token streams ride that mechanism, and the trace viewer renders them
as overlays (entropy, the trainer↔sampling mismatch, the IPO stable
mask) next to the loss mask.

**Layout** (replaces
`rollouts/step_N/{train,eval}/{all,effective}/traces.jsonl`):

```
<run_dir>/monitors/file/metrics.jsonl                              # every metric row, tagged by producer
<run_dir>/monitors/file/traces/stream.jsonl                        # every episode, appended as it arrives
<run_dir>/monitors/file/traces/stream.index.jsonl                  # one compact row per episode, with its byte offset
<run_dir>/monitors/file/traces/annotations/<producer>.jsonl        # trace updates: orch ship-time facts, trainer per-token streams
<run_dir>/monitors/file/traces/annotations/<producer>.index.jsonl  # each update's scalars and where its record sits
```

Everything the file monitor dumps lives under its own directory, and
nothing is written there when the monitor is off. The traces and
everything written about them sit under `traces/`, and every index is
named for the stream it indexes and sits beside it. Each file is
append-only with exactly one writer, so there are no locks and live
tailing keeps working.

**Steps are events, not locations.** A trace is dispatched at one step,
arrives at another and is trained at a third, so a step directory could
only ever be honest about one of them — and picking arrival forced the
arrival step onto the batch wire just so the trainer could find the
right directory. Instead each step is stamped as its own event on the
record. `orchestrator/annotations.py` owns both events: `stamp_arrival`
puts `info.kind` plus `info.dispatch` / `info.arrival` (`{step, time}`)
on a trace as its episode lands, and `stamp_ship` produces the update
carrying `info.effective` and `info.ship` — the orchestrator step whose
batch shipped the cohort, or for eval the policy version the epoch
measured. Staleness is `ship.step - dispatch.step`; the trace viewer
shows all three for a train trace, and an eval trace shows the step it
measured instead (it never ships in a batch and never goes stale).

- **Annotations**: one record format and one fold, in
`prime_rl.monitors.trace_updates`, used by the file monitor, the trainer
writer and the dashboard. An update names a trace and carries an `info`
dict merged into the trace's own plus per-branch token streams,
full-length over the branch's token prefix (nulls mark unknown
positions) so folding never depends on the producer's loss mask.
- **Indexes**: the file monitor summarises each episode into
`stream.index.jsonl` as it writes it, and each update's scalars into the
producer's `.index.jsonl`, both with byte offsets. A reader browses the
indexes and seeks for the one episode it opens, so the cost of listing a
run stops scaling with the token streams — which outweigh the episodes
themselves.
- **Branch identity on the batch wire**: `TrainingSample` gains
`trace_id` / `branch_index`; `MicroBatch` carries them per sequence,
parallel to `sequence_lengths`, preserved through packing/padding and
nulled on dummy micro batches.
- **Trainer**: accumulates one update per trained sequence per forward
(packing-boundary first value and non-finite values are null), gathers
them to rank 0 at the end of each step, and logs them through its own
file monitor — the same monitor it already logs metrics through — rather
than writing to disk behind it. Always on; the token-export path is
gone.
- **Dashboard**: same HTTP API shape. The traces tab opens on the whole
stream — newest first, paged as you scroll, with a histogram of episodes
finished per interval you can click to narrow to a moment — and switches
to step mode for the cohort that shipped at one step (arrow keys walk
the step bar). Episode reads fold every annotation onto the record, so
the overlays work in both views. Token signals are Advantage, Entropy,
Mismatch (`r − log r − 1`, computed client-side from the trainer and
sampling logprobs), Stable mask (`|Δp|` vs the run's IPO `eps`), Loss
Mask and Content Mask; an overlay the open episode cannot colour is
disabled in the selector and names the input it is missing, rather than
silently painting nothing. In a token overlay the reasoning renders
inside the token spans that already cover it instead of in its own box.
- Verifiers gained only the two per-token node fields the records land
on (`MessageNode.trainer_logprobs` / `entropies`, with matching `Branch`
spread properties) —
[verifiers#2481](https://github.com/PrimeIntellect-ai/verifiers/pull/2481),
merged; `deps/verifiers` tracks verifiers main.

## Verification

Reverse-text, 4 steps: 645 episodes on one stream, 496 annotated by both
producers, 55,694 masked tokens folded with every node's compact arrays
equal to its masked-token count. Mean KL mismatch 0.0014, mean entropy
0.61. Staleness came out as 336 traces shipped at their dispatch step
and 160 a step later — the lag the old layout could not express. Re-run
end to end on a 20-step reverse-text run after the layout change.
SFT-online-eval and verifiers `uv run eval` run shapes checked through
the real API with a FastAPI test client; the dashboard's browser smoke
suite covers the stream/step views, the histogram, the step bar and
every token signal.

## Breaking

- The `rollouts/` trace tree is gone. Episodes now live in one
`monitors/file/traces/stream.jsonl` stream, written once at arrival,
with the effective cohort expressed as
`monitors/file/traces/annotations/<producer>.jsonl` records instead of
duplicate episode copies (per-token advantages and the scalar advantage
now arrive via annotations). The dashboard reads only the new layout;
runs recorded before this change need the old dashboard.
- `metrics.jsonl` moves from the run root to
`monitors/file/metrics.jsonl`.
- `trainer.enable_token_export` is removed and `token_exports/` is no
longer written; the trainer's per-token streams are always logged as
annotations.
- The filesystem batch transport writes packed micro batches to
`batches/step_<n>/rank_<r>.bin` (previously `rollouts/step_<n>/`).

## 20-step GLM-Air ScaleSWE comparison

- The baseline ran `main`; the comparison ran this PR. The code change
was the only behavioral difference. Run names, output directories, and
conversion cache paths were isolated.
- Trainer step 1: before 874.0 s; after 822.0 s (-5.9%).
- Trainer steps 1–20: before 3,179.2 s; after 2,995.2 s (-5.8%).
- Steady trainer steps 2–20: before 121.3 s mean / 120.0 s median; after
114.4 s mean / 99.0 s median. The after run was 5.7% faster by mean step
time.
- Trace data at each run's trainer step-20 cutoff: before 3.516 GB
across duplicated `all` and `effective` traces; after 3.476 GB across
the arrival stream plus orchestrator and trainer annotations. The after
layout was 1.1% smaller despite 864 MB of per-token trainer logprob and
entropy annotations.
- Dashboard on the after run at step 20: a 128-episode page took 15.7
ms, a 2.22 MB annotated episode took 42.7 ms, and its timeline took 9.7
ms.

The after job was cancelled after step 24 at the researcher's request.
The baseline completed trainer step 20.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Large observability and on-disk contract change (breaking paths and
removed `trainer.enable_token_export`); training/orchestration logic is
mostly additive but any tool still expecting `rollouts/` or root
`metrics.jsonl` will break.
> 
> **Overview**
> Replaces the per-step `rollouts/.../traces.jsonl` tree with a **file
monitor layout** under `monitors/file/`: metrics at `metrics.jsonl`,
episodes in one append-only `traces/stream.jsonl` plus sidecar indexes,
and **append-only trace annotations** per producer (orchestrator
ship-time facts, trainer per-token streams).
> 
> **Orchestrator/evals** stamp arrival metadata on episodes at log time
and log **effective cohort** membership, advantages, and ship step via
`log_annotations` instead of duplicating episode files. **Trainer**
drops `enable_token_export` / `token_exports/`; per-token logprobs and
entropies always go through the same annotation path. **Dashboard**
reads the new layout: stream vs step cohort views, paged
`/api/runs/.../episodes`, arrival histogram, and token overlays
(entropy, mismatch KL, IPO stable mask, masks) folded from annotations.
> 
> Docs, skills, configs, and `run_single_benchmark.py` are updated for
the new paths and for skipping non-step metric rows. Filesystem batch
transport writes to `batches/step_*` instead of under `rollouts/`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
16bf663b7805ecfe7d993ff6b6d34c8b7bc47308. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-01 17:17:54 -07:00
41 changed files with 2006 additions and 908 deletions
+8 -3
View File
@@ -23,6 +23,7 @@ import torch
from pydantic import Field
from prime_rl.utils.config import BaseConfig, cli
from prime_rl.utils.pathing import get_file_monitor_dir
MAX_LORAS = 4
@@ -207,13 +208,16 @@ def aggregate_metrics(metrics_path: Path) -> dict:
Each metrics.jsonl line is one monitor.log call (``{"step": N, ...}``);
merge the lines per step, drop the first (warmup) step, and compute
mean/std/min/max per metric like the old --bench JSON export did.
mean/std/min/max per metric like the old --bench JSON export did. Rows
keyed by wall time rather than step (``step: null``) are not per-step and
are skipped.
"""
per_step: dict[int, dict] = {}
with open(metrics_path) as f:
for line in f:
row = json.loads(line)
per_step.setdefault(row["step"], {}).update(row)
if row.get("step") is not None:
per_step.setdefault(row["step"], {}).update(row)
steps = sorted(per_step)[1:] # Exclude first warmup step
columns = {
@@ -255,7 +259,8 @@ def run_benchmark(config: BenchmarkConfig) -> None:
return
# The SFT entrypoint writes to output_dir/<run.name>, the RL trainer to output_dir directly
metrics_path = output_dir / "bench" / "metrics.jsonl" if config.type == "sft" else output_dir / "metrics.jsonl"
run_dir = output_dir / "bench" if config.type == "sft" else output_dir
metrics_path = get_file_monitor_dir(run_dir) / "metrics.jsonl"
start_time = time.perf_counter()
try:
+1 -1
View File
@@ -2,7 +2,7 @@
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions) that aren't surfaced here.
## Table of Contents
+1 -1
View File
@@ -277,4 +277,4 @@ uv run sft @ sft.toml --data.type fake --max-steps 4
uv run trainer @ train.toml --data.fake --max-steps 4
```
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `metrics.jsonl` to the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `monitors/file/metrics.jsonl` under the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
+2 -2
View File
@@ -351,13 +351,13 @@ tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
### Dashboard
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from `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.
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. 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
W&B is off by default (the file monitor, which writes `metrics.jsonl` and the per-step trace files to the run directory, is on by default):
W&B is off by default (the file monitor, which writes the metrics and the trace stream under the run's `monitors/file/` directory, is on by default):
```bash
uv run rl @ rl.toml --monitors.wandb # default project, random name
-1
View File
@@ -84,7 +84,6 @@ partition = "all" # FILL IN: set to your cluster's partition
[trainer]
dist_timeout_seconds = 1800
enable_token_export = true
[trainer.model]
name = "zai-org/GLM-5.1"
+13
View File
@@ -21,6 +21,19 @@ env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 5
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text-eval"
num_examples = 256
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -25,7 +25,8 @@ class WandbMonitorConfig(BaseConfig):
class FileMonitorConfig(BaseConfig):
path: Path = Path("metrics.jsonl")
"""Path of the JSONL file, relative to the component's ``output_dir`` (absolute paths win)."""
"""Path of the metrics JSONL file, relative to the file monitor's directory under the
component's ``output_dir`` (``monitors/file/``; absolute paths win)."""
class PrimeMonitorConfig(BaseConfig):
@@ -100,7 +100,7 @@ class SharedMonitorsConfig(BaseConfig):
"""Shared W&B config. Propagated to trainer and orchestrator."""
file: FileMonitorConfig | None = None
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/metrics.jsonl`` on both trainer and orchestrator."""
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/monitors/file/metrics.jsonl`` on both trainer and orchestrator."""
prime: PrimeMonitorConfig | None = None
"""Prime platform monitor. Propagated to the orchestrator only — the trainer has no platform integration."""
@@ -668,9 +668,6 @@ class TrainerConfig(BaseConfig):
metrics_server: MetricsServerConfig | None = None
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
enable_token_export: bool = False
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
env_vars: EnvVars = {}
"""Extra environment variables for the trainer process(es). Merged on top of the launcher defaults."""
-10
View File
@@ -86,16 +86,6 @@ The `sft` entrypoint takes the same eval shape at the top level for online evals
In TOML, an empty section header (`[ckpt]`) does the same.
## RL trainer token exports
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `<run_dir>/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
```toml
enable_token_export = true
```
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
## Key files
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
+3 -1
View File
@@ -73,7 +73,9 @@ curl -sS -X POST $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/view
`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
address the episode by stable `id`. The traces tab opens on the whole stream;
`subset: "effective"` switches it to the cohort that shipped at one step. 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.
+38 -18
View File
@@ -50,15 +50,15 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
- `{run_dir}/configs/latest/` — the current attempt's command, launch TOML, and `resolved/` JSON files. Each launch stays under `configs/attempt_<n>/`.
- `{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}/monitors/file/` — the metrics, and the traces with the annotations about them (see Episodes below).
### Dashboard
`uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR` if set; several dirs can be tracked at
once) serves a local web dashboard at `http://localhost:7788` with four views per run:
metrics (the W&B overview sections, read from `metrics.jsonl`), per-attempt config
files, a rollout trace viewer with a per-token advantage/logprob view, and merged
component logs. It only reads the run dirs — safe to run against a live run.
files, a rollout trace viewer with per-token overlays (advantage, trainer logprob,
entropy, KL mismatch, stable/loss/content masks), and merged component logs. It only reads the run dirs — safe to run against a live run.
`--port`/`--host` pick the bind address; a taken port automatically bumps to the next
free one, so several dashboards run side by side without coordination. GPU deps live
behind the `gpu` extra, so `uv sync --extra dashboard && uv run dashboard` works
@@ -162,27 +162,47 @@ 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}/monitors/file/metrics.jsonl # every metric row, tagged by producer
{run_dir}/monitors/file/traces/stream.jsonl # every episode, appended as it arrives
{run_dir}/monitors/file/traces/stream.index.jsonl # one compact row per episode, with its byte offset
{run_dir}/monitors/file/traces/annotations/{producer}.jsonl # trace updates: orch ship-time facts, trainer per-token streams
{run_dir}/monitors/file/traces/annotations/{producer}.index.jsonl # each update's scalars and where its record sits
```
JSONL files of native `vf.Episode` records (training tensors excluded), one line per episode.
`all` gets every completed episode as it arrives — including trace-less failures,
curriculum-rejected work, and work that never enters a batch — so it is crash-durable.
`effective` contains the admitted clean trainable traces grouped into their original episodes
(eval: the non-errored trainable epoch cohort). Each record carries its provenance at the
episode level: `env` (`id` plus the orchestrator's `name`), full `task`, `group` (`id`),
and `run`. Training-run records discriminate train/eval work and include dispatch
step plus an optional live-policy version span. Traces retain their own task,
verifiers, agent, and runtime fields.
Everything the file monitor dumps lives under `monitors/file/`; nothing is written
there when the monitor is off. The traces and everything written about them sit under
`traces/`, and every index is named for the stream it indexes and sits beside it. Those
indexes are what keep reading a run cheap: a consumer browses them instead of the
streams, and seeks by the offsets they carry to read a single episode or its token
streams. Both are derived, so deleting them only costs a reader the work of rebuilding
what it needs. `stream.jsonl` is a stream of native `vf.Episode`
records (training tensors excluded), one line per episode in arrival order, whatever
kind of work it did — including trace-less failures, curriculum-rejected work, and
work that never enters a batch, so it is crash-durable. Each record carries its
provenance: `env` (`id` plus the orchestrator's `name`), full `task`, `group` (`id`),
and `run`.
A trace has several steps, so each is stamped as its own event rather than implied by
where the record sits. The file monitor stamps `info.kind` and `info.dispatch`/
`info.arrival` (`{step, time}` each) as an episode lands; the ship-time annotation adds
`info.effective` and `info.ship` — the orchestrator step whose batch shipped the
cohort, or for eval the step that produced the policy it measured. Staleness is
`ship.step - dispatch.step`. Only `effective` ties to a step; `all` is the whole stream.
Everything learned after arrival is an append-only trace update keyed by `trace_id`,
one file per producer so each has a single writer: the orchestrator records cohort
membership, the scalar advantage and per-branch advantage streams; the trainer records
its recomputed per-token logprobs and entropies. Readers fold the updates onto the
stream records, newest winning.
```bash
wc -l {run_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
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
wc -l {run_dir}/monitors/file/traces/stream.jsonl
jq '.traces[].rewards' {run_dir}/monitors/file/traces/stream.jsonl
jq 'select(.ok | not) | {id, env: .env.id, errors}' {run_dir}/monitors/file/traces/stream.jsonl
jq '{trace_id, info}' {run_dir}/monitors/file/traces/annotations/orch.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}/batches/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank).
### Common failure modes
+462 -245
View File
@@ -2,8 +2,8 @@
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.
Reads everything from run output directories (metrics.jsonl, logs/attempt_N,
rollouts/step_N) — no wandb or network required. Usage:
Reads everything from run output directories (the file monitor's metrics and trace
streams, logs/attempt_N) — no wandb or network required. Usage:
uv run dashboard [output_dir ...] [--port 7788] [--host 127.0.0.1]
@@ -13,6 +13,7 @@ Multiple output directories can be tracked at once.
import argparse
import asyncio
import hashlib
import math
import os
import sys
import threading
@@ -23,7 +24,11 @@ from pathlib import Path
import orjson
from prime_rl.entrypoints.dashboard import DAEMON_FILE, DIRS_FILE, STATE_DIR, registry_lock
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
from prime_rl.monitors.file.traces.index import summarize_episode
from prime_rl.monitors.file.traces.update import branch_node_paths, fold_trace_updates
from prime_rl.utils.config import default_output_dir
from prime_rl.utils.pathing import get_file_monitor_dir
from prime_rl.utils.process import set_proc_title
try:
@@ -68,16 +73,18 @@ 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, bytes, list[int]]] = OrderedDict()
_summaries_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
_annotations_cache: OrderedDict[Path, tuple[tuple, dict[str, dict], dict[Path, int]]] = OrderedDict()
_index_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
_rows_cache: OrderedDict[Path, tuple] = OrderedDict() # key, rows, entered, by_trace, consumed, last row
_tokenizer_cache: dict[str, object] = {}
_piece_cache: dict[tuple[str, int], str] = {}
_json_cache: dict[Path, tuple[tuple[int, float], dict]] = {}
_steps_cache: dict[Path, tuple[float, list[int]]] = {}
def is_run_dir(path: Path) -> bool:
if not path.is_dir() or path.name.startswith("."):
return False
return any((path / marker).exists() for marker in ("configs", "logs", "metrics.jsonl", "rollouts"))
return any((path / marker).exists() for marker in ("configs", "logs", "monitors", "traces.jsonl"))
_dirs_file_state: tuple[float, list[Path]] = (0.0, [])
@@ -193,15 +200,6 @@ def numbered_dirs(parent: Path, prefix: str) -> list[tuple[int, Path]]:
)
def size_etag(path: Path, etag: str | None) -> tuple[str, dict | None]:
"""Etag = file size: the trace files are append-only, so an unchanged size means
an unchanged response. Returns (current_etag, short-circuit response or None)."""
current = str(path.stat().st_size)
if etag is not None and etag == current:
return current, {"unchanged": True, "etag": current}
return current, None
def model_name(config: dict) -> str | None:
"""`model` is a string on eval configs, a {name} object on rl/sft ones."""
model = config.get("model")
@@ -248,22 +246,14 @@ def attempt_numbers(run_dir: Path) -> list[int]:
return [n for n, _ in numbered_dirs(run_dir / "logs", "attempt_")]
def metrics_file(run_dir: Path) -> Path:
"""The run's metric stream, as the file monitor dumps it."""
return get_file_monitor_dir(run_dir) / "metrics.jsonl"
def step_numbers(run_dir: Path) -> list[int]:
"""Rollout step numbers, cached by the rollouts dir mtime (which changes when a
step dir is created) — polled per run on every /api/runs tick."""
rollouts = run_dir / "rollouts"
try:
mtime = rollouts.stat().st_mtime
except OSError:
return []
with _lock:
cached = _steps_cache.get(rollouts)
if cached and cached[0] == mtime:
return cached[1]
steps = [n for n, _ in numbered_dirs(rollouts, "step_")]
with _lock:
_steps_cache[rollouts] = (mtime, steps)
return steps
"""The steps a cohort shipped at — what a run's progress is measured in."""
return sorted({step for _, step in effective_steps(run_dir)})
def run_meta(run_dir: Path) -> dict:
@@ -275,7 +265,7 @@ def run_meta(run_dir: Path) -> dict:
return sorted(p.stem for p in (resolved / "envs" / split).glob("*.json"))
steps = step_numbers(run_dir)
metrics_path = run_dir / "metrics.jsonl"
metrics_path = metrics_file(run_dir)
started = updated = None
if metrics_path.is_file():
updated = metrics_path.stat().st_mtime
@@ -286,9 +276,9 @@ def run_meta(run_dir: Path) -> dict:
started = orjson.loads(f.readline()).get("time")
except orjson.JSONDecodeError:
started = None
root_traces = run_dir / "traces.jsonl"
if updated is None and root_traces.is_file(): # eval runs have no metrics.jsonl
updated = root_traces.stat().st_mtime
stream = traces_file(run_dir)
if updated is None and stream is not None: # eval runs have no metrics
updated = stream.stat().st_mtime
started = configs.stat().st_mtime if configs.is_dir() else None
return {
"name": run_dir.name,
@@ -504,7 +494,7 @@ so the first charts paint long before a 100MB metrics.jsonl finishes loading."""
@app.get("/api/runs/{run}/metrics")
def read_metrics(run: str, offset: int = 0) -> dict:
path = get_run_dir(run) / "metrics.jsonl"
path = metrics_file(get_run_dir(run))
if not path.is_file():
return {"rows": [], "offset": 0, "size": 0}
size = path.stat().st_size
@@ -528,49 +518,32 @@ def read_metrics(run: str, offset: int = 0) -> dict:
# ------------------------------------------------------------------------ rollouts
RECENT_STEPS = 64
_avail_cache: dict[Path, dict[str, bool]] = {} # step dir -> known-present subsets
_avail_scan_counter = 0
def traces_file(run_dir: Path) -> Path | None:
"""The run's episode stream. prime-rl dumps it through the file monitor; a
verifiers ``uv run eval`` run writes its own at the run root."""
for path in (get_trace_stream(run_dir), run_dir / "traces.jsonl"):
if path.is_file() and path.stat().st_size > 0:
return path
return None
EVAL_ROOT_STEP = (0, "eval", "all")
"""The virtual address of a stepless `uv run eval` run's root traces.jsonl —
the one convention shared by the step listing and traces_path."""
def eval_root_traces(run_dir: Path) -> Path | None:
root = run_dir / "traces.jsonl"
return root if root.is_file() and root.stat().st_size > 0 else None
def require_stream(run_dir: Path) -> Path:
path = traces_file(run_dir)
if path is None:
raise HTTPException(404, "no traces for this run")
return path
def rollout_steps(run_dir: Path) -> list[dict]:
"""Presence only — never reads trace files. Presence is monotonic (files only
appear), so known-present subsets are cached forever; absent ones re-stat every
poll only for the newest steps — older gaps (an eval landing late at its trigger
step) are picked up by a full rescan every 10th call."""
global _avail_scan_counter
_avail_scan_counter += 1
full_rescan = _avail_scan_counter % 10 == 1
numbered = numbered_dirs(run_dir / "rollouts", "step_")
recent_cutoff = numbered[-1][0] - RECENT_STEPS if numbered else 0
steps = []
for number, step_dir in numbered:
available = _avail_cache.setdefault(step_dir, {})
if len(available) < 4 and (full_rescan or number >= recent_cutoff):
for kind in ("train", "eval"):
for subset in ("all", "effective"):
key = f"{kind}/{subset}"
if key in available:
continue
path = step_dir / kind / subset / "traces.jsonl"
if path.is_file() and path.stat().st_size > 0:
available[key] = True
if available:
steps.append({"step": number, "available": available})
root = eval_root_traces(run_dir)
if not steps and root is not None:
steps.append({"step": EVAL_ROOT_STEP[0], "available": {f"{EVAL_ROOT_STEP[1]}/{EVAL_ROOT_STEP[2]}": True}})
return steps
"""The steps a cohort can be addressed by, and the kinds of work each one holds.
Only a cohort ties to a step — the orchestrator step whose batch shipped it, or
for eval the policy version it measured — so the steps come from the annotations.
The stream itself is not addressed by step."""
by_step: dict[int, set[str]] = {}
for kind, step in effective_steps(run_dir):
by_step.setdefault(step, set()).add(kind)
return [{"step": step, "kinds": sorted(kinds)} for step, kinds in sorted(by_step.items())]
def line_offsets(path: Path) -> list[int]:
@@ -616,88 +589,6 @@ def line_offsets(path: Path) -> list[int]:
return current
def walk_timing(obj: dict, prefix: str, out: dict[str, float]) -> None:
"""Flatten a trace timing tree to phase -> seconds (same walk as the viewer)."""
if isinstance(obj.get("duration"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + obj["duration"]
elif isinstance(obj.get("start"), (int, float)) and isinstance(obj.get("end"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + (obj["end"] - obj["start"])
for key, value in obj.items():
if isinstance(value, dict):
walk_timing(value, f"{prefix}/{key}" if prefix else key, out)
def summarize_episode(line: int, rec: dict) -> dict:
rewards, advantages = [], []
input_tokens = output_tokens = turns = branches = 0
stop_condition = None
reward_parts: dict[str, list[float]] = {}
metric_parts: dict[str, list[float]] = {}
timing: dict[str, float] = {}
costs: list[float] = []
for trace in rec.get("traces") or []:
costs.extend(
usage["cost"]
for call in trace.get("calls") or []
if isinstance(usage := call.get("usage") or {}, dict) and isinstance(usage.get("cost"), (int, float))
)
nodes = trace.get("nodes") or []
parents = {node.get("parent") for node in nodes if "parent" in node}
branches += max(0, len(nodes) - len(parents))
if trace.get("rewards"): # skip reward-less seats (e.g. a judge) in the episode mean
rewards.append(
sum(
(r.get("score") or 0) * (r.get("weight") if r.get("weight") is not None else 1)
for r in trace["rewards"].values()
if isinstance(r, dict)
)
)
for name, r in (trace.get("rewards") or {}).items():
if isinstance(r, dict) and isinstance(r.get("score"), (int, float)):
reward_parts.setdefault(name, []).append(r["score"])
for name, value in (trace.get("metrics") or {}).items():
if isinstance(value, (int, float)):
metric_parts.setdefault(name, []).append(value)
if isinstance(trace.get("timing"), dict):
walk_timing(trace["timing"], "", timing)
advantage = (trace.get("info") or {}).get("advantage")
if advantage is not None:
advantages.append(advantage)
for node in nodes:
n_tokens = len(node.get("token_ids") or [])
if node.get("sampled"):
output_tokens += n_tokens
else:
input_tokens += n_tokens
if (node.get("message") or {}).get("role") == "assistant":
turns += 1
stop_condition = trace.get("stop_condition", stop_condition)
if input_tokens == 0 and output_tokens == 0: # some eval traces carry no token arrays
for call in trace.get("calls") or []:
usage = call.get("usage") or {}
input_tokens += usage.get("prompt_tokens") or 0
output_tokens += usage.get("completion_tokens") or 0
return {
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
"metrics": {name: sum(v) / len(v) for name, v in metric_parts.items()},
"timing": timing,
"cost": sum(costs) if costs else None,
"line": line,
"id": rec.get("id"),
"env": (rec.get("env") or {}).get("id") or (rec.get("env") or {}).get("name"),
"group": (rec.get("group") or {}).get("id"),
"ok": rec.get("ok"),
"num_errors": len(rec.get("errors") or []),
"reward": sum(rewards) / len(rewards) if rewards else None,
"advantage": sum(advantages) / len(advantages) if advantages else None,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"turns": turns,
"branches": branches,
"stop_condition": stop_condition,
}
def episode_summaries(path: Path) -> list[dict]:
offsets = line_offsets(path)
with _lock:
@@ -719,9 +610,9 @@ def episode_summaries(path: Path) -> list[dict]:
for line_no in range(cached_count, len(offsets)):
raw = f.readline()
try:
summaries.append(summarize_episode(line_no, orjson.loads(raw)))
summaries.append(summarize_episode(line_no + 1, orjson.loads(raw)))
except orjson.JSONDecodeError:
summaries.append({"line": line_no, "id": None, "error": "unparseable"})
summaries.append({"line": line_no + 1, "id": None, "error": "unparseable"})
with _lock:
_lru_put(_summaries_cache, path, (len(offsets), summaries))
write_sidecar(path, summaries)
@@ -733,6 +624,7 @@ def episode_summaries(path: Path) -> list[dict]:
# result is persisted outside the run dir (the dashboard never writes there),
# so a revisit — or a dashboard restart — skips the parse entirely.
SIDECAR_DIR = STATE_DIR
SIDECAR_FORMAT = 4
SIDECAR_WRITE_INTERVAL_S = 20.0
_sidecar_written: dict[Path, tuple[float, int]] = {} # path -> (last write time, count)
@@ -758,7 +650,8 @@ def load_sidecar(path: Path) -> list[dict] | None:
data = read_json(sidecar_path(path))
try:
if (
data.get("path") != str(path.resolve())
data.get("format") != SIDECAR_FORMAT
or data.get("path") != str(path.resolve())
or path.stat().st_size < data["size"]
or data.get("checkpoint") != file_checkpoint(path, data["size"]).hex()
):
@@ -777,6 +670,7 @@ def write_sidecar(path: Path, summaries: list[dict]) -> None:
SIDECAR_DIR.mkdir(parents=True, exist_ok=True)
size = path.stat().st_size
payload = {
"format": SIDECAR_FORMAT,
"path": str(path.resolve()),
"size": size,
"checkpoint": file_checkpoint(path, size).hex(),
@@ -789,26 +683,11 @@ def write_sidecar(path: Path, summaries: list[dict]) -> None:
def traces_path(run: str, step: int, kind: str, subset: str) -> Path:
"""The run's episode stream. ``step``/``kind``/``subset`` never select a file —
every episode is on disk exactly once — they select the read-time filter."""
if kind not in ("train", "eval") or subset not in ("all", "effective"):
raise HTTPException(400, "kind must be train|eval, subset all|effective")
run_dir = get_run_dir(run)
path = run_dir / "rollouts" / f"step_{step}" / kind / subset / "traces.jsonl"
if path.is_file():
return path
if (step, kind, subset) == EVAL_ROOT_STEP:
root = eval_root_traces(run_dir)
if root is not None:
return root
raise HTTPException(404, "no traces for this step/kind/subset")
def read_episode_record(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())
return require_stream(get_run_dir(run))
def message_text(message: dict) -> str:
@@ -838,22 +717,111 @@ def timeline_reward(trace: dict) -> float | None:
)
def trace_branch_paths(nodes: list[dict]) -> list[list[int]]:
"""Return VF-native root-to-leaf branches in leaf-index order."""
if not nodes:
def _file_size(path: Path) -> int:
try:
return path.stat().st_size
except OSError:
return -1
def annotations_files(run_dir: Path) -> list[Path]:
"""The annotation records themselves, one file per producer — their indexes are
named for them, so a name that is already an index is one of those."""
directory = get_annotations_dir(run_dir)
if not directory.is_dir():
return []
parents = {parent for node in nodes if isinstance((parent := node.get("parent")), int) and 0 <= parent < len(nodes)}
paths = []
for leaf in (index for index in range(len(nodes)) if index not in parents):
path = []
seen = set()
node_index: int | None = leaf
while isinstance(node_index, int) and 0 <= node_index < len(nodes) and node_index not in seen:
seen.add(node_index)
path.append(node_index)
node_index = nodes[node_index].get("parent")
paths.append(list(reversed(path)))
return paths
return sorted(path for path in directory.glob("*.jsonl") if not path.name.endswith(".index.jsonl"))
def annotation_source(data: Path) -> Path:
"""The file a producer's rows are read from: its index when it wrote one, else the
records themselves. Whatever depends on those rows versions itself by this file's
size - the record file can grow before its index row is flushed, and a version
taken from it would miss the index completing."""
index = get_index_path(data)
return index if index.is_file() else data
def annotation_rows(data: Path) -> list[dict]:
"""A producer's updates as index rows - ``{trace_id, info, offset}`` - read from its
index when it wrote one, and derived from the records themselves when it did not."""
rows = index_rows(get_index_path(data))
if rows is not None:
return rows
size = data.stat().st_size
with _lock:
cached = _lru_get(_index_cache, data)
if cached and cached[0] == size:
return cached[1]
rows, offset = [], 0
with data.open("rb") as f:
for raw in f:
try:
update = orjson.loads(raw)
except orjson.JSONDecodeError:
break
rows.append({"trace_id": update.get("trace_id"), "info": update.get("info"), "offset": offset})
offset += len(raw)
with _lock:
_lru_put(_index_cache, data, (size, rows))
return rows
def annotation_index(run_dir: Path) -> dict[str, dict]:
"""Trace id -> the scalars its updates carry, and where each record sits.
Reads the producers' indexes when they exist, so answering "which cohort, what
credit" never touches the token streams — they can outweigh the traces themselves.
A producer that wrote no index is read in full."""
files = annotations_files(run_dir)
key = tuple((data.name, _file_size(annotation_source(data))) for data in files)
cache_key = get_annotations_dir(run_dir)
with _lock:
cached = _lru_get(_annotations_cache, cache_key)
if cached and cached[0] == key:
return cached[1]
# Producers only append, so the fold resumes from the row each one was last read
# to. The map is copied rather than grown in place: a request already iterating
# the previous one must not see it change size under it.
consumed, index = ({}, {}) if cached is None else (dict(cached[2]), dict(cached[1]))
def note(trace_id: str | None, info: dict, data: Path, offset: int) -> None:
if not trace_id:
return
entry = index.setdefault(trace_id, {"info": {}, "at": []})
entry["info"].update(info)
entry["at"].append((data, offset))
for data in files:
rows = annotation_rows(data)
for row in rows[consumed.get(data, 0) :]:
note(row.get("trace_id"), row.get("info") or {}, data, row.get("offset", 0))
consumed[data] = len(rows)
with _lock:
_lru_put(_annotations_cache, cache_key, (key, index, consumed))
return index
def trace_updates(run_dir: Path, trace_id: str) -> list[dict]:
"""Every update recorded against one trace, read by seeking to each record."""
entry = annotation_index(run_dir).get(trace_id)
updates = []
for path, offset in (entry or {}).get("at", []):
try:
with path.open("rb") as f:
f.seek(offset)
updates.append(orjson.loads(f.readline()))
except (OSError, orjson.JSONDecodeError):
continue
return updates
def ipo_eps(run_dir: Path) -> float:
"""The run's IPO threshold: how far a token's probability may move before the
loss drops it. It is what the stable-mask overlay colours against."""
loss = read_json(resolved_config_dir(run_dir) / "trainer.json").get("loss") or {}
eps = loss.get("eps") if loss.get("type") == "ipo" else None
return eps if isinstance(eps, (int, float)) else 0.1
def token_usage(usage: dict) -> tuple[int | None, int | None, int | None]:
@@ -1015,7 +983,7 @@ def project_episode_timeline(episode: dict) -> dict:
lane_groups = []
for trace_index, trace in enumerate(episode.get("traces") or []):
nodes = trace.get("nodes") or []
branch_paths = trace_branch_paths(nodes)
branch_paths = branch_node_paths(nodes)
node_branch_counts: dict[int, int] = {}
for path in branch_paths:
for node_index in path:
@@ -1102,40 +1070,264 @@ def project_episode_timeline(episode: dict) -> dict:
return {"lanes": lanes}
NICE_BINS = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400]
def nice_bin(ideal: float) -> float:
"""The smallest round interval at least this wide, so bars land on seconds,
minutes or hours a reader recognises rather than 93.4s."""
return next((step for step in NICE_BINS if step >= ideal), NICE_BINS[-1])
SORT_KEYS = {"arrival", "duration", "reward", "output_tokens", "turns", "group"}
def stream_index_file(run_dir: Path) -> Path:
"""Where the stream's index would sit — beside the stream, named for it. A stream
written by a producer that indexes nothing simply has no file there."""
stream = traces_file(run_dir)
return get_index_path(stream) if stream else get_index_path(get_trace_stream(run_dir))
def index_rows(path: Path) -> list[dict] | None:
"""The rows of an index the file monitor wrote, read incrementally: an index is
append-only, so only the bytes past the last read are parsed. ``None`` when there
is no index, which is the reader's cue to derive what it needs itself."""
if not path.is_file():
return None
size = path.stat().st_size
with _lock:
cached = _lru_get(_index_cache, path)
if cached and cached[0] == size:
return cached[1]
rows, read_from = (list(cached[1]), cached[0]) if cached and cached[0] < size else ([], 0)
with path.open("rb") as f:
f.seek(read_from)
for raw in f:
if not raw.endswith(b"\n"):
break # a torn tail line: the writer is mid-append
try:
rows.append(orjson.loads(raw))
except orjson.JSONDecodeError:
break
read_from += len(raw)
with _lock:
_lru_put(_index_cache, path, (read_from, rows))
return rows
def written_index(run_dir: Path) -> list[dict] | None:
"""The stream's own index, when the stream's producer wrote one."""
return index_rows(stream_index_file(run_dir))
def episode_rows(run_dir: Path) -> list[dict]:
"""The run's episode index: one row per episode of the stream, in arrival order,
carrying the cohort step its annotations give it.
Everything here is append-only, so the work tracks the growth rather than the run:
new episodes are entered as they arrive, and a new ship-time update stamps only the
episodes that own its trace. A browse request pays for what changed since the last
one, however long the run gets."""
path = traces_file(run_dir)
if path is None:
return []
files = annotations_files(run_dir)
key = (
_file_size(stream_index_file(run_dir)),
path.stat().st_size,
*(_file_size(annotation_source(f)) for f in files),
)
with _lock:
cached = _lru_get(_rows_cache, run_dir)
if cached and cached[0] == key:
return cached[1]
rows = written_index(run_dir)
if rows is None:
rows = episode_summaries(path)
# Resume only over the very rows stamped last time: a shorter list is a rewrite,
# and a list rebuilt from disk holds new dicts the trace map would no longer reach.
entered = cached[2] if cached else 0
resume = bool(cached) and len(rows) >= entered and (entered == 0 or rows[entered - 1] is cached[5])
by_trace, consumed = (cached[3], dict(cached[4])) if resume else ({}, {})
if not resume:
entered = 0
for row in rows[entered:]:
row["step"] = None
for trace_id in row.get("trace_ids") or []:
by_trace.setdefault(trace_id, []).append(row)
for data in files:
updates = annotation_rows(data)
for update in updates[consumed.get(data, 0) :]:
info = update.get("info") or {}
step = (info.get("ship") or {}).get("step")
if not info.get("effective") or not isinstance(step, int):
continue
for row in by_trace.get(update.get("trace_id"), ()):
row["step"] = step if row["step"] is None else min(row["step"], step)
consumed[data] = len(updates)
with _lock:
_lru_put(_rows_cache, run_dir, (key, rows, len(rows), by_trace, consumed, rows[-1] if rows else None))
return rows
def row_filter(
*,
step: int | None = None,
kind: str | None = None,
env: str | None = None,
episode: str | None = None,
errors_only: bool = False,
start: float | None = None,
end: float | None = None,
):
"""A predicate over index rows. A step selects the cohort shipped at it — for
train work the orchestrator step, for eval the policy version — which is the only
sense in which an episode belongs to a step."""
def keep(row: dict) -> bool:
if step is not None and row.get("step") != step:
return False
if kind and row.get("kind") != kind:
return False
if env and row.get("env") != env:
return False
if episode is not None and row.get("id") != episode:
return False
if errors_only and not (row.get("num_errors") or not row.get("ok")):
return False
arrival = row.get("arrival") or 0
return not ((start is not None and arrival < start) or (end is not None and arrival >= end))
return keep
def filter_rows(rows: list[dict], **narrow) -> list[dict]:
keep = row_filter(**narrow)
return [row for row in rows if keep(row)]
def index_facets(run_dir: Path) -> tuple[list[str], list[str]]:
"""The envs and kinds the stream holds, for the filter controls."""
rows = episode_rows(run_dir)
envs = {row["env"] for row in rows if row.get("env")}
kinds = {row.get("kind") for row in rows}
return sorted(envs), [kind for kind in ("train", "eval") if kind in kinds]
@app.get("/api/runs/{run}/episodes")
def list_stream_episodes(
run: str,
step: int | None = None,
kind: str | None = None,
env: str | None = None,
episode: str | None = None,
errors_only: bool = False,
sort: str = "arrival",
order: str = "desc",
offset: int = Query(default=0, ge=0),
limit: int = Query(default=128, ge=1, le=512),
start: float | None = None,
end: float | None = None,
etag: str | None = None,
upto: int | None = Query(default=None, ge=0),
) -> dict:
"""One page of the stream. The client scrolls by asking for the next offset, so a
run of any length costs the same to browse.
A live stream grows at its head, which would shift every offset under a reader
mid-scroll. ``upto`` pins the page to the stream as it stood at that many lines -
the length the first page reported - so later pages address a list that no longer
moves, whatever the sort."""
run_dir = get_run_dir(run)
path = require_stream(run_dir)
current_etag = stream_etag(run_dir, path)
if etag is not None and etag == current_etag and offset == 0:
return {"unchanged": True, "etag": current_etag}
rows = episode_rows(run_dir)
lines = len(rows)
if upto is not None:
rows = rows[:upto]
envs, kinds = index_facets(run_dir)
keep = row_filter(step=step, kind=kind, env=env, episode=episode, errors_only=errors_only, start=start, end=end)
if sort == "arrival":
# the index is already in arrival order: walk it from the right end and stop
# once the page is full, so the common view costs a page rather than a run
ordered = reversed(rows) if order == "desc" else rows
page, total = [], 0
for row in ordered:
if not keep(row):
continue
if offset <= total < offset + limit:
page.append(row)
total += 1
else:
matching = [row for row in rows if keep(row)]
blank = "" if sort == "group" else 0
if sort in SORT_KEYS:
matching.sort(key=lambda row: (row.get(sort) is None, row.get(sort) or blank), reverse=order == "desc")
page, total = matching[offset : offset + limit], len(matching)
return {
"etag": current_etag,
"lines": lines,
"total": total,
"offset": offset,
"envs": envs,
"kinds": kinds,
"episodes": page,
}
@app.get("/api/runs/{run}/episodes/histogram")
def episode_histogram(
run: str,
step: int | None = None,
kind: str | None = None,
env: str | None = None,
errors_only: bool = False,
bars: int = Query(default=80, ge=8, le=500),
) -> dict:
"""Episodes finishing per time bin, over the same filters as the table — the
stream's shape, and the thing you click to narrow it to a moment. The range fits
the episodes and the bin is the roundest interval that keeps the bar count sane,
so a run of any length reads the same."""
run_dir = get_run_dir(run)
rows = filter_rows(episode_rows(run_dir), step=step, kind=kind, env=env, errors_only=errors_only)
arrivals = sorted(row["arrival"] for row in rows if isinstance(row.get("arrival"), (int, float)))
if not arrivals:
return {"bins": [], "bin": 60, "start": None, "end": None, "total": 0}
bin = nice_bin(max(arrivals[-1] - arrivals[0], 1e-9) / bars)
# square the edges to bin boundaries so the bars carry round timestamps
start = math.floor(arrivals[0] / bin) * bin
end = math.floor(arrivals[-1] / bin) * bin + bin
counts: dict[int, int] = {}
for arrival in arrivals:
index = int((arrival - start) // bin)
counts[index] = counts.get(index, 0) + 1
span = max(1, int(round((end - start) / bin)))
return {
"bins": [[start + index * bin, counts.get(index, 0)] for index in range(span)],
"bin": bin,
"start": start,
"end": end,
"total": sum(counts.values()),
}
@app.get("/api/runs/{run}/rollouts")
def list_rollouts(run: str) -> dict:
return {"steps": rollout_steps(get_run_dir(run))}
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}")
def list_episodes(
run: str,
step: int,
kind: str,
subset: str,
limit: int = Query(default=5000, ge=1, le=5000),
episode: str | None = None,
env: str | None = None,
errors_only: bool = False,
sort: str = "line",
order: str = "asc",
etag: str | None = None,
) -> dict:
path = traces_path(run, step, kind, subset)
current_etag, unchanged = size_etag(path, etag)
if unchanged:
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:
summaries = [s for s in summaries if s.get("num_errors") or not s.get("ok")]
if sort in ("reward", "advantage", "output_tokens", "turns", "group"):
summaries = sorted(summaries, key=lambda s: (s.get(sort) is None, s.get(sort) or 0), reverse=(order == "desc"))
return {"total": len(summaries), "etag": current_etag, "envs": envs, "episodes": summaries[:limit]}
def stream_etag(run_dir: Path, path: Path) -> str:
"""What a listing depends on: the stream, and the annotations that give its rows
their cohort and credit. Both are append-only, so their sizes are the version."""
return f"{path.stat().st_size}-{sum(_file_size(annotation_source(f)) for f in annotations_files(run_dir))}"
def effective_steps(run_dir: Path) -> set[tuple[str, int]]:
"""The (kind, step) pairs an effective cohort can be addressed by."""
return {(row["kind"], row["step"]) for row in episode_rows(run_dir) if row.get("step") is not None}
def get_tokenizer(model: str):
@@ -1217,16 +1409,17 @@ def rendered_token_text(trace: dict, model: str | None) -> dict:
}
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/series")
def episode_series(run: str, step: int, kind: str, subset: str, etag: str | None = None, after: int = 0) -> dict:
"""Per-episode series over a traces file (x = episode order): reward, shape, and the
@app.get("/api/runs/{run}/episodes/series")
def episode_series(run: str, kind: str | None = None, etag: str | None = None, after: int = 0) -> dict:
"""Per-episode series over the stream (x = arrival order): reward, shape, and the
nested rewards/metrics/timing keys — the metrics view for eval runs. `after` returns
only episodes past that index, so a growing file ships increments, not the world."""
path = traces_path(run, step, kind, subset)
current_etag, unchanged = size_etag(path, etag)
if unchanged:
return unchanged
summaries = episode_summaries(path)
only episodes past that index, so a growing stream ships increments, not the world."""
run_dir = get_run_dir(run)
path = require_stream(run_dir)
current_etag = stream_etag(run_dir, path)
if etag is not None and etag == current_etag:
return {"unchanged": True, "etag": current_etag}
summaries = [s for s in episode_summaries(path) if not kind or s.get("kind") == kind]
keys: set[str] = set()
for s in summaries:
keys.update(
@@ -1246,30 +1439,53 @@ 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")
def read_episode_at(path: Path, line: int, offset: int | None = None) -> dict:
"""One episode. A written index carries the byte offset, so reading it never
touches the rest of the stream."""
if offset is None:
offsets = line_offsets(path)
if not 1 <= line <= len(offsets):
raise HTTPException(404, "episode line out of range")
offset = offsets[line - 1]
with path.open("rb") as f:
f.seek(offsets[line])
return orjson.loads(f.readline())
f.seek(offset)
try:
return orjson.loads(f.readline())
except orjson.JSONDecodeError as error:
# a record torn by a crash, or the stream's last line caught mid-append
raise HTTPException(422, f"episode {line} is unparseable") from error
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/{line}")
def episode_offset(run_dir: Path, line: int) -> int | None:
rows = written_index(run_dir)
if rows is None or not 1 <= line <= len(rows):
return None
return rows[line - 1].get("offset")
@app.get("/api/runs/{run}/episodes/{line}")
def get_episode(
run: str,
step: int,
kind: str,
subset: str,
line: int,
tokens: bool = False,
rendered: bool = False,
) -> dict:
path = traces_path(run, step, kind, subset)
rec = read_episode_at(path, line)
"""One episode, by its line in the stream, with every annotation folded on."""
run_dir = get_run_dir(run)
path = require_stream(run_dir)
rec = read_episode_at(path, line, episode_offset(run_dir, line))
# only the opened episode's streams are read, by seeking to each of its records
for trace in rec.get("traces") or []:
updates = trace_updates(run_dir, trace.get("id") or "")
if not updates:
continue
stamped = fold_trace_updates(trace, updates)
if stamped:
ship_step = ((trace.get("info") or {}).get("ship") or {}).get("step")
trace["train_annotations"] = {"step": ship_step, "nodes": stamped, "eps": ipo_eps(run_dir)}
if not tokens and not rendered:
return rec
fallback_model = model_name(main_config(get_run_dir(run))[1])
fallback_model = model_name(main_config(run_dir)[1])
for trace in rec.get("traces") or []:
client = ((trace.get("agent") or {}).get("config") or {}).get("client") or {}
model = client.get("renderer_model_name") or fallback_model
@@ -1364,7 +1580,7 @@ def validate_view_command(cmd: dict) -> dict:
rec = None
if episode is not None:
matches = [s["line"] for s in episode_summaries(path) if s.get("id") == episode]
matches = [row["line"] for row in episode_rows(get_run_dir(run)) if row.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:
@@ -1468,9 +1684,10 @@ async def view_events() -> "StreamingResponse":
)
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/{line}/timeline")
def get_episode_timeline(run: str, step: int, kind: str, subset: str, line: int) -> dict:
return project_episode_timeline(read_episode_at(traces_path(run, step, kind, subset), line))
@app.get("/api/runs/{run}/episodes/{line}/timeline")
def get_episode_timeline(run: str, line: int) -> dict:
run_dir = get_run_dir(run)
return project_episode_timeline(read_episode_at(require_stream(run_dir), line, episode_offset(run_dir, line)))
# -------------------------------------------------------------------------- static
File diff suppressed because it is too large Load Diff
+79 -63
View File
@@ -78,48 +78,60 @@
</section>
<section id="tab-traces" hidden>
<div class="controls" id="step-bar">
<div class="controls" id="trace-bar">
<div class="seg" id="trace-mode">
<button data-mode="stream" class="active" title="every episode, newest first">Stream</button>
<button data-mode="step" title="the cohort shipped at one step">Step</button>
</div>
<div id="trace-filter-wrap" class="dd-wrap">
<button id="trace-filter-btn" class="btn dd-btn" title="filter">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
<span id="trace-filter-count" class="badge" hidden></span>
</button>
<div class="dd-menu dd-filters" id="trace-filter-menu" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row"><span class="t-label">kind</span>
<div class="seg toggle-seg" id="trace-kinds">
<button data-kind="train" class="on">train</button>
<button data-kind="eval" class="on">eval</button>
</div>
</div>
<label class="dd-row"><span class="t-label">env</span>
<select id="trace-env"><option value="">all envs</option></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<select id="trace-sort" title="sort" data-label="sort">
<option value="arrival:desc">arrival ↓</option>
<option value="arrival:asc">arrival ↑</option>
<option value="group:asc">group</option>
<option value="duration:desc">total time ↓</option>
<option value="duration:asc">total time ↑</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
</select>
<span id="trace-status" class="muted"></span>
<div class="spacer"></div>
<button id="trace-clear-bin" class="btn" hidden>clear selection</button>
</div>
<div class="controls" id="step-bar" hidden>
<button id="step-prev" class="btn tm-nav" title="previous step">‹</button>
<div id="step-blocks"></div>
<button id="step-next" class="btn tm-nav" title="next step">›</button>
<span id="step-label" class="t-label"></span>
</div>
<div class="controls">
<div id="trace-filter-wrap" class="dd-wrap">
<button id="trace-filter-btn" class="btn dd-btn" title="filter &amp; sort">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
</button>
<div id="trace-filter-menu" class="dd-menu" hidden>
<label class="t-label">env</label>
<select id="trace-env"><option value="">all envs</option></select>
<label class="t-label">sort</label>
<select id="trace-sort">
<option value="line:asc">order: arrival</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="advantage:desc">advantage ↓</option>
<option value="advantage:asc">advantage ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
<option value="group:asc">group</option>
</select>
<label class="toggle"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<div class="seg" id="trace-kind">
<button data-kind="train" class="active">Train</button>
<button data-kind="eval">Eval</button>
</div>
<div class="seg" id="trace-subset">
<button data-subset="all">All</button>
<button data-subset="effective" class="active">Effective</button>
</div>
<span id="trace-status" class="muted"></span>
<div id="trace-chart">
<div class="chart-head"><span class="chart-title">Episodes finished</span><span id="trace-chart-sub" class="muted"></span></div>
<div id="trace-hist"></div>
<div id="hist-tip" hidden></div>
</div>
<div id="episode-table-wrap">
<table id="episode-table">
<thead><tr>
<th>#</th><th>env</th><th>group</th><th>reward</th><th>adv</th>
<th>#</th><th>arrived</th><th>took</th><th>kind</th><th>env</th><th>group</th><th>reward</th>
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>status</th>
</tr></thead>
<tbody></tbody>
@@ -165,44 +177,46 @@
<div id="drawer-backdrop" hidden></div>
<div id="trace-modal" hidden>
<aside id="tm-left">
<div class="tm-head tm-stephead">
<div class="tm-head tm-stephead" id="tm-stephead">
<button id="tm-step-prev" class="btn tm-nav" title="previous step">‹</button>
<span id="tm-step-label"></span>
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
</div>
<div class="tm-head tm-ctlrow">
<div id="tm-filter-wrap" class="dd-wrap">
<button id="tm-filter-btn" class="btn dd-btn" title="filter &amp; sort">
<button id="tm-filter-btn" class="btn dd-btn" title="filter">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
</button>
<div id="tm-filter-menu" class="dd-menu" hidden>
<label class="t-label">env</label>
<select id="tm-env"><option value="">all envs</option></select>
<label class="t-label">sort</label>
<select id="tm-sort">
<option value="line:asc">order: arrival</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="advantage:desc">advantage ↓</option>
<option value="advantage:asc">advantage ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
<option value="group:asc">group</option>
</select>
<label class="toggle"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
<div class="dd-menu dd-filters" id="tm-filter-menu" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row"><span class="t-label">kind</span>
<div class="seg toggle-seg" id="tm-kinds">
<button data-kind="train" class="on">train</button>
<button data-kind="eval" class="on">eval</button>
</div>
</div>
<label class="dd-row"><span class="t-label">env</span>
<select id="tm-env"><option value="">all envs</option></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<select id="tm-sort" title="sort" data-label="sort">
<option value="arrival:desc">arrival ↓</option>
<option value="arrival:asc">arrival ↑</option>
<option value="group:asc">group</option>
<option value="duration:desc">total time ↓</option>
<option value="duration:asc">total time ↑</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
</select>
</div>
<div class="tm-head tm-ctlrow" id="tm-kind-row">
<div class="seg" id="tm-kind">
<button data-kind="train">Train</button>
<button data-kind="eval">Eval</button>
</div>
</div>
<div class="tm-head tm-ctlrow" id="tm-subset-row">
<div class="seg" id="tm-subset">
<button data-subset="all">All</button>
<button data-subset="effective">Effective</button>
<div class="tm-head tm-ctlrow" id="tm-mode-row">
<div class="seg" id="tm-mode">
<button data-mode="stream">Stream</button>
<button data-mode="step">Step</button>
</div>
</div>
<div class="tm-head">
@@ -224,12 +238,14 @@
<button data-mode="messages" class="active">Messages</button>
<button data-mode="rendered">Rendered</button>
</div>
<select id="token-signal" title="Choose the token signal for either view. Text is uncolored; other options color recorded tokens by advantage, log probability, training mask, or message-content membership.">
<select id="token-signal" title="Choose the token signal for either view. Text is uncolored; other options color recorded tokens by advantage, loss/content mask membership, or the trainer's annotations (entropy, the mismatch between its recomputed logprobs and the sampling ones, and the IPO stable mask).">
<option value="">Text</option>
<option value="advantage">Advantage</option>
<option value="logprob">Logprob</option>
<option value="mask">Mask</option>
<option value="is_content">Content</option>
<option value="entropy">Entropy</option>
<option value="mismatch_kl">Mismatch</option>
<option value="stable_mask">Stable mask</option>
<option value="mask">Loss Mask</option>
<option value="is_content">Content Mask</option>
</select>
<button id="tm-collapse" class="btn">collapse</button>
<button id="tm-expand" class="btn">expand</button>
+89 -2
View File
@@ -135,9 +135,26 @@ select:focus, .search:focus { border-color: var(--grey-6); }
.dd-opt:hover { background: var(--grey-2); color: var(--grey-6); }
.dd-opt.active { color: var(--accent); }
.dd-opt.disabled { color: var(--grey-3); cursor: default; }
/* an option with nothing to offer greys out and names its reason */
.dd-opt.unavailable { display: flex; justify-content: space-between; gap: 28px; }
.dd-opt.unavailable:hover { background: none; color: var(--grey-3); }
.dd-why { color: var(--grey-3); }
.dd-note {
padding: 5px 12px 7px;
margin-bottom: 4px;
border-bottom: 1px solid var(--hairline);
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--grey-4);
}
.dd-btn.unavailable { color: var(--grey-4); }
.dd-menu {
position: absolute;
top: 34px;
/* anchor to the trigger's left edge: without it the menu lays out from its
static position and runs off the side of the window */
left: 0;
z-index: 40;
background: var(--grey-1);
border: 1px solid var(--grey-3);
@@ -792,7 +809,8 @@ mark.hit {
.tl-tooltip dd { color: var(--grey-6); margin: 0; }
.tl-tooltip-hint { color: var(--grey-4); border-top: 1px solid var(--hairline); margin-top: 9px; padding-top: 7px; font-size: 9.5px; }
.trace-errors { margin-top: auto; padding-top: 12px; }
/* the banners lead the transcript, so they stand off the first entry */
.trace-errors { margin-top: auto; padding-top: 12px; margin-bottom: 14px; }
.trace-error-banner {
border: 1px solid var(--negative);
background: rgba(255, 69, 57, 0.08);
@@ -892,7 +910,7 @@ details.sub .sub-name { font-weight: 500; color: var(--grey-6); }
details.sub > .entry-body { border-top: 1px solid var(--hairline); }
/* tool definitions are model context, but deliberately sit outside numbered messages */
details.tool-definitions, details.rendered-transcript {
details.tool-definitions, .rendered-transcript {
border: 1px solid var(--grey-3);
margin-bottom: 12px;
background: rgba(183, 166, 250, 0.025);
@@ -1091,3 +1109,72 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
font-size: 12px;
}
#view-toast .toast-text { color: var(--grey-6); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* filter & sort popover */
.dd-filters { min-width: 210px; display: flex; flex-direction: column; gap: 6px; }
.dd-sec {
text-transform: uppercase;
font-size: 10px;
letter-spacing: 0.08em;
color: var(--grey-4);
border-bottom: 1px solid var(--grey-3);
padding-bottom: 3px;
margin-top: 2px;
}
.dd-filters .dd-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin: 0; }
/* controls sit right, sized to their content, so the label reads as the row's subject */
.dd-filters .dd-row select, .dd-filters .dd-row .dd-select, .dd-filters .dd-row .seg { margin-left: auto; }
.dd-filters .dd-row .dd-btn { justify-content: space-between; gap: 8px; }
.dd-filters .t-label { white-space: nowrap; }
/* episodes-finished histogram */
#trace-chart { padding: 8px 12px 4px; border-bottom: 1px solid var(--grey-2); }
#trace-chart .chart-head { display: flex; align-items: baseline; gap: 10px; margin-bottom: 4px; }
#trace-chart .chart-title { font-size: 12px; font-weight: 600; }
#trace-hist { overflow-x: auto; }
#trace-hist svg { display: block; max-width: 100%; }
.hbar { fill: var(--accent); opacity: 0.7; cursor: pointer; }
.hbar:hover { opacity: 1; }
.hbar.on { opacity: 1; fill: #fff; }
.hgrid { stroke: var(--grey-3); stroke-width: 1; vector-effect: non-scaling-stroke; }
.hax { fill: var(--grey-4); font-size: 10px; }
.hval { text-anchor: end; }
#episode-table td.nowrap { white-space: nowrap; }
/* kind filter: each side toggles on its own, so both or one can be shown */
.toggle-seg button { opacity: 0.4; }
.toggle-seg button.on { opacity: 1; color: var(--accent); }
.toggle-seg button.absent.on { color: var(--grey-4); }
/* histogram hover card */
#trace-chart { position: relative; }
#hist-tip {
position: absolute;
z-index: 50;
pointer-events: none;
background: var(--grey-1);
border: 1px solid var(--grey-3);
padding: 6px 8px;
min-width: 150px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
font-size: 11px;
}
#hist-tip .tip-head { color: var(--accent); margin-bottom: 4px; }
#hist-tip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
#hist-tip .tip-row span:first-child { color: var(--grey-4); }
/* the label reads as the button's own name, so it takes the button's colour */
.dd-select .dd-btn .dd-label { text-transform: uppercase; font-weight: 400; color: inherit; }
/* rendered tokens: a header row over the sequence, not a disclosure */
.rendered-head {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
padding: 7px 12px;
background: var(--grey-2);
border-bottom: 1px solid var(--hairline);
}
+3
View File
@@ -36,6 +36,7 @@ from prime_rl import monitors
from prime_rl.configs.evals import EvalsConfig
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
from prime_rl.evals.ckpt import CheckpointManager
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
@@ -465,6 +466,7 @@ class Evals:
group_id = item.group_id
else:
item_step = eval_work(item).step
stamp_arrival([item], "eval", item_step)
await monitors.log([item], item_step, "eval", "all")
eval_batch = self.eval_sink.add(item)
group_id = episode_group_id(item)
@@ -508,6 +510,7 @@ class Evals:
if batch.episodes.effective:
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
await monitors.log_annotations(stamp_batch(batch.episodes.effective.vf_episodes, batch.step))
episodes = batch.episodes
effective = episodes.effective
+9
View File
@@ -122,6 +122,15 @@ async def log(
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
async def log_annotations(updates: list[dict[str, Any]]) -> None:
"""Log trace updates to all registered monitors."""
for monitor in MONITORS:
try:
await monitor.log_annotations(updates)
except Exception as e:
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
async def finalize() -> None:
"""Finalize the run on all registered monitors."""
for monitor in MONITORS:
+4
View File
@@ -53,5 +53,9 @@ class Monitor(ABC):
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Log episodes."""
async def log_annotations(self, updates: list[dict[str, Any]]) -> None:
"""Log trace updates — post-hoc facts about traces this run already logged.
Monitors that only carry scalars ignore them."""
async def finalize(self) -> None:
"""Finalize run."""
-67
View File
@@ -1,67 +0,0 @@
from __future__ import annotations
import asyncio
import json
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, TextIO
import orjson
from prime_rl.configs.monitors import FileMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.utils.utils import sanitize
if TYPE_CHECKING:
import verifiers.v1 as vf
class FileMonitor(Monitor):
"""Logs metrics and episodes to local JSONL files."""
config: FileMonitorConfig
file: TextIO
async def init(self, output_dir: Path, producer: str | None = None) -> None:
self.output_dir = output_dir
self.producer = producer
self.path = output_dir / self.config.path
self.path.parent.mkdir(parents=True, exist_ok=True)
# Line-buffered append so a concurrently-running dashboard can tail the file.
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
"""``step=None`` logs a time-keyed row (e.g. inference metrics, which are
sampled on wall time rather than the training step)."""
sanitized, dropped = sanitize(metrics)
if dropped:
self.logger.warning(
f"Dropping {len(dropped)} non-finite value(s) from {self.config.path}: {', '.join(dropped[:5])}"
)
row = {"step": step, "time": time.time(), **sanitized}
if self.producer is not None:
row["producer"] = self.producer
self.file.write(json.dumps(row) + "\n")
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Append the cohort to its per-step episode file. ``all`` grows one
episode at a time as they complete, ``effective`` one batch at a time on finalize,
so an in-progress run can be inspected live. Episode-level failures are
preserved even when no trace was produced."""
def write() -> None:
path = self.output_dir / "rollouts" / f"step_{step}" / kind / subset / "traces.jsonl"
path.parent.mkdir(parents=True, exist_ok=True)
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
with open(path, "ab") as f:
for episode in episodes:
f.write(orjson.dumps(episode.to_record(), default=str, option=opts))
# Record serialization is heavy pure-Python work; keep it off the event loop.
# Awaited (not fire-and-forget) so appends to one file never interleave.
await asyncio.to_thread(write)
async def finalize(self) -> None:
self.logger.info(f"Finalized metrics at {self.path}")
+3
View File
@@ -0,0 +1,3 @@
from prime_rl.monitors.file.monitor import FileMonitor
__all__ = ["FileMonitor"]
+108
View File
@@ -0,0 +1,108 @@
from __future__ import annotations
import asyncio
import json
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, TextIO
import orjson
from prime_rl.configs.monitors import FileMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
from prime_rl.monitors.file.traces.index import index_row
from prime_rl.monitors.file.traces.update import update_index_row
from prime_rl.utils.pathing import get_file_monitor_dir
from prime_rl.utils.utils import sanitize
if TYPE_CHECKING:
import verifiers.v1 as vf
OPTS = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
class FileMonitor(Monitor):
"""Logs metrics and episodes to local JSONL files."""
config: FileMonitorConfig
file: TextIO
async def init(self, output_dir: Path, producer: str | None = None) -> None:
self.output_dir = output_dir
self.producer = producer
index = get_index_path(get_trace_stream(output_dir))
# a relaunch appends to the stream it finds, so the numbering carries on
self._logged = sum(1 for _ in index.open("rb")) if index.is_file() else 0
self.path = get_file_monitor_dir(output_dir) / self.config.path
self.path.parent.mkdir(parents=True, exist_ok=True)
# Line-buffered append so a concurrently-running dashboard can tail the file.
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
"""``step=None`` logs a time-keyed row (e.g. inference metrics, which are
sampled on wall time rather than the training step)."""
sanitized, dropped = sanitize(metrics)
if dropped:
self.logger.warning(
f"Dropping {len(dropped)} non-finite value(s) from {self.config.path}: {', '.join(dropped[:5])}"
)
row = {"step": step, "time": time.time(), **sanitized}
if self.producer is not None:
row["producer"] = self.producer
self.file.write(json.dumps(row) + "\n")
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Append each episode to the trace stream as it completes — every episode is
serialized exactly once, in arrival order, whatever its kind, so an in-progress
run can be tailed. Episode-level failures are preserved even when no trace was
produced. The shipped cohort writes no second copy: what it learns arrives as
annotations that readers fold back onto the stream."""
if subset == "effective":
return
def write() -> None:
path = get_trace_stream(self.output_dir)
path.parent.mkdir(parents=True, exist_ok=True)
# An index row goes out with every episode: summarising the record here,
# while it is already in hand, saves every reader from parsing a stream
# that outgrows memory long before the run does.
with open(path, "ab") as f, open(get_index_path(path), "ab") as index:
offset = f.tell()
for episode in episodes:
record = episode.to_record()
line = orjson.dumps(record, default=str, option=OPTS)
f.write(line)
self._logged += 1
index.write(orjson.dumps(index_row(self._logged, record, offset), default=str, option=OPTS))
offset += len(line)
# Record serialization is heavy pure-Python work; keep it off the event loop.
# Awaited (not fire-and-forget) so appends to one file never interleave.
await asyncio.to_thread(write)
async def log_annotations(self, updates: list[dict[str, Any]]) -> None:
"""Append trace updates to this producer's annotation file — one writer per
file, so producers never interleave."""
if not updates:
return
def write() -> None:
path = get_annotations_dir(self.output_dir) / f"{self.producer or 'unknown'}.jsonl"
path.parent.mkdir(parents=True, exist_ok=True)
# the scalars go to a sibling index so a reader can answer "which cohort,
# what credit" without touching the token streams
with open(path, "ab") as f, open(get_index_path(path), "ab") as index:
offset = f.tell()
for update in updates:
line = orjson.dumps(update, option=OPTS)
f.write(line)
index.write(orjson.dumps(update_index_row(update, offset), option=OPTS))
offset += len(line)
await asyncio.to_thread(write)
async def finalize(self) -> None:
self.logger.info(f"Finalized metrics at {self.path}")
@@ -0,0 +1,33 @@
"""Where the file monitor puts the traces, and everything written about them.
The stream and its annotations live under one directory so nothing beside them has to
be read as belonging to them, and every index is named for the stream it indexes and
sits beside it.
"""
from pathlib import Path
from prime_rl.utils.pathing import get_file_monitor_dir
def get_trace_dir(output_dir: Path) -> Path:
return get_file_monitor_dir(output_dir) / "traces"
def get_trace_stream(output_dir: Path) -> Path:
"""Every episode, appended as it arrives."""
return get_trace_dir(output_dir) / "stream.jsonl"
def get_annotations_dir(output_dir: Path) -> Path:
"""One file per producer of trace updates: orch ship-time facts, trainer streams."""
return get_trace_dir(output_dir) / "annotations"
def get_index_path(path: Path) -> Path:
"""A stream's index, beside it, so a reader pairs the two without knowing who
wrote them."""
return path.with_name(path.name.replace(".jsonl", ".index.jsonl"))
__all__ = ["get_annotations_dir", "get_index_path", "get_trace_dir", "get_trace_stream"]
+133
View File
@@ -0,0 +1,133 @@
"""The episode index - one compact row per episode, so a reader never has to parse
the stream to browse it.
The file monitor writes a row as each episode lands, when the record is already in
hand and summarising it is nearly free, and records the byte offset it wrote the
episode at so a reader can seek straight to one. A stream another producer wrote has
no index, so its reader derives the same rows itself.
"""
def walk_timing(obj: dict, prefix: str, out: dict[str, float]) -> None:
"""Flatten a trace timing tree to phase -> seconds (same walk as the viewer)."""
if isinstance(obj.get("duration"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + obj["duration"]
elif isinstance(obj.get("start"), (int, float)) and isinstance(obj.get("end"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + (obj["end"] - obj["start"])
for key, value in obj.items():
if isinstance(value, dict):
walk_timing(value, f"{prefix}/{key}" if prefix else key, out)
def episode_kind(rec: dict) -> str:
"""The kind of work an episode did. The file monitor stamps it as the episode
lands; a stream written by another producer (a verifiers ``uv run eval`` run) is
read off its run info instead."""
for trace in rec.get("traces") or []:
if (kind := (trace.get("info") or {}).get("kind")) in ("train", "eval"):
return kind
run = rec.get("run") or {}
return (run.get("work") or {}).get("type") or run.get("type") or "eval"
def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
"""One index row: what the table, the filters, the chart and the sort need.
``line`` numbers the episode within the stream from 1, so the last of n reads as
n — it is what a reader sees and what addresses the episode."""
rewards, advantages = [], []
input_tokens = output_tokens = turns = branches = 0
stop_condition = None
reward_parts: dict[str, list[float]] = {}
metric_parts: dict[str, list[float]] = {}
timing: dict[str, float] = {}
costs: list[float] = []
for trace in rec.get("traces") or []:
costs.extend(
usage["cost"]
for call in trace.get("calls") or []
if isinstance(usage := call.get("usage") or {}, dict) and isinstance(usage.get("cost"), (int, float))
)
nodes = trace.get("nodes") or []
parents = {node.get("parent") for node in nodes if "parent" in node}
branches += max(0, len(nodes) - len(parents))
if trace.get("rewards"): # skip reward-less seats (e.g. a judge) in the episode mean
rewards.append(
sum(
(r.get("score") or 0) * (r.get("weight") if r.get("weight") is not None else 1)
for r in trace["rewards"].values()
if isinstance(r, dict)
)
)
for name, r in (trace.get("rewards") or {}).items():
if isinstance(r, dict) and isinstance(r.get("score"), (int, float)):
reward_parts.setdefault(name, []).append(r["score"])
for name, value in (trace.get("metrics") or {}).items():
if isinstance(value, (int, float)):
metric_parts.setdefault(name, []).append(value)
if isinstance(trace.get("timing"), dict):
walk_timing(trace["timing"], "", timing)
advantage = (trace.get("info") or {}).get("advantage")
if advantage is not None:
advantages.append(advantage)
for node in nodes:
n_tokens = len(node.get("token_ids") or [])
if node.get("sampled"):
output_tokens += n_tokens
else:
input_tokens += n_tokens
if (node.get("message") or {}).get("role") == "assistant":
turns += 1
stop_condition = trace.get("stop_condition", stop_condition)
if input_tokens == 0 and output_tokens == 0: # some eval traces carry no token arrays
for call in trace.get("calls") or []:
usage = call.get("usage") or {}
input_tokens += usage.get("prompt_tokens") or 0
output_tokens += usage.get("completion_tokens") or 0
first_info = ((rec.get("traces") or [{}])[0].get("info")) or {}
return {
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
"metrics": {name: sum(v) / len(v) for name, v in metric_parts.items()},
"timing": timing,
"cost": sum(costs) if costs else None,
"line": line,
"offset": offset,
"id": rec.get("id"),
"kind": episode_kind(rec),
"trace_ids": [trace_id for trace in rec.get("traces") or [] if (trace_id := trace.get("id"))],
"env": (rec.get("env") or {}).get("id") or (rec.get("env") or {}).get("name"),
"group": (rec.get("group") or {}).get("id"),
"ok": rec.get("ok"),
"num_errors": len(rec.get("errors") or []),
"reward": sum(rewards) / len(rewards) if rewards else None,
"advantage": sum(advantages) / len(advantages) if advantages else None,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"turns": turns,
"branches": branches,
"stop_condition": stop_condition,
# when the episode landed and how long it was alive: the stream's x axis,
# and the one duration worth sorting a stream by
"arrival": (first_info.get("arrival") or {}).get("time"),
"duration": _episode_duration(first_info, timing),
}
def _episode_duration(info: dict, timing: dict[str, float]) -> float | None:
"""Wall-clock seconds from dispatch to arrival, or the summed phases for a record
that predates those stamps."""
dispatched = (info.get("dispatch") or {}).get("time")
arrived = (info.get("arrival") or {}).get("time")
if isinstance(dispatched, (int, float)) and isinstance(arrived, (int, float)):
return max(0.0, arrived - dispatched)
phases = [value for key, value in timing.items() if "/" not in key]
return sum(phases) if phases else None
def index_row(line: int, rec: dict, offset: int) -> dict:
"""The row the file monitor writes. The nested reward/metric/timing maps are left
out: only the per-episode series view needs them, and they dominate the size."""
row = summarize_episode(line, rec, offset)
for key in ("rewards", "metrics", "timing"):
row.pop(key, None)
return row
+100
View File
@@ -0,0 +1,100 @@
"""Trace updates — post-hoc facts about a completed trace, recorded beside it.
An episode is serialized once, when it arrives. Everything a consumer learns later
is an update naming the trace: an ``info`` dict merged into the trace's own, plus
per-token streams over a branch, full-length across the branch's token prefix (nulls
mark unknown positions, so a stream never depends on the producer's loss mask).
Each producer appends its own file under the trace directory's ``annotations/``, so
every file has exactly one writer. Readers fold the updates onto the arrival records
in write order, newest wins.
"""
from typing import Any
UPDATE_VERSION = 1
STREAM_FIELDS = ("advantages", "trainer_logprobs", "entropies")
"""Per-token streams an update may carry, compacted onto node fields of the same name."""
def update_index_row(update: dict[str, Any], offset: int) -> dict[str, Any]:
"""An update's scalars plus where its record sits. The per-token streams stay in
the annotation file: a reader browsing a run needs the scalars, and only the
episode it opens needs the streams."""
return {"trace_id": update.get("trace_id"), "offset": offset, "info": update.get("info") or {}}
def make_update(
trace_id: str,
*,
info: dict[str, Any] | None = None,
branches: dict[int, dict[str, list]] | None = None,
) -> dict[str, Any]:
"""One update record. ``branches`` maps a branch index to its token streams."""
return {
"version": UPDATE_VERSION,
"trace_id": trace_id,
"info": info or {},
"branches": [{"index": index, **streams} for index, streams in (branches or {}).items()],
}
def branch_node_paths(nodes: list[dict]) -> list[list[int]]:
"""Root-to-leaf node indexes, one path per branch, in leaf order."""
if not nodes:
return []
parents = {parent for node in nodes if isinstance((parent := node.get("parent")), int) and 0 <= parent < len(nodes)}
paths = []
for leaf in (index for index in range(len(nodes)) if index not in parents):
path: list[int] = []
seen: set[int] = set()
node_index: int | None = leaf
while isinstance(node_index, int) and 0 <= node_index < len(nodes) and node_index not in seen:
seen.add(node_index)
path.append(node_index)
node_index = nodes[node_index].get("parent")
paths.append(list(reversed(path)))
return paths
def _deep_merge(old: Any, new: Any) -> Any:
if isinstance(old, dict) and isinstance(new, dict):
return {**old, **{key: _deep_merge(old.get(key), value) for key, value in new.items()}}
return new
def fold_trace_updates(trace: dict, updates: list[dict]) -> int:
"""Apply updates onto a raw trace record in write order, newest winning.
Merges each ``info`` and projects every branch stream onto the branch's nodes,
compact over each node's mask like the node's own ``logprobs``. A node takes a
stream only when it is fully covered with non-null values at every sampled
position, so a truncated stream leaves the tail nodes untouched. Returns how many
nodes carry trainer logprobs afterwards."""
nodes = trace.get("nodes") or []
paths = branch_node_paths(nodes)
for update in updates:
if update.get("info"):
trace["info"] = _deep_merge(trace.get("info") or {}, update["info"])
for branch in update.get("branches") or []:
branch_index = branch.get("index")
if not isinstance(branch_index, int) or not 0 <= branch_index < len(paths):
continue
for field in STREAM_FIELDS:
stream = branch.get(field)
if not stream:
continue
cursor = 0
for node_index in paths[branch_index]:
node = nodes[node_index]
token_ids = node.get("token_ids") or []
span = stream[cursor : cursor + len(token_ids)]
cursor += len(token_ids)
if len(span) < len(token_ids):
break
values = [v for v, sampled in zip(span, node.get("mask") or []) if sampled]
if not values or any(v is None for v in values):
continue
node[field] = values
return sum(1 for node in nodes if node.get("trainer_logprobs"))
+49
View File
@@ -0,0 +1,49 @@
"""What the orchestrator knows about an episode, recorded as it learns it.
An episode is serialized once, when it arrives, so a trace's later facts cannot be
implied by where its record sits. Both events below are stamped explicitly: what the
orchestrator knows at arrival goes onto the trace before it is logged, and what a batch
adds when it takes the episode becomes an append-only update the reader folds back on.
"""
from __future__ import annotations
import time
from typing import Any
import verifiers.v1 as vf
from prime_rl.monitors.base import Kind
from prime_rl.monitors.file.traces.update import make_update
def stamp_arrival(episodes: list[vf.Episode], kind: Kind, step: int) -> None:
"""Stamp what an episode's traces are known to have done as they land: the kind of
work, the step that dispatched them, and the step they came back at."""
now = time.time()
for episode in episodes:
work = getattr(episode.run, "work", None)
for trace in episode.traces:
trace.info["kind"] = kind
if work is not None:
trace.info["dispatch"] = {"step": work.step, "time": trace.timing.start}
trace.info["arrival"] = {"step": step, "time": now}
def stamp_batch(episodes: list[vf.Episode], step: int) -> list[dict[str, Any]]:
"""The updates a batched cohort adds over its arrival records: membership, the step
it ties to, the scalar advantage, and the per-token advantage streams."""
now = time.time()
updates = []
for episode in episodes:
for trace in episode.traces:
info: dict[str, Any] = {"effective": True, "ship": {"step": step, "time": now}}
if (advantage := trace.info.get("advantage")) is not None:
info["advantage"] = advantage
branches = {
branch.index: {"advantages": advantages}
for branch in trace.branches
if (advantages := branch.advantages) is not None
}
updates.append(make_update(trace.id, info=info, branches=branches))
return updates
+7 -2
View File
@@ -37,6 +37,7 @@ import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before tr
from prime_rl import monitors
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.algo.routing import is_trainable
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
@@ -559,6 +560,7 @@ class Orchestrator:
raise ValueError("Orchestrated episode is missing training-run provenance")
kind = episode.run.work.type
step = episode.run.work.step if kind == "eval" else self.progress.step
stamp_arrival([episode], kind, step)
await monitors.log([episode], step, kind, "all")
if kind == "eval":
@@ -649,9 +651,11 @@ class Orchestrator:
await self.version_advanced.wait()
self.wait_for_policy_time += time.perf_counter() - hold_start
# The effective (clean, trained-on) subset is logged at ship time; the full arrival
# window already streamed into the ``all`` cohort on arrival.
# The effective (clean, trained-on) subset is logged at ship time as annotation
# records against each trace's arrival record - membership, advantages, the step
# it shipped at - never a second episode copy.
await monitors.log(effective.vf_episodes, step, "train", "effective")
await monitors.log_annotations(stamp_batch(effective.vf_episodes, step))
pack_start_time = time.perf_counter()
micro_batch_grid = await asyncio.to_thread(self.packer.pack, batch.samples)
@@ -908,6 +912,7 @@ class Orchestrator:
# ``env_name``); the full returned cohort already streamed into ``all`` on arrival.
if batch.episodes.effective:
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
await monitors.log_annotations(stamp_batch(batch.episodes.effective.vf_episodes, batch.step))
policy_spans = [eval_work(episode).policy for episode in batch.episodes]
if any(span is None for span in policy_spans):
raise ValueError(f"Eval {batch.env_name} step {batch.step} is missing policy provenance")
@@ -166,6 +166,8 @@ def trace_to_samples(trace: vf.Trace, *, env_name: str = "") -> list[TrainingSam
ref_kl_weights=_loss_weights(branch, "ref_kl", trained_loss_nodes["ref_kl"]),
advantages=branch.advantages,
sampling_mask=_encode_sampling_mask(branch.sampling_mask, len(token_ids)),
trace_id=trace.id,
branch_index=branch.index,
)
)
if not samples:
+19 -1
View File
@@ -493,6 +493,8 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
ce_weights=ce_weights,
ref_kl_weights=ref_kl_weights,
seq_lens=[len(input_ids)],
trace_ids=[training_example.trace_id or ""],
branch_indices=[training_example.branch_index if training_example.branch_index is not None else -1],
)
@@ -597,6 +599,8 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
seq_lens: list[int] = []
routed_experts: RoutedExperts | None = None
sampling_mask: SamplingMask | None = SamplingMask(ids=b"", counts=b"") if has_sampling_mask else None
trace_ids: list[str] = []
branch_indices: list[int] = []
for sample in bin_content.samples:
sample_len = len(sample.input_ids)
@@ -638,6 +642,8 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
sample_mask = sample.sampling_mask if sample.sampling_mask is not None else _empty_sampling_mask(sample_len)
sampling_mask.ids += sample_mask.ids
sampling_mask.counts += sample_mask.counts
trace_ids.extend(sample.trace_ids or [""] * len(sample.sequence_lengths))
branch_indices.extend(sample.branch_indices or [-1] * len(sample.sequence_lengths))
sequence_lengths = [len(sample.input_ids) for sample in bin_content.samples]
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
@@ -661,6 +667,8 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
ce_weights=streams["ce_weights"],
ref_kl_weights=streams["ref_kl_weights"],
seq_lens=seq_lens,
trace_ids=trace_ids,
branch_indices=branch_indices,
)
@@ -771,7 +779,8 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
micro_batch.ref_logprobs.extend([0.0] * padding_size)
# Padding is loss-masked, so no component trains it; fill every stream
# with 0.0 (not the pack-boundary defaults) so a padded pure-ce batch
# still reads as rl-empty in token export, which keys off nonzero weights.
# still reads as rl-empty to consumers that key off nonzero weights
# (e.g. the per-env mismatch metrics).
for stream_name in STREAM_FILL:
stream = getattr(micro_batch, stream_name)
if stream is not None:
@@ -813,6 +822,12 @@ def _assert_token_arrays_aligned(micro_batch: MicroBatch) -> None:
assert sum(micro_batch.sequence_lengths) == num_tokens, (
f"sequence_lengths sum {sum(micro_batch.sequence_lengths)} != {num_tokens} tokens"
)
num_sequences = len(micro_batch.sequence_lengths)
for name in ("trace_ids", "branch_indices"):
values = getattr(micro_batch, name)
assert values is None or len(values) == num_sequences, (
f"{name} misaligned after packing: {len(values)} != {num_sequences} sequences"
)
assert sum(micro_batch.seq_lens) == num_tokens, f"seq_lens sum {sum(micro_batch.seq_lens)} != {num_tokens} tokens"
if micro_batch.routed_experts is not None:
assert micro_batch.routed_experts.shape[0] == num_tokens, (
@@ -841,6 +856,9 @@ def _make_dummy_batch(source: MicroBatch) -> MicroBatch:
dummy.ref_kl_weights = None
# Fully loss-masked, so replaying sampling masks would be pure wasted work.
dummy.sampling_mask = None
# The copied identity would double-annotate the source's traces.
dummy.trace_ids = None
dummy.branch_indices = None
return dummy
+82
View File
@@ -0,0 +1,82 @@
import asyncio
import math
from collections.abc import Mapping
from typing import Any
import torch
import torch.distributed as dist
from torch import Tensor
from prime_rl import monitors
from prime_rl.monitors.file.traces.update import make_update
class AnnotationWriter:
"""Collects the trainer's per-token streams (recomputed logprobs, entropies) during
a step and logs them as trace updates — one record per trained sequence, keyed by
``(trace_id, branch_index)``. Streams are full-length over the sample's token prefix
so readers can fold them onto trace nodes without knowing the trainer's loss mask.
``export`` accumulates locally per micro batch; ``flush`` gathers every rank's
records to rank 0, the only rank running monitors. CP ranks past the first
accumulate nothing since they share their micro batches."""
def __init__(self, parallel_dims: Any, world: Any) -> None:
self.world = world
self.is_duplicate_rank = parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0
self._pending: list[dict[str, Any]] = []
def export(self, micro_batch: Mapping[str, Any], model_output: Mapping[str, Tensor]) -> None:
if self.is_duplicate_rank:
return
trace_ids = micro_batch["trace_ids"]
branch_indices = micro_batch["branch_indices"]
if not trace_ids or not branch_indices:
return
sequence_lengths = micro_batch["sequence_lengths"]
loss_mask = [bool(v) for v in micro_batch["loss_mask"].detach().cpu().reshape(-1).tolist()]
env_names = micro_batch["env_names"]
trainer_logprobs = _tensor_to_floats(model_output["logprobs"])
entropies = _tensor_to_floats(model_output["entropy"])
start = 0
for trace_id, branch_index, length in zip(trace_ids, branch_indices, sequence_lengths):
span_start, end = start, start + length
start = end
if not trace_id or branch_index < 0:
continue
# Trailing padding is appended to the last sample and folded into its length.
while end > span_start and env_names[end - 1] == "" and not loss_mask[end - 1]:
end -= 1
if end <= span_start or not any(loss_mask[span_start:end]):
continue
logprob_span = trainer_logprobs[span_start:end]
entropy_span = entropies[span_start:end]
# After the right shift, a sample's first value crosses the packing boundary.
logprob_span[0] = None
entropy_span[0] = None
self._pending.append(
make_update(
trace_id,
branches={branch_index: {"trainer_logprobs": logprob_span, "entropies": entropy_span}},
)
)
def flush(self) -> None:
"""Gather the step's records to rank 0 and log them; collective, so every rank
must call it once per step."""
records, self._pending = self._pending, []
if dist.is_initialized() and self.world.world_size > 1:
gathered: list[list[dict[str, Any]]] | None = None
if self.world.rank == 0:
gathered = [[] for _ in range(self.world.world_size)]
dist.gather_object(records, gathered, dst=0)
if gathered is None:
return
records = [record for rank_records in gathered for record in rank_records]
asyncio.run(monitors.log_annotations(records))
def _tensor_to_floats(tensor: Tensor) -> list[float | None]:
values = tensor.detach().to(dtype=torch.float32, device="cpu").reshape(-1).tolist()
return [float(value) if math.isfinite(value) else None for value in values]
+11
View File
@@ -30,6 +30,11 @@ class TensorMicroBatch(TypedDict):
env_names: list[str]
sequence_lengths: list[int]
# Per-sequence branch identity, parallel to sequence_lengths; None on
# synthetic data. "" / -1 mark an unknown sequence (e.g. a dummy batch).
trace_ids: list[str] | None
branch_indices: list[int] | None
# Batch level
lora_num_tokens: Int[Tensor, "n_loras"]
seq_lens: Int[Tensor, "segments"]
@@ -123,6 +128,8 @@ class FakeDataLoader:
"temperatures": torch.ones(input_ids.shape[0]).unsqueeze(0),
"env_names": ["fake"] * input_ids.shape[0],
"sequence_lengths": sequence_lengths,
"trace_ids": None,
"branch_indices": None,
"loss_mask": loss_mask.unsqueeze(0),
"lora_num_tokens": torch.tensor([input_ids.shape[0]], dtype=torch.int32),
"seq_lens": torch.tensor(sequence_lengths, dtype=torch.long),
@@ -153,6 +160,8 @@ class FakeDataLoader:
"temperatures": torch.ones(self.seq_len).unsqueeze(0),
"env_names": ["fake"] * self.seq_len,
"sequence_lengths": [self.seq_len],
"trace_ids": None,
"branch_indices": None,
"loss_mask": torch.ones(self.seq_len, dtype=torch.bool).unsqueeze(0),
"lora_num_tokens": torch.tensor([self.seq_len], dtype=torch.int32),
"seq_lens": torch.tensor([self.seq_len], dtype=torch.long),
@@ -235,6 +244,8 @@ class DataLoader:
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
env_names=micro_batch.env_names,
sequence_lengths=micro_batch.sequence_lengths,
trace_ids=micro_batch.trace_ids,
branch_indices=micro_batch.branch_indices,
# Single adapter: every token in the batch belongs to it (padding included).
lora_num_tokens=torch.tensor([len(micro_batch.input_ids)], dtype=torch.int32),
seq_lens=torch.tensor(micro_batch.seq_lens, dtype=torch.long),
-256
View File
@@ -1,256 +0,0 @@
import atexit
import json
import math
from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import Any
import torch
from torch import Tensor
from prime_rl.configs.trainer import IPOLossConfig, TrainerConfig
from prime_rl.trainer.rl.loss import compute_importance_ratio_and_mismatch_kl
SCHEMA_VERSION = 1
class DisabledTokenExporter:
def export(self, *args: Any, **kwargs: Any) -> None:
return
def mark_stable(self) -> None:
return
def close(self) -> None:
return
class TokenExporter:
def __init__(
self,
output_dir: Path,
rank: int,
) -> None:
self.rank = rank
self.output_dir = output_dir / "token_exports"
self._closed = False
self._initialized_files: set[tuple[int, int]] = set()
self._sequences_by_file: dict[tuple[int, int], int] = {}
self._pending_stable_dirs: set[Path] = set()
atexit.register(self.close)
def export(
self,
step: int,
micro_step: int,
micro_batch: Mapping[str, Any],
model_output: Mapping[str, Tensor],
sequence_lengths: list[int],
loss_config: Any,
) -> None:
columns = _export_columns(micro_batch, model_output, loss_config)
_check_lengths(columns)
file_key = (step, self.rank)
start = 0
for micro_sequence_idx, length in enumerate(sequence_lengths):
raw_end = start + length
end = _trim_padding(columns, start, raw_end)
if end > start and any(columns["loss_mask"][start:end]):
self._write(
{
"schema_version": SCHEMA_VERSION,
"step": step,
"rank": self.rank,
"micro_step": micro_step,
"micro_sequence_idx": micro_sequence_idx,
"export_sequence_idx": self._sequences_by_file.get(file_key, 0),
"env_name": _first_non_empty(columns["env_names"][start:end]),
**_slice_columns(columns, start, end),
},
step,
)
self._sequences_by_file[file_key] = self._sequences_by_file.get(file_key, 0) + 1
start = raw_end
def close(self) -> None:
if self._closed:
return
self._closed = True
def mark_stable(self) -> None:
# The caller barriers first so a STABLE only lands after every rank flushed.
while self._pending_stable_dirs:
stable_dir = self._pending_stable_dirs.pop()
(stable_dir / "STABLE").touch()
def _export_dir(self, step: int) -> Path:
return self.output_dir / f"step_{step}"
def _export_file(self, step: int) -> Path:
if self._closed:
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
step_dir = self._export_dir(step)
try:
step_dir.mkdir(parents=True, exist_ok=True)
except FileExistsError:
if not step_dir.is_dir():
raise
return step_dir / f"rank_{self.rank}.jsonl"
def _write(self, record: dict[str, Any], step: int) -> None:
if self._closed:
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
file_key = (step, self.rank)
mode = "a" if file_key in self._initialized_files else "w"
export_file = self._export_file(step)
with export_file.open(mode, encoding="utf-8") as file:
file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
self._initialized_files.add(file_key)
self._pending_stable_dirs.add(export_file.parent)
def setup_token_exporter(
config: TrainerConfig, parallel_dims: Any, world: Any, logger: Any
) -> TokenExporter | DisabledTokenExporter:
if not config.enable_token_export:
return DisabledTokenExporter()
if parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0:
return DisabledTokenExporter()
exporter = TokenExporter(config.output_dir, world.rank)
logger.info(f"Writing token exports under {exporter.output_dir}")
return exporter
def _export_columns(
micro_batch: Mapping[str, Any], model_output: Mapping[str, Tensor], loss_config: Any
) -> dict[str, list[Any]]:
token_ids = _tensor_to_ints(micro_batch["input_ids"])
seq_len = len(token_ids)
trainer_logprobs = model_output["logprobs"]
export_tensors = _compute_export_tensors(micro_batch, trainer_logprobs, loss_config)
return {
"token_ids": token_ids,
"position_ids": _tensor_to_ints(micro_batch["position_ids"]),
"loss_mask": _tensor_to_bools(micro_batch["loss_mask"]),
"advantages": _tensor_to_floats(micro_batch["advantages"]),
"inference_logprobs": _tensor_to_floats(micro_batch["inference_logprobs"]),
"trainer_logprobs": _tensor_to_floats(trainer_logprobs),
"entropy": _tensor_to_floats(model_output["entropy"]),
"mismatch_kl": _optional_tensor_to_floats(export_tensors["mismatch_kl"], seq_len),
"log_importance_ratio": _optional_tensor_to_floats(export_tensors["log_importance_ratio"], seq_len),
"importance_ratio": _optional_tensor_to_floats(export_tensors["importance_ratio"], seq_len),
"prob_delta": _optional_tensor_to_floats(export_tensors["prob_delta"], seq_len),
"is_masked": _optional_tensor_to_bools(export_tensors["is_masked"], seq_len),
"is_masked_high": _optional_tensor_to_bools(export_tensors["is_masked_high"], seq_len),
"is_masked_low": _optional_tensor_to_bools(export_tensors["is_masked_low"], seq_len),
# Component weight streams; ``None`` columns mean the defaults (rl 1.0
# on the loss mask, no ce/ref_kl component).
"rl_weights": _optional_tensor_to_floats(micro_batch.get("rl_weights"), seq_len),
"ce_weights": _optional_tensor_to_floats(micro_batch.get("ce_weights"), seq_len),
"ref_kl_weights": _optional_tensor_to_floats(micro_batch.get("ref_kl_weights"), seq_len),
"env_names": list(micro_batch["env_names"]),
}
def _compute_export_tensors(
micro_batch: Mapping[str, Any], trainer_logprobs: Tensor, loss_config: Any
) -> dict[str, Tensor | None]:
fields: dict[str, Tensor | None] = {
"log_importance_ratio": None,
"importance_ratio": None,
"mismatch_kl": None,
"prob_delta": None,
"is_masked": None,
"is_masked_high": None,
"is_masked_low": None,
}
# Ratio-based fields are meaningless when no token has sampling logprobs
# (e.g. pure CE batches distilling frozen-model tokens): no rl member
# (stream present but all-zero) and no ref_kl member.
rl_weights = micro_batch.get("rl_weights")
ref_kl_weights = micro_batch.get("ref_kl_weights")
no_rl = rl_weights is not None and not bool((rl_weights != 0).any())
no_ref_kl = ref_kl_weights is None or not bool((ref_kl_weights != 0).any())
if no_rl and no_ref_kl:
return fields
inference_logprobs = micro_batch["inference_logprobs"].to(trainer_logprobs.device)
loss_mask = micro_batch["loss_mask"].to(trainer_logprobs.device)
with torch.no_grad():
log_ratio, ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(trainer_logprobs, inference_logprobs)
prob_delta = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
fields["log_importance_ratio"] = log_ratio
fields["importance_ratio"] = ratio
fields["mismatch_kl"] = mismatch_kl
fields["prob_delta"] = prob_delta
if isinstance(loss_config, IPOLossConfig):
invalid_high = prob_delta > loss_config.eps
invalid_low = prob_delta < -loss_config.eps
fields["is_masked"] = loss_mask & (invalid_high | invalid_low)
fields["is_masked_high"] = loss_mask & invalid_high
fields["is_masked_low"] = loss_mask & invalid_low
return fields
def _tensor_to_ints(tensor: Tensor) -> list[int]:
return [int(value) for value in tensor.detach().cpu().reshape(-1).tolist()]
def _tensor_to_bools(tensor: Tensor) -> list[bool]:
return [bool(value) for value in tensor.detach().cpu().reshape(-1).tolist()]
def _tensor_to_floats(tensor: Tensor) -> list[float | None]:
values = tensor.detach().to(dtype=torch.float32, device="cpu").reshape(-1).tolist()
return [_json_float(value) for value in values]
def _optional_tensor_to_floats(tensor: Tensor | None, seq_len: int) -> list[float | None]:
if tensor is None:
return [None] * seq_len
return _tensor_to_floats(tensor)
def _optional_tensor_to_bools(tensor: Tensor | None, seq_len: int) -> list[bool | None]:
if tensor is None:
return [None] * seq_len
return _tensor_to_bools(tensor)
def _check_lengths(columns: Mapping[str, Sequence[Any]]) -> None:
lengths = {key: len(values) for key, values in columns.items()}
if len(set(lengths.values())) != 1:
raise ValueError(f"Token export fields must have aligned lengths, got {lengths}")
def _slice_columns(columns: Mapping[str, Sequence[Any]], start: int, end: int) -> dict[str, list[Any]]:
return {key: list(values[start:end]) for key, values in columns.items() if key != "env_names"}
def _trim_padding(columns: Mapping[str, Sequence[Any]], start: int, end: int) -> int:
env_names = columns["env_names"]
loss_mask = columns["loss_mask"]
while end > start and env_names[end - 1] == "" and not loss_mask[end - 1]:
end -= 1
return end
def _json_float(value: float | None) -> float | None:
if value is None:
return None
value = float(value)
if not math.isfinite(value):
return None
return value
def _first_non_empty(values: Sequence[str]) -> str | None:
for value in values:
if value:
return value
return None
+4 -15
View File
@@ -36,7 +36,7 @@ from prime_rl.trainer.rl.loss import (
shift_tensor_left,
shift_tensor_right,
)
from prime_rl.trainer.rl.token_export import setup_token_exporter
from prime_rl.trainer.rl.annotations import AnnotationWriter
from prime_rl.trainer.model import (
forward,
get_full_offload_dtype_policy,
@@ -258,7 +258,7 @@ def train(config: TrainerConfig):
)
logger.debug(f"Initialized data loader in {format_time(time.perf_counter() - t0)}")
token_exporter = setup_token_exporter(config, parallel_dims, world, logger)
annotation_writer = AnnotationWriter(parallel_dims, world)
gc_handler = GarbageCollection(config.gc.interval) if config.gc else None
@@ -560,14 +560,7 @@ def train(config: TrainerConfig):
for env_name, indices in mismatch_env_to_indices.items():
tensors[f"mismatch_kl/{env_name}"].append(mismatch_kl[indices])
token_exporter.export(
progress.step,
micro_step,
micro_batch,
out,
sequence_lengths,
config.loss,
)
annotation_writer.export(micro_batch, out)
if is_tt_moe_model(model):
load_balance_stats = get_load_balance_stats(model)
@@ -589,9 +582,7 @@ def train(config: TrainerConfig):
micro_step_message += f" | Routing Conf. {tensors['routing_confidence'][-1].mean().item():.4f}"
logger.debug(micro_step_message)
if config.enable_token_export:
dist.barrier()
token_exporter.mark_stable()
annotation_writer.flush()
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
# across dp_cp so the final gradient is the true per-token mean over the global batch.
@@ -754,8 +745,6 @@ def train(config: TrainerConfig):
prof.export_chrome_trace(trace_file)
logger.info(f"Saved trace to {trace_file}")
token_exporter.close()
# Write final checkpoint
if config.ckpt is not None:
logger.info(f"Saving final checkpoint at step {progress.step}")
+5 -5
View File
@@ -3,7 +3,7 @@ from pathlib import Path
from prime_rl.transports.batch.base import BatchReceiver, BatchSender
from prime_rl.transports.batch.types import MicroBatch
from prime_rl.utils.pathing import get_rollout_dir, get_step_path, sync_wait_for_path
from prime_rl.utils.pathing import get_batch_dir, get_step_path, sync_wait_for_path
class FileSystemBatchSender(BatchSender):
@@ -11,7 +11,7 @@ class FileSystemBatchSender(BatchSender):
def __init__(self, output_dir: Path, data_world_size: int, current_step: int = 0):
super().__init__(output_dir, data_world_size)
self.rollout_dir = get_rollout_dir(output_dir)
self.batch_dir = get_batch_dir(output_dir)
self.current_step = current_step
async def send(self, micro_batch_grid: list[list[MicroBatch]]) -> None:
@@ -21,7 +21,7 @@ class FileSystemBatchSender(BatchSender):
for micro_batch_list in micro_batch_grid:
assert len(micro_batch_list) == len(micro_batch_grid[0]), "All micro batch lists must have the same length"
step_path = get_step_path(self.rollout_dir, self.current_step)
step_path = get_step_path(self.batch_dir, self.current_step)
step_path.mkdir(parents=True, exist_ok=True)
await asyncio.to_thread(self._encode_and_write, micro_batch_grid, step_path)
self.current_step += 1
@@ -40,11 +40,11 @@ class FileSystemBatchReceiver(BatchReceiver):
def __init__(self, output_dir: Path, data_rank: int, current_step: int = 0):
super().__init__(output_dir, data_rank)
self.rollout_dir = get_rollout_dir(output_dir)
self.batch_dir = get_batch_dir(output_dir)
self.current_step = current_step
def _get_micro_batch_path(self) -> Path:
return get_step_path(self.rollout_dir, self.current_step) / f"rank_{self.data_rank}.bin"
return get_step_path(self.batch_dir, self.current_step) / f"rank_{self.data_rank}.bin"
def wait(self) -> None:
"""Wait for the micro batch file to appear on disk."""
+14 -2
View File
@@ -76,10 +76,16 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
# samples without live rl member tokens (the trainer raises otherwise).
advantages: list[float] | None = None
# Last field on purpose: array_like structs encode positionally, so appending
# Appended fields only: array_like structs encode positionally, so appending
# keeps the wire layout of earlier fields stable across versions.
sampling_mask: SamplingMask | None = None
# Identity of the branch this sample was built from, so the trainer can key
# its per-token annotations back to the rollout trace. ``None`` on synthetic
# samples (e.g. fake data).
trace_id: str | None = None
branch_index: int | None = None
# Orchestrator -> Trainer
class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
@@ -109,5 +115,11 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
ce_weights: list[float] | None = None
ref_kl_weights: list[float] | None = None
# See TrainingSample.sampling_mask; appended last for wire-layout stability.
# See TrainingSample.sampling_mask; appended for wire-layout stability.
sampling_mask: SamplingMask | None = None
# Per-sequence branch identity, parallel to ``sequence_lengths`` (see
# TrainingSample.trace_id). ``""`` / ``-1`` mark an unknown sequence
# (e.g. a dummy micro batch). ``None`` when no packed sample carried one.
trace_ids: list[str] | None = None
branch_indices: list[int] | None = None
+10 -4
View File
@@ -204,8 +204,14 @@ def get_ckpt_dir(output_dir: Path) -> Path:
return output_dir / "checkpoints"
def get_rollout_dir(output_dir: Path) -> Path:
return output_dir / "rollouts"
def get_batch_dir(output_dir: Path) -> Path:
return output_dir / "batches"
def get_file_monitor_dir(output_dir: Path) -> Path:
"""Everything the file monitor dumps locally: the metrics, and the traces with
the annotations about them."""
return output_dir / "monitors" / "file"
def get_eval_dir(output_dir: Path) -> Path:
@@ -305,12 +311,12 @@ def validate_run_dir(
def clean_future_steps(output_dir: Path, resume_step: int) -> None:
"""Remove stale rollouts past ``resume_step`` and broadcasts from it onward.
"""Remove stale step artifacts past ``resume_step`` and broadcasts from it onward.
Pass ``resume_step=-1`` to wipe every step directory (fresh runs).
"""
cleanup_rules = [
(get_rollout_dir(output_dir), lambda step: step > resume_step),
(get_batch_dir(output_dir), lambda step: step > resume_step),
(get_broadcast_dir(output_dir), lambda step: step >= resume_step),
]
+2 -1
View File
@@ -19,11 +19,12 @@ from prime_rl.utils.logger import get_logger
# ruff: noqa: F401
from prime_rl.utils.pathing import (
get_all_ckpt_steps,
get_batch_dir,
get_broadcast_dir,
get_ckpt_dir,
get_eval_dir,
get_file_monitor_dir,
get_log_dir,
get_rollout_dir,
get_step_path,
resolve_latest_ckpt_step,
sync_wait_for_path,
+1 -1
View File
@@ -112,7 +112,7 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
page.wait_for_timeout(1500)
assert page.locator("#config-view .j-line").count() > 10, "resolved config tree did not render"
# traces: when the run saved rollouts, episodes must render and open
# traces: when the run shipped a cohort, episodes must render and open
rollout_steps = page.evaluate(
f"""fetch('{base}/api/runs/{run_name}/rollouts').then(r => r.json()).then(d => d.steps.length)"""
)
+38
View File
@@ -129,6 +129,44 @@ def test_prepare_batch_balances_micro_batches_across_workers(
assert sum(1 for loss_mask in batch.loss_mask if loss_mask) == 0
def test_prepare_batch_preserves_branch_identity(make_training_example):
examples = []
for i in range(5):
example = make_training_example()
example.trace_id = f"trace-{i}"
example.branch_index = i
examples.append(example)
examples.append(make_training_example()) # no identity -> sentinels
batches_per_gpu = prepare_batch(
rollouts=examples,
seq_len=4,
num_train_workers=2,
bin_cost=build_bin_cost(None),
pad_to_multiple_of=8,
)
seen: set[tuple[str, int]] = set()
for batch in _flatten_batches(batches_per_gpu):
if not _has_loss_tokens(batch):
# Dummies are copies of real batches; identity must not survive the copy.
assert batch.trace_ids is None and batch.branch_indices is None
continue
assert len(batch.trace_ids) == len(batch.branch_indices) == len(batch.sequence_lengths)
seen.update(zip(batch.trace_ids, batch.branch_indices))
assert seen == {(f"trace-{i}", i) for i in range(5)} | {("", -1)}
def test_prepare_sample_truncation_keeps_identity():
sample = make_sized_training_example(10)
sample.trace_id = "trace-x"
sample.branch_index = 2
micro_batch = prepare_sample(sample, seq_len=4)
assert len(micro_batch.input_ids) == 4
assert micro_batch.trace_ids == ["trace-x"]
assert micro_batch.branch_indices == [2]
def test_randomized_packing_invariants():
rng = np.random.default_rng(0)
-5
View File
@@ -405,11 +405,6 @@ def test_policy_sources_reject_mixed_top_k_capture():
)
def test_trainer_enable_token_export_cli_flag():
assert not cli(TrainerConfig, args=[]).enable_token_export
assert cli(TrainerConfig, args=["--enable-token-export"]).enable_token_export
def test_single_node_auto_inference_ports_follow_server_port():
config = RLConfig.model_validate(
{
+6 -6
View File
@@ -3,8 +3,8 @@ import pytest
from prime_rl.utils.pathing import (
clean_future_steps,
create_attempt_dirs,
get_batch_dir,
get_broadcast_dir,
get_rollout_dir,
get_step_path,
validate_run_dir,
)
@@ -103,17 +103,17 @@ def test_clean_outside_output_dir_raises(tmp_path):
def test_clean_future_steps_rebuilds_resume_broadcast(tmp_path):
rollout_dir = get_rollout_dir(tmp_path)
batch_dir = get_batch_dir(tmp_path)
broadcast_dir = get_broadcast_dir(tmp_path)
for parent in (rollout_dir, broadcast_dir):
for parent in (batch_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(batch_dir, 1).exists()
assert get_step_path(batch_dir, 2).exists()
assert not get_step_path(batch_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()