Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
21a4a32450 | ||
|
|
a070beecbd | ||
|
|
7da7c4d108 | ||
|
|
9e3be00b39 | ||
|
|
ef66401434 |
+2
-1
@@ -217,7 +217,8 @@ SFT multi-node:
|
||||
```toml
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1 # required only for online evals
|
||||
gpus_per_node = 8
|
||||
```
|
||||
|
||||
|
||||
+8
-7
@@ -200,15 +200,15 @@ num_infer_gpus = 1 # inference
|
||||
|
||||
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
|
||||
#### Multi-Node (Decoupled Trainer and Inference Pool)
|
||||
#### Multi-Node Trainer and Inference Pool
|
||||
|
||||
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two separate SLURM jobs**. `deployment.num_train_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
|
||||
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and evals process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2 # trainer job
|
||||
num_infer_nodes = 1 # eval job (inference pool + evals)
|
||||
num_train_nodes = 2 # trainer nodes
|
||||
num_infer_nodes = 1 # inference pool + evals
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
@@ -217,7 +217,7 @@ tensor_parallel_size = 8
|
||||
job_name = "my-run"
|
||||
```
|
||||
|
||||
The launcher submits the eval job after the trainer allocation starts. The trainer publishes its rank-0 hostname in the shared run directory, and the eval job uses it to join the NCCL weight-broadcast group. Each weight transfer is synchronous, but eval rollout execution overlaps with later training steps. After the final transfer, the trainer job releases its nodes while the eval job finishes the final epoch and exits. Without `max_steps`, the eval job never sees a final broadcast and holds its allocation until walltime. Trainer and evals log to one shared W&B run — the trainer creates it, and the evals process finalizes it. Any trainer-to-inference node layout works because `num_train_nodes` and `num_infer_nodes` are independent.
|
||||
The shared script passes the trainer rank-0 hostname directly to the evals process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, evals never sees a final broadcast, so the job remains active until walltime. Trainer and evals log to one shared W&B run. The trainer creates it, and evals finalizes it.
|
||||
|
||||
### SFT-Specific Knobs
|
||||
|
||||
@@ -321,6 +321,7 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
|
||||
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
|
||||
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
|
||||
├── orchestrator.log # single instance, single file
|
||||
├── evals.log # SFT online-eval process
|
||||
├── inference.log # symlink → inference/node_0.log on multi-node
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node trainer stdout (multi-node only)
|
||||
@@ -331,12 +332,12 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
|
||||
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
|
||||
```
|
||||
|
||||
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/latest/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
|
||||
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
|
||||
|
||||
```bash
|
||||
tail -F <run_dir>/logs/latest/{trainer,orchestrator,inference}.log
|
||||
tail -F <run_dir>/logs/latest/{trainer,orchestrator,evals,inference}.log
|
||||
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
|
||||
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
|
||||
```
|
||||
|
||||
@@ -175,9 +175,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
"""Training nodes."""
|
||||
|
||||
num_infer_nodes: int = Field(0, ge=0, validation_alias=AliasChoices("num_infer_nodes", "num_eval_nodes"))
|
||||
"""Inference nodes for online evals (alias: ``num_eval_nodes``). Submitted as a separate SLURM job, decoupled
|
||||
from the trainer job. The eval job can outlive the trainer job while it evaluates
|
||||
the final weight broadcast."""
|
||||
"""Inference nodes for online evals (alias: ``num_eval_nodes``). These nodes share
|
||||
one SLURM allocation with the trainer nodes."""
|
||||
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
@@ -394,18 +393,18 @@ class SFTConfig(BaseConfig):
|
||||
raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
|
||||
|
||||
if self.deployment.type == "multi_node":
|
||||
# Decoupled deployment: the launcher submits a dedicated SLURM job running the
|
||||
# inference pool (one engine per DP rank behind a router) plus the evals process.
|
||||
# Dedicated nodes in the SFT allocation run the inference pool, router,
|
||||
# env servers, and evals process.
|
||||
if self.inference is None:
|
||||
raise ValueError(
|
||||
"Multi-node online evals require an [inference] block - the launcher submits "
|
||||
"a dedicated SLURM job running the inference pool and the evals process."
|
||||
"Multi-node online evals require an [inference] block - dedicated nodes in the "
|
||||
"SFT allocation run the inference pool and evals process."
|
||||
)
|
||||
if self.deployment.num_infer_nodes < 1:
|
||||
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
|
||||
if self.inference.router is None:
|
||||
raise ValueError(
|
||||
"Multi-node online evals require an inference router - the eval job starts one "
|
||||
"Multi-node online evals require an inference router - the launcher starts one "
|
||||
"router in front of the per-rank engines. Remove inference.router = 'None'."
|
||||
)
|
||||
if self.inference.vllm.model != self.model.name:
|
||||
@@ -426,10 +425,10 @@ class SFTConfig(BaseConfig):
|
||||
if self.max_steps is None:
|
||||
warnings.warn(
|
||||
"Online evals without max_steps: the evals process never sees a final checkpoint, "
|
||||
"so the eval SLURM job holds its allocation until its walltime.",
|
||||
"so the SFT SLURM job holds its allocation until its walltime.",
|
||||
stacklevel=2,
|
||||
)
|
||||
# The client is wired at runtime by the eval sbatch script (the router and
|
||||
# The client is wired at runtime by the SFT sbatch script (the router and
|
||||
# per-rank admin URLs are only known once SLURM assigns hosts).
|
||||
return self
|
||||
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
"""Export a verifiers v1 eval run (traces.jsonl) as an SFT dataset for `uv run sft`.
|
||||
|
||||
Reads a finished run's saved traces and reshapes them into the dataset shape the SFT trainer
|
||||
consumes directly (see `prime_rl.trainer.sft.data`): a `messages` column (OpenAI chat wire
|
||||
shape) plus a `tools` column (the tools the model was shown, from `Trace.tools`,
|
||||
JSON-encoded — heterogeneous JSON-schema dicts don't fit a fixed Arrow schema). One row per
|
||||
branch: a linear rollout contributes one sample, a compacted/subagent rollout one per branch
|
||||
(one training sample is built per branch).
|
||||
|
||||
Selection: generation-errored traces (`stop_condition == "error"`) always drop — a broken
|
||||
transcript is not a sample. A scoring-only error keeps the generation outcome as its stop
|
||||
condition and a complete conversation, so it stays; its reward may be partial/zero, which
|
||||
`--min-reward` handles.
|
||||
|
||||
Usage (from the prime-rl repo):
|
||||
uv run python scripts/export_sft.py <run-dir> [--min-reward 1.0] [--drop-truncated]
|
||||
[-o OUT_DIR] [--push HF_REPO_ID]
|
||||
|
||||
Writes `<run-dir>/sft/train.parquet` by default — point the trainer at it with
|
||||
`--data.name <run-dir>/sft`. Requires a verifiers release carrying `Trace.tools`
|
||||
(PrimeIntellect-ai/verifiers#1963).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from datasets import Dataset
|
||||
from verifiers.v1 import Trace, WireTrace
|
||||
from verifiers.v1.dialects.chat import message_to_wire
|
||||
|
||||
|
||||
def sft_rows(trace: Trace) -> list[dict]:
|
||||
"""A trace's SFT rows — one per branch: the branch's conversation as OpenAI chat wire
|
||||
dicts plus the trace's advertised tools, JSON-encoded."""
|
||||
tools = json.dumps([t.model_dump(mode="json", exclude_none=True) for t in trace.tools or []])
|
||||
return [
|
||||
{
|
||||
"messages": [message_to_wire(m) for m in branch.messages],
|
||||
"tools": tools,
|
||||
}
|
||||
for branch in trace.branches
|
||||
if branch.messages
|
||||
]
|
||||
|
||||
|
||||
def keep(trace: Trace, min_reward: float | None, drop_truncated: bool) -> bool:
|
||||
"""Whether a trace is worth training on (see module docstring for the error semantics)."""
|
||||
if trace.stop_condition == "error":
|
||||
return False
|
||||
if drop_truncated and trace.is_truncated:
|
||||
return False
|
||||
return min_reward is None or trace.reward >= min_reward
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("run_dir", type=Path, help="the eval run dir (holds traces.jsonl)")
|
||||
parser.add_argument("--min-reward", type=float, default=None, help="keep traces with reward >= this")
|
||||
parser.add_argument("--drop-truncated", action="store_true", help="drop budget-cut traces")
|
||||
parser.add_argument("-o", "--output-dir", type=Path, default=None, help="default: <run-dir>/sft")
|
||||
parser.add_argument("--push", default=None, help="HF repo id to push to instead of writing parquet")
|
||||
args = parser.parse_args()
|
||||
|
||||
traces_path = args.run_dir / "traces.jsonl"
|
||||
if not traces_path.exists():
|
||||
raise SystemExit(f"no traces.jsonl in {args.run_dir}")
|
||||
|
||||
total, rows = 0, []
|
||||
with traces_path.open(encoding="utf-8") as f:
|
||||
for line in f:
|
||||
if not line.strip():
|
||||
continue
|
||||
total += 1
|
||||
trace = WireTrace.model_validate(json.loads(line))
|
||||
if keep(trace, args.min_reward, args.drop_truncated):
|
||||
rows.extend(sft_rows(trace))
|
||||
print(f"export-sft: {total} trace(s) -> {len(rows)} row(s)")
|
||||
if not rows:
|
||||
raise SystemExit("export-sft: no rows to export after selection")
|
||||
|
||||
dataset = Dataset.from_list(rows)
|
||||
if args.push:
|
||||
dataset.push_to_hub(args.push)
|
||||
print(f"export-sft: pushed to {args.push}")
|
||||
return
|
||||
out = args.output_dir or args.run_dir / "sft"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
dataset.to_parquet(str(out / "train.parquet"))
|
||||
print(f"export-sft: wrote {out / 'train.parquet'} -> train with --data.name {out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -82,7 +82,7 @@ Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`
|
||||
{run_dir}/logs/latest/
|
||||
├── trainer.log # rank 0 stdout
|
||||
├── orchestrator.log # orchestrator stdout
|
||||
├── evals.log # SFT online-eval evals stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evals.log)
|
||||
├── evals.log # SFT online-eval evals stdout
|
||||
├── inference.log # vLLM stdout
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node (multi-node only)
|
||||
|
||||
@@ -69,6 +69,7 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
|
||||
- Config: `SFTConfig` (`packages/prime-rl-configs/src/prime_rl/configs/sft.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/sft.py`
|
||||
- SLURM: single- and multi-node
|
||||
- Multi-node online evals use one SLURM job with `num_train_nodes + num_infer_nodes` nodes. The generated `launcher/sft.sbatch` assigns inference nodes first, then trainer nodes.
|
||||
|
||||
## `inference` — vLLM server
|
||||
|
||||
@@ -122,7 +123,7 @@ env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/envs/eval/{name}.log`.
|
||||
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/latest/envs/eval/{name}.log`.
|
||||
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
|
||||
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
|
||||
directories (metrics, resolved configs, rollout traces, cited reports,
|
||||
component logs) at
|
||||
http://localhost:7788. Needs the `dashboard` extra. Every instance also serves
|
||||
http://localhost:7788. The trace viewer includes transcript and synchronized
|
||||
agent timeline views; timeline activities open the corresponding transcript
|
||||
call. Needs the `dashboard` extra. Every instance also serves
|
||||
the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
|
||||
(one dashboard per host per user); `--isolated` serves only the given dirs and
|
||||
skips the registry. See `skills/dashboard/SKILL.md` for discovery,
|
||||
|
||||
@@ -278,6 +278,7 @@ def run_meta(run_dir: Path) -> dict:
|
||||
"type": run_type,
|
||||
"model": model_name(config),
|
||||
"dataset": (config.get("data") or {}).get("name"),
|
||||
"has_validation": run_type == "sft" and config.get("val") is not None,
|
||||
"env": ((config.get("env") or {}).get("taskset") or {}).get("id"),
|
||||
"total_episodes": (config.get("num_tasks") or 0) * (config.get("num_rollouts") or 0) or None,
|
||||
"max_steps": config.get("max_steps"),
|
||||
@@ -365,7 +366,7 @@ def list_logfiles(run: str, attempt: str = "latest") -> dict:
|
||||
for path in sorted(attempt_dir.rglob("*.log")):
|
||||
component, label = log_component(path.relative_to(attempt_dir))
|
||||
add(path, component, label)
|
||||
# The evals process writes its env-server logs outside attempt_N (logs/envs/eval/*.log).
|
||||
# Include unscoped env logs from runs created before attempt-scoped eval logging.
|
||||
for path in sorted((run_dir / "logs" / "envs").rglob("*.log")):
|
||||
add(path, f"env:{path.stem}", f"{path.stem} (evals)")
|
||||
return {"attempt": attempt_num, "attempts": attempts, "files": files}
|
||||
@@ -781,6 +782,306 @@ def traces_path(run: str, step: int, kind: str, subset: str) -> Path:
|
||||
raise HTTPException(404, "no traces for this step/kind/subset")
|
||||
|
||||
|
||||
def read_episode_record(path: Path, line: int) -> dict:
|
||||
offsets = line_offsets(path)
|
||||
if not 0 <= line < len(offsets):
|
||||
raise HTTPException(404, "episode line out of range")
|
||||
with path.open("rb") as f:
|
||||
f.seek(offsets[line])
|
||||
return orjson.loads(f.readline())
|
||||
|
||||
|
||||
def message_text(message: dict) -> str:
|
||||
content = message.get("content")
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
return "".join(part.get("text", "") if isinstance(part, dict) else str(part) for part in content)
|
||||
return "" if content is None else str(content)
|
||||
|
||||
|
||||
def timeline_status(trace: dict) -> str:
|
||||
if not trace.get("is_completed"):
|
||||
return "running"
|
||||
if not trace.get("ok") and (trace.get("errors") or trace.get("stop_condition") == "error"):
|
||||
return "failed"
|
||||
return "completed"
|
||||
|
||||
|
||||
def timeline_reward(trace: dict) -> float | None:
|
||||
rewards = [reward for reward in (trace.get("rewards") or {}).values() if isinstance(reward, dict)]
|
||||
if not rewards:
|
||||
return None
|
||||
return sum(
|
||||
(reward.get("score") or 0) * (reward.get("weight") if reward.get("weight") is not None else 1)
|
||||
for reward in rewards
|
||||
)
|
||||
|
||||
|
||||
def trace_branch_paths(nodes: list[dict]) -> list[list[int]]:
|
||||
"""Return VF-native root-to-leaf branches in leaf-index order."""
|
||||
if not nodes:
|
||||
return []
|
||||
parents = {parent for node in nodes if isinstance((parent := node.get("parent")), int) and 0 <= parent < len(nodes)}
|
||||
paths = []
|
||||
for leaf in (index for index in range(len(nodes)) if index not in parents):
|
||||
path = []
|
||||
seen = set()
|
||||
node_index: int | None = leaf
|
||||
while isinstance(node_index, int) and 0 <= node_index < len(nodes) and node_index not in seen:
|
||||
seen.add(node_index)
|
||||
path.append(node_index)
|
||||
node_index = nodes[node_index].get("parent")
|
||||
paths.append(list(reversed(path)))
|
||||
return paths
|
||||
|
||||
|
||||
def token_usage(usage: dict) -> tuple[int | None, int | None, int | None]:
|
||||
prompt_tokens = usage.get("prompt_tokens")
|
||||
output_tokens = usage.get("completion_tokens")
|
||||
if "cached_input_tokens" in usage:
|
||||
return prompt_tokens, usage.get("cached_input_tokens"), output_tokens
|
||||
cached_tokens = (usage.get("prompt_tokens_details") or {}).get("cached_tokens")
|
||||
input_tokens = (
|
||||
max(0, prompt_tokens - cached_tokens) if prompt_tokens is not None and cached_tokens else prompt_tokens
|
||||
)
|
||||
return input_tokens, cached_tokens, output_tokens
|
||||
|
||||
|
||||
def activity_spans(
|
||||
trace: dict,
|
||||
node_indexes: set[int],
|
||||
*,
|
||||
include_unlinked: bool = False,
|
||||
shared_node_indexes: set[int] | None = None,
|
||||
) -> list[dict]:
|
||||
nodes = trace.get("nodes") or []
|
||||
spans = []
|
||||
for call_index, call in enumerate(trace.get("calls") or []):
|
||||
node_index = call.get("node")
|
||||
if node_index is None:
|
||||
if not include_unlinked:
|
||||
continue
|
||||
node = {}
|
||||
elif node_index not in node_indexes:
|
||||
continue
|
||||
else:
|
||||
node = nodes[node_index]
|
||||
call_time = call.get("time") or {}
|
||||
started = call_time.get("start")
|
||||
ended = call_time.get("end")
|
||||
usage = call.get("usage") or {}
|
||||
input_tokens, cached_tokens, output_tokens = token_usage(usage)
|
||||
reasoning_tokens = usage.get("reasoning_tokens")
|
||||
if reasoning_tokens is None:
|
||||
reasoning_tokens = (usage.get("completion_tokens_details") or {}).get("reasoning_tokens")
|
||||
text = " ".join(message_text(node.get("message") or {}).split())
|
||||
spans.append(
|
||||
{
|
||||
"kind": "model_call",
|
||||
"label": f"turn {len(spans) + 1}",
|
||||
"track": "activity",
|
||||
"call_index": call_index,
|
||||
"node_index": node_index,
|
||||
"shared": node_index in shared_node_indexes if shared_node_indexes is not None else False,
|
||||
"started_at": started,
|
||||
"ended_at": ended,
|
||||
"status": "completed" if ended is not None or trace.get("is_completed") else "running",
|
||||
"snippet": text[:240],
|
||||
"input_tokens": input_tokens,
|
||||
"cached_tokens": cached_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"reasoning_tokens": reasoning_tokens,
|
||||
"cost": usage.get("cost"),
|
||||
}
|
||||
)
|
||||
return sorted(spans, key=lambda span: span["started_at"] if span["started_at"] is not None else float("inf"))
|
||||
|
||||
|
||||
def lifecycle_spans(trace: dict) -> list[dict]:
|
||||
timing = trace.get("timing") or {}
|
||||
spans = []
|
||||
for kind, label in (
|
||||
("boot", "boot"),
|
||||
("setup", "setup"),
|
||||
("agent", "agent"),
|
||||
("finalize", "finalize"),
|
||||
("scoring", "scoring"),
|
||||
):
|
||||
span = timing.get(kind) or {}
|
||||
if not span.get("start"):
|
||||
continue
|
||||
spans.append(
|
||||
{
|
||||
"kind": kind,
|
||||
"label": label,
|
||||
"track": "lifecycle",
|
||||
"started_at": span["start"],
|
||||
"ended_at": span.get("end") or None,
|
||||
"status": "completed" if span.get("end") or trace.get("is_completed") else "running",
|
||||
}
|
||||
)
|
||||
return spans
|
||||
|
||||
|
||||
def timeline_lane(
|
||||
trace: dict,
|
||||
trace_index: int,
|
||||
*,
|
||||
label: str,
|
||||
depth: int,
|
||||
branch: bool,
|
||||
lifecycle: list[dict],
|
||||
activities: list[dict],
|
||||
started_at: float | None = None,
|
||||
) -> dict:
|
||||
spans = lifecycle + activities
|
||||
starts = [span["started_at"] for span in spans if span.get("started_at") is not None]
|
||||
ends = [span["ended_at"] for span in spans if span.get("ended_at") is not None]
|
||||
started = started_at if started_at is not None else min(starts or ends, default=None)
|
||||
status = (
|
||||
("completed" if all(span["status"] == "completed" for span in lifecycle + activities) else "running")
|
||||
if branch
|
||||
else timeline_status(trace)
|
||||
)
|
||||
ended = max(ends, default=None) if status != "running" else None
|
||||
agent = trace.get("agent") or {}
|
||||
config = agent.get("config") or {}
|
||||
client = config.get("client") or {}
|
||||
|
||||
def total(field: str) -> int | float | None:
|
||||
values = [span[field] for span in activities if isinstance(span.get(field), (int, float))]
|
||||
return sum(values) if values else None
|
||||
|
||||
input_tokens = total("input_tokens")
|
||||
cached_tokens = total("cached_tokens")
|
||||
output_tokens = total("output_tokens")
|
||||
reasoning_tokens = total("reasoning_tokens")
|
||||
total_input_tokens = input_tokens + (cached_tokens or 0) if input_tokens is not None else None
|
||||
total_tokens = (
|
||||
total_input_tokens + output_tokens if total_input_tokens is not None and output_tokens is not None else None
|
||||
)
|
||||
context_lengths = [
|
||||
(span.get("input_tokens") or 0) + (span.get("cached_tokens") or 0)
|
||||
for span in activities
|
||||
if span.get("input_tokens") is not None
|
||||
]
|
||||
return {
|
||||
"trace_index": trace_index,
|
||||
"label": label,
|
||||
"model": config.get("model") or client.get("renderer_model_name") or "",
|
||||
"depth": depth,
|
||||
"started_at": started,
|
||||
"ended_at": ended,
|
||||
"status": status,
|
||||
"outcome": status if branch else (trace.get("stop_condition") or status),
|
||||
"reward": timeline_reward(trace),
|
||||
"usage": {
|
||||
"model_calls": len(activities),
|
||||
"input_tokens": input_tokens,
|
||||
"cached_tokens": cached_tokens,
|
||||
"total_input_tokens": total_input_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"reasoning_tokens": reasoning_tokens,
|
||||
"max_context_tokens": max(context_lengths, default=None),
|
||||
"total_tokens": total_tokens,
|
||||
"cost": total("cost"),
|
||||
},
|
||||
"spans": spans,
|
||||
}
|
||||
|
||||
|
||||
def project_episode_timeline(episode: dict) -> dict:
|
||||
lane_groups = []
|
||||
for trace_index, trace in enumerate(episode.get("traces") or []):
|
||||
nodes = trace.get("nodes") or []
|
||||
branch_paths = trace_branch_paths(nodes)
|
||||
node_branch_counts: dict[int, int] = {}
|
||||
for path in branch_paths:
|
||||
for node_index in path:
|
||||
node_branch_counts[node_index] = node_branch_counts.get(node_index, 0) + 1
|
||||
role = (trace.get("agent") or {}).get("name") or "agent"
|
||||
parent = timeline_lane(
|
||||
trace,
|
||||
trace_index,
|
||||
label=role,
|
||||
depth=0,
|
||||
branch=False,
|
||||
lifecycle=lifecycle_spans(trace),
|
||||
activities=activity_spans(trace, set(), include_unlinked=True),
|
||||
started_at=(trace.get("timing") or {}).get("start"),
|
||||
)
|
||||
branches = []
|
||||
for branch_index, path in enumerate(branch_paths):
|
||||
node_indexes = set(path)
|
||||
shared_node_indexes = {node_index for node_index in path if node_branch_counts.get(node_index, 0) > 1}
|
||||
unique_node_indexes = node_indexes - shared_node_indexes
|
||||
activities = activity_spans(
|
||||
trace,
|
||||
node_indexes,
|
||||
shared_node_indexes=shared_node_indexes,
|
||||
)
|
||||
path_timestamps = [
|
||||
nodes[node_index].get("timestamp")
|
||||
for node_index in path
|
||||
if nodes[node_index].get("timestamp") is not None
|
||||
]
|
||||
unique_timestamps = [
|
||||
nodes[node_index].get("timestamp")
|
||||
for node_index in unique_node_indexes
|
||||
if nodes[node_index].get("timestamp") is not None
|
||||
]
|
||||
activity_starts = [span["started_at"] for span in activities if span["started_at"] is not None]
|
||||
unique_activity_starts = [
|
||||
span["started_at"] for span in activities if not span["shared"] and span["started_at"] is not None
|
||||
]
|
||||
branch_start = min(activity_starts or path_timestamps, default=None)
|
||||
sort_start = min(
|
||||
unique_activity_starts or unique_timestamps or activity_starts or path_timestamps, default=None
|
||||
)
|
||||
branch_end = max(
|
||||
[span["ended_at"] for span in activities if span.get("ended_at") is not None] + path_timestamps,
|
||||
default=None,
|
||||
)
|
||||
branch_completed = bool(trace.get("is_completed"))
|
||||
label = f"branch {branch_index}"
|
||||
branch_lifecycle = (
|
||||
[
|
||||
{
|
||||
"kind": "agent",
|
||||
"label": label,
|
||||
"track": "lifecycle",
|
||||
"started_at": branch_start,
|
||||
"ended_at": branch_end if branch_completed else None,
|
||||
"status": "completed" if branch_completed else "running",
|
||||
"node_index": path[-1],
|
||||
}
|
||||
]
|
||||
if branch_start is not None
|
||||
else []
|
||||
)
|
||||
branches.append(
|
||||
(
|
||||
sort_start,
|
||||
branch_index,
|
||||
timeline_lane(
|
||||
trace,
|
||||
trace_index,
|
||||
label=label,
|
||||
depth=1,
|
||||
branch=True,
|
||||
lifecycle=branch_lifecycle,
|
||||
activities=activities,
|
||||
),
|
||||
)
|
||||
)
|
||||
branches.sort(key=lambda item: (item[0] if item[0] is not None else float("inf"), item[1]))
|
||||
lane_groups.append((parent, [lane for _, _, lane in branches]))
|
||||
lane_groups.sort(key=lambda group: group[0]["started_at"] if group[0]["started_at"] is not None else float("inf"))
|
||||
lanes = [lane for parent, children in lane_groups for lane in (parent, *children)]
|
||||
return {"lanes": lanes}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/rollouts")
|
||||
def list_rollouts(run: str) -> dict:
|
||||
return {"steps": rollout_steps(get_run_dir(run))}
|
||||
@@ -1147,6 +1448,11 @@ async def view_events() -> "StreamingResponse":
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/{line}/timeline")
|
||||
def get_episode_timeline(run: str, step: int, kind: str, subset: str, line: int) -> dict:
|
||||
return project_episode_timeline(read_episode_at(traces_path(run, step, kind, subset), line))
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------- static
|
||||
|
||||
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
||||
|
||||
@@ -574,7 +574,10 @@ function buildSections(meta) {
|
||||
const sections = [];
|
||||
const evalEnvs = meta.eval_envs || [];
|
||||
if (meta.type === "sft") {
|
||||
sections.push({ name: "train", panels: SFT_TRAIN_METRICS.map((m) => ({ metric: m })) });
|
||||
const trainMetrics = meta.has_validation
|
||||
? SFT_TRAIN_METRICS
|
||||
: SFT_TRAIN_METRICS.filter((m) => !m.startsWith("val/"));
|
||||
sections.push({ name: "train", panels: trainMetrics.map((m) => ({ metric: m })) });
|
||||
if (evalEnvs.length) sections.push(...evalEnvs.map((e) => evalSection(`eval/${e}`, escRe(e), true)));
|
||||
else sections.push(evalSection("eval", ".*"));
|
||||
sections.push({ name: "stability", panels: SFT_STABILITY_METRICS.map((m) => ({ metric: m })) });
|
||||
@@ -681,6 +684,15 @@ function groupColors(groups) {
|
||||
return groups.length > 1 ? groups.map((_, i) => PALETTE[i % PALETTE.length]) : [SINGLE_SERIES];
|
||||
}
|
||||
|
||||
function singletonPoints(series, color) {
|
||||
return {
|
||||
show: () => series.points.size === 1,
|
||||
size: 6,
|
||||
width: 0,
|
||||
fill: color,
|
||||
};
|
||||
}
|
||||
|
||||
/* flatten groups into uPlot series defs + data columns + tooltip meta */
|
||||
function buildChartLayout(entry, timeAxis) {
|
||||
const groups = panelGroups(entry.series);
|
||||
@@ -705,7 +717,7 @@ function buildChartLayout(entry, timeAxis) {
|
||||
width: 1.25,
|
||||
dash: si > 0 ? [6, 4] : undefined,
|
||||
spanGaps: true,
|
||||
points: { show: false },
|
||||
points: singletonPoints(strand.main, color),
|
||||
});
|
||||
const m = { label: labels[mainIdx] || "value", stat: statOf(strand.main.key) ?? "value", color, dataIdx: cols.length };
|
||||
meta.push(m);
|
||||
@@ -714,7 +726,14 @@ function buildChartLayout(entry, timeAxis) {
|
||||
const bandIdx = {};
|
||||
for (const s of aux) {
|
||||
cols.push({ s, role: "aux" });
|
||||
uSeries.push({ stroke: hexToRgba(color, 0.55), width: 1, dash: [3, 3], spanGaps: true, points: { show: false } });
|
||||
const auxColor = hexToRgba(color, 0.55);
|
||||
uSeries.push({
|
||||
stroke: auxColor,
|
||||
width: 1,
|
||||
dash: [3, 3],
|
||||
spanGaps: true,
|
||||
points: singletonPoints(s, auxColor),
|
||||
});
|
||||
if (s === strand.lo) bandIdx.lo = cols.length;
|
||||
if (s === strand.hi) bandIdx.hi = cols.length;
|
||||
}
|
||||
@@ -1962,6 +1981,10 @@ let currentTraceIdx = 0;
|
||||
let currentBranchIdx = 0;
|
||||
let episodeOpenVersion = 0;
|
||||
let episodeEnrichmentVersion = 0;
|
||||
let currentTimeline = null;
|
||||
let traceView = prefs.traceView === "timeline" ? "timeline" : "transcript";
|
||||
let pendingTimelineNode = null;
|
||||
let pendingTimelineCall = null;
|
||||
|
||||
const COPY_SVG =
|
||||
`<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">` +
|
||||
@@ -2075,6 +2098,20 @@ function fetchEpisode(line, withTokens, withRendered = false) {
|
||||
return api(`/api/runs/${encodeURIComponent(state.run)}/rollouts/${traces.step}/${traces.kind}/${traces.subset}/${line}${qs}`);
|
||||
}
|
||||
|
||||
function fetchEpisodeTimeline(line) {
|
||||
const traces = state.traces;
|
||||
return api(`/api/runs/${encodeURIComponent(state.run)}/rollouts/${traces.step}/${traces.kind}/${traces.subset}/${line}/timeline`);
|
||||
}
|
||||
|
||||
async function ensureTimeline() {
|
||||
if (currentTimeline || currentLine == null) return;
|
||||
const line = currentLine;
|
||||
const requestVersion = episodeOpenVersion;
|
||||
const timeline = await fetchEpisodeTimeline(line);
|
||||
if (line !== currentLine || requestVersion !== episodeOpenVersion) return;
|
||||
currentTimeline = timeline;
|
||||
}
|
||||
|
||||
/* token strings multiply the payload of a big episode, so they are fetched only
|
||||
for token signals or the rendered-token view — the plain view ships the raw record */
|
||||
async function ensureTokens() {
|
||||
@@ -2103,7 +2140,11 @@ async function openEpisode(line, target = {}) {
|
||||
renderModalStep();
|
||||
renderRolloutList();
|
||||
$("#tm-messages").innerHTML = `<div class="chart-empty">loading episode…</div>`;
|
||||
$("#tm-timeline").innerHTML = `<div class="chart-empty">loading timeline…</div>`;
|
||||
$("#tm-meta").innerHTML = "";
|
||||
currentTimeline = null;
|
||||
pendingTimelineNode = null;
|
||||
pendingTimelineCall = null;
|
||||
const withTokens = !!$("#token-signal").value;
|
||||
const withRendered = state.traces.viewMode === "rendered";
|
||||
const episode = await fetchEpisode(line, withTokens, withRendered);
|
||||
@@ -2113,6 +2154,7 @@ async function openEpisode(line, target = {}) {
|
||||
currentEpisode = episode;
|
||||
currentTraceIdx = target.trace ?? 0;
|
||||
currentBranchIdx = target.branch ?? 0;
|
||||
if (traceView === "timeline") await ensureTimeline();
|
||||
renderEpisode();
|
||||
await ensureTokens();
|
||||
if (line === currentLine && requestVersion === episodeOpenVersion) renderEpisode();
|
||||
@@ -2125,6 +2167,9 @@ function closeDrawer() {
|
||||
$("#drawer-backdrop").hidden = true;
|
||||
$("#tm-back").hidden = true;
|
||||
currentEpisode = null;
|
||||
currentTimeline = null;
|
||||
pendingTimelineNode = null;
|
||||
pendingTimelineCall = null;
|
||||
currentLine = null;
|
||||
pendingHighlight = null;
|
||||
}
|
||||
@@ -2367,6 +2412,22 @@ function errorBannersHtml(errors) {
|
||||
);
|
||||
}
|
||||
|
||||
function normalizedCallUsage(usage = {}) {
|
||||
let input = usage.prompt_tokens;
|
||||
let cached = usage.cached_input_tokens;
|
||||
if (cached == null) {
|
||||
cached = usage.prompt_tokens_details?.cached_tokens;
|
||||
if (input != null && cached) input = Math.max(0, input - cached);
|
||||
}
|
||||
return {
|
||||
input,
|
||||
cached,
|
||||
output: usage.completion_tokens,
|
||||
reasoning: usage.reasoning_tokens ?? usage.completion_tokens_details?.reasoning_tokens,
|
||||
cost: usage.cost,
|
||||
};
|
||||
}
|
||||
|
||||
function renderMessages(ep, trace, branches) {
|
||||
const container = $("#tm-messages");
|
||||
entriesObserver?.disconnect();
|
||||
@@ -2387,7 +2448,22 @@ function renderMessages(ep, trace, branches) {
|
||||
let maxAbsAdv = 0;
|
||||
for (const node of trace.nodes || [])
|
||||
for (const a of node.advantages || []) maxAbsAdv = Math.max(maxAbsAdv, Math.abs(a));
|
||||
const callsByNode = new Map((trace.calls || []).map((c) => [c.node, c]));
|
||||
const indexedCalls = (trace.calls || []).map((call, index) => ({ call, index }));
|
||||
const callsByNode = new Map();
|
||||
for (const item of indexedCalls) {
|
||||
const calls = callsByNode.get(item.call.node) || [];
|
||||
calls.push(item);
|
||||
callsByNode.set(item.call.node, calls);
|
||||
}
|
||||
const callChipHtml = ({ call, index }) => {
|
||||
const fields = [`call ${index + 1}`];
|
||||
if (call.finish_reason) fields.push(call.finish_reason);
|
||||
const { input, cached, output } = normalizedCallUsage(call.usage);
|
||||
if (input != null) fields.push(`${fmtCompact(input)} in`);
|
||||
if (cached != null) fields.push(`${fmtCompact(cached)} cache`);
|
||||
if (output != null) fields.push(`${fmtCompact(output)} out`);
|
||||
return `<span class="chip" data-call-index="${index}">${esc(fields.join(" · "))}</span>`;
|
||||
};
|
||||
// agent highlights (sticky until the next view command or drawer close)
|
||||
const hl =
|
||||
pendingHighlight &&
|
||||
@@ -2407,14 +2483,12 @@ function renderMessages(ep, trace, branches) {
|
||||
const entryHtml = (idx, i) => {
|
||||
const node = trace.nodes[idx];
|
||||
const role = node.message?.role ?? "?";
|
||||
const call = callsByNode.get(idx);
|
||||
const marks = hlByNode.get(idx) || [];
|
||||
const chips = [];
|
||||
if (concatenated && node.parent != null && node.parent !== idx - 1) chips.push(`↳ branches from ${node.parent + 1}`);
|
||||
if (node.sampled) chips.push("sampled");
|
||||
if (call?.finish_reason) chips.push(call.finish_reason);
|
||||
if (call?.usage) chips.push(`${call.usage.prompt_tokens ?? "?"}→${call.usage.completion_tokens ?? "?"} tok`);
|
||||
else if (node.token_ids?.length) chips.push(`${node.token_ids.length} tok`);
|
||||
const nodeCalls = callsByNode.get(idx) || [];
|
||||
if (!nodeCalls.length && node.token_ids?.length) chips.push(`${node.token_ids.length} tok`);
|
||||
const text = messageText(node.message);
|
||||
const contentMarks = marks.filter((h) => !h.field || h.field === "content");
|
||||
const contentMarked = contentMarks.some((h) => h.quote && findQuote(text, h.quote, h.prefix, h.suffix));
|
||||
@@ -2431,11 +2505,12 @@ function renderMessages(ep, trace, branches) {
|
||||
if (reasoning) subs.push(reasoningBlock(reasoning, reasoningMarks));
|
||||
const toolCalls = (node.message?.tool_calls || []).map(toolCallHtml);
|
||||
const messageHtml =
|
||||
`<details class="entry ${esc(role)}${marked ? " hl-entry" : ""}"${role === "system" && !marked ? "" : " open"}>` +
|
||||
`<details class="entry ${esc(role)}${marked ? " hl-entry" : ""}" data-node="${idx}"${role === "system" && !marked ? "" : " open"}>` +
|
||||
`<summary><span class="entry-num">${String(i + 1).padStart(2, "0")}</span>` +
|
||||
`<span class="entry-role">${esc(role)}</span>` +
|
||||
`<span class="entry-preview">${preview(text, 180)}</span>` +
|
||||
chips.map((c) => `<span class="chip">${esc(c)}</span>`).join("") +
|
||||
nodeCalls.map(callChipHtml).join("") +
|
||||
`<button class="icon-btn" data-copy="${idx}" title="copy message">${COPY_SVG}</button>` +
|
||||
`<span class="entry-chev">›</span></summary>` +
|
||||
subs.join("") +
|
||||
@@ -2449,11 +2524,23 @@ function renderMessages(ep, trace, branches) {
|
||||
// first chunk forces enough entries into the DOM to scroll to
|
||||
const CHUNK = 30;
|
||||
const lastMark = Math.max(-1, ...[...hlByNode.keys()].map((n) => path.indexOf(n)));
|
||||
let rendered = Math.min(path.length, Math.max(CHUNK, lastMark + 3));
|
||||
const targetPosition = pendingTimelineNode == null ? -1 : path.indexOf(pendingTimelineNode);
|
||||
let rendered = Math.min(path.length, Math.max(CHUNK, lastMark + 3, targetPosition + 1));
|
||||
const unlinkedCallsHtml = indexedCalls
|
||||
.filter(({ call }) => !Number.isInteger(call.node) || call.node < 0 || call.node >= (trace.nodes || []).length)
|
||||
.map(
|
||||
(item) =>
|
||||
`<details class="entry model-call" data-call-index="${item.index}" open>` +
|
||||
`<summary><span class="entry-num">C${String(item.index + 1).padStart(2, "0")}</span>` +
|
||||
`<span class="entry-role">model call</span><span class="entry-preview">${esc(item.call.model || "unlinked call")}</span>` +
|
||||
`${callChipHtml(item)}<span class="entry-chev">›</span></summary></details>`,
|
||||
)
|
||||
.join("");
|
||||
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>` : "") +
|
||||
unlinkedCallsHtml +
|
||||
errorsHtml;
|
||||
if (hl && !hl.scrolled) {
|
||||
const first = container.querySelector(".hl-entry");
|
||||
@@ -2537,28 +2624,35 @@ function renderMeta(ep, trace, branches) {
|
||||
parts.push(metaRow("branches", branches.length));
|
||||
parts.push(metaRow("tool calls", nodes.reduce((acc, n) => acc + (n.message?.tool_calls?.length || 0), 0)));
|
||||
|
||||
const usage = { input: 0, output: 0, reasoning: 0, cached: 0 };
|
||||
let hasUsage = false;
|
||||
const usage = { input: null, output: null, reasoning: null, cached: null, maxContext: null, cost: null };
|
||||
const addUsage = (field, value) => {
|
||||
if (value != null) usage[field] = (usage[field] ?? 0) + value;
|
||||
};
|
||||
for (const call of trace.calls || []) {
|
||||
const u = call.usage || {};
|
||||
if (u.prompt_tokens != null || u.completion_tokens != null) hasUsage = true;
|
||||
usage.input += u.prompt_tokens ?? 0;
|
||||
usage.output += u.completion_tokens ?? 0;
|
||||
usage.reasoning += u.completion_tokens_details?.reasoning_tokens ?? 0;
|
||||
usage.cached += u.prompt_tokens_details?.cached_tokens ?? 0;
|
||||
const current = normalizedCallUsage(call.usage);
|
||||
addUsage("input", current.input);
|
||||
addUsage("cached", current.cached);
|
||||
addUsage("output", current.output);
|
||||
addUsage("reasoning", current.reasoning);
|
||||
addUsage("cost", current.cost);
|
||||
if (current.input != null) {
|
||||
const context = current.input + (current.cached ?? 0);
|
||||
usage.maxContext = Math.max(usage.maxContext ?? 0, context);
|
||||
}
|
||||
}
|
||||
const totalInput = usage.input == null ? null : usage.input + (usage.cached ?? 0);
|
||||
const totalTokens = totalInput == null || usage.output == null ? null : totalInput + usage.output;
|
||||
const hasUsage = usage.input != null || usage.cached != null || usage.output != null;
|
||||
if (hasUsage) {
|
||||
parts.push(`<div class="meta-sec">usage</div>`);
|
||||
parts.push(metaRow("input tokens", fmtCompact(usage.input)));
|
||||
parts.push(metaRow("output tokens", fmtCompact(usage.output)));
|
||||
if (usage.reasoning) parts.push(metaRow("reasoning tokens", fmtCompact(usage.reasoning)));
|
||||
if (usage.cached) parts.push(metaRow("cached tokens", fmtCompact(usage.cached)));
|
||||
// API-priced runs report per-call cost; local deployments usually don't
|
||||
const traceCost = (t) => (t.calls || []).reduce((acc, c) => acc + (c.usage?.cost ?? 0), 0);
|
||||
const allTraces = ep.traces || [];
|
||||
if (allTraces.some((t) => (t.calls || []).some((c) => c.usage?.cost != null)))
|
||||
parts.push(metaRow("cost", fmtCost(allTraces.reduce((acc, t) => acc + traceCost(t), 0))));
|
||||
parts.push(metaRow("total tokens", fmtCompact(usage.input + usage.output)));
|
||||
if (usage.input != null) parts.push(metaRow("input tokens", fmtCompact(usage.input)));
|
||||
if (usage.cached != null) parts.push(metaRow("cached input", fmtCompact(usage.cached)));
|
||||
if (totalInput != null) parts.push(metaRow("total input", fmtCompact(totalInput)));
|
||||
if (usage.output != null) parts.push(metaRow("output tokens", fmtCompact(usage.output)));
|
||||
if (usage.reasoning != null) parts.push(metaRow("reasoning tokens", fmtCompact(usage.reasoning)));
|
||||
if (usage.maxContext != null) parts.push(metaRow("max context length", fmtCompact(usage.maxContext)));
|
||||
if (usage.cost != null) parts.push(metaRow("cost", fmtCost(usage.cost)));
|
||||
if (totalTokens != null) parts.push(metaRow("total tokens", fmtCompact(totalTokens)));
|
||||
}
|
||||
|
||||
parts.push(`<div class="meta-sec">state</div>`);
|
||||
@@ -2598,6 +2692,122 @@ function renderMeta(ep, trace, branches) {
|
||||
$("#tm-meta").innerHTML = parts.join("");
|
||||
}
|
||||
|
||||
function timelineClock(ts) {
|
||||
if (ts == null) return "—";
|
||||
return new Date(ts * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
|
||||
}
|
||||
|
||||
function timelineTipAttr(payload) {
|
||||
return ` data-timeline-tip="${esc(JSON.stringify(payload))}"`;
|
||||
}
|
||||
|
||||
function appendTimelineUsage(rows, usage, aggregate = false) {
|
||||
if (!usage) return;
|
||||
if (aggregate && usage.model_calls != null) rows.push(["model calls", fmtNum(usage.model_calls)]);
|
||||
if (usage.input_tokens != null) rows.push(["input tokens", fmtCompact(usage.input_tokens)]);
|
||||
if (usage.cached_tokens != null) rows.push(["cached input", fmtCompact(usage.cached_tokens)]);
|
||||
if (usage.total_input_tokens != null) rows.push(["total input", fmtCompact(usage.total_input_tokens)]);
|
||||
if (usage.output_tokens != null) rows.push(["output tokens", fmtCompact(usage.output_tokens)]);
|
||||
if (usage.reasoning_tokens != null) rows.push(["reasoning tokens", fmtCompact(usage.reasoning_tokens)]);
|
||||
if (usage.max_context_tokens != null) rows.push(["max context length", fmtCompact(usage.max_context_tokens)]);
|
||||
if (usage.total_tokens != null) rows.push(["total tokens", fmtCompact(usage.total_tokens)]);
|
||||
if (usage.cost != null) rows.push(["cost", fmtCost(usage.cost)]);
|
||||
}
|
||||
|
||||
function timelineSpanHtml(lane, span, start, total) {
|
||||
const partial = span.started_at == null || span.ended_at == null;
|
||||
const left = span.started_at == null ? 0 : Math.max(0, Math.min(100, ((span.started_at - start) / total) * 100));
|
||||
const width = partial ? 0.35 : Math.max(0.35, Math.min(100 - left, ((span.ended_at - span.started_at) / total) * 100));
|
||||
const rows = [
|
||||
["start", span.started_at == null ? "unknown" : timelineClock(span.started_at)],
|
||||
["end", span.ended_at == null ? (span.status === "running" ? "open" : "unknown") : timelineClock(span.ended_at)],
|
||||
["duration", partial ? "—" : fmtDuration(span.ended_at - span.started_at)],
|
||||
];
|
||||
if (span.track === "activity") {
|
||||
if (span.shared) rows.push(["branch role", "shared prefix"]);
|
||||
const totalInput = span.input_tokens == null ? null : span.input_tokens + (span.cached_tokens || 0);
|
||||
appendTimelineUsage(rows, {
|
||||
input_tokens: span.input_tokens,
|
||||
cached_tokens: span.cached_tokens,
|
||||
total_input_tokens: totalInput,
|
||||
output_tokens: span.output_tokens,
|
||||
reasoning_tokens: span.reasoning_tokens,
|
||||
max_context_tokens: totalInput,
|
||||
total_tokens: totalInput == null || span.output_tokens == null ? null : totalInput + span.output_tokens,
|
||||
cost: span.cost,
|
||||
});
|
||||
} else {
|
||||
appendTimelineUsage(rows, lane.usage, true);
|
||||
}
|
||||
const tip = timelineTipAttr({
|
||||
kind: span.track === "activity" ? "activity" : "lifecycle",
|
||||
title: `${lane.label} — ${span.label}`,
|
||||
snippet: span.snippet || "",
|
||||
rows,
|
||||
hint: span.track === "activity" ? "Click to open this call in the transcript." : "Click to open this trace transcript.",
|
||||
});
|
||||
const node = span.node_index == null ? "" : ` data-tl-node="${span.node_index}"`;
|
||||
const call = span.call_index == null ? "" : ` data-tl-call="${span.call_index}"`;
|
||||
return (
|
||||
`<button class="tl-span ${esc(span.track)} ${esc(span.kind)} ${span.shared ? "shared" : ""} ${span.status === "running" ? "running" : ""} ${partial ? "untimed" : ""}"` +
|
||||
` style="left:${left.toFixed(3)}%;width:${width.toFixed(3)}%" data-tl-trace="${lane.trace_index}"${node}${call}${tip}></button>`
|
||||
);
|
||||
}
|
||||
|
||||
function timelineLaneHtml(lane, start, total) {
|
||||
const grids = [25, 50, 75].map((left) => `<i class="tl-gridline" style="left:${left}%"></i>`).join("");
|
||||
const spans = (lane.spans || []).map((span) => timelineSpanHtml(lane, span, start, total)).join("");
|
||||
const duration = lane.started_at == null || lane.ended_at == null ? "—" : fmtDuration(lane.ended_at - lane.started_at);
|
||||
const ended = lane.ended_at == null ? (lane.status === "running" ? "open" : "unknown") : timelineClock(lane.ended_at);
|
||||
const model = lane.model
|
||||
? `<div class="tl-label-meta" title="${esc(lane.model)}">${esc(lane.model)}</div>`
|
||||
: "";
|
||||
return (
|
||||
`<div class="tl-lane" data-tl-trace="${lane.trace_index}">` +
|
||||
`<div class="tl-label" style="padding-left:${10 + (lane.depth || 0) * 18}px">` +
|
||||
`${lane.depth ? '<span class="tl-tree">└</span>' : ""}<span class="tl-dot" style="background:${PALETTE[lane.trace_index % PALETTE.length]}"></span>` +
|
||||
`<span class="tl-label-copy"><div class="tl-label-name" title="${esc(lane.label)}">${esc(lane.label)}</div>` +
|
||||
`${model}</span></div>` +
|
||||
`<div class="tl-track">${grids}${spans}</div>` +
|
||||
`<div class="tl-time"><span>${duration}</span><span class="muted">${ended}</span></div>` +
|
||||
`<div class="tl-outcome"><span class="tl-state ${esc(lane.status)}">${esc(lane.outcome || lane.status)}</span>` +
|
||||
`${lane.reward == null ? "" : `<span class="tl-reward">reward ${fmtReward(lane.reward)}</span>`}</div></div>`
|
||||
);
|
||||
}
|
||||
|
||||
function renderTimeline() {
|
||||
const target = $("#tm-timeline");
|
||||
const timeline = currentTimeline;
|
||||
if (!timeline) {
|
||||
target.innerHTML = `<div class="chart-empty">loading timeline…</div>`;
|
||||
return;
|
||||
}
|
||||
if (!(timeline.lanes || []).length) {
|
||||
target.innerHTML = emptyState("no timeline", "this episode carries no agent traces");
|
||||
return;
|
||||
}
|
||||
const starts = timeline.lanes.map((lane) => lane.started_at).filter((value) => value != null);
|
||||
const ends = timeline.lanes.map((lane) => lane.ended_at ?? lane.started_at).filter((value) => value != null);
|
||||
const start = starts.length ? Math.min(...starts) : 0;
|
||||
const end = ends.length ? Math.max(...ends) : start + 1;
|
||||
const total = Math.max(1, end - start);
|
||||
const axis = [0, 0.25, 0.5, 0.75, 1]
|
||||
.map((fraction) => `<span style="left:${fraction * 100}%">${fraction ? fmtDuration(total * fraction) : "0"}</span>`)
|
||||
.join("");
|
||||
target.innerHTML =
|
||||
`<div class="tl-shell"><div class="tl-head"><span>branches</span><div class="tl-axis">${axis}</div><span>duration / end</span><span>state / outcome</span></div>` +
|
||||
timeline.lanes.map((lane) => timelineLaneHtml(lane, start, total)).join("") +
|
||||
`</div>`;
|
||||
}
|
||||
|
||||
async function setTraceView(view) {
|
||||
traceView = view;
|
||||
setActive("#tm-view", "view", view);
|
||||
if (view === "timeline") await ensureTimeline();
|
||||
renderEpisode();
|
||||
savePrefs();
|
||||
}
|
||||
|
||||
function renderEpisode() {
|
||||
const ep = currentEpisode;
|
||||
if (!ep) return;
|
||||
@@ -2608,14 +2818,10 @@ function renderEpisode() {
|
||||
if (currentBranchIdx >= branches.length) currentBranchIdx = 0;
|
||||
const traceTabs = $("#tm-trace-tabs");
|
||||
traceTabs.hidden = traces.length <= 1;
|
||||
// multi-agent episodes: label each trace by its agent name (seat), index only
|
||||
// as a tiebreak when names repeat or are missing
|
||||
const names = traces.map((t) => t.agent?.name);
|
||||
const label = (i) => (names[i] && names.indexOf(names[i]) === names.lastIndexOf(names[i]) ? names[i] : `${names[i] ?? "trace"} ${i}`);
|
||||
traceTabs.innerHTML =
|
||||
traces.length > 1
|
||||
? traces
|
||||
.map((_, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}">${esc(label(i))}</button>`)
|
||||
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
.join("")
|
||||
: "";
|
||||
const branchTabs = $("#tm-branch-tabs");
|
||||
@@ -2627,10 +2833,18 @@ function renderEpisode() {
|
||||
.join("") +
|
||||
`<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);
|
||||
const timeline = traceView === "timeline";
|
||||
$("#tm-tabs-row").hidden = timeline || (traceTabs.hidden && branchTabs.hidden);
|
||||
$("#tm-messages").hidden = timeline;
|
||||
$("#tm-timeline").hidden = !timeline;
|
||||
$("#token-signal").closest(".dd-select").hidden = timeline;
|
||||
$("#tm-collapse").hidden = timeline;
|
||||
$("#tm-expand").hidden = timeline;
|
||||
setActive("#tm-view", "view", traceView);
|
||||
if (timeline) renderTimeline();
|
||||
else renderMessages(ep, trace, branches);
|
||||
renderMeta(ep, trace, branches);
|
||||
}
|
||||
|
||||
@@ -3654,6 +3868,75 @@ $("#trace-view-mode").addEventListener("click", async (e) => {
|
||||
renderEpisode();
|
||||
savePrefs();
|
||||
});
|
||||
$("#tm-view").addEventListener("click", (e) => {
|
||||
const button = e.target.closest("[data-view]");
|
||||
if (button && button.dataset.view !== traceView) setTraceView(button.dataset.view);
|
||||
});
|
||||
$("#tm-timeline").addEventListener("click", async (e) => {
|
||||
const target = e.target.closest("[data-tl-trace]");
|
||||
if (!target) return;
|
||||
e.stopPropagation();
|
||||
currentTraceIdx = +target.dataset.tlTrace;
|
||||
const node = target.dataset.tlNode == null ? null : +target.dataset.tlNode;
|
||||
const call = target.dataset.tlCall == null ? null : +target.dataset.tlCall;
|
||||
if (node != null) {
|
||||
const trace = currentEpisode?.traces?.[currentTraceIdx];
|
||||
const branches = trace ? traceBranches(trace) : [];
|
||||
const branch = branches.findIndex((path) => path.includes(node));
|
||||
currentBranchIdx = branch >= 0 ? branch : -1;
|
||||
pendingTimelineNode = node;
|
||||
pendingTimelineCall = call;
|
||||
state.traces.viewMode = "messages";
|
||||
} else {
|
||||
currentBranchIdx = 0;
|
||||
pendingTimelineNode = null;
|
||||
pendingTimelineCall = call;
|
||||
if (call != null) state.traces.viewMode = "messages";
|
||||
}
|
||||
await setTraceView("transcript");
|
||||
requestAnimationFrame(() => {
|
||||
const entry =
|
||||
pendingTimelineCall == null
|
||||
? pendingTimelineNode == null
|
||||
? null
|
||||
: $(`#tm-messages [data-node="${pendingTimelineNode}"]`)
|
||||
: $(`#tm-messages [data-call-index="${pendingTimelineCall}"]`);
|
||||
entry?.scrollIntoView({ block: "center" });
|
||||
const details = entry?.closest("details");
|
||||
if (details) details.open = true;
|
||||
pendingTimelineNode = null;
|
||||
pendingTimelineCall = null;
|
||||
});
|
||||
});
|
||||
const timelineTip = document.createElement("div");
|
||||
timelineTip.className = "tl-tooltip";
|
||||
timelineTip.hidden = true;
|
||||
document.body.appendChild(timelineTip);
|
||||
function moveTimelineTip(e) {
|
||||
const gap = 12;
|
||||
const left = Math.min(e.clientX + gap, window.innerWidth - timelineTip.offsetWidth - 8);
|
||||
const top = Math.min(e.clientY + gap, window.innerHeight - timelineTip.offsetHeight - 8);
|
||||
timelineTip.style.left = `${Math.max(8, left)}px`;
|
||||
timelineTip.style.top = `${Math.max(8, top)}px`;
|
||||
}
|
||||
$("#tm-timeline").addEventListener("mouseover", (e) => {
|
||||
const target = e.target.closest("[data-timeline-tip]");
|
||||
if (!target) return;
|
||||
const payload = JSON.parse(target.dataset.timelineTip);
|
||||
timelineTip.innerHTML =
|
||||
`<div class="tl-tooltip-kind">${esc(payload.kind)}</div><div class="tl-tooltip-title">${esc(payload.title)}</div>` +
|
||||
`${payload.snippet ? `<div class="tl-tooltip-snippet">${esc(payload.snippet)}</div>` : ""}` +
|
||||
`<dl>${payload.rows.map(([key, value]) => `<dt>${esc(key)}</dt><dd>${esc(value)}</dd>`).join("")}</dl>` +
|
||||
`<div class="tl-tooltip-hint">${esc(payload.hint)}</div>`;
|
||||
timelineTip.hidden = false;
|
||||
moveTimelineTip(e);
|
||||
});
|
||||
$("#tm-timeline").addEventListener("mousemove", (e) => {
|
||||
if (!timelineTip.hidden) moveTimelineTip(e);
|
||||
});
|
||||
$("#tm-timeline").addEventListener("mouseout", (e) => {
|
||||
if (e.target.closest("[data-timeline-tip]") && !e.relatedTarget?.closest?.("[data-timeline-tip]")) timelineTip.hidden = true;
|
||||
});
|
||||
$("#tm-trace-tabs").addEventListener("click", (e) => {
|
||||
const btn = e.target.closest("[data-trace]");
|
||||
if (btn) { currentTraceIdx = +btn.dataset.trace; currentBranchIdx = 0; renderEpisode(); }
|
||||
@@ -3734,6 +4017,7 @@ function savePrefs() {
|
||||
traceErrorsOnly: state.traces.errorsOnly,
|
||||
traceSort: `${state.traces.sort}:${state.traces.order}`,
|
||||
traceViewMode: state.traces.viewMode,
|
||||
traceView,
|
||||
logView: state.logs.view,
|
||||
logComponents: state.logs.components ? [...state.logs.components] : null,
|
||||
logLevel: state.logs.level,
|
||||
|
||||
@@ -203,6 +203,10 @@
|
||||
<div class="tm-head">
|
||||
<span class="tm-title">Trace Viewer</span>
|
||||
<button id="tm-back" class="btn" hidden title="back to the report">← report</button>
|
||||
<div class="seg" id="tm-view">
|
||||
<button data-view="transcript" class="active">Transcript</button>
|
||||
<button data-view="timeline">Timeline</button>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<div class="seg" id="trace-view-mode">
|
||||
<button data-mode="messages" class="active">Messages</button>
|
||||
@@ -224,6 +228,7 @@
|
||||
<div id="tm-branch-tabs" class="seg" hidden></div>
|
||||
</div>
|
||||
<div id="tm-messages"></div>
|
||||
<div id="tm-timeline" hidden></div>
|
||||
</section>
|
||||
<aside id="tm-right">
|
||||
<div class="tm-head"><span class="tm-title">Overview</span></div>
|
||||
|
||||
@@ -643,6 +643,12 @@ mark.hit {
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
min-height: 48px;
|
||||
}
|
||||
.tm-tabs-row {
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
.tm-title { font-size: 12px; font-weight: 500; color: var(--grey-6); white-space: nowrap; }
|
||||
#tm-left { border-right: 1px solid var(--hairline); display: flex; flex-direction: column; min-height: 0; }
|
||||
#tm-left .search { margin: 10px 14px 6px; }
|
||||
@@ -686,9 +692,78 @@ mark.hit {
|
||||
#tm-main { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
|
||||
#tm-messages { display: flex; flex: 1; flex-direction: column; overflow-y: auto; padding: 14px 16px; }
|
||||
#tm-messages > * { flex-shrink: 0; }
|
||||
#tm-timeline { flex: 1; min-height: 0; overflow: auto; padding: 14px 16px 24px; }
|
||||
#tm-right { border-left: 1px solid var(--hairline); overflow-y: auto; min-height: 0; }
|
||||
#tm-meta { padding: 12px 14px; }
|
||||
|
||||
/* episode timeline: lifecycle spans above exact model-call activity */
|
||||
.tl-shell { min-width: 780px; border: 1px solid var(--hairline); }
|
||||
.tl-head, .tl-lane {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(160px, 220px) minmax(390px, 1fr) 105px 150px;
|
||||
}
|
||||
.tl-head {
|
||||
min-height: 42px;
|
||||
align-items: end;
|
||||
color: var(--grey-4);
|
||||
font-size: 9px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
border-bottom: 1px solid var(--grey-3);
|
||||
}
|
||||
.tl-head > span { padding: 8px 10px; }
|
||||
.tl-axis { position: relative; align-self: stretch; min-width: 0; }
|
||||
.tl-axis span { position: absolute; bottom: 8px; transform: translateX(-50%); white-space: nowrap; }
|
||||
.tl-axis span:first-child { transform: none; }
|
||||
.tl-axis span:last-child { transform: translateX(-100%); }
|
||||
.tl-lane { min-height: 66px; border-bottom: 1px solid var(--hairline-faint); cursor: pointer; }
|
||||
.tl-lane:last-child { border-bottom: 0; }
|
||||
.tl-lane:hover { background: rgba(255, 255, 255, 0.025); }
|
||||
.tl-label, .tl-time, .tl-outcome { padding: 11px 10px; min-width: 0; }
|
||||
.tl-label { display: flex; align-items: flex-start; gap: 8px; }
|
||||
.tl-tree { color: var(--grey-3); flex-shrink: 0; }
|
||||
.tl-dot { width: 6px; height: 6px; margin-top: 5px; background: var(--chart-2); flex-shrink: 0; }
|
||||
.tl-label-copy { min-width: 0; }
|
||||
.tl-label-name { color: var(--grey-6); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tl-label-meta { color: var(--grey-4); font-size: 9.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tl-track { position: relative; height: 42px; margin: 11px 0; border: 1px solid var(--hairline); overflow: hidden; }
|
||||
.tl-gridline { position: absolute; top: 0; bottom: 0; border-left: 1px solid var(--hairline-faint); pointer-events: none; }
|
||||
.tl-span { position: absolute; min-width: 3px; cursor: pointer; border: 0; padding: 0; }
|
||||
.tl-span.lifecycle { top: 7px; height: 13px; opacity: 0.78; }
|
||||
.tl-span.activity { top: 28px; height: 6px; background: var(--grey-4); }
|
||||
.tl-span.activity.shared { opacity: 0.28; }
|
||||
.tl-span.untimed { border-left: 3px double var(--grey-6); }
|
||||
.tl-span:hover, .tl-span:focus-visible { opacity: 1; outline: 1px solid var(--grey-6); outline-offset: 1px; }
|
||||
.tl-span.boot, .tl-span.setup { background: var(--grey-4); }
|
||||
.tl-span.agent { background: var(--chart-2); }
|
||||
.tl-span.finalize { background: var(--chart-1); }
|
||||
.tl-span.scoring { background: var(--chart-3); }
|
||||
.tl-span.running { border-right: 2px solid var(--accent); }
|
||||
.tl-time { color: var(--grey-5); font-size: 11px; }
|
||||
.tl-time .muted { display: block; font-size: 9.5px; }
|
||||
.tl-outcome { display: flex; flex-direction: column; align-items: flex-start; gap: 5px; font-size: 9.5px; }
|
||||
.tl-state, .tl-reward { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
|
||||
.tl-state.completed { color: var(--positive); }
|
||||
.tl-state.failed { color: var(--negative); }
|
||||
.tl-state.running { color: var(--infra); }
|
||||
.tl-reward { color: var(--chart-3); }
|
||||
.tl-tooltip {
|
||||
position: fixed;
|
||||
z-index: 60;
|
||||
width: min(390px, calc(100vw - 24px));
|
||||
padding: 12px 14px;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
pointer-events: none;
|
||||
}
|
||||
.tl-tooltip-kind { color: var(--accent); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
|
||||
.tl-tooltip-title { color: var(--grey-6); font-size: 12px; margin: 3px 0 8px; }
|
||||
.tl-tooltip-snippet { color: var(--grey-5); font-size: 11px; margin-bottom: 9px; white-space: normal; }
|
||||
.tl-tooltip dl { display: grid; grid-template-columns: auto 1fr; gap: 2px 16px; margin: 0; font-size: 10.5px; }
|
||||
.tl-tooltip dt { color: var(--grey-4); }
|
||||
.tl-tooltip dd { color: var(--grey-6); margin: 0; }
|
||||
.tl-tooltip-hint { color: var(--grey-4); border-top: 1px solid var(--hairline); margin-top: 9px; padding-top: 7px; font-size: 9.5px; }
|
||||
|
||||
.trace-errors { margin-top: auto; padding-top: 12px; }
|
||||
.trace-error-banner {
|
||||
border: 1px solid var(--negative);
|
||||
|
||||
+56
-130
@@ -24,7 +24,6 @@ from prime_rl.utils.pathing import (
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
get_log_dir,
|
||||
latest_log_dir,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
@@ -43,8 +42,6 @@ from prime_rl.utils.process import (
|
||||
|
||||
SFT_CONFIG = "sft.json"
|
||||
SFT_SBATCH = "sft.sbatch"
|
||||
EVAL_SBATCH = "eval.sbatch"
|
||||
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
|
||||
|
||||
INFERENCE_CONFIG = "inference.json"
|
||||
EVALS_CONFIG = "evals.json"
|
||||
@@ -151,7 +148,11 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
assert config.slurm is not None
|
||||
assert config.slurm.template_path is not None
|
||||
|
||||
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
|
||||
template_dirs = [config.slurm.template_path.parent]
|
||||
bundled_templates = find_package_resource("templates")
|
||||
if bundled_templates is not None:
|
||||
template_dirs.append(bundled_templates)
|
||||
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
|
||||
template = env.get_template(config.slurm.template_path.name)
|
||||
|
||||
trainer_env_vars = {
|
||||
@@ -170,23 +171,53 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
else:
|
||||
online_eval = config.eval is not None
|
||||
eval_vars = {}
|
||||
if online_eval:
|
||||
assert config.inference is not None
|
||||
inference_env_vars = {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
}
|
||||
eval_vars = {
|
||||
"router": config.inference.router,
|
||||
"router_port": config.inference.server.port,
|
||||
"backend_port": config.inference.backend_port,
|
||||
"data_parallel_rpc_port": config.inference.vllm.data_parallel_rpc_port,
|
||||
"dp_per_node": config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
|
||||
"enable_expert_parallel": config.inference.vllm.enable_expert_parallel,
|
||||
"inference_env_vars": inference_env_vars,
|
||||
"evals_env_vars": {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
},
|
||||
"eval_env_names": [source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
}
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=get_config_dir(config.run_dir),
|
||||
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,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
ranks_filter=",".join(map(str, config.log.ranks_filter)),
|
||||
prl_run_id=prl_run_id,
|
||||
run_name=config.run.name,
|
||||
online_eval=online_eval,
|
||||
use_nccl_broadcast=(
|
||||
config.eval is not None
|
||||
and config.weight_broadcast is not None
|
||||
and config.weight_broadcast.type == "nccl"
|
||||
),
|
||||
**eval_vars,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -194,70 +225,13 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Path, prl_run_id: str | None) -> None:
|
||||
"""Write the SLURM script for the decoupled online-eval job (inference pool +
|
||||
env servers + evals) to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
assert config.slurm is not None
|
||||
assert config.slurm.template_path is not None
|
||||
assert config.deployment.type == "multi_node"
|
||||
assert config.inference is not None
|
||||
|
||||
# The eval template is bundled next to the trainer templates; a custom
|
||||
# slurm.template_path directory takes precedence so both can be overridden.
|
||||
template_dirs = [config.slurm.template_path.parent]
|
||||
bundled_templates = find_package_resource("templates")
|
||||
if bundled_templates is not None:
|
||||
template_dirs.append(bundled_templates)
|
||||
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
|
||||
template = env.get_template(EVAL_TEMPLATE)
|
||||
|
||||
inference_env_vars = {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
}
|
||||
evals_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
|
||||
|
||||
script = template.render(
|
||||
**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,
|
||||
router_port=config.inference.server.port,
|
||||
backend_port=config.inference.backend_port,
|
||||
data_parallel_rpc_port=config.inference.vllm.data_parallel_rpc_port,
|
||||
dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
|
||||
enable_expert_parallel=config.inference.vllm.enable_expert_parallel,
|
||||
inference_env_vars=inference_env_vars,
|
||||
evals_env_vars=evals_env_vars,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
prl_run_id=prl_run_id,
|
||||
run_name=config.run.name,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def sft_slurm(config: SFTConfig):
|
||||
"""Run SFT training via SLURM. With online evals on a multi-node deployment, the
|
||||
trainer and the eval deployment (inference pool + evals) are two independent
|
||||
SLURM jobs. The trainer publishes its rank-0 hostname through the shared run
|
||||
directory so the eval deployment can join its NCCL weight-broadcast group."""
|
||||
"""Run SFT training and its online-eval deployment in one SLURM allocation."""
|
||||
assert config.slurm is not None
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
decoupled_eval = config.deployment.type == "multi_node" and config.eval is not None
|
||||
online_eval = config.deployment.type == "multi_node" and config.eval is not None
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
write_launch_toml(config.run_dir, "sft")
|
||||
@@ -267,99 +241,50 @@ def sft_slurm(config: SFTConfig):
|
||||
if config.deployment.type == "multi_node"
|
||||
else {"slurm", "dry_run", "clean"}
|
||||
)
|
||||
if decoupled_eval:
|
||||
if online_eval:
|
||||
# The trainer job only needs [eval] for the weight-broadcast cadence; the
|
||||
# inference pool lives in the eval job.
|
||||
# inference pool runs on its dedicated nodes in the same allocation.
|
||||
exclude = exclude | {"inference"}
|
||||
write_config(config, config_path, exclude=exclude)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
# Trainer and evals processes log to a single shared W&B run across both jobs,
|
||||
# keyed by the launcher's run id.
|
||||
# Trainer and evals processes log to a single shared W&B run.
|
||||
prl_run_id: str | None = None
|
||||
if decoupled_eval and config.monitors.wandb is not None:
|
||||
if online_eval and config.monitors.wandb is not None:
|
||||
prl_run_id = os.environ["PRL_RUN_ID"]
|
||||
|
||||
launcher_dir = get_launcher_dir(config.run_dir)
|
||||
if online_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(f"Wrote eval subconfigs to {config_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}")
|
||||
|
||||
# The trainer job is submitted first and the eval job depends on it having started:
|
||||
# the trainer creates the shared W&B run, and the evals process's joiner init only
|
||||
# retries for a bounded window — starting the evals process while the trainer job pends
|
||||
# would crash it at wandb init.
|
||||
script_paths = [script_path]
|
||||
if decoupled_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(f"Wrote eval subconfigs to {config_dir}")
|
||||
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]
|
||||
|
||||
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
|
||||
log_message = format_log_message(
|
||||
log_dir=latest_log_dir(config.run_dir),
|
||||
trainer=True,
|
||||
num_train_nodes=num_nodes,
|
||||
evals=online_eval,
|
||||
inference=online_eval,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)] if online_eval else None,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
)
|
||||
if decoupled_eval:
|
||||
# The eval job logs at stable (non-attempt) paths under the run dir.
|
||||
log_message += "\n" + format_log_message(
|
||||
log_dir=get_log_dir(config.run_dir),
|
||||
evals=True,
|
||||
inference=True,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
).removeprefix("Logs:\n")
|
||||
|
||||
if config.dry_run:
|
||||
if decoupled_eval:
|
||||
trainer_submit = f" TRAIN_JOB_ID=$(sbatch --parsable {script_paths[0]} | cut -d';' -f1)"
|
||||
eval_submit = f" sbatch --dependency=after:$TRAIN_JOB_ID {script_paths[1]}"
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
|
||||
eval_submit = (
|
||||
" sbatch --dependency=after:$TRAIN_JOB_ID "
|
||||
f"--export=ALL,TRAIN_JOB_ID=$TRAIN_JOB_ID {script_paths[1]}"
|
||||
)
|
||||
submit = "\n".join((trainer_submit, eval_submit))
|
||||
else:
|
||||
submit = f" sbatch {script_paths[0]}"
|
||||
note = (
|
||||
"\n\nSubmit the trainer job first. The eval job starts after the trainer allocation is ready."
|
||||
if decoupled_eval
|
||||
else ""
|
||||
)
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n{submit}{note}\n\n{log_message}")
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
submitted_job_ids: list[str] = []
|
||||
for path in script_paths:
|
||||
# --parsable prints ``<job_id>[;<cluster>]`` — the human-readable format varies
|
||||
# (e.g. multi-cluster sbatch appends "on cluster <name>").
|
||||
cmd = ["sbatch", "--parsable"]
|
||||
if submitted_job_ids:
|
||||
# Hold the eval job until the trainer job has started (not finished).
|
||||
cmd.append(f"--dependency=after:{submitted_job_ids[-1]}")
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
|
||||
cmd.append(f"--export=ALL,TRAIN_JOB_ID={submitted_job_ids[-1]}")
|
||||
cmd.append(str(path))
|
||||
logger.info(f"Submitting: {' '.join(cmd)}")
|
||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
for job_id in submitted_job_ids:
|
||||
logger.warning(f"Cancelling already-submitted job {job_id}")
|
||||
subprocess.run(["scancel", job_id], capture_output=True, text=True)
|
||||
sys.exit(1)
|
||||
job_id = result.stdout.strip().split(";")[0]
|
||||
submitted_job_ids.append(job_id)
|
||||
logger.success(f"Submitted batch job {job_id}")
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(log_message)
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
|
||||
@@ -484,6 +409,7 @@ def sft_local(config: SFTConfig):
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
"PRL_LOG_DIR": str(log_dir),
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "evals",
|
||||
},
|
||||
|
||||
@@ -28,6 +28,7 @@ import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
|
||||
from prime_rl import monitors
|
||||
@@ -51,7 +52,7 @@ from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_def
|
||||
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
|
||||
from prime_rl.utils.config import dump_resolved_config
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir
|
||||
from prime_rl.utils.pathing import create_attempt_log_dir, get_all_ckpt_steps, get_config_dir
|
||||
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
@@ -67,8 +68,13 @@ STARTUP_BROADCAST_TIMEOUT_S = 1200
|
||||
|
||||
|
||||
class Evals:
|
||||
def __init__(self, config: EvalsConfig) -> None:
|
||||
def __init__(self, config: EvalsConfig, log_dir: Path | None = None) -> None:
|
||||
self.config = config
|
||||
self.log_dir = log_dir or (
|
||||
Path(os.environ["PRL_LOG_DIR"])
|
||||
if "PRL_LOG_DIR" in os.environ
|
||||
else create_attempt_log_dir(config.output_dir)
|
||||
)
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
mode = f"online (broadcasts_dir={config.online.broadcasts_dir})" if config.online is not None else "standalone"
|
||||
@@ -209,7 +215,7 @@ class Evals:
|
||||
config = self.config
|
||||
addresses = config.eval.env_addresses
|
||||
config_dir = get_config_dir(config.output_dir) / "envs" / "eval"
|
||||
log_dir = get_log_dir(config.output_dir) / "envs" / "eval"
|
||||
log_dir = self.log_dir / "envs" / "eval"
|
||||
for source in config.eval.source:
|
||||
if source.serve.address is not None:
|
||||
continue
|
||||
@@ -461,8 +467,8 @@ class Evals:
|
||||
|
||||
|
||||
@clean_exit
|
||||
async def run_evals(config: EvalsConfig) -> None:
|
||||
evals = Evals(config)
|
||||
async def run_evals(config: EvalsConfig, log_dir: Path | None = None) -> None:
|
||||
evals = Evals(config, log_dir)
|
||||
try:
|
||||
await evals.run()
|
||||
# Finalize only on a clean exit — a crashed evals must not mark the run completed.
|
||||
@@ -472,11 +478,9 @@ async def run_evals(config: EvalsConfig) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.entrypoints.evals import main as entrypoint_main
|
||||
|
||||
set_proc_title("Evals")
|
||||
asyncio.run(run_evals(cli(EvalsConfig)))
|
||||
entrypoint_main()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
#SBATCH --job-name={{ job_name }}
|
||||
#SBATCH --nodes={{ num_nodes }}
|
||||
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --partition={{ partition }}
|
||||
@@ -26,14 +26,23 @@
|
||||
set -e
|
||||
|
||||
# Configs
|
||||
export NUM_NODES={{ num_nodes }}
|
||||
export NUM_TRAIN_NODES={{ num_train_nodes }}
|
||||
export NUM_INFER_NODES={{ num_infer_nodes }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
{% if online_eval -%}
|
||||
export ROUTER_PORT={{ router_port }}
|
||||
export BACKEND_PORT={{ backend_port }}
|
||||
export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
export DP_PER_NODE={{ dp_per_node }}
|
||||
{%- endif %}
|
||||
|
||||
# Paths
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_PATH={{ config_path }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export TRAIN_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
|
||||
@@ -41,72 +50,90 @@ export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
|
||||
mkdir -p $LOG_DIR/trainer
|
||||
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
|
||||
{% if online_eval -%}
|
||||
mkdir -p $LOG_DIR/inference
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
{% endif %}
|
||||
# Clean exits do not trigger srun --kill-on-bad-exit. Each terminal role
|
||||
# publishes its successful exit so every node uses the same completion condition.
|
||||
export TRAINER_DONE=$LAUNCHER_DIR/.sft_trainer_done_$SLURM_JOB_ID
|
||||
{% if online_eval -%}
|
||||
export EVAL_DONE=$LAUNCHER_DIR/.sft_eval_done_$SLURM_JOB_ID
|
||||
{%- endif %}
|
||||
mkdir -p "$LAUNCHER_DIR"
|
||||
rm -f "$TRAINER_DONE"{% if online_eval %} "$EVAL_DONE"{% endif %}
|
||||
|
||||
{% if prl_run_id %}
|
||||
# Trainer and evals (separate SLURM job) log to a single shared W&B run whose id
|
||||
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
|
||||
# outlives the trainer) finalizes it.
|
||||
# Trainer and evals log to one shared W&B run. The trainer creates the run,
|
||||
# and the evals process finalizes it after the final epoch.
|
||||
export PRL_RUN_ID={{ prl_run_id }}
|
||||
export PRL_RUN_NAME={{ run_name }}
|
||||
export WANDB_RUN_ID=$PRL_RUN_ID
|
||||
export WANDB_SHARED_MODE=1
|
||||
export WANDB_SHARED_PRIMARY=trainer
|
||||
export WANDB_SHARED_FINISHER=evals
|
||||
export WANDB_SHARED_LABEL=trainer
|
||||
export WANDB_PROGRAM="uv run sft"
|
||||
{% endif %}
|
||||
# Networking
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
echo "HOSTNAMES=${HOSTNAMES[@]}"
|
||||
|
||||
export MASTER_ADDR="${HOSTNAMES[0]}"
|
||||
# Networking. Inference nodes occupy the first ranks, followed by trainer nodes.
|
||||
HOSTNAMES=( $(scontrol show hostnames $SLURM_JOB_NODELIST) )
|
||||
TRAIN_HOSTS=( ${HOSTNAMES[@]:$NUM_INFER_NODES:$NUM_TRAIN_NODES} )
|
||||
export ALL_HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
export MASTER_ADDR="${TRAIN_HOSTS[0]}"
|
||||
export MASTER_PORT=29500
|
||||
echo "HOSTNAMES=${HOSTNAMES[*]}"
|
||||
echo "TRAIN_HOSTS=${TRAIN_HOSTS[*]}"
|
||||
echo "MASTER_ADDR=${MASTER_ADDR}"
|
||||
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" > "$LAUNCHER_DIR/.sft_nccl_host_$SLURM_JOB_ID"
|
||||
{% endif %}
|
||||
|
||||
{% if online_eval -%}
|
||||
INFER_HOSTS=( ${HOSTNAMES[@]:0:$NUM_INFER_NODES} )
|
||||
export HOSTNAMES_STR="${INFER_HOSTS[*]}"
|
||||
INFER_URLS="http://${INFER_HOSTS[0]}:${ROUTER_PORT}/v1"
|
||||
ADMIN_URLS=""
|
||||
ROUTER_ARGS=""
|
||||
for host in ${INFER_HOSTS[@]}; do
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + d))/v1"
|
||||
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))"
|
||||
done
|
||||
done
|
||||
export INFER_URLS
|
||||
export ADMIN_URLS
|
||||
export ROUTER_ARGS
|
||||
echo "INFER_HOSTS=${INFER_HOSTS[*]}"
|
||||
echo "INFER_URLS=${INFER_URLS}"
|
||||
echo "ADMIN_URLS=${ADMIN_URLS}"
|
||||
{%- endif %}
|
||||
|
||||
# Install environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): run the sync once on
|
||||
# every node. Re-source .env because unexported vars do not cross srun.
|
||||
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
|
||||
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
|
||||
SYNC_SH
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
cd $PROJECT_DIR && uv sync --all-extras --all-packages
|
||||
# Shared venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
{{ pre_run_command }}
|
||||
{% endif %}
|
||||
|
||||
# Cleanup stale node-local state from prior jobs. Orphan python/torchrun/vllm
|
||||
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
|
||||
# termination and cause the next launch to hang. Harmless on clean nodes.
|
||||
#
|
||||
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
|
||||
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
|
||||
# because the surviving literal `vllm` strings below appear in the cmdline.
|
||||
# Cleanup stale node-local state from prior jobs. Orphan python, torchrun, and
|
||||
# vLLM processes can otherwise retain GPUs or IPC files after SLURM termination.
|
||||
srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
pkill -9 "vllm::.*" 2>/dev/null
|
||||
sleep 2
|
||||
@@ -116,53 +143,141 @@ srun bash -s <<'CLEANUP_SH'
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
CLEANUP_SH
|
||||
|
||||
# Run SFT
|
||||
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
|
||||
# tasks so a single trainer crash terminates the entire SLURM job instead of
|
||||
# leaving the surviving ranks (and their nodes) idle.
|
||||
#
|
||||
# The body goes to bash on stdin through a quoted heredoc instead of a
|
||||
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
|
||||
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
|
||||
# need no escaping. Nothing in the body reads stdin, which would otherwise eat
|
||||
# the rest of the script.
|
||||
# Run trainer and online-eval roles in one SLURM step. A non-zero exit on any
|
||||
# node terminates the other roles. Clean trainer exits let the final eval drain.
|
||||
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
set -o pipefail
|
||||
|
||||
# Setup environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
|
||||
# Higher ulimit
|
||||
ulimit -n 65536
|
||||
|
||||
# Infiniband setup
|
||||
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
|
||||
export NCCL_IB_HCA=$IB_HCA
|
||||
IB_HCA=$(ibv_devinfo 2>/dev/null | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" | paste -sd,)
|
||||
[ -n "$IB_HCA" ] && export NCCL_IB_HCA=$IB_HCA
|
||||
|
||||
{% if online_eval -%}
|
||||
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
INFER_NODE_RANK=$SLURM_PROCID
|
||||
LOCAL_IP=$(hostname -I | awk "{print \$1}")
|
||||
CONFIG_PATH=$CONFIG_DIR/inference.json
|
||||
|
||||
# Inference env vars: launcher defaults + [env_vars] + [inference.env_vars]
|
||||
{%- for key, value in inference_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
|
||||
{% include '_launch_rank.sh.j2' %}
|
||||
{% include '_launch_router.sh.j2' %}
|
||||
|
||||
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
|
||||
| tee $LOG_DIR/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
TP=$((GPUS_PER_NODE / DP_PER_NODE))
|
||||
EP={{ "1" if enable_expert_parallel else "0" }}
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
|
||||
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
|
||||
if [ "$EP" -eq 1 ] && [ "$DP_PER_NODE" -gt 1 ]; then
|
||||
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
|
||||
else
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$LOG_DIR/inference/router.log"
|
||||
{%- if eval_env_names %}
|
||||
|
||||
mkdir -p $LOG_DIR/envs/eval
|
||||
{%- for name in eval_env_names %}
|
||||
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.json \
|
||||
> $LOG_DIR/envs/eval/{{ name }}.log 2>&1 &
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
# Evals drives inference through the router and sends admin operations
|
||||
# directly to each engine.
|
||||
{%- for key, value in evals_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
(
|
||||
PRL_LOG_DIR=$LOG_DIR WANDB_SHARED_LABEL=evals uv run evals \
|
||||
@ $CONFIG_DIR/evals.json \
|
||||
--eval.client.base-url $INFER_URLS \
|
||||
--eval.client.admin-base-url $ADMIN_URLS \
|
||||
{%- if use_nccl_broadcast %}
|
||||
--weight-broadcast.host $MASTER_ADDR \
|
||||
{%- endif %}
|
||||
2>&1 | tee $LOG_DIR/evals.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ]; then
|
||||
touch "$EVAL_DONE" || exit $?
|
||||
fi
|
||||
exit "$COMPONENT_CODE"
|
||||
) &
|
||||
fi
|
||||
else
|
||||
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
|
||||
{%- else %}
|
||||
TRAIN_NODE_RANK=$SLURM_PROCID
|
||||
{%- endif %}
|
||||
|
||||
# Trainer env vars: launcher defaults + [env_vars]
|
||||
{%- for key, value in trainer_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
|
||||
echo $HOSTNAMES | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_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.sft.train \
|
||||
@ $CONFIG_PATH \
|
||||
echo $ALL_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.sft.train \
|
||||
@ $TRAIN_CONFIG_PATH \
|
||||
{%- if use_nccl_broadcast %}
|
||||
--weight-broadcast.host 0.0.0.0 \
|
||||
--weight-broadcast.host 0.0.0.0 \
|
||||
{%- endif %}
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
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 online_eval %}fi{% endif %}
|
||||
|
||||
# Every node stays in the shared srun step until all terminal roles finish.
|
||||
{% if online_eval -%}
|
||||
( until [ -f "$TRAINER_DONE" ] && [ -f "$EVAL_DONE" ]; do sleep 10; done ) &
|
||||
{% else -%}
|
||||
( until [ -f "$TRAINER_DONE" ]; do sleep 10; done ) &
|
||||
{% endif -%}
|
||||
COMPLETION_PID=$!
|
||||
|
||||
# Ignore clean component exits until the shared completion condition is met.
|
||||
# Propagate failures through --kill-on-bad-exit=1.
|
||||
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)
|
||||
echo "[$(hostname)] completion condition met with code $EXIT_CODE - terminating remaining processes"
|
||||
for pid in $REMAINING_PIDS; do
|
||||
kill -TERM $pid 2>/dev/null || true
|
||||
done
|
||||
exit $EXIT_CODE
|
||||
LAUNCH_SH
|
||||
|
||||
@@ -1,260 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
#SBATCH --job-name={{ job_name }}-eval
|
||||
#SBATCH --nodes={{ num_infer_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --partition={{ partition }}
|
||||
{%- if account %}
|
||||
#SBATCH --account={{ account }}
|
||||
{%- endif %}
|
||||
{%- if time %}
|
||||
#SBATCH --time={{ time }}
|
||||
{%- endif %}
|
||||
{%- if nodelist %}
|
||||
#SBATCH --nodelist={{ nodelist }}
|
||||
{%- endif %}
|
||||
{%- if exclude %}
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#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
|
||||
# runs in a separate SLURM job. This job exits after evaluating the final weight
|
||||
# broadcast (max_steps).
|
||||
|
||||
# Exit immediately on any failed command so a crash anywhere releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
set -e
|
||||
|
||||
# Configs
|
||||
export NUM_NODES={{ num_infer_nodes }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
export ROUTER_PORT={{ router_port }}
|
||||
export BACKEND_PORT={{ backend_port }}
|
||||
export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
|
||||
# Paths
|
||||
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.
|
||||
[ -d $OUTPUT_DIR/logs/inference ] && mv $OUTPUT_DIR/logs/inference $OUTPUT_DIR/logs/inference_prev_$(date +%s)
|
||||
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 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
|
||||
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
|
||||
# outlives the trainer) finalizes it.
|
||||
export PRL_RUN_ID={{ prl_run_id }}
|
||||
export PRL_RUN_NAME={{ run_name }}
|
||||
export WANDB_RUN_ID=$PRL_RUN_ID
|
||||
export WANDB_SHARED_MODE=1
|
||||
export WANDB_SHARED_PRIMARY=trainer
|
||||
export WANDB_SHARED_FINISHER=evals
|
||||
export WANDB_PROGRAM="uv run sft"
|
||||
{% endif %}
|
||||
# Networking
|
||||
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="$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"
|
||||
echo "TRAIN_HOST=${TRAIN_HOST}"
|
||||
{% endif %}
|
||||
|
||||
# Single global router on node 0 fronts every per-rank endpoint; admin ops
|
||||
# (pause/update_weights/resume) bypass it and hit each rank directly.
|
||||
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
|
||||
DP_PER_NODE={{ dp_per_node }}
|
||||
ADMIN_URLS=""
|
||||
ROUTER_ARGS=""
|
||||
for host in ${HOSTNAMES[@]}; do
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + d))/v1"
|
||||
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))"
|
||||
done
|
||||
done
|
||||
export INFER_URLS
|
||||
export ADMIN_URLS
|
||||
export ROUTER_ARGS
|
||||
echo "HOSTNAMES=${HOSTNAMES[@]}"
|
||||
echo "INFER_URLS=${INFER_URLS}"
|
||||
echo "ADMIN_URLS=${ADMIN_URLS}"
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
|
||||
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
|
||||
SYNC_SH
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
{{ pre_run_command }}
|
||||
{% endif %}
|
||||
|
||||
# Cleanup stale node-local state from prior jobs. Orphan python/vllm processes and
|
||||
# vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM termination and
|
||||
# cause the next launch to hang. Harmless on clean nodes.
|
||||
#
|
||||
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
|
||||
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
|
||||
# because the surviving literal `vllm` strings below appear in the cmdline.
|
||||
srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
pkill -9 "vllm::.*" 2>/dev/null
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|vllm|vllm::" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
CLEANUP_SH
|
||||
|
||||
# Run the eval deployment
|
||||
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
|
||||
# tasks so a crashed engine/router/evals terminates the SLURM job instead
|
||||
# of leaving the surviving ranks holding nodes.
|
||||
#
|
||||
# The body goes to bash on stdin through a quoted heredoc instead of a
|
||||
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
|
||||
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
|
||||
# (including in the shared _launch_*.sh.j2 includes) need no escaping. Nothing in
|
||||
# the body reads stdin, which would otherwise eat the rest of the script.
|
||||
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
# pipefail ensures `cmd | tee log` propagates `cmd` failures, and the
|
||||
# wait/cleanup block at the end of this script surfaces background
|
||||
# process crashes (router, engines) as task failures.
|
||||
set -o pipefail
|
||||
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
|
||||
# Higher ulimit
|
||||
ulimit -n 65536
|
||||
|
||||
# Infiniband setup
|
||||
IB_HCA=$(ibv_devinfo 2>/dev/null | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" | paste -sd,)
|
||||
[ -n "$IB_HCA" ] && export NCCL_IB_HCA=$IB_HCA
|
||||
|
||||
INFER_NODE_RANK=$SLURM_PROCID
|
||||
LOCAL_IP=$(hostname -I | awk "{print \$1}")
|
||||
# Inference env vars: launcher defaults + [env_vars] + [inference.env_vars]
|
||||
{%- for key, value in inference_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
|
||||
{% include '_launch_rank.sh.j2' %}
|
||||
{% include '_launch_router.sh.j2' %}
|
||||
|
||||
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
|
||||
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
DP_PER_NODE={{ dp_per_node }}
|
||||
TP=$((GPUS_PER_NODE / DP_PER_NODE))
|
||||
EP={{ "1" if enable_expert_parallel else "0" }}
|
||||
|
||||
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
|
||||
# each pinned to its TP slice of GPUs. Each node is an independent replica, so any MoE EP
|
||||
# group is node-local (rendezvous on LOCAL_IP); dense models run independent engines.
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
|
||||
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
|
||||
if [ "$EP" -eq 1 ] && [ "$DP_PER_NODE" -gt 1 ]; then
|
||||
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
|
||||
else
|
||||
# Dense or single-DP-rank EP (dp=1, e.g. EP within one tp=8 group):
|
||||
# independent single-engine servers. vLLM rejects the external-LB DP
|
||||
# args when data_parallel_size == 1; enable_expert_parallel in the
|
||||
# inference config alone shards experts across the TP group.
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
# Single global router on node 0 (external LB across all per-rank endpoints)
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
|
||||
{%- if eval_env_names %}
|
||||
|
||||
# One env server per eval source next to the evals process, which connects to each
|
||||
# source at its deterministic loopback address (so this node), polling until
|
||||
# they are up - the servers and the evals process start in parallel.
|
||||
{%- for name in eval_env_names %}
|
||||
mkdir -p $OUTPUT_DIR/logs/envs/eval
|
||||
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.json \
|
||||
> $OUTPUT_DIR/logs/envs/eval/{{ name }}.log 2>&1 &
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
# The evals process watches trainer broadcast markers and drives the pool:
|
||||
# data plane through the router, admin ops per rank.
|
||||
{%- for key, value in evals_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
WANDB_SHARED_LABEL=evals uv run evals \
|
||||
@ $CONFIG_DIR/evals.json \
|
||||
--eval.client.base-url $INFER_URLS \
|
||||
--eval.client.admin-base-url $ADMIN_URLS \
|
||||
{%- if use_nccl_broadcast %}
|
||||
--weight-broadcast.host $TRAIN_HOST \
|
||||
{%- endif %}
|
||||
2>&1 | tee $OUTPUT_DIR/logs/evals.log &
|
||||
EVALS_PID=$!
|
||||
else
|
||||
# Watch for the completion sentinel so this node's wait below returns when
|
||||
# the evals process (on node 0) finishes cleanly.
|
||||
( until [ -f "$EVAL_DONE" ]; do sleep 10; done ) &
|
||||
fi
|
||||
|
||||
# Wait for the first background job to exit and propagate its exit code. This
|
||||
# turns background process crashes (engines, router, env servers, evals)
|
||||
# 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 -p FINISHED_PID
|
||||
EXIT_CODE=$?
|
||||
if [ "${FINISHED_PID:-}" = "${EVALS_PID:-none}" ]; then
|
||||
# Publish completion so the sentinel watchers on the other nodes release too
|
||||
# (a zero exit here never trips --kill-on-bad-exit).
|
||||
touch "$EVAL_DONE"
|
||||
fi
|
||||
echo "[$(hostname)] component exited with code $EXIT_CODE - terminating remaining processes"
|
||||
for pid in $(jobs -p); do
|
||||
kill -TERM $pid 2>/dev/null || true
|
||||
done
|
||||
exit $EXIT_CODE
|
||||
LAUNCH_SH
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Convert episode traces into a branch-level Hugging Face dataset.
|
||||
|
||||
Train and eval runs save one episode per line in `traces.jsonl`. This tool writes one
|
||||
dataset row for every branch of every agent trace. It does not select or filter rows.
|
||||
|
||||
Each row includes `messages` and JSON-encoded `tools` for SFT. It also includes trace,
|
||||
agent, task, run, outcome, error, timing, and usage metadata. Scalar outcome fields such
|
||||
as `reward`, `stop_condition`, `has_error`, and `is_truncated` stay as top-level columns
|
||||
so later scripts can filter them directly. Metadata with variable schemas stays as JSON.
|
||||
|
||||
Usage (from the prime-rl repo):
|
||||
uv run python tools/convert_traces_to_hf_dataset.py <traces.jsonl> --name <dir-or-repo-id>
|
||||
[--subset default] [--split train] [--public] [--local]
|
||||
|
||||
By default, the tool creates a private Hugging Face Hub repo named `<name>`. Use `--public`
|
||||
to create a public repo. With `--local`, it writes `<name>/<subset>/<split>.parquet` and
|
||||
registers it in `<name>/README.md` instead.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
from datasets import Dataset
|
||||
from pydantic import BaseModel
|
||||
from verifiers.v1 import Trace, WireEpisode
|
||||
from verifiers.v1.dialects.chat import message_to_wire
|
||||
|
||||
|
||||
def jsonable(value: Any) -> Any:
|
||||
if isinstance(value, BaseModel):
|
||||
return value.model_dump(mode="json", exclude_none=True)
|
||||
if isinstance(value, list):
|
||||
return [jsonable(item) for item in value]
|
||||
if isinstance(value, dict):
|
||||
return {key: jsonable(item) for key, item in value.items()}
|
||||
return value
|
||||
|
||||
|
||||
def as_json(value: Any) -> str:
|
||||
return json.dumps(jsonable(value))
|
||||
|
||||
|
||||
def trace_rows(episode: WireEpisode, trace: Trace) -> list[dict]:
|
||||
"""Convert each branch of one trace without selecting or filtering it."""
|
||||
last_error = trace.last_error
|
||||
run = episode.run
|
||||
work = getattr(run, "work", None)
|
||||
policy = getattr(work, "policy", None)
|
||||
common = {
|
||||
"episode_id": episode.id,
|
||||
"episode_ok": episode.ok,
|
||||
"episode_has_error": bool(episode.errors),
|
||||
"episode_errors": as_json(episode.errors),
|
||||
"env_id": episode.env.id,
|
||||
"env_name": episode.env.name,
|
||||
"group_id": episode.group.id if episode.group else None,
|
||||
"run_type": run.type if run else None,
|
||||
"run_id": run.id if run else None,
|
||||
"run_name": run.name if run else None,
|
||||
"work_type": work.type if work else None,
|
||||
"step": getattr(work, "step", None),
|
||||
"policy_start": policy.start if policy else None,
|
||||
"policy_end": policy.end if policy else None,
|
||||
"trace_id": trace.id,
|
||||
"trace_version": trace.version,
|
||||
"verifiers_version": trace.verifiers.version,
|
||||
"verifiers_commit": trace.verifiers.commit,
|
||||
"task_type": trace.task.type,
|
||||
"task_data": as_json(trace.task.data),
|
||||
"task_key": trace.task.key,
|
||||
"task_hash": trace.task.hash,
|
||||
"agent": trace.agent.name,
|
||||
"trainable": trace.agent.trainable,
|
||||
"agent_config": as_json(trace.agent.config),
|
||||
"agent_runtime": as_json(trace.agent.runtime),
|
||||
"tools": as_json(trace.tools),
|
||||
"reward": trace.reward,
|
||||
"rewards": as_json(trace.rewards),
|
||||
"metrics": as_json(trace.metrics),
|
||||
"info": as_json(trace.info),
|
||||
"is_completed": trace.is_completed,
|
||||
"ok": trace.ok,
|
||||
"stop_condition": trace.stop_condition,
|
||||
"has_error": trace.has_error,
|
||||
"error_type": last_error.type if last_error else None,
|
||||
"error_message": last_error.message if last_error else None,
|
||||
"error_status_code": last_error.status_code if last_error else None,
|
||||
"errors": as_json(trace.errors),
|
||||
"is_truncated": trace.is_truncated,
|
||||
"request_rewrites": as_json(trace.request_rewrites),
|
||||
"response_rewrites": as_json(trace.response_rewrites),
|
||||
"extra_usage": as_json(trace.extra_usage),
|
||||
"timing": as_json(trace.timing),
|
||||
"num_branches": trace.num_branches,
|
||||
"num_turns": trace.num_turns,
|
||||
"num_input_tokens": trace.num_input_tokens,
|
||||
"num_output_tokens": trace.num_output_tokens,
|
||||
"num_total_tokens": trace.num_total_tokens,
|
||||
}
|
||||
return [
|
||||
{
|
||||
**common,
|
||||
"branch_index": branch.index,
|
||||
"messages": [message_to_wire(m) for m in branch.messages],
|
||||
"calls": as_json(branch.calls),
|
||||
"branch_num_input_tokens": branch.num_input_tokens,
|
||||
"branch_num_output_tokens": branch.num_output_tokens,
|
||||
"branch_num_total_tokens": branch.num_total_tokens,
|
||||
}
|
||||
for branch in trace.branches
|
||||
]
|
||||
|
||||
|
||||
def register_in_dataset_card(root: Path, subset: str, split: str, rel_path: str) -> None:
|
||||
"""Point the dataset card's `configs` metadata at the parquet, so
|
||||
`load_dataset(root, subset, split=split)` resolves it."""
|
||||
readme = root / "README.md"
|
||||
meta: dict = {}
|
||||
body = ""
|
||||
if readme.exists():
|
||||
text = readme.read_text()
|
||||
lines = text.splitlines(keepends=True)
|
||||
end = next((i for i, line in enumerate(lines[1:], 1) if line.strip() == "---"), None)
|
||||
if lines and lines[0].strip() == "---" and end is not None:
|
||||
header = "".join(lines[1:end])
|
||||
body = "".join(lines[end + 1 :])
|
||||
meta = yaml.safe_load(header) or {}
|
||||
else:
|
||||
body = text
|
||||
configs = meta.setdefault("configs", [])
|
||||
config = next((c for c in configs if c["config_name"] == subset), None)
|
||||
if config is None:
|
||||
config = {"config_name": subset, "data_files": []}
|
||||
configs.append(config)
|
||||
entry = next((e for e in config["data_files"] if e["split"] == split), None)
|
||||
if entry is None:
|
||||
config["data_files"].append({"split": split, "path": rel_path})
|
||||
else:
|
||||
entry["path"] = rel_path
|
||||
text = f"---\n{yaml.safe_dump(meta, sort_keys=False)}---\n{body}"
|
||||
readme.write_text(text if text.endswith("\n") else text + "\n")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("traces", type=Path, help="a run's traces.jsonl (one episode per line)")
|
||||
parser.add_argument("--name", required=True, help="HF repo id, or output dataset dir with --local")
|
||||
parser.add_argument("--subset", default="default", help="dataset config name")
|
||||
parser.add_argument("--split", default="train", help="dataset split name")
|
||||
parser.add_argument("--public", action="store_true", help="make a new Hub dataset public")
|
||||
parser.add_argument("--local", action="store_true", help="write parquet locally instead of pushing")
|
||||
args = parser.parse_args()
|
||||
if args.local and args.public:
|
||||
parser.error("--public cannot be used with --local")
|
||||
|
||||
num_episodes, num_traces, rows = 0, 0, []
|
||||
with args.traces.open(encoding="utf-8") as f:
|
||||
for line in f:
|
||||
if not line.strip():
|
||||
continue
|
||||
num_episodes += 1
|
||||
episode = WireEpisode.model_validate(json.loads(line))
|
||||
for trace in episode.traces:
|
||||
num_traces += 1
|
||||
rows.extend(trace_rows(episode, trace))
|
||||
print(f"traces-to-hf: {num_episodes} episode(s) -> {num_traces} trace(s) -> {len(rows)} branch(es)")
|
||||
if not rows:
|
||||
raise SystemExit("traces-to-hf: no branches found")
|
||||
|
||||
dataset = Dataset.from_list(rows)
|
||||
if not args.local:
|
||||
dataset.push_to_hub(
|
||||
args.name,
|
||||
config_name=args.subset,
|
||||
split=args.split,
|
||||
private=not args.public,
|
||||
)
|
||||
print(
|
||||
f"traces-to-hf: pushed to {args.name} (subset={args.subset}, split={args.split}, private={not args.public})"
|
||||
)
|
||||
return
|
||||
root = Path(args.name)
|
||||
rel_path = f"{args.subset}/{args.split}.parquet"
|
||||
path = root / rel_path
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
dataset.to_parquet(str(path))
|
||||
register_in_dataset_card(root, args.subset, args.split, rel_path)
|
||||
print(f"traces-to-hf: wrote {path} (subset={args.subset}, split={args.split})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user