Compare commits

...
Author SHA1 Message Date
rasdaniandGitHub 3460245d63 feat(dashboard): expose tool context and rendered tokens (#3377)
## Summary

- show `trace.tools` as a distinct, collapsible model-context block in
the Messages view, with tool counts/names, full descriptions, formatted
parameter schemas, and per-item/schema/all copy actions
- add a separate `Rendered` view that decodes recorded post-renderer
`token_ids` for the selected trace and branch as a full sequence,
retaining special tokens and offering decoded-text and authoritative-ID
copy actions
- compose both `Messages` and `Rendered` with the `Text`, `Advantage`,
`Logprob`, `Mask`, and `Content` signal dropdown, with explicit
unavailable states for missing IDs, missing model metadata, tokenizer
load failures, and decode failures

## Details

The Messages view continues to render literal `message.content`. Tool
definitions are shown immediately after the first system message in a
purple-accented context card, so they are not presented as
system-message text; traces without a system message keep the card at
the top. The collapsed row shows the count and normalized names;
expanding it exposes each full description and scrollable JSON schema.
Direct tool objects, OpenAI-style `function` wrappers, multiple
definitions, missing fields, and malformed values degrade to readable
fallback labels.

Rendered does not rerun or infer a chat template. The server uses
`client.renderer_model_name` with the existing run-model fallback,
concatenates the recorded node spans in the selected root-to-leaf order,
and calls the tokenizer once for the full sequence with special-token
skipping disabled. The selected branch controls which decoded sequence
is shown; the all-branches option uses recorded node write order. With
`Text` selected, Rendered shows that exact full-sequence decode. With
another signal selected, it shows the same recorded sequence as token
spans with the existing color scale and token hover metadata.

Compatibility is intentionally additive: the default endpoint response
and default Messages/Text display stay unchanged, token strings are
still fetched lazily for overlays, and full rendered text is only added
when `rendered=true` is requested. The mode buttons and signal dropdown
are independent, and a one-time preference migration recovers sessions
that briefly saved `Rendered` in the signal field.

Episode navigation and token/render enrichment use separate request
lifecycles. Opening or closing an episode invalidates prior enrichment,
while changing controls during an in-flight open no longer discards the
episode response; the newly opened episode then picks up any enrichment
required by the latest controls. Decode failures remain branch-local in
the viewer: valid text for the selected branch is shown even if another
branch fails to decode.

## Verification

- `uv run --no-sync ruff format --check
src/prime_rl/dashboard/server.py`
- `uv run --no-sync ruff check src/prime_rl/dashboard/server.py`
- `uv run ruff check src/prime_rl/dashboard`
- `node --check src/prime_rl/dashboard/static/app.js`
- `git diff origin/main...HEAD --check`
- exercised a generic synthetic two-branch trace through the live
dashboard API with three tool-definition shapes; verified renderer-model
selection, retained `<|im_start|>` / `<|im_end|>` markers, separate
branch text, all-node ordering, and existing per-token pieces

## Visual description

A compact `Tool definitions · 3 tools · lookup, calculate, tool 3` row
appears directly after the system message. It expands into nested tool
cards with full prose and scrollable monospace schemas. `Messages` /
`Rendered` buttons sit beside a signal dropdown containing `Text`,
`Advantage`, `Logprob`, `Mask`, and `Content`. Either mode can use any
signal; Rendered/Text shows the exact decoded transcript, while Rendered
with an overlay shows colored token spans. A hover tooltip describes the
signal choices. A screenshot is not included because a browser runtime
was unavailable in the checkout used for verification.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Additive dashboard and optional episode API fields; no changes to
training, auth, or data persistence beyond larger lazy-loaded episode
payloads.
> 
> **Overview**
> The trace viewer adds **Messages** vs **Rendered** modes and surfaces
**`trace.tools`** as model context separate from message text.
> 
> In **Messages**, tool definitions appear in a collapsible context
block (after the first system message when present), with descriptions,
parameter schemas, and copy actions; message bodies still show literal
**`message.content`**. **Rendered** decodes recorded post-renderer
**`token_ids`** per branch (or all nodes) via **`renderer_model_name`**
with run-model fallback—no chat-template reconstruction—and reports
missing IDs, model, tokenizer, or decode failures.
> 
> The episode API accepts optional **`tokens`** and **`rendered`** query
params; **`rendered_token_text`** on the server concatenates branch
paths and decodes full sequences with special tokens retained. The UI
lazily fetches enrichment, versions open/enrichment requests to avoid
stale responses, and shares the Text / Advantage / Logprob / Mask /
Content signal dropdown across both modes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
596f7d3fe9746c9283d8a872b1d506c26a525e1a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-25 11:40:30 -07:00
3758321f08 fix: preserve final eval during teardown (#3324)
## Summary

- Use successful trainer and orchestrator exits as the shared completion
condition in local and multi-node SLURM launchers.
- Let each SLURM component publish `.trainer.done` or
`.orchestrator.done`, then stop inference after both markers exist.
- Make trainer-only fake-data SLURM runs stop after `.trainer.done`; no
orchestrator exists in that mode.
- Store all generated SLURM scripts and coordination files under
`<run_dir>/launcher/`.
- Store SLURM stdout and stderr under `<run_dir>/launcher/logs/`.
- Apply the launcher layout to RL, SFT, decoupled SFT eval, and
standalone inference entrypoints.
- Keep local launchers unchanged on disk. They do not create `launcher/`
because they persist no launcher files.
- Preserve failure propagation through `srun --kill-on-bad-exit=1`.

At `max_steps`, the trainer can exit while the orchestrator still drains
the final eval. The template previously tore down the node after the
first background process exited. This killed the final eval. A clean
exit also did not trigger `--kill-on-bad-exit`, so inference nodes could
hold the allocation until wall time.

## Breaking

- Generated SLURM scripts move from `<run_dir>/*.sbatch` to
`<run_dir>/launcher/*.sbatch`. Update manual submission commands and
tooling to use the new paths.
- SLURM job logs move from `<run_dir>/*job_*.log` to
`<run_dir>/launcher/logs/*job_*.log`. Update log collection and
monitoring paths.

## Verification

Before this change, a 1000-step GLM-4.5-Air run lost its final eval at
450 of 500 tasks. The six-node allocation then remained active for
another 23 hours.

After this change, a 10-step reverse-text run evaluated at its final
step and exited successfully:

- The final eval completed all 64 rollouts with no rollout errors.
- The trainer finished at 01:39:08 UTC.
- The orchestrator drained its pipeline and finished at 01:39:14 UTC.
- Inference stopped after both terminal components finished.
- The launcher exited with code 0 and released both GPUs.

A two-node trainer-only fake-data dry run rendered a one-marker watcher
with no `ORCHESTRATOR_DONE` reference. The normal inference path still
rendered the two-marker watcher. Both scripts passed `bash -n`.

All RL, SFT, decoupled SFT eval, and inference SLURM variants rendered
successfully. Every rendered script passed `bash -n`. Local RL, SFT, and
inference dry runs did not create `launcher/`.

An additional two-node SLURM run used the regular reverse-text
configuration with 100 eval rollouts per evaluation:

- The trainer completed all 20 steps and wrote `launcher/.trainer.done`.
- The orchestrator continued to drain queued evaluations after trainer
completion.
- The orchestrator then wrote `launcher/.orchestrator.done`.
- Both nodes logged teardown with exit code 0, and the job released its
allocation.

Ruff passed. The pathing unit tests passed with 10 tests.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes multi-node SLURM lifecycle and coordination (eval completion
vs allocation hold time) and breaks paths for manual `sbatch` and log
monitoring; incorrect completion logic could still strand nodes or kill
in-flight evals.
> 
> **Overview**
> Fixes premature SLURM teardown at `max_steps` when the trainer exits
while the orchestrator is still draining the **final eval**. Multi-node
RL jobs no longer stop on the first background process exit; trainer
rank 0 and the orchestrator publish **`launcher/.trainer.done`** and
**`launcher/.orchestrator.done`** on success, and every node waits for
the appropriate pair (trainer-only vs trainer+orchestrator) before
killing inference and releasing the allocation. Failures still propagate
via **`srun --kill-on-bad-exit=1`**.
> 
> **Breaking layout change:** generated `*.sbatch` scripts, coordination
sentinels, and SLURM `job_*.log` output move from the run directory root
to **`&lt;run_dir&gt;/launcher/`** and **`launcher/logs/`** for RL, SFT,
decoupled SFT eval, and standalone inference. Entrypoints and Jinja
templates pass `launcher_dir` / `launcher_log_dir`; local launches stay
unchanged on disk (no `launcher/`). Docs and training skills note the
new paths; `format_log_message` and `LAUNCHER_ARTIFACTS` validation
follow the same layout.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
02f3807d4a4f9cd53830b9b90e4035c386d01bdc. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 21:58:23 -07:00
Mika SenghaasandGitHub 01dc127b1a fix: synchronize before the pre-broadcast empty_cache (#3383)
## Summary
- One-line fix for the deterministic `CUDA error: an illegal memory
access` that killed every SignSGD run without full optimizer offload
since #3234.
- `torch.cuda.empty_cache()` returns cached blocks to the driver; a
kernel still in flight that references a cached block faults once its
block is freed under it. The pre-broadcast `empty_cache` (added in #3234
for FP8 gather headroom) runs immediately after `optimizer.step()` —
SignSGD's per-param loop leaves thousands of tiny kernels still running
at that point, while AdamW's compact foreach step happens to finish in
time, which is why only SignSGD crashed. Draining pending work with
`torch.cuda.synchronize()` before releasing blocks closes the race for
every optimizer, at ~ms cost once per step.

## Verification

All on the same GLM-4.5-Air scaleswe config (2 trainer + 2 inference
nodes, `sign_sgd` + `optim_cpu_offload`, no full offload):

| state | outcome |
|---|---|
| main | illegal memory access right after step 1, 2/2 slurm attempts |
| main + `CUDA_LAUNCH_BLOCKING=1` | no crash — ordering, not indexing |
| **main + this one line** | [runs
clean](https://wandb.ai/primeintellect/swe-ablations?nw=nwuser&search=sgd-nooffload):
11+ steps and counting, healthy grad norms, no restarts |

Supersedes #3373 — its foreach SignSGD rewrite turned out to be
unnecessary for correctness (verified by running the untouched optimizer
with only this line).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the per-step RL training hot path and GPU memory lifecycle
before weight broadcast; the change is narrow and matches existing
synchronize-before-empty_cache patterns elsewhere, but any extra sync
can affect step timing.
> 
> **Overview**
> Fixes a **CUDA illegal memory access** that could occur right after
`optimizer.step()` when the trainer frees GPU cache before broadcasting
weights.
> 
> The pre-broadcast `torch.cuda.empty_cache()` (for FP8 gather headroom)
can return cached blocks to the driver while **optimizer kernels are
still in flight**—especially with SignSGD’s many small per-parameter
updates. The change **drains pending GPU work** via
`torch.cuda.synchronize()` immediately before `empty_cache()`, with
expanded comments explaining the race.
> 
> This is a one-line behavioral fix in the RL training loop’s
weight-broadcast path; it does not change broadcast semantics, only
ordering so memory is not reclaimed under active kernels.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8947aa400631ca5a2dab829642f7755fab7dafd0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 18:33:04 -07:00
Konstantin DunasandGitHub 663b53bbc2 fix: silence W&B Weave advertisement on wandb.init (#3380) 2026-08-25 01:51:29 +02:00
21 changed files with 446 additions and 90 deletions
+3 -1
View File
@@ -194,9 +194,11 @@ Launch:
```bash
uv run rl @ base_rl.toml @ my_slurm.toml # submits via sbatch
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script + resolved config, exits
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes launcher/rl.sbatch + resolved config, exits
```
Every SLURM entrypoint stores its generated scripts and coordination files under `<run_dir>/launcher/`. SLURM stdout and stderr go to `launcher/logs/`. Local launches do not create `launcher/`.
### `[deployment]` Block
`[deployment]` is a discriminated union picked by `type` — `single_node` or `multi_node` for RL/SFT, with an extra disaggregated variant for inference. RL multi-node:
+2
View File
@@ -93,6 +93,8 @@ Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`
└── envs/{train,eval}/{env_name}.log # one log file per env
```
SLURM batch logs are under `{run_dir}/launcher/logs/*job_*.log`.
Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough. Drop into per-node or per-rank logs only when debugging. All logs are loguru with `HH:mm:ss LEVEL message`; levels: `DEBUG`, `INFO`, `SUCCESS`, `WARNING`, `ERROR`.
Scan for problems:
+3
View File
@@ -7,6 +7,8 @@ description: How to launch prime-rl training runs — the `rl`, `sft`, `inferenc
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory.
## Run directories
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, broadcasts, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
@@ -43,6 +45,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`)
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
- SLURM: single- and multi-node
- Multi-node SLURM stops after `.trainer.done` for trainer-only fake-data runs. Runs with inference stop after both `.trainer.done` and `.orchestrator.done`.
- Environment packages: before launching a config with a non-core verifier env id,
verify the package imports under `uv run` (for example
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
+8
View File
@@ -15,6 +15,14 @@ cluster head node, a laptop against a mounted outputs dir:
uv sync --extra dashboard && uv run dashboard [output_dir ...]
```
The trace viewer's **Messages** mode keeps structured `message.content` and
`trace.tools` visibly separate. **Rendered** decodes each selected branch's
recorded post-renderer `token_ids` as one sequence, retaining special tokens;
it never reconstructs a chat template. The recorded IDs remain the source of
truth, and the viewer reports when IDs, the renderer model, or its tokenizer
are unavailable. Text, advantage, logprob, mask, and content signals apply to
both views; Rendered with Text uses the exact full-sequence decode.
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
The integration suite covers it end to end (`tests/integration/dashboard_smoke.py`
runs after every integration test).
+66 -7
View File
@@ -767,6 +767,56 @@ def decode_pieces(model: str, ids: list[int]) -> list[str] | None:
return pieces
def trace_node_paths(trace: dict) -> list[list[int]]:
"""Root-to-leaf node indexes in the same order as the trace viewer."""
nodes = trace.get("nodes") or []
has_child = {node.get("parent") for node in nodes if isinstance(node, dict) and isinstance(node.get("parent"), int)}
paths = []
for leaf in (index for index in range(len(nodes)) if index not in has_child):
path = []
seen = set()
index = leaf
while isinstance(index, int) and 0 <= index < len(nodes) and index not in seen:
seen.add(index)
path.append(index)
parent = nodes[index].get("parent") if isinstance(nodes[index], dict) else None
index = parent if isinstance(parent, int) else None
paths.append(list(reversed(path)))
return paths
def rendered_token_text(trace: dict, model: str | None) -> dict:
"""Decode recorded post-renderer IDs as full branch sequences."""
nodes = trace.get("nodes") or []
paths = trace_node_paths(trace)
if not any(isinstance(node, dict) and node.get("token_ids") for node in nodes):
return {"status": "missing_token_ids", "model": model, "paths": []}
if not model:
return {"status": "missing_model", "model": None, "paths": []}
tokenizer = get_tokenizer(model)
if tokenizer is None:
return {"status": "tokenizer_unavailable", "model": model, "paths": []}
def decode_path(path: list[int]) -> dict:
ids = [token_id for index in path for token_id in (nodes[index].get("token_ids") or [])]
try:
text = tokenizer.decode(ids, skip_special_tokens=False)
except Exception:
text = None
return {"nodes": path, "token_count": len(ids), "text": text}
rendered_paths = [decode_path(path) for path in paths]
all_nodes = list(range(len(nodes)))
all_nodes_rendered = decode_path(all_nodes)
status = "ok" if all(path["text"] is not None for path in rendered_paths + [all_nodes_rendered]) else "decode_error"
return {
"status": status,
"model": model,
"paths": rendered_paths,
"all_nodes": all_nodes_rendered,
}
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/series")
def episode_series(run: str, step: int, kind: str, subset: str, etag: str | None = None, after: int = 0) -> dict:
"""Per-episode series over a traces file (x = episode order): reward, shape, and the
@@ -797,7 +847,15 @@ def episode_series(run: str, step: int, kind: str, subset: str, etag: str | None
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/{line}")
def get_episode(run: str, step: int, kind: str, subset: str, line: int, tokens: bool = False) -> dict:
def get_episode(
run: str,
step: int,
kind: str,
subset: str,
line: int,
tokens: bool = False,
rendered: bool = False,
) -> dict:
path = traces_path(run, step, kind, subset)
offsets = line_offsets(path)
if not 0 <= line < len(offsets):
@@ -805,17 +863,18 @@ def get_episode(run: str, step: int, kind: str, subset: str, line: int, tokens:
with path.open("rb") as f:
f.seek(offsets[line])
rec = orjson.loads(f.readline())
if not tokens:
if not tokens and not rendered:
return rec
fallback_model = model_name(main_config(get_run_dir(run))[1])
for trace in rec.get("traces") or []:
client = ((trace.get("agent") or {}).get("config") or {}).get("client") or {}
model = client.get("renderer_model_name") or fallback_model
if not model:
continue
for node in trace.get("nodes") or []:
if node.get("token_ids"):
node["token_strs"] = decode_pieces(model, node["token_ids"])
if tokens and model:
for node in trace.get("nodes") or []:
if node.get("token_ids"):
node["token_strs"] = decode_pieces(model, node["token_ids"])
if rendered:
trace["rendered_tokens"] = rendered_token_text(trace, model)
return rec
+170 -18
View File
@@ -45,6 +45,7 @@ const state = {
errorsOnly: prefs.traceErrorsOnly ?? false,
sort: (prefs.traceSort ?? "line:asc").split(":")[0],
order: (prefs.traceSort ?? "line:asc").split(":")[1],
viewMode: prefs.tokenSignal === "rendered" ? "rendered" : (prefs.traceViewMode ?? "messages"),
},
};
@@ -1947,6 +1948,8 @@ let currentEpisode = null;
let currentLine = null;
let currentTraceIdx = 0;
let currentBranchIdx = 0;
let episodeOpenVersion = 0;
let episodeEnrichmentVersion = 0;
const COPY_SVG =
`<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">` +
@@ -2051,42 +2054,61 @@ async function modalStep(delta) {
}
}
function fetchEpisode(line, withTokens) {
function fetchEpisode(line, withTokens, withRendered = false) {
const traces = state.traces;
const qs = withTokens ? "?tokens=true" : "";
const params = new URLSearchParams();
if (withTokens) params.set("tokens", "true");
if (withRendered) params.set("rendered", "true");
const qs = params.size ? `?${params}` : "";
return api(`/api/runs/${encodeURIComponent(state.run)}/rollouts/${traces.step}/${traces.kind}/${traces.subset}/${line}${qs}`);
}
/* token strings multiply the payload of a big episode, so they are fetched only
while a token signal is selected — the plain view ships the raw record */
for token signals or the rendered-token view — the plain view ships the raw record */
async function ensureTokens() {
if (!currentEpisode || currentEpisode._hasTokens || !$("#token-signal").value) return;
if (!currentEpisode) return;
const wantsPieces = !!$("#token-signal").value;
const wantsRendered = state.traces.viewMode === "rendered";
if ((!wantsPieces || currentEpisode._hasTokens) && (!wantsRendered || currentEpisode._hasRendered)) return;
const line = currentLine;
const episode = await fetchEpisode(line, true);
if (line !== currentLine) return;
episode._hasTokens = true;
const withTokens = wantsPieces || !!currentEpisode._hasTokens;
const withRendered = wantsRendered || !!currentEpisode._hasRendered;
const requestVersion = ++episodeEnrichmentVersion;
const episode = await fetchEpisode(line, withTokens, withRendered);
if (line !== currentLine || requestVersion !== episodeEnrichmentVersion) return;
episode._hasTokens = withTokens;
episode._hasRendered = withRendered;
currentEpisode = episode;
}
async function openEpisode(line) {
const requestVersion = ++episodeOpenVersion;
episodeEnrichmentVersion++;
$("#trace-modal").hidden = false;
$("#drawer-backdrop").hidden = false;
currentLine = line;
currentEpisode = null;
renderModalStep();
renderRolloutList();
$("#tm-messages").innerHTML = `<div class="chart-empty">loading episode…</div>`;
$("#tm-meta").innerHTML = "";
const withTokens = !!$("#token-signal").value;
const episode = await fetchEpisode(line, withTokens);
if (line !== currentLine) return; // user already moved to another rollout
const withRendered = state.traces.viewMode === "rendered";
const episode = await fetchEpisode(line, withTokens, withRendered);
if (line !== currentLine || requestVersion !== episodeOpenVersion) return;
episode._hasTokens = withTokens;
episode._hasRendered = withRendered;
currentEpisode = episode;
currentTraceIdx = 0;
currentBranchIdx = 0;
renderEpisode();
await ensureTokens();
if (line === currentLine && requestVersion === episodeOpenVersion) renderEpisode();
}
function closeDrawer() {
episodeOpenVersion++;
episodeEnrichmentVersion++;
$("#trace-modal").hidden = true;
$("#drawer-backdrop").hidden = true;
currentEpisode = null;
@@ -2145,7 +2167,7 @@ function renderTokenNode(node, signal, maxAbsAdv) {
const logprobAt = alignedSignal(node, node.logprobs);
const advantageAt = alignedSignal(node, node.advantages);
const spans = ids.map((id, i) => {
const text = strs ? strs[i] : ` ${id} `;
const text = strs?.[i] ?? ` ${id} `;
const logprob = logprobAt(i), advantage = advantageAt(i);
let bg = "";
if (signal === "advantage" && advantage != null && maxAbsAdv > 0) {
@@ -2205,6 +2227,95 @@ function reasoningBlock(content) {
);
}
function normalizedTools(tools) {
if (tools == null) return [];
return Array.isArray(tools) ? tools : [tools];
}
function toolParts(tool, index) {
if (!tool || typeof tool !== "object" || Array.isArray(tool))
return { name: `tool ${index + 1}`, description: "Malformed tool definition", parameters: tool };
const value = tool.function && typeof tool.function === "object" ? tool.function : tool;
return {
name: typeof value.name === "string" && value.name ? value.name : `tool ${index + 1}`,
description: typeof value.description === "string" ? value.description : "No description recorded.",
parameters: value.parameters ?? value.input_schema ?? value.schema ?? null,
};
}
function toolDefinitionsHtml(trace) {
const tools = normalizedTools(trace.tools);
if (!tools.length) return "";
const names = tools.map((tool, i) => toolParts(tool, i).name);
const body = tools.map((tool, i) => {
const parts = toolParts(tool, i);
const schema = parts.parameters == null ? "No parameters/schema recorded." :
typeof parts.parameters === "string" ? parts.parameters : JSON.stringify(parts.parameters, null, 2);
return (
`<details class="tool-definition"><summary><span class="tool-def-name">${esc(parts.name)}</span>` +
`<span class="entry-preview">${preview(parts.description, 140)}</span>` +
`<button class="icon-btn" data-copy-tool="${i}" title="copy full tool definition">${COPY_SVG}</button>` +
`<span class="entry-chev">›</span></summary>` +
`<div class="tool-description">${esc(parts.description)}</div>` +
`<div class="schema-head"><span>Parameters / JSON schema</span>` +
`<button class="icon-btn" data-copy-schema="${i}" title="copy parameters/schema">${COPY_SVG}</button></div>` +
`<pre class="tool-schema">${esc(schema)}</pre></details>`
);
}).join("");
return (
`<details class="tool-definitions"><summary><span class="context-label">Tool definitions</span>` +
`<span class="chip">${tools.length} tool${tools.length === 1 ? "" : "s"}</span>` +
`<span class="entry-preview">${esc(names.join(", "))}</span>` +
`<button class="icon-btn" data-copy-tools title="copy all tool definitions">${COPY_SVG}</button>` +
`<span class="entry-chev">›</span></summary>` +
body + `</details>`
);
}
function renderedTokensHtml(trace, branches) {
const rendered = trace.rendered_tokens;
const errors = errorBannersHtml(episodeErrors(currentEpisode, trace));
if (!rendered) return emptyState("rendered text not loaded", "select this view again to load recorded token IDs") + errors;
const signal = $("#token-signal").value;
const path = currentPath(trace, branches);
const tokenCount = path.reduce((count, index) => count + (trace.nodes[index]?.token_ids?.length || 0), 0);
const unavailable = {
missing_token_ids: ["no recorded token IDs", "This trace cannot provide post-renderer text because its nodes have no token_ids."],
missing_model: ["tokenizer model unavailable", "Neither renderer_model_name nor the run model was recorded."],
tokenizer_unavailable: ["tokenizer unavailable", `Could not load the recorded renderer tokenizer${rendered.model ? ` (${rendered.model})` : ""}. Token IDs remain authoritative.`],
decode_error: ["recorded tokens could not be decoded", "The tokenizer was found, but it could not decode this recorded sequence."],
};
const selected = currentBranchIdx === -1 ? rendered.all_nodes : rendered.paths?.[currentBranchIdx];
if (signal && tokenCount) {
let maxAbsAdv = 0;
for (const node of trace.nodes || [])
for (const advantage of node.advantages || []) maxAbsAdv = Math.max(maxAbsAdv, Math.abs(advantage));
const body = path.map((index) => renderTokenNode(trace.nodes[index], signal, maxAbsAdv)).join("");
return (
`<details class="rendered-transcript" open><summary><span class="context-label">Rendered tokens/text</span>` +
`<span class="chip">${fmtCompact(tokenCount)} tokens</span>` +
(selected?.text != null ? `<span class="entry-preview">${preview(selected.text, 180)}</span>` : `<span class="entry-preview"></span>`) +
(selected?.text != null ? `<button class="icon-btn" data-copy-rendered="text" title="copy decoded text">${COPY_SVG}</button>` : "") +
`<button class="icon-btn" data-copy-rendered="ids" title="copy authoritative token IDs">IDs</button>` +
`<span class="entry-chev">›</span></summary>` +
`<pre class="rendered-text">${body}</pre></details>` + errors
);
}
if (selected?.text == null) {
const [title, detail] = unavailable[rendered.status] ?? ["rendered text unavailable", "The recorded token sequence could not be decoded."];
return emptyState(title, detail) + errors;
}
return (
`<details class="rendered-transcript" open><summary><span class="context-label">Rendered tokens/text</span>` +
`<span class="chip">${fmtCompact(selected.token_count)} tokens</span>` +
`<span class="entry-preview">${preview(selected.text, 180)}</span>` +
`<button class="icon-btn" data-copy-rendered="text" title="copy decoded text">${COPY_SVG}</button>` +
`<button class="icon-btn" data-copy-rendered="ids" title="copy authoritative token IDs">IDs</button>` +
`<span class="entry-chev">›</span></summary>` +
`<pre class="rendered-text">${esc(selected.text)}</pre></details>` + errors
);
}
let entriesObserver = null;
function episodeErrors(ep, trace) {
@@ -2243,9 +2354,15 @@ function renderMessages(ep, trace, branches) {
container.innerHTML = emptyState("no traces", "this episode carries no trace data") + errorsHtml;
return;
}
if (state.traces.viewMode === "rendered") {
container.innerHTML = renderedTokensHtml(trace, branches);
return;
}
const signal = $("#token-signal").value;
const path = currentPath(trace, branches);
const concatenated = currentBranchIdx === -1;
const toolsHtml = toolDefinitionsHtml(trace);
const systemPosition = path.findIndex((idx) => trace.nodes[idx]?.message?.role === "system");
let maxAbsAdv = 0;
for (const node of trace.nodes || [])
for (const a of node.advantages || []) maxAbsAdv = Math.max(maxAbsAdv, Math.abs(a));
@@ -2266,7 +2383,7 @@ function renderMessages(ep, trace, branches) {
const reasoning = node.message?.reasoning_content ?? node.message?.reasoning;
if (reasoning) subs.push(reasoningBlock(reasoning));
const toolCalls = (node.message?.tool_calls || []).map(toolCallHtml);
return (
const messageHtml =
`<details class="entry ${esc(role)}"${role === "system" ? "" : " open"}>` +
`<summary><span class="entry-num">${String(i + 1).padStart(2, "0")}</span>` +
`<span class="entry-role">${esc(role)}</span>` +
@@ -2277,14 +2394,15 @@ function renderMessages(ep, trace, branches) {
subs.join("") +
(body ? `<div class="entry-body">${body}</div>` : "") +
toolCalls.join("") +
`</details>`
);
`</details>`;
return messageHtml + (i === systemPosition ? toolsHtml : "");
};
// long traces render in chunks as the reader scrolls — a 1MB episode with
// hundreds of turns paints the first screen immediately
const CHUNK = 30;
let rendered = Math.min(path.length, CHUNK);
container.innerHTML =
(systemPosition === -1 ? toolsHtml : "") +
path.slice(0, rendered).map(entryHtml).join("") +
(rendered < path.length ? `<div id="tm-more" class="chart-empty">scroll for ${path.length - rendered} more entries</div>` : "") +
errorsHtml;
@@ -2449,6 +2567,7 @@ function renderEpisode() {
`<button data-branch="-1" class="${currentBranchIdx === -1 ? "active" : ""}" title="all branches concatenated top to bottom">all</button>`
: "";
$("#tm-tabs-row").hidden = traceTabs.hidden && branchTabs.hidden;
setActive("#trace-view-mode", "mode", state.traces.viewMode);
renderRolloutList();
renderMessages(ep, trace, branches);
renderMeta(ep, trace, branches);
@@ -2882,6 +3001,15 @@ $("#token-signal").addEventListener("change", async () => {
renderEpisode();
savePrefs();
});
$("#trace-view-mode").addEventListener("click", async (e) => {
const btn = e.target.closest("[data-mode]");
if (!btn || btn.dataset.mode === state.traces.viewMode) return;
state.traces.viewMode = btn.dataset.mode;
setActive("#trace-view-mode", "mode", state.traces.viewMode);
await ensureTokens();
renderEpisode();
savePrefs();
});
$("#tm-trace-tabs").addEventListener("click", (e) => {
const btn = e.target.closest("[data-trace]");
if (btn) { currentTraceIdx = +btn.dataset.trace; currentBranchIdx = 0; renderEpisode(); }
@@ -2895,18 +3023,41 @@ $("#tm-list").addEventListener("click", (e) => {
if (item) openEpisode(+item.dataset.line);
});
$("#tm-collapse").addEventListener("click", () =>
document.querySelectorAll("#tm-messages details.entry").forEach((d) => (d.open = false))
document.querySelectorAll("#tm-messages details").forEach((d) => (d.open = false))
);
$("#tm-expand").addEventListener("click", () =>
document.querySelectorAll("#tm-messages details").forEach((d) => (d.open = true))
);
$("#tm-messages").addEventListener("click", (e) => {
const btn = e.target.closest("[data-copy]");
const btn = e.target.closest("[data-copy], [data-copy-tool], [data-copy-schema], [data-copy-tools], [data-copy-rendered]");
if (!btn) return;
e.preventDefault();
e.stopPropagation();
const node = currentEpisode?.traces?.[currentTraceIdx]?.nodes?.[+btn.dataset.copy];
if (node) copyText(messageText(node.message), btn);
const trace = currentEpisode?.traces?.[currentTraceIdx];
if (!trace) return;
if (btn.dataset.copy != null) {
const node = trace.nodes?.[+btn.dataset.copy];
if (node) copyText(messageText(node.message), btn);
return;
}
const tools = normalizedTools(trace.tools);
if (btn.hasAttribute("data-copy-tools")) return copyText(JSON.stringify(tools, null, 2), btn);
if (btn.dataset.copyTool != null) return copyText(JSON.stringify(tools[+btn.dataset.copyTool], null, 2), btn);
if (btn.dataset.copySchema != null) {
const schema = toolParts(tools[+btn.dataset.copySchema], +btn.dataset.copySchema).parameters;
return copyText(typeof schema === "string" ? schema : JSON.stringify(schema, null, 2), btn);
}
if (btn.dataset.copyRendered) {
const rendered = trace.rendered_tokens;
const selected = currentBranchIdx === -1 ? rendered?.all_nodes : rendered?.paths?.[currentBranchIdx];
if (btn.dataset.copyRendered === "text") {
if (selected?.text != null) copyText(selected.text, btn);
return;
}
const path = currentPath(trace, traceBranches(trace));
const ids = path.flatMap((index) => trace.nodes?.[index]?.token_ids || []);
return copyText(JSON.stringify(ids), btn);
}
});
$("#tm-meta").addEventListener("click", (e) => {
const btn = e.target.closest("[data-copytext]");
@@ -2938,6 +3089,7 @@ function savePrefs() {
collapsedSections: [...state.metrics.collapsedSections],
traceErrorsOnly: state.traces.errorsOnly,
traceSort: `${state.traces.sort}:${state.traces.order}`,
traceViewMode: state.traces.viewMode,
logView: state.logs.view,
logComponents: state.logs.components ? [...state.logs.components] : null,
logLevel: state.logs.level,
@@ -3000,7 +3152,7 @@ document.addEventListener("visibilitychange", () => {
renderLogLevel();
$("#log-search").value = prefs.logSearch ?? "";
$("#config-search").value = prefs.configSearch ?? "";
$("#token-signal").value = prefs.tokenSignal ?? "";
$("#token-signal").value = prefs.tokenSignal === "rendered" ? "" : (prefs.tokenSignal ?? "");
for (const sel of ["#run-select", "#trace-env", "#trace-sort", "#tm-env", "#tm-sort", "#attempt-select", "#token-signal"])
dressSelect($(sel));
syncTraceFilterControls();
+10 -6
View File
@@ -190,12 +190,16 @@
<div class="tm-head">
<span class="tm-title">Trace Viewer</span>
<div class="spacer"></div>
<select id="token-signal">
<option value="">text view</option>
<option value="advantage">tokens: advantage</option>
<option value="logprob">tokens: logprob</option>
<option value="mask">tokens: mask</option>
<option value="is_content">tokens: is_content</option>
<div class="seg" id="trace-view-mode">
<button data-mode="messages" class="active">Messages</button>
<button data-mode="rendered">Rendered</button>
</div>
<select id="token-signal" title="Choose the token signal for either view. Text is uncolored; other options color recorded tokens by advantage, log probability, training mask, or message-content membership.">
<option value="">Text</option>
<option value="advantage">Advantage</option>
<option value="logprob">Logprob</option>
<option value="mask">Mask</option>
<option value="is_content">Content</option>
</select>
<button id="tm-collapse" class="btn">collapse</button>
<button id="tm-expand" class="btn">expand</button>
+37
View File
@@ -788,6 +788,43 @@ details.sub > summary {
details.sub .sub-name { font-weight: 500; color: var(--grey-6); }
details.sub > .entry-body { border-top: 1px solid var(--hairline); }
/* tool definitions are model context, but deliberately sit outside numbered messages */
details.tool-definitions, details.rendered-transcript {
border: 1px solid var(--grey-3);
margin-bottom: 12px;
background: rgba(183, 166, 250, 0.025);
}
details.tool-definitions > summary, details.rendered-transcript > summary,
details.tool-definition > summary {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
padding: 7px 12px;
background: var(--grey-2);
}
details.tool-definitions[open] > summary, details.rendered-transcript[open] > summary,
details.tool-definition[open] > summary { border-bottom: 1px solid var(--hairline); }
details.tool-definitions[open] > summary .entry-chev,
details.rendered-transcript[open] > summary .entry-chev,
details.tool-definition[open] > summary .entry-chev { transform: rotate(90deg); }
.context-label, .tool-def-name { color: var(--chart-2); font-size: 10px; font-weight: 500; letter-spacing: var(--track-caps); text-transform: uppercase; }
details.tool-definition { margin: 8px 12px; border: 1px solid var(--hairline); }
.tool-description { padding: 10px 12px; color: var(--grey-5); font-size: 12px; white-space: pre-wrap; word-break: break-word; }
.schema-head { display: flex; align-items: center; padding: 6px 12px; border-top: 1px solid var(--hairline); color: var(--grey-4); font-size: 10px; letter-spacing: var(--track-caps); text-transform: uppercase; }
.schema-head .icon-btn { margin-left: auto; }
.tool-schema, .rendered-text {
margin: 0;
padding: 12px 14px;
overflow: auto;
color: var(--grey-5);
font: 400 11px/1.55 var(--font-mono);
tab-size: 2;
}
.tool-schema { max-height: 380px; border-top: 1px solid var(--hairline); white-space: pre; }
.rendered-text { white-space: pre-wrap; overflow-wrap: anywhere; }
#trace-view-mode button { white-space: nowrap; }
/* right pane: overview metadata */
.tm-reward-big { color: var(--positive); }
.tm-reward-big.neg { color: var(--negative); }
+10 -2
View File
@@ -10,7 +10,13 @@ from typing import Any
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_config_dir, latest_log_dir
from prime_rl.utils.pathing import (
format_log_message,
get_config_dir,
get_launcher_dir,
get_launcher_log_dir,
latest_log_dir,
)
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
@@ -71,6 +77,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.output_dir,
launcher_log_dir=get_launcher_log_dir(config.output_dir),
gpus_per_node=config.deployment.gpus_per_node,
dp_per_node=dp_per_node,
num_nodes=getattr(config.deployment, "num_nodes", 1),
@@ -116,6 +123,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
script = template.render(**template_vars)
script_path.parent.mkdir(parents=True, exist_ok=True)
get_launcher_log_dir(config.output_dir).mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
@@ -131,7 +139,7 @@ def inference_slurm(config: InferenceConfig):
config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node)
logger.info(f"Wrote config to {config_path}")
script_path = config.output_dir / INFERENCE_SBATCH
script_path = get_launcher_dir(config.output_dir) / INFERENCE_SBATCH
write_slurm_script(config, config_path, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
+13 -3
View File
@@ -24,6 +24,8 @@ from prime_rl.utils.pathing import (
format_log_message,
get_ckpt_dir,
get_config_dir,
get_launcher_dir,
get_launcher_log_dir,
latest_log_dir,
resolve_latest_ckpt_step,
validate_run_dir,
@@ -373,8 +375,9 @@ def rl_local(config: RLConfig):
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Check for errors from monitor threads
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
# Trainer and orchestrator completion is the successful stop condition.
completion_events = (stop_events["trainer"], stop_events["orchestrator"])
while not all(event.is_set() for event in completion_events):
if error_queue:
error = error_queue[0]
logger.error(f"Error: {error}")
@@ -461,6 +464,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
**config.slurm.template_vars,
config_path=config_dir / RL_CONFIG,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
gpus_per_node=config.deployment.gpus_per_node,
)
elif config.inference is not None and config.inference.deployment.type == "disaggregated":
@@ -472,6 +477,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
run_name=config.run.name,
config_dir=config_dir,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
nodes_per_infer_replica=infer_deploy.num_nodes,
@@ -513,6 +520,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
run_name=config.run.name,
config_dir=config_dir, # TODO: should prob have each subconfig path separately
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.total_infer_nodes,
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
@@ -545,6 +554,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
)
script_path.parent.mkdir(parents=True, exist_ok=True)
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
@@ -593,7 +603,7 @@ def rl_slurm(config: RLConfig):
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
)
script_path = config.run_dir / RL_SBATCH
script_path = get_launcher_dir(config.run_dir) / RL_SBATCH
write_slurm_script(config, config_dir, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
+13 -2
View File
@@ -22,6 +22,8 @@ from prime_rl.utils.pathing import (
get_broadcast_dir,
get_ckpt_dir,
get_config_dir,
get_launcher_dir,
get_launcher_log_dir,
get_log_dir,
latest_log_dir,
resolve_latest_ckpt_step,
@@ -163,6 +165,8 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
gpus_per_node=config.deployment.gpus_per_node,
)
else:
@@ -170,6 +174,8 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
trainer_env_vars=trainer_env_vars,
num_nodes=config.deployment.num_train_nodes,
gpus_per_node=config.deployment.gpus_per_node,
@@ -184,6 +190,7 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
@@ -218,6 +225,8 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
**config.slurm.template_vars,
config_dir=config_dir,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
num_infer_nodes=config.deployment.num_infer_nodes,
gpus_per_node=config.deployment.gpus_per_node,
router=config.inference.router,
@@ -235,6 +244,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
)
script_path.parent.mkdir(parents=True, exist_ok=True)
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
@@ -270,7 +280,8 @@ def sft_slurm(config: SFTConfig):
if decoupled_eval and config.monitors.wandb is not None:
prl_run_id = os.environ["PRL_RUN_ID"]
script_path = config.run_dir / SFT_SBATCH
launcher_dir = get_launcher_dir(config.run_dir)
script_path = launcher_dir / SFT_SBATCH
write_slurm_script(config, config_path, script_path, prl_run_id)
logger.info(f"Wrote SLURM script to {script_path}")
@@ -282,7 +293,7 @@ def sft_slurm(config: SFTConfig):
if decoupled_eval:
write_eval_subconfigs(config, config_dir, strip_router=True)
logger.info(f"Wrote eval subconfigs to {config_dir}")
eval_script_path = config.run_dir / EVAL_SBATCH
eval_script_path = launcher_dir / EVAL_SBATCH
write_eval_slurm_script(config, config_dir, eval_script_path, prl_run_id)
logger.info(f"Wrote eval SLURM script to {eval_script_path}")
script_paths = [script_path, eval_script_path]
+3
View File
@@ -42,6 +42,9 @@ class WandbMonitor(Monitor):
self.logger.debug(f"Found WANDB_ARGS in environment variables {wandb_args}")
sys.argv = json.loads(wandb_args)
# W&B advertises Weave on every init when it sees openai/verifiers imported.
os.environ.setdefault("WANDB_DISABLE_WEAVE", "1")
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
# requires a server connection and can't work offline.
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1" and os.environ.get("WANDB_MODE") not in (
+2 -2
View File
@@ -18,8 +18,8 @@
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
# Exit immediately on any failed command so a crash anywhere releases the
# allocation instead of leaving zombie processes holding nodes.
+67 -27
View File
@@ -18,8 +18,8 @@
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
# Exit immediately on any failed command so a crash anywhere releases the
# allocation instead of leaving zombie processes holding nodes.
@@ -58,6 +58,7 @@ export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parall
export PROJECT_DIR={{ project_dir }}
export CONFIG_DIR={{ config_dir }}
export OUTPUT_DIR={{ output_dir }}
export LAUNCHER_DIR={{ launcher_dir }}
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
ATTEMPT=1
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
@@ -67,6 +68,16 @@ ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
ln -sfn inference/node_0.log $LOG_DIR/inference.log
# Clean exits do not trigger srun --kill-on-bad-exit. Each terminal component
# publishes its successful exit through the shared launcher directory. Every node
# uses the same completion condition before it tears down support processes.
export TRAINER_DONE=$LAUNCHER_DIR/.trainer.done
{% if num_infer_nodes > 0 -%}
export ORCHESTRATOR_DONE=$LAUNCHER_DIR/.orchestrator.done
{% endif -%}
mkdir -p "$LAUNCHER_DIR"
rm -f "$TRAINER_DONE"{% if num_infer_nodes > 0 %} "$ORCHESTRATOR_DONE"{% endif %}
export PRL_RUN_ID=${PRL_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")}
export PRL_RUN_NAME={{ run_name }}
export WANDB_RUN_ID=$PRL_RUN_ID
@@ -400,21 +411,28 @@ else
echo $HOSTNAMES_STR | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
WANDB_SHARED_LABEL=trainer uv run torchrun \
--role=trainer \
--nnodes=$NUM_TRAIN_NODES \
--nproc-per-node=$GPUS_PER_NODE \
--node-rank=$TRAIN_NODE_RANK \
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
--rdzv-id=job_$SLURM_JOB_ID \
--log-dir=$LOG_DIR/trainer/torchrun \
--tee=3 \
--redirects=3 \
--local-ranks-filter={{ ranks_filter }} \
-m prime_rl.trainer.rl.train \
@ $CONFIG_DIR/trainer.json \
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log &
(
WANDB_SHARED_LABEL=trainer uv run torchrun \
--role=trainer \
--nnodes=$NUM_TRAIN_NODES \
--nproc-per-node=$GPUS_PER_NODE \
--node-rank=$TRAIN_NODE_RANK \
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
--rdzv-id=job_$SLURM_JOB_ID \
--log-dir=$LOG_DIR/trainer/torchrun \
--tee=3 \
--redirects=3 \
--local-ranks-filter={{ ranks_filter }} \
-m prime_rl.trainer.rl.train \
@ $CONFIG_DIR/trainer.json \
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
COMPONENT_CODE=$?
if [ "$COMPONENT_CODE" -eq 0 ] && [ "$TRAIN_NODE_RANK" -eq 0 ]; then
touch "$TRAINER_DONE" || exit $?
fi
exit "$COMPONENT_CODE"
) &
{% if num_infer_nodes > 0 %} fi{% endif %}
{% if num_infer_nodes > 0 %}
# Launch the orchestrator on the node ORCH_ADDR points at (see the ORCH_PROCID
@@ -450,19 +468,41 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
{%- endfor %}
{%- endif %}
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $LOG_DIR/orchestrator.log &
(
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $LOG_DIR/orchestrator.log
COMPONENT_CODE=$?
if [ "$COMPONENT_CODE" -eq 0 ]; then
touch "$ORCHESTRATOR_DONE" || exit $?
fi
exit "$COMPONENT_CODE"
) &
fi
{% endif %}
# Wait for the first background job to exit and propagate its exit code. This
# turns background process crashes (router, orchestrator) into task failures
# that --kill-on-bad-exit=1 can broadcast to the other nodes so the whole job
# tears down instead of leaving zombies holding the allocation.
wait -n
EXIT_CODE=$?
# Every node watches the terminal components for successful completion.
{% if num_infer_nodes > 0 -%}
# Inference runs stop after both the trainer and orchestrator finish.
( until [ -f "$TRAINER_DONE" ] && [ -f "$ORCHESTRATOR_DONE" ]; do sleep 10; done ) &
{% else -%}
# Trainer-only runs stop when the trainer finishes.
( until [ -f "$TRAINER_DONE" ]; do sleep 10; done ) &
{% endif -%}
COMPLETION_PID=$!
# A clean component exit is not enough to stop the run. Keep waiting for the
# shared completion condition. Propagate any failure through
# --kill-on-bad-exit=1 so every node tears down.
while true; do
wait -n -p FINISHED_PID
EXIT_CODE=$?
if [ "$EXIT_CODE" -ne 0 ] || [ "${FINISHED_PID:-}" = "$COMPLETION_PID" ]; then
break
fi
done
REMAINING_PIDS=$(jobs -p)
{%- if cleanup_grace_period %}
# Cross-node teardown is driven by `srun --kill-on-bad-exit=1`, which reaps peer
@@ -18,8 +18,8 @@
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
# Exit immediately on any failed command so a crash on any node releases the
# allocation instead of leaving zombie processes holding nodes.
@@ -33,6 +33,7 @@ export GPUS_PER_NODE={{ gpus_per_node }}
export PROJECT_DIR={{ project_dir }}
export CONFIG_PATH={{ config_path }}
export OUTPUT_DIR={{ output_dir }}
export LAUNCHER_DIR={{ launcher_dir }}
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
ATTEMPT=1
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
@@ -65,7 +66,7 @@ echo "MASTER_PORT=${MASTER_PORT}"
{% if use_nccl_broadcast %}
# The eval job has a separate allocation. Publish the trainer's NCCL host through
# the shared run directory under this job ID.
printf '%s\n' "$MASTER_ADDR" > "$OUTPUT_DIR/.sft_nccl_host_$SLURM_JOB_ID"
printf '%s\n' "$MASTER_ADDR" > "$LAUNCHER_DIR/.sft_nccl_host_$SLURM_JOB_ID"
{% endif %}
# Install environment
@@ -18,8 +18,8 @@
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/eval_job_%j.log
#SBATCH --error={{ output_dir }}/eval_job_%j.log
#SBATCH --output={{ launcher_log_dir }}/eval_job_%j.log
#SBATCH --error={{ launcher_log_dir }}/eval_job_%j.log
# Online-eval job for a decoupled SFT run: the inference pool (one vLLM engine per
# DP rank behind a single router) plus the evals process and its env servers. The trainer
@@ -42,6 +42,7 @@ export PROJECT_DIR={{ project_dir }}
export CONFIG_DIR={{ config_dir }}
export CONFIG_PATH=$CONFIG_DIR/inference.json
export OUTPUT_DIR={{ output_dir }}
export LAUNCHER_DIR={{ launcher_dir }}
# Move a previous job's inference logs aside instead of deleting them: rm of log
# files another job's processes still hold open can wedge in the NFS client and
# hang the whole job before srun even runs.
@@ -50,10 +51,9 @@ mkdir -p $OUTPUT_DIR/logs/inference
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
# A clean evals exit cannot trip srun --kill-on-bad-exit (which only propagates
# failures), so node 0 publishes completion through this job-scoped sentinel and the
# other nodes watch for it to release their engines. Stale sentinels from other job
# IDs are inert, so only this job's own path needs clearing.
export EVAL_DONE=$OUTPUT_DIR/.eval_done_$SLURM_JOB_ID
# failures), so node 0 publishes completion through this sentinel and the other nodes
# watch for it to release their engines.
export EVAL_DONE=$LAUNCHER_DIR/.eval.done
rm -f "$EVAL_DONE"
{% if prl_run_id %}
# Trainer (separate SLURM job) and evals log to a single shared W&B run whose id
@@ -72,7 +72,7 @@ export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
export HOSTNAMES_STR="${HOSTNAMES[*]}"
{% if use_nccl_broadcast %}
: "${TRAIN_JOB_ID:?TRAIN_JOB_ID is required for NCCL weight broadcast}"
TRAIN_HOST_FILE="$OUTPUT_DIR/.sft_nccl_host_$TRAIN_JOB_ID"
TRAIN_HOST_FILE="$LAUNCHER_DIR/.sft_nccl_host_$TRAIN_JOB_ID"
until [ -s "$TRAIN_HOST_FILE" ]; do sleep 1; done
export TRAIN_HOST=$(<"$TRAIN_HOST_FILE")
rm -f "$TRAIN_HOST_FILE"
@@ -18,8 +18,8 @@
{%- if exclude %}
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
# Exit immediately if any setup command or the launcher fails so the SLURM job
# releases its allocation instead of holding nodes after a crash.
@@ -18,8 +18,8 @@
{%- if exclude %}
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
# Exit immediately if any setup command or the launcher fails so the SLURM job
# releases its allocation instead of holding nodes after a crash.
+6 -1
View File
@@ -604,7 +604,12 @@ def train(config: TrainerConfig):
broadcast_weights_start_time = time.perf_counter()
# The per-layer gather + fp8 conversion peaks ~50 GiB above the
# resident weights; release cached blocks (incl. offload-stream
# pools) so the broadcast gets the full headroom.
# pools) so the broadcast gets the full headroom. Drain all
# pending work first: empty_cache returns blocks to the driver,
# so a still-running kernel holding a cached block (e.g. the
# optimizer step's tail) faults with an illegal memory access
# once its block is freed under it.
torch.cuda.synchronize()
torch.cuda.empty_cache()
weight_sender.broadcast(model, step=progress.step)
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
+12 -5
View File
@@ -61,7 +61,7 @@ def format_log_message(
log_lines: list[str] = []
if job_log:
log_lines.append(f"{i1}{'Job:':<{col}}tail -F {log_dir.parent.parent}/job_*.log")
log_lines.append(f"{i1}{'Job:':<{col}}tail -F {get_launcher_log_dir(log_dir.parent.parent)}/*job_*.log")
if trainer:
log_lines.append(f"{i1}{'Trainer:':<{col}}tail -F {log_dir}/trainer.log")
if num_train_nodes > 1:
@@ -129,6 +129,14 @@ def write_launch_toml(run_dir: Path, name: str) -> None:
(config_dir / f"{name}.toml").write_text("\n".join(texts))
def get_launcher_dir(output_dir: Path) -> Path:
return output_dir / "launcher"
def get_launcher_log_dir(output_dir: Path) -> Path:
return get_launcher_dir(output_dir) / "logs"
def get_ckpt_dir(output_dir: Path) -> Path:
return output_dir / "checkpoints"
@@ -174,10 +182,9 @@ def has_checkpoints(output_dir: Path) -> bool:
return ckpt_dir.exists() and any(ckpt_dir.iterdir())
# Launcher artifacts that may exist in a run directory before training starts: resolved
# configs and the SLURM script/job log (a submitted job re-invokes the entrypoint inside
# the run directory). Everything else is treated as artifacts of a previous run.
LAUNCHER_ARTIFACTS = ("configs", "rl.sbatch", "sft.sbatch", "job_*.log")
# Launcher artifacts may exist before training starts. Everything else is treated as
# artifacts of a previous run.
LAUNCHER_ARTIFACTS = ("configs", "launcher")
def has_run_artifacts(run_dir: Path) -> bool:
+6 -2
View File
@@ -19,8 +19,12 @@ def test_dir_with_launcher_artifacts_passes(tmp_path):
run_dir.mkdir()
(run_dir / "configs").mkdir()
(run_dir / "configs" / "trainer.toml").touch()
(run_dir / "rl.sbatch").touch()
(run_dir / "job_1234.log").touch()
(run_dir / "launcher").mkdir()
(run_dir / "launcher" / "rl.sbatch").touch()
(run_dir / "launcher" / ".trainer.done").touch()
(run_dir / "launcher" / ".orchestrator.done").touch()
(run_dir / "launcher" / "logs").mkdir()
(run_dir / "launcher" / "logs" / "job_1234.log").touch()
validate_run_dir(run_dir, output_dir=tmp_path, resuming=False, clean=False)