Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3460245d63 | ||
|
|
3758321f08 | ||
|
|
01dc127b1a | ||
|
|
663b53bbc2 |
+3
-1
@@ -194,9 +194,11 @@ Launch:
|
||||
|
||||
```bash
|
||||
uv run rl @ base_rl.toml @ my_slurm.toml # submits via sbatch
|
||||
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script + resolved config, exits
|
||||
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes launcher/rl.sbatch + resolved config, exits
|
||||
```
|
||||
|
||||
Every SLURM entrypoint stores its generated scripts and coordination files under `<run_dir>/launcher/`. SLURM stdout and stderr go to `launcher/logs/`. Local launches do not create `launcher/`.
|
||||
|
||||
### `[deployment]` Block
|
||||
|
||||
`[deployment]` is a discriminated union picked by `type` — `single_node` or `multi_node` for RL/SFT, with an extra disaggregated variant for inference. RL multi-node:
|
||||
|
||||
@@ -93,6 +93,8 @@ Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`
|
||||
└── envs/{train,eval}/{env_name}.log # one log file per env
|
||||
```
|
||||
|
||||
SLURM batch logs are under `{run_dir}/launcher/logs/*job_*.log`.
|
||||
|
||||
Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough. Drop into per-node or per-rank logs only when debugging. All logs are loguru with `HH:mm:ss LEVEL message`; levels: `DEBUG`, `INFO`, `SUCCESS`, `WARNING`, `ERROR`.
|
||||
|
||||
Scan for problems:
|
||||
|
||||
@@ -7,6 +7,8 @@ description: How to launch prime-rl training runs — the `rl`, `sft`, `inferenc
|
||||
|
||||
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
|
||||
|
||||
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory.
|
||||
|
||||
## Run directories
|
||||
|
||||
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, broadcasts, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
|
||||
@@ -43,6 +45,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
|
||||
- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
|
||||
- SLURM: single- and multi-node
|
||||
- Multi-node SLURM stops after `.trainer.done` for trainer-only fake-data runs. Runs with inference stop after both `.trainer.done` and `.orchestrator.done`.
|
||||
- Environment packages: before launching a config with a non-core verifier env id,
|
||||
verify the package imports under `uv run` (for example
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
|
||||
|
||||
@@ -15,6 +15,14 @@ cluster head node, a laptop against a mounted outputs dir:
|
||||
uv sync --extra dashboard && uv run dashboard [output_dir ...]
|
||||
```
|
||||
|
||||
The trace viewer's **Messages** mode keeps structured `message.content` and
|
||||
`trace.tools` visibly separate. **Rendered** decodes each selected branch's
|
||||
recorded post-renderer `token_ids` as one sequence, retaining special tokens;
|
||||
it never reconstructs a chat template. The recorded IDs remain the source of
|
||||
truth, and the viewer reports when IDs, the renderer model, or its tokenizer
|
||||
are unavailable. Text, advantage, logprob, mask, and content signals apply to
|
||||
both views; Rendered with Text uses the exact full-sequence decode.
|
||||
|
||||
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
|
||||
The integration suite covers it end to end (`tests/integration/dashboard_smoke.py`
|
||||
runs after every integration test).
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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,7 +10,13 @@ from typing import Any
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, latest_log_dir
|
||||
from prime_rl.utils.pathing import (
|
||||
format_log_message,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
latest_log_dir,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
@@ -71,6 +77,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.output_dir,
|
||||
launcher_log_dir=get_launcher_log_dir(config.output_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
dp_per_node=dp_per_node,
|
||||
num_nodes=getattr(config.deployment, "num_nodes", 1),
|
||||
@@ -116,6 +123,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
script = template.render(**template_vars)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.output_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -131,7 +139,7 @@ def inference_slurm(config: InferenceConfig):
|
||||
config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
script_path = config.output_dir / INFERENCE_SBATCH
|
||||
script_path = get_launcher_dir(config.output_dir) / INFERENCE_SBATCH
|
||||
write_slurm_script(config, config_path, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ from prime_rl.utils.pathing import (
|
||||
format_log_message,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
latest_log_dir,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
@@ -373,8 +375,9 @@ def rl_local(config: RLConfig):
|
||||
logger.success("Launcher complete")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
# Check for errors from monitor threads
|
||||
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
|
||||
# Trainer and orchestrator completion is the successful stop condition.
|
||||
completion_events = (stop_events["trainer"], stop_events["orchestrator"])
|
||||
while not all(event.is_set() for event in completion_events):
|
||||
if error_queue:
|
||||
error = error_queue[0]
|
||||
logger.error(f"Error: {error}")
|
||||
@@ -461,6 +464,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_dir / RL_CONFIG,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
elif config.inference is not None and config.inference.deployment.type == "disaggregated":
|
||||
@@ -472,6 +477,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
|
||||
nodes_per_infer_replica=infer_deploy.num_nodes,
|
||||
@@ -513,6 +520,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir, # TODO: should prob have each subconfig path separately
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.total_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
|
||||
@@ -545,6 +554,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -593,7 +603,7 @@ def rl_slurm(config: RLConfig):
|
||||
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
|
||||
)
|
||||
|
||||
script_path = config.run_dir / RL_SBATCH
|
||||
script_path = get_launcher_dir(config.run_dir) / RL_SBATCH
|
||||
write_slurm_script(config, config_dir, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@ from prime_rl.utils.pathing import (
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
get_log_dir,
|
||||
latest_log_dir,
|
||||
resolve_latest_ckpt_step,
|
||||
@@ -163,6 +165,8 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
else:
|
||||
@@ -170,6 +174,8 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
num_nodes=config.deployment.num_train_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
@@ -184,6 +190,7 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -218,6 +225,8 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
|
||||
**config.slurm.template_vars,
|
||||
config_dir=config_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router=config.inference.router,
|
||||
@@ -235,6 +244,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -270,7 +280,8 @@ def sft_slurm(config: SFTConfig):
|
||||
if decoupled_eval and config.monitors.wandb is not None:
|
||||
prl_run_id = os.environ["PRL_RUN_ID"]
|
||||
|
||||
script_path = config.run_dir / SFT_SBATCH
|
||||
launcher_dir = get_launcher_dir(config.run_dir)
|
||||
script_path = launcher_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, script_path, prl_run_id)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
@@ -282,7 +293,7 @@ def sft_slurm(config: SFTConfig):
|
||||
if decoupled_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(f"Wrote eval subconfigs to {config_dir}")
|
||||
eval_script_path = config.run_dir / EVAL_SBATCH
|
||||
eval_script_path = launcher_dir / EVAL_SBATCH
|
||||
write_eval_slurm_script(config, config_dir, eval_script_path, prl_run_id)
|
||||
logger.info(f"Wrote eval SLURM script to {eval_script_path}")
|
||||
script_paths = [script_path, eval_script_path]
|
||||
|
||||
@@ -42,6 +42,9 @@ class WandbMonitor(Monitor):
|
||||
self.logger.debug(f"Found WANDB_ARGS in environment variables {wandb_args}")
|
||||
sys.argv = json.loads(wandb_args)
|
||||
|
||||
# W&B advertises Weave on every init when it sees openai/verifiers imported.
|
||||
os.environ.setdefault("WANDB_DISABLE_WEAVE", "1")
|
||||
|
||||
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
|
||||
# requires a server connection and can't work offline.
|
||||
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1" and os.environ.get("WANDB_MODE") not in (
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately on any failed command so a crash anywhere releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately on any failed command so a crash anywhere releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
@@ -58,6 +58,7 @@ export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parall
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
@@ -67,6 +68,16 @@ ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
|
||||
# Clean exits do not trigger srun --kill-on-bad-exit. Each terminal component
|
||||
# publishes its successful exit through the shared launcher directory. Every node
|
||||
# uses the same completion condition before it tears down support processes.
|
||||
export TRAINER_DONE=$LAUNCHER_DIR/.trainer.done
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
export ORCHESTRATOR_DONE=$LAUNCHER_DIR/.orchestrator.done
|
||||
{% endif -%}
|
||||
mkdir -p "$LAUNCHER_DIR"
|
||||
rm -f "$TRAINER_DONE"{% if num_infer_nodes > 0 %} "$ORCHESTRATOR_DONE"{% endif %}
|
||||
|
||||
export PRL_RUN_ID=${PRL_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")}
|
||||
export PRL_RUN_NAME={{ run_name }}
|
||||
export WANDB_RUN_ID=$PRL_RUN_ID
|
||||
@@ -400,21 +411,28 @@ else
|
||||
|
||||
echo $HOSTNAMES_STR | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
|
||||
WANDB_SHARED_LABEL=trainer uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.json \
|
||||
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log &
|
||||
(
|
||||
WANDB_SHARED_LABEL=trainer uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.json \
|
||||
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ] && [ "$TRAIN_NODE_RANK" -eq 0 ]; then
|
||||
touch "$TRAINER_DONE" || exit $?
|
||||
fi
|
||||
exit "$COMPONENT_CODE"
|
||||
) &
|
||||
{% if num_infer_nodes > 0 %} fi{% endif %}
|
||||
{% if num_infer_nodes > 0 %}
|
||||
# Launch the orchestrator on the node ORCH_ADDR points at (see the ORCH_PROCID
|
||||
@@ -450,19 +468,41 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $LOG_DIR/orchestrator.log &
|
||||
(
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $LOG_DIR/orchestrator.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ]; then
|
||||
touch "$ORCHESTRATOR_DONE" || exit $?
|
||||
fi
|
||||
exit "$COMPONENT_CODE"
|
||||
) &
|
||||
fi
|
||||
{% endif %}
|
||||
|
||||
# Wait for the first background job to exit and propagate its exit code. This
|
||||
# turns background process crashes (router, orchestrator) into task failures
|
||||
# that --kill-on-bad-exit=1 can broadcast to the other nodes so the whole job
|
||||
# tears down instead of leaving zombies holding the allocation.
|
||||
wait -n
|
||||
EXIT_CODE=$?
|
||||
# Every node watches the terminal components for successful completion.
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
# Inference runs stop after both the trainer and orchestrator finish.
|
||||
( until [ -f "$TRAINER_DONE" ] && [ -f "$ORCHESTRATOR_DONE" ]; do sleep 10; done ) &
|
||||
{% else -%}
|
||||
# Trainer-only runs stop when the trainer finishes.
|
||||
( until [ -f "$TRAINER_DONE" ]; do sleep 10; done ) &
|
||||
{% endif -%}
|
||||
COMPLETION_PID=$!
|
||||
|
||||
# A clean component exit is not enough to stop the run. Keep waiting for the
|
||||
# shared completion condition. Propagate any failure through
|
||||
# --kill-on-bad-exit=1 so every node tears down.
|
||||
while true; do
|
||||
wait -n -p FINISHED_PID
|
||||
EXIT_CODE=$?
|
||||
if [ "$EXIT_CODE" -ne 0 ] || [ "${FINISHED_PID:-}" = "$COMPLETION_PID" ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
REMAINING_PIDS=$(jobs -p)
|
||||
{%- if cleanup_grace_period %}
|
||||
# Cross-node teardown is driven by `srun --kill-on-bad-exit=1`, which reaps peer
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately on any failed command so a crash on any node releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
@@ -33,6 +33,7 @@ export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_PATH={{ config_path }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
@@ -65,7 +66,7 @@ echo "MASTER_PORT=${MASTER_PORT}"
|
||||
{% if use_nccl_broadcast %}
|
||||
# The eval job has a separate allocation. Publish the trainer's NCCL host through
|
||||
# the shared run directory under this job ID.
|
||||
printf '%s\n' "$MASTER_ADDR" > "$OUTPUT_DIR/.sft_nccl_host_$SLURM_JOB_ID"
|
||||
printf '%s\n' "$MASTER_ADDR" > "$LAUNCHER_DIR/.sft_nccl_host_$SLURM_JOB_ID"
|
||||
{% endif %}
|
||||
|
||||
# Install environment
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/eval_job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/eval_job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/eval_job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/eval_job_%j.log
|
||||
|
||||
# Online-eval job for a decoupled SFT run: the inference pool (one vLLM engine per
|
||||
# DP rank behind a single router) plus the evals process and its env servers. The trainer
|
||||
@@ -42,6 +42,7 @@ export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export CONFIG_PATH=$CONFIG_DIR/inference.json
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Move a previous job's inference logs aside instead of deleting them: rm of log
|
||||
# files another job's processes still hold open can wedge in the NFS client and
|
||||
# hang the whole job before srun even runs.
|
||||
@@ -50,10 +51,9 @@ mkdir -p $OUTPUT_DIR/logs/inference
|
||||
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
|
||||
# A clean evals exit cannot trip srun --kill-on-bad-exit (which only propagates
|
||||
# failures), so node 0 publishes completion through this job-scoped sentinel and the
|
||||
# other nodes watch for it to release their engines. Stale sentinels from other job
|
||||
# IDs are inert, so only this job's own path needs clearing.
|
||||
export EVAL_DONE=$OUTPUT_DIR/.eval_done_$SLURM_JOB_ID
|
||||
# failures), so node 0 publishes completion through this sentinel and the other nodes
|
||||
# watch for it to release their engines.
|
||||
export EVAL_DONE=$LAUNCHER_DIR/.eval.done
|
||||
rm -f "$EVAL_DONE"
|
||||
{% if prl_run_id %}
|
||||
# Trainer (separate SLURM job) and evals log to a single shared W&B run whose id
|
||||
@@ -72,7 +72,7 @@ export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
export HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
{% if use_nccl_broadcast %}
|
||||
: "${TRAIN_JOB_ID:?TRAIN_JOB_ID is required for NCCL weight broadcast}"
|
||||
TRAIN_HOST_FILE="$OUTPUT_DIR/.sft_nccl_host_$TRAIN_JOB_ID"
|
||||
TRAIN_HOST_FILE="$LAUNCHER_DIR/.sft_nccl_host_$TRAIN_JOB_ID"
|
||||
until [ -s "$TRAIN_HOST_FILE" ]; do sleep 1; done
|
||||
export TRAIN_HOST=$(<"$TRAIN_HOST_FILE")
|
||||
rm -f "$TRAIN_HOST_FILE"
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
{%- if exclude %}
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately if any setup command or the launcher fails so the SLURM job
|
||||
# releases its allocation instead of holding nodes after a crash.
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
{%- if exclude %}
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately if any setup command or the launcher fails so the SLURM job
|
||||
# releases its allocation instead of holding nodes after a crash.
|
||||
|
||||
@@ -604,7 +604,12 @@ def train(config: TrainerConfig):
|
||||
broadcast_weights_start_time = time.perf_counter()
|
||||
# The per-layer gather + fp8 conversion peaks ~50 GiB above the
|
||||
# resident weights; release cached blocks (incl. offload-stream
|
||||
# pools) so the broadcast gets the full headroom.
|
||||
# pools) so the broadcast gets the full headroom. Drain all
|
||||
# pending work first: empty_cache returns blocks to the driver,
|
||||
# so a still-running kernel holding a cached block (e.g. the
|
||||
# optimizer step's tail) faults with an illegal memory access
|
||||
# once its block is freed under it.
|
||||
torch.cuda.synchronize()
|
||||
torch.cuda.empty_cache()
|
||||
weight_sender.broadcast(model, step=progress.step)
|
||||
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
|
||||
|
||||
@@ -61,7 +61,7 @@ def format_log_message(
|
||||
|
||||
log_lines: list[str] = []
|
||||
if job_log:
|
||||
log_lines.append(f"{i1}{'Job:':<{col}}tail -F {log_dir.parent.parent}/job_*.log")
|
||||
log_lines.append(f"{i1}{'Job:':<{col}}tail -F {get_launcher_log_dir(log_dir.parent.parent)}/*job_*.log")
|
||||
if trainer:
|
||||
log_lines.append(f"{i1}{'Trainer:':<{col}}tail -F {log_dir}/trainer.log")
|
||||
if num_train_nodes > 1:
|
||||
@@ -129,6 +129,14 @@ def write_launch_toml(run_dir: Path, name: str) -> None:
|
||||
(config_dir / f"{name}.toml").write_text("\n".join(texts))
|
||||
|
||||
|
||||
def get_launcher_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "launcher"
|
||||
|
||||
|
||||
def get_launcher_log_dir(output_dir: Path) -> Path:
|
||||
return get_launcher_dir(output_dir) / "logs"
|
||||
|
||||
|
||||
def get_ckpt_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "checkpoints"
|
||||
|
||||
@@ -174,10 +182,9 @@ def has_checkpoints(output_dir: Path) -> bool:
|
||||
return ckpt_dir.exists() and any(ckpt_dir.iterdir())
|
||||
|
||||
|
||||
# Launcher artifacts that may exist in a run directory before training starts: resolved
|
||||
# configs and the SLURM script/job log (a submitted job re-invokes the entrypoint inside
|
||||
# the run directory). Everything else is treated as artifacts of a previous run.
|
||||
LAUNCHER_ARTIFACTS = ("configs", "rl.sbatch", "sft.sbatch", "job_*.log")
|
||||
# Launcher artifacts may exist before training starts. Everything else is treated as
|
||||
# artifacts of a previous run.
|
||||
LAUNCHER_ARTIFACTS = ("configs", "launcher")
|
||||
|
||||
|
||||
def has_run_artifacts(run_dir: Path) -> bool:
|
||||
|
||||
@@ -19,8 +19,12 @@ def test_dir_with_launcher_artifacts_passes(tmp_path):
|
||||
run_dir.mkdir()
|
||||
(run_dir / "configs").mkdir()
|
||||
(run_dir / "configs" / "trainer.toml").touch()
|
||||
(run_dir / "rl.sbatch").touch()
|
||||
(run_dir / "job_1234.log").touch()
|
||||
(run_dir / "launcher").mkdir()
|
||||
(run_dir / "launcher" / "rl.sbatch").touch()
|
||||
(run_dir / "launcher" / ".trainer.done").touch()
|
||||
(run_dir / "launcher" / ".orchestrator.done").touch()
|
||||
(run_dir / "launcher" / "logs").mkdir()
|
||||
(run_dir / "launcher" / "logs" / "job_1234.log").touch()
|
||||
validate_run_dir(run_dir, output_dir=tmp_path, resuming=False, clean=False)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user