Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05967ffcd2 | ||
|
|
21a4a32450 | ||
|
|
a070beecbd | ||
|
|
7da7c4d108 | ||
|
|
9e3be00b39 | ||
|
|
ef66401434 | ||
|
|
be5855cfe3 | ||
|
|
43365ec52f | ||
|
|
ab5de8fff4 | ||
|
|
97d32d947f | ||
|
|
6b3364d1a8 | ||
|
|
544bd6205a | ||
|
|
3460245d63 | ||
|
|
3758321f08 | ||
|
|
01dc127b1a | ||
|
|
663b53bbc2 | ||
|
|
f96a46f090 | ||
|
|
01994b8168 | ||
|
|
e6b5e4de5d |
@@ -31,6 +31,7 @@ Namespaces are one honking great idea -- let's do more of those!
|
||||
## Running code
|
||||
|
||||
- **Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
|
||||
- **Tools vs entrypoints**: standalone scripts in `tools/` use plain argparse with positional args; `[project.scripts]` entrypoints use pydantic-config (`@ file.toml` + dotted CLI overrides).
|
||||
- **Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
|
||||
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
|
||||
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
|
||||
|
||||
@@ -247,8 +247,8 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
|
||||
Then inspect the resolved config:
|
||||
|
||||
```bash
|
||||
ls /tmp/reverse-dry/check/configs/resolved/
|
||||
ls /tmp/reverse-dry/check/configs/latest/resolved/
|
||||
# rl.json trainer.json orchestrator.json inference.json
|
||||
```
|
||||
|
||||
Each per-process JSON reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/check/configs/resolved/trainer.json`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
|
||||
Each per-process JSON reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/check/configs/latest/resolved/trainer.json`, etc.). Each launch also remains under `configs/attempt_<n>/`. This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
|
||||
|
||||
+5
-2
@@ -194,9 +194,11 @@ Launch:
|
||||
|
||||
```bash
|
||||
uv run rl @ base_rl.toml @ my_slurm.toml # submits via sbatch
|
||||
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script + resolved config, exits
|
||||
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes launcher/rl.sbatch + resolved config, exits
|
||||
```
|
||||
|
||||
Every SLURM entrypoint stores its generated scripts and coordination files under `<run_dir>/launcher/`. SLURM stdout and stderr go to `launcher/logs/`. Local launches do not create `launcher/`.
|
||||
|
||||
### `[deployment]` Block
|
||||
|
||||
`[deployment]` is a discriminated union picked by `type` — `single_node` or `multi_node` for RL/SFT, with an extra disaggregated variant for inference. RL multi-node:
|
||||
@@ -215,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
|
||||
```
|
||||
|
||||
|
||||
+35
-12
@@ -77,11 +77,11 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
|
||||
| Knob | What it does |
|
||||
|---|---|
|
||||
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). |
|
||||
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). Defaults to `$PRL_OUTPUT_DIR` if set, else `outputs`. |
|
||||
| `--run.name <name>` | Run name, also the run directory name under `<output_dir>` (override the directory separately via `--run.dir`). Auto-generated as `<envs>--<model>--<short-id>` when unset, so every launch gets a fresh, readable run directory. Set an explicit name for a predictable path — required to resume the run later. |
|
||||
| `--clean` | Wipe the run directory before starting. Useful when re-running a named run during iteration. |
|
||||
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
|
||||
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
|
||||
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/latest/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
|
||||
|
||||
### Algorithms
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -263,8 +263,8 @@ Checkpointing is split across processes because the orchestrator and trainer can
|
||||
|
||||
| Process | What's saved | Where |
|
||||
|---|---|---|
|
||||
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_N/trainer/` |
|
||||
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_N/orchestrator/` |
|
||||
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_{n}/trainer/` |
|
||||
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_{n}/orchestrator/` |
|
||||
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
|
||||
|
||||
### Enabling Checkpoints
|
||||
@@ -297,8 +297,28 @@ uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
|
||||
--resume.dir outputs/my-run/checkpoints/step_10
|
||||
```
|
||||
|
||||
### Exporting Checkpoints
|
||||
|
||||
Trainer checkpoints are DCP-sharded; export them to HF-format safetensors with `tools/convert_dcp_to_bf16.py`. The script reads the model config from the run's resolved config and writes sharded safetensors plus config/tokenizer assets to `<ckpt_dir>/weights` (or a second positional arg). It exports full fine-tunes only — LoRA checkpoints are rejected.
|
||||
|
||||
```bash
|
||||
# single process (1 GPU)
|
||||
uv run python tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
|
||||
|
||||
# multi-rank for faster gathers and models that don't fit one GPU
|
||||
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
|
||||
```
|
||||
|
||||
The exported directory loads directly into `uv run inference --vllm.model <dir>` or any HF consumer. Quantize it to blockwise FP8 (DeepSeek/GLM format, loads natively in vLLM) with `tools/convert_bf16_to_fp8.py <dir>`, or go straight from the checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (each rank quantizes its gathered slice, writes only `<ckpt_dir>/weights-FP8` — no intermediate bf16 export); dequantize an fp8-only release (e.g. GLM-5-FP8) for training with `tools/convert_fp8_to_bf16.py <dir>`.
|
||||
|
||||
## Observability
|
||||
|
||||
### Config Files
|
||||
|
||||
Each launch writes its input TOML and resolved JSON files to
|
||||
`<run_dir>/configs/attempt_<n>/`. Resumed runs keep the earlier configs.
|
||||
`configs/latest` points to the current attempt.
|
||||
|
||||
### Log Files
|
||||
|
||||
The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>/` — every launch (fresh or resumed) gets its own numbered attempt directory, and `logs/latest` symlinks to the current one. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
|
||||
@@ -307,6 +327,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)
|
||||
@@ -317,19 +338,21 @@ 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
|
||||
```
|
||||
|
||||
### Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with four views per run: metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved configs, a rollout trace viewer with a per-token advantage/logprob view, and merged component logs. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved configs, a rollout trace viewer with a per-token advantage/logprob view, merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
|
||||
|
||||
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
|
||||
|
||||
### Weights & Biases
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
from pathlib import Path
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import SerializeAsAny, model_validator
|
||||
from pydantic import Field, SerializeAsAny, model_validator
|
||||
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
|
||||
class EnvServerConfig(BaseConfig):
|
||||
@@ -20,8 +20,8 @@ class EnvServerConfig(BaseConfig):
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
|
||||
@@ -6,7 +6,7 @@ from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, LogConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
|
||||
class EvalsEvalConfig(EvalConfig):
|
||||
@@ -86,9 +86,9 @@ class EvalsConfig(BaseConfig):
|
||||
"""Weight transport for online evals. The ``sft`` launcher fills this from its
|
||||
resolved trainer transport. None uses filesystem reloads."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — rollout traces and logs are written as
|
||||
subdirectories. Shared with the trainer for online evals."""
|
||||
subdirectories. Shared with the trainer for online evals. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from pydantic import ConfigDict, Field, model_validator
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
from prime_rl.configs.shared import EnvVars, LogConfig, SlurmConfig
|
||||
from prime_rl.utils.config import find_package_resource
|
||||
from prime_rl.utils.config import default_output_dir, find_package_resource
|
||||
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
|
||||
|
||||
# TODO: Set thinking/ solution budget
|
||||
@@ -471,8 +471,8 @@ class InferenceConfig(BaseConfig):
|
||||
slurm: SlurmConfig | None = None
|
||||
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory for SLURM logs and generated scripts."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory for SLURM logs and generated scripts. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
@@ -22,7 +22,7 @@ from prime_rl.configs.shared import (
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import TokenizerConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
|
||||
class LoRAConfig(BaseConfig):
|
||||
@@ -491,8 +491,8 @@ class OrchestratorConfig(BaseConfig):
|
||||
rollout_transport: TransportConfig = ZMQTransportConfig()
|
||||
"""Transport used to ship rollouts from orchestrator to trainer."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
tasks_per_minute: int | None = Field(None, ge=1)
|
||||
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
|
||||
|
||||
@@ -41,7 +41,7 @@ from prime_rl.configs.trainer import (
|
||||
TokenizerConfig,
|
||||
TrainerConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
|
||||
from prime_rl.utils.validation import (
|
||||
propagate_shared_fields,
|
||||
validate_shared_ckpt_config,
|
||||
@@ -243,8 +243,8 @@ class RLConfig(BaseConfig):
|
||||
run: RunConfig = Field(default_factory=RunConfig)
|
||||
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory that groups related runs. Each run writes its artifacts to ``output_dir / run.name``."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory that groups related runs. Each run writes its artifacts to ``output_dir / run.name``. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
clean: bool = False
|
||||
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
|
||||
@@ -299,6 +299,10 @@ class RLConfig(BaseConfig):
|
||||
slurm: SlurmConfig | None = None
|
||||
"""SLURM configuration. If None, runs locally."""
|
||||
|
||||
dashboard: bool = True
|
||||
"""Make sure a local dashboard daemon serves this run's output dir (started on
|
||||
demand in interactive sessions; an already-running daemon's URL is logged)."""
|
||||
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
@@ -467,9 +471,6 @@ class RLConfig(BaseConfig):
|
||||
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
|
||||
"have no disk artifact to load from."
|
||||
)
|
||||
# The final version v{max_steps} is broadcast iff something consumes it:
|
||||
# training never samples from it, but a configured final eval measures it.
|
||||
broadcast_final = self.orchestrator.eval is not None
|
||||
if self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
inference_world_size = (
|
||||
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
|
||||
@@ -481,7 +482,6 @@ class RLConfig(BaseConfig):
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
broadcast_final=broadcast_final,
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
transport_config = dict(
|
||||
@@ -497,10 +497,10 @@ class RLConfig(BaseConfig):
|
||||
self.orchestrator.weight_broadcast = orchestrator_config_type(**common_config, **transport_config)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig(
|
||||
timeout=self.weight_broadcast.timeout, broadcast_final=broadcast_final
|
||||
timeout=self.weight_broadcast.timeout
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig(
|
||||
timeout=self.weight_broadcast.timeout, broadcast_final=broadcast_final
|
||||
timeout=self.weight_broadcast.timeout
|
||||
)
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
|
||||
@@ -33,7 +33,7 @@ from prime_rl.configs.trainer import (
|
||||
WeightBroadcastConfig,
|
||||
validate_scheduler,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
|
||||
|
||||
|
||||
class BaseDataConfig(BaseConfig):
|
||||
@@ -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``."""
|
||||
@@ -233,8 +232,8 @@ class SFTConfig(BaseConfig):
|
||||
run: RunConfig = Field(default_factory=RunConfig)
|
||||
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
clean: bool = False
|
||||
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
|
||||
@@ -285,6 +284,10 @@ class SFTConfig(BaseConfig):
|
||||
slurm: SlurmConfig | None = None
|
||||
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
|
||||
|
||||
dashboard: bool = True
|
||||
"""Make sure a local dashboard daemon serves this run's output dir (started on
|
||||
demand in interactive sessions; an already-running daemon's URL is logged)."""
|
||||
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
@@ -390,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:
|
||||
@@ -422,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
|
||||
|
||||
|
||||
@@ -42,12 +42,6 @@ class BaseWeightBroadcastConfig(BaseConfig):
|
||||
"""Timeout in seconds for the broadcast handshake and transfer. The trainer
|
||||
fails the run when no consumer acknowledges an offered version in time."""
|
||||
|
||||
broadcast_final: bool = True
|
||||
"""Internal - stamped by the RL/SFT launcher, never set by users: whether the
|
||||
trainer broadcasts the final version v{max_steps}. True iff something consumes
|
||||
it (a configured final eval) - training itself never samples from the final
|
||||
version."""
|
||||
|
||||
|
||||
class RunConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
|
||||
@@ -16,7 +16,7 @@ from prime_rl.configs.shared import (
|
||||
TransportConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
# -- Shared trainer configs (used by both SFT and RL trainers) --
|
||||
|
||||
@@ -619,8 +619,8 @@ class TrainerConfig(BaseConfig):
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
matmul_precision: Literal["highest", "high", "medium"] = "high"
|
||||
"""Precision for float32 matrix multiplications. ``highest`` is full FP32 (required on ROCm/AMD GPUs to avoid catastrophic precision loss in softmax over large vocabularies). ``high`` enables TF32 on NVIDIA GPUs for a speedup with minor precision tradeoff. See ``torch.set_float32_matmul_precision``."""
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -6,6 +7,11 @@ from pydantic_config import BaseConfig as BaseConfig # noqa: F401
|
||||
from pydantic_config import cli # noqa: F401
|
||||
|
||||
|
||||
def default_output_dir() -> Path:
|
||||
"""Default output directory: ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
return Path(os.environ.get("PRL_OUTPUT_DIR", "outputs"))
|
||||
|
||||
|
||||
def dump_resolved_config(config: BaseModel, exclude: set[str] | None = None) -> dict:
|
||||
"""Dump a resolved config for a machine-written JSON artifact.
|
||||
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "prime-rl"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
description = "Async RL Training at Scale"
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
@@ -22,6 +22,7 @@ dependencies = [
|
||||
"tenacity>=8.2.0",
|
||||
"openai>=1.106.1",
|
||||
"orjson>=3.11.0",
|
||||
"psutil>=7.0.0",
|
||||
"rich>=14.0.0",
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
@@ -41,7 +42,7 @@ trainer = "prime_rl.entrypoints.trainer:main"
|
||||
orchestrator = "prime_rl.entrypoints.orchestrator:main"
|
||||
evals = "prime_rl.entrypoints.evals:main"
|
||||
env-server = "prime_rl.entrypoints.env_server:main"
|
||||
dashboard = "prime_rl.dashboard.server:main"
|
||||
dashboard = "prime_rl.entrypoints.dashboard:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
|
||||
|
||||
@@ -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()
|
||||
@@ -47,6 +47,8 @@ def _qwen3_5_moe_vlm_config():
|
||||
tc.num_attention_heads = 4
|
||||
tc.num_key_value_heads = 2
|
||||
tc.head_dim = 64
|
||||
# mrope_section must sum to rotary_dim // 2 for the shrunken head_dim
|
||||
tc.rope_parameters["mrope_section"] = [3, 3, 2]
|
||||
tc.moe_intermediate_size = 128
|
||||
tc.shared_expert_intermediate_size = 128
|
||||
tc.num_experts = 4
|
||||
|
||||
@@ -17,7 +17,7 @@ uv run rl --model @ model.toml --data @ data.toml # nes
|
||||
uv run rl @ base.toml --trainer @ trainer.toml --trainer.lr 1e-3 # mixed
|
||||
```
|
||||
|
||||
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base.
|
||||
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base. `output_dir` has one extra fallback: CLI > config files > `$PRL_OUTPUT_DIR` > `"outputs"`.
|
||||
|
||||
Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max_model_len`).
|
||||
|
||||
@@ -25,7 +25,7 @@ Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max
|
||||
|
||||
```bash
|
||||
uv run rl --help # all fields and defaults
|
||||
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved configs (JSON) to /tmp/x/check/configs
|
||||
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved JSON to /tmp/x/check/configs/latest
|
||||
```
|
||||
|
||||
## Validators
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
---
|
||||
name: dashboard
|
||||
description: Find, start, use, and stop the local run dashboard for metrics, configs, traces, logs, and reports. Use when asked for its URL, to watch or inspect a run, to control the open dashboard, or to create a cited dashboard report explicitly requested by the user.
|
||||
---
|
||||
|
||||
# Run dashboard
|
||||
|
||||
`uv sync --extra dashboard && uv run dashboard [output_dir ...]` (default
|
||||
`outputs/`, or `$PRL_OUTPUT_DIR` if set) serves a web UI at `http://localhost:7788`. It only reads run
|
||||
dirs — safe against live runs — and installs anywhere (cluster head node,
|
||||
laptop against a mounted outputs dir): GPU dependencies live behind the
|
||||
`gpu` extra.
|
||||
|
||||
The Config and Logs views default to `latest (attempt <n>)`. Select an attempt
|
||||
to inspect the immutable config or log files from an earlier launch.
|
||||
|
||||
Every dashboard instance serves the dirs it was started with **plus** every dir
|
||||
in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`, re-read
|
||||
live). Launchers (`rl`, `sft`) register their output dir on every
|
||||
start and, in interactive sessions, auto-start a dashboard only when none is
|
||||
live — an already-running one absorbs the new dir automatically, whatever port
|
||||
it is on. `--no-dashboard` opts a run out; non-interactive launches (CI, nohup)
|
||||
register their dir but never spawn.
|
||||
|
||||
## Isolated mode
|
||||
|
||||
`--isolated` serves only the given dirs: no registry read or write, no
|
||||
discovery claim, and launchers ignore the instance. Use it for focused views
|
||||
(demos, debugging one run dir) or to keep a scratch dir out of the registry.
|
||||
|
||||
## Finding the live dashboard
|
||||
|
||||
The live port can differ from 7788 (a taken port bumps to the next free one),
|
||||
so read the discovery file:
|
||||
|
||||
```bash
|
||||
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
|
||||
curl -sf $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/runs > /dev/null && echo live
|
||||
ps aux | grep PRL::Dashboard # process title
|
||||
```
|
||||
|
||||
Hand the researcher the `url` from `daemon.json`. Launcher logs also print it:
|
||||
startup ends with a `Dashboard · <url>` banner. The auto-started instance logs
|
||||
to `~/.cache/prime-rl/dashboard/daemon.log`.
|
||||
|
||||
## Stopping / restarting
|
||||
|
||||
```bash
|
||||
kill $(jq -r .pid ~/.cache/prime-rl/dashboard/daemon.json) # the discovered instance
|
||||
pkill -f PRL::Dashboard # every dashboard on the host
|
||||
```
|
||||
|
||||
A clean exit releases `daemon.json`; a stale file from a dead process is taken
|
||||
over by the next start. Killing a dashboard never affects runs (it only reads),
|
||||
and killing a run never takes the dashboard down (it runs in its own session).
|
||||
Restart by launching any run, or directly: `uv run dashboard`.
|
||||
|
||||
## Point the open dashboard
|
||||
|
||||
Use `POST /api/view` to show relevant run data in every connected dashboard
|
||||
tab:
|
||||
|
||||
```bash
|
||||
curl -sS -X POST $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/view \
|
||||
-H 'content-type: application/json' -d '{
|
||||
"run": "demo-rl", "tab": "traces",
|
||||
"step": 0, "kind": "train", "subset": "effective",
|
||||
"episode": "ep-s00-reverse-text-0",
|
||||
"highlight": [{"node": 3, "quote": "hint: reverse the words", "reason": "tool result the policy conditioned on"}]
|
||||
}'
|
||||
```
|
||||
|
||||
`run` is required; other fields are optional and leave unspecified UI state
|
||||
unchanged. For trace evidence, supply `step`, `kind`, and `subset` together and
|
||||
address the episode by stable `id`. Use optional `trace` and `branch` indices
|
||||
for multi-agent traces and `highlight` entries shaped as `{node, quote,
|
||||
reason, field?}`. On `409`, tell the user to open the returned `url`; the stored
|
||||
command applies when the tab connects.
|
||||
|
||||
## Write a report only when asked
|
||||
|
||||
Create a report only when the user explicitly asks for one. Otherwise answer
|
||||
normally; use `/api/view` when showing trace evidence would help.
|
||||
|
||||
Write requested reports to `<run>/reports/<slug>.md`, then POST `{"run": ...,
|
||||
"tab": "report", "report": "<slug>"}`. Use Markdown with a frontmatter
|
||||
`title` and one-line JSON citation definitions:
|
||||
|
||||
```markdown
|
||||
---
|
||||
title: Why does reward dip at step 4?
|
||||
---
|
||||
|
||||
The dip is provider errors, not policy regression [^err].
|
||||
|
||||
[^err]: {"step": 4, "kind": "train", "subset": "all", "episode": "ep-...", "node": 0, "quote": "engine overloaded", "note": "The failed call that emptied this step's batch."}
|
||||
```
|
||||
|
||||
The frontmatter `title` is rendered as the report H1; do not repeat it with a
|
||||
Markdown `#` heading. The inline renderer supports only HTTP(S) and anchor
|
||||
links. Relative Markdown links render as literal text, so identify local source
|
||||
files with inline code paths or link to a supported HTTP endpoint.
|
||||
|
||||
Each citation requires `step`, `kind`, `subset`, `episode`, `quote`, and `note`.
|
||||
Use the top-level rollout record `id` returned by the dashboard episode-list
|
||||
API—not a nested `traces[*].id`, and never `line`. Copy a short, distinctive
|
||||
quote exactly; matching is case-sensitive and whitespace-insensitive. Keep
|
||||
`note` to 1–2 sentences explaining why the quote supports the claim.
|
||||
|
||||
Cite major empirical, comparative, and diagnostic conclusions, but not routine
|
||||
explanation. Use exact trace citations for trajectory-level claims. For
|
||||
aggregate statistics, identify the run and source file; do not imply that one
|
||||
example trajectory proves the aggregate.
|
||||
|
||||
Use adjacent markers (`[^a] [^b]`) only when one claim genuinely depends on
|
||||
distinct passages, such as a comparison or corroboration. Use one citation
|
||||
when one passage is sufficient.
|
||||
|
||||
Optional fields are `run`, `trace`, `branch`, `node`, `field`, `prefix`, and
|
||||
`suffix`. Use `field: "content"` or `"reasoning"` only to disambiguate message
|
||||
parts. Use verbatim adjacent `prefix`/`suffix` only when a quote repeats.
|
||||
Ambiguous or mismatched citations remain broken and do not navigate.
|
||||
|
||||
Use Markdown; raw HTML is escaped.
|
||||
|
||||
Before handoff, reload the report and verify through the dashboard API that
|
||||
every referenced citation resolves uniquely to its episode, node, and quote.
|
||||
Confirm zero broken citations, one rendered title, and no unsupported relative
|
||||
links.
|
||||
@@ -9,7 +9,7 @@ description: Monitor an ongoing prime-rl training run — find the output direct
|
||||
|
||||
### On launch
|
||||
|
||||
1. Find the run dir and read the resolved configs at `{run_dir}/configs/resolved/` (start with `rl.json`, or `orchestrator.json` on local runs). The launch TOML is copied verbatim to `{run_dir}/configs/rl.toml`. The run dir is `{output_dir}/{run_name}` — `run.name` auto-generates as `<envs>--<model>--<short-id>`, so if you only know the output dir, pick the most recently modified subdirectory (`ls -t {output_dir} | head -1`) or read `run.name` from the launch command.
|
||||
1. Find the run dir and read the resolved configs at `{run_dir}/configs/latest/resolved/` (start with `rl.json`, or `orchestrator.json` on local runs). The launch TOML is copied verbatim to `{run_dir}/configs/latest/rl.toml`. The run dir is `{output_dir}/{run_name}` — `run.name` auto-generates as `<envs>--<model>--<short-id>`, so if you only know the output dir, pick the most recently modified subdirectory (`ls -t {output_dir} | head -1`) or read `run.name` from the launch command.
|
||||
2. Confirm all processes are alive and the run is making progress.
|
||||
3. Write the initial summary into `{run_dir}/STATUS.md`.
|
||||
|
||||
@@ -48,15 +48,15 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
|
||||
|
||||
### Where to find things
|
||||
|
||||
- `{run_dir}/configs/` — the launch TOML copied verbatim (`rl.toml`/`sft.toml`), plus `resolved/` with the per-component resolved configs, written as JSON so explicit None settings round-trip.
|
||||
- `{run_dir}/configs/latest/` — the current attempt's launch TOML and `resolved/` JSON files. Each launch stays under `configs/attempt_<n>/`.
|
||||
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
|
||||
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved episodes (see Episodes below).
|
||||
- `{run_dir}/rollouts/step_{n}/{train,eval}/` — saved episodes (see Episodes below).
|
||||
|
||||
### Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`; several dirs can be tracked at
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR` if set; several dirs can be tracked at
|
||||
once) serves a local web dashboard at `http://localhost:7788` with four views per run:
|
||||
metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved config
|
||||
metrics (the W&B overview sections, read from `metrics.jsonl`), per-attempt config
|
||||
files, a rollout trace viewer with a per-token advantage/logprob view, and merged
|
||||
component logs. It only reads the run dirs — safe to run against a live run.
|
||||
`--port`/`--host` pick the bind address; a taken port automatically bumps to the next
|
||||
@@ -64,13 +64,25 @@ free one, so several dashboards run side by side without coordination. GPU deps
|
||||
behind the `gpu` extra, so `uv sync --extra dashboard && uv run dashboard` works
|
||||
without the training stack (e.g. on a head node).
|
||||
|
||||
**Daemon (auto-start)**: launchers auto-start one dashboard per host per user and a
|
||||
live one absorbs each new run's output dir automatically — see the `dashboard` skill
|
||||
for discovery, kill/restart commands, and `--isolated`. The short version: the live
|
||||
port can differ from 7788 (a taken port bumps), so read the discovery file:
|
||||
|
||||
```bash
|
||||
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
|
||||
ps aux | grep PRL::Dashboard # the daemon's process title
|
||||
```
|
||||
|
||||
Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`.
|
||||
|
||||
### Logs
|
||||
|
||||
```
|
||||
{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)
|
||||
@@ -81,6 +93,8 @@ without the training stack (e.g. on a head node).
|
||||
└── envs/{train,eval}/{env_name}.log # one log file per env
|
||||
```
|
||||
|
||||
SLURM batch logs are under `{run_dir}/launcher/logs/*job_*.log`.
|
||||
|
||||
Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough. Drop into per-node or per-rank logs only when debugging. All logs are loguru with `HH:mm:ss LEVEL message`; levels: `DEBUG`, `INFO`, `SUCCESS`, `WARNING`, `ERROR`.
|
||||
|
||||
Scan for problems:
|
||||
@@ -148,8 +162,8 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
|
||||
### Episodes
|
||||
|
||||
```
|
||||
{run_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per episode as it completes
|
||||
{run_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
{run_dir}/rollouts/step_{n}/{train,eval}/all/traces.jsonl # appended per episode as it completes
|
||||
{run_dir}/rollouts/step_{n}/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
```
|
||||
|
||||
JSONL files of native `vf.Episode` records (training tensors excluded), one line per episode.
|
||||
@@ -168,7 +182,7 @@ jq '.traces[].rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.ok | not) | {id, env: .env.id, errors}' {run_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
```
|
||||
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
|
||||
|
||||
### Common failure modes
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ description: How to launch prime-rl training runs — the `rl`, `sft`, `inferenc
|
||||
|
||||
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
|
||||
|
||||
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory. Every launch writes configs under `configs/attempt_<n>/`; `configs/latest` points to the current attempt.
|
||||
|
||||
## Run directories
|
||||
|
||||
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, broadcasts, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
|
||||
@@ -43,6 +45,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
|
||||
- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
|
||||
- SLURM: single- and multi-node
|
||||
- Multi-node SLURM stops after `.trainer.done` for trainer-only fake-data runs. Runs with inference stop after both `.trainer.done` and `.orchestrator.done`.
|
||||
- Environment packages: before launching a config with a non-core verifier env id,
|
||||
verify the package imports under `uv run` (for example
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
|
||||
@@ -66,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
|
||||
|
||||
@@ -119,11 +123,15 @@ 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`)
|
||||
|
||||
## Exporting checkpoints
|
||||
|
||||
Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`). Convert to HF safetensors with `uv run python tools/convert_dcp_to_bf16.py <run_dir>/checkpoints/step_{n}` (writes `<ckpt_dir>/weights`, serveable via `uv run inference --vllm.model <dir>`; model config auto-read from the run’s `configs/latest/resolved/trainer.json`/`sft.json`; multi-rank via `torchrun --nproc-per-node N`; full fine-tunes only, LoRA rejected). Quantize a bf16 HF dir to blockwise FP8 with `tools/convert_bf16_to_fp8.py <dir>` (vLLM-native format), or straight from a checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (rank-parallel, writes only `<ckpt_dir>/weights-FP8`, no bf16 on disk); dequantize fp8-only releases with `tools/convert_fp8_to_bf16.py <dir>`. Caveat: on SM120 GPUs (RTX PRO 6000) vLLM 0.26 picks `CutlassFp8BlockScaledMMKernel` for blockwise-fp8 checkpoints and it silently degrades outputs — serve with `VLLM_DISABLED_KERNELS=CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel` to fall back to the Triton kernel.
|
||||
|
||||
## Summary
|
||||
|
||||
| Command | Purpose | Typical use |
|
||||
@@ -139,3 +147,11 @@ env.agent.runtime.type = "subprocess"
|
||||
- `packages/prime-rl-configs/src/prime_rl/configs/` — all config classes
|
||||
- `configs/debug/` — minimal debug configs
|
||||
- `examples/` — full example configs (e.g. `reverse-text/`)
|
||||
|
||||
## Dashboard
|
||||
|
||||
Interactive launches auto-start one shared dashboard daemon per user (process title
|
||||
`PRL::Dashboard`) and end startup with a `Dashboard · <url>` banner. Relay
|
||||
that URL to the researcher. Discovery: `~/.cache/prime-rl/dashboard/daemon.json` holds
|
||||
the live `url` (the port can differ from 7788 when it was taken). `--no-dashboard`
|
||||
opts a run out.
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
# Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
|
||||
directories (metrics, resolved configs, rollout traces, component logs) at
|
||||
http://localhost:7788. Needs the `dashboard` extra.
|
||||
directories (metrics, resolved configs, rollout traces, cited reports,
|
||||
component logs) at
|
||||
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,
|
||||
kill/restart commands, and the local view-command/report contract.
|
||||
|
||||
The Config and Logs views keep each launch attempt available. Both views open
|
||||
at `latest (attempt <n>)` and let you select an earlier attempt.
|
||||
|
||||
GPU dependencies live behind the `gpu` extra, so this works anywhere — a
|
||||
cluster head node, a laptop against a mounted outputs dir:
|
||||
@@ -11,6 +21,14 @@ cluster head node, a laptop against a mounted outputs dir:
|
||||
uv sync --extra dashboard && uv run dashboard [output_dir ...]
|
||||
```
|
||||
|
||||
The trace viewer's **Messages** mode keeps structured `message.content` and
|
||||
`trace.tools` visibly separate. **Rendered** decodes each selected branch's
|
||||
recorded post-renderer `token_ids` as one sequence, retaining special tokens;
|
||||
it never reconstructs a chat template. The recorded IDs remain the source of
|
||||
truth, and the viewer reports when IDs, the renderer model, or its tokenizer
|
||||
are unavailable. Text, advantage, logprob, mask, and content signals apply to
|
||||
both views; Rendered with Text uses the exact full-sequence decode.
|
||||
|
||||
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
|
||||
The integration suite covers it end to end (`tests/integration/dashboard_smoke.py`
|
||||
runs after every integration test).
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+1382
-181
File diff suppressed because it is too large
Load Diff
@@ -23,8 +23,10 @@
|
||||
<button data-tab="config">Config</button>
|
||||
<button data-tab="metrics" class="active">Metrics</button>
|
||||
<button data-tab="traces">Traces</button>
|
||||
<button data-tab="report">Report</button>
|
||||
<button data-tab="logs">Logs</button>
|
||||
</nav>
|
||||
<label class="toggle" title="apply agent view commands as they arrive"><input type="checkbox" id="follow-toggle" checked><span class="dot"></span>follow</label>
|
||||
<label class="toggle" title="poll for updates"><input type="checkbox" id="live-toggle" checked><span class="dot"></span>live</label>
|
||||
</header>
|
||||
|
||||
@@ -53,6 +55,8 @@
|
||||
|
||||
<section id="tab-config" hidden>
|
||||
<div class="controls">
|
||||
<label class="t-label">attempt</label>
|
||||
<select id="config-attempt-select"></select>
|
||||
<div class="seg" id="config-format">
|
||||
<button data-fmt="toml">TOML</button>
|
||||
<button data-fmt="json">JSON</button>
|
||||
@@ -71,16 +75,6 @@
|
||||
<span id="step-label" class="t-label"></span>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<div class="seg" id="trace-kind">
|
||||
<button data-kind="train" class="active">Train</button>
|
||||
<button data-kind="eval">Eval</button>
|
||||
</div>
|
||||
<div class="seg" id="trace-subset">
|
||||
<button data-subset="all">All</button>
|
||||
<button data-subset="effective" class="active">Effective</button>
|
||||
</div>
|
||||
<span id="trace-status" class="muted"></span>
|
||||
<div class="spacer"></div>
|
||||
<div id="trace-filter-wrap" class="dd-wrap">
|
||||
<button id="trace-filter-btn" class="btn dd-btn" title="filter & sort">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
|
||||
@@ -102,8 +96,16 @@
|
||||
<label class="toggle"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="seg" id="trace-kind">
|
||||
<button data-kind="train" class="active">Train</button>
|
||||
<button data-kind="eval">Eval</button>
|
||||
</div>
|
||||
<div class="seg" id="trace-subset">
|
||||
<button data-subset="all">All</button>
|
||||
<button data-subset="effective" class="active">Effective</button>
|
||||
</div>
|
||||
<span id="trace-status" class="muted"></span>
|
||||
</div>
|
||||
<div id="trace-empty" hidden></div>
|
||||
<div id="episode-table-wrap">
|
||||
<table id="episode-table">
|
||||
<thead><tr>
|
||||
@@ -115,6 +117,17 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="tab-report" hidden>
|
||||
<div class="controls">
|
||||
<label class="t-label">report</label>
|
||||
<select id="report-select"></select>
|
||||
<span id="report-verify" class="muted"></span>
|
||||
<div class="spacer"></div>
|
||||
<span id="report-status" class="muted"></span>
|
||||
</div>
|
||||
<div id="report-wrap"><article id="report-body"></article></div>
|
||||
</section>
|
||||
|
||||
<section id="tab-logs" hidden>
|
||||
<div class="controls">
|
||||
<label class="t-label">attempt</label>
|
||||
@@ -147,11 +160,36 @@
|
||||
<span id="tm-step-label"></span>
|
||||
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
|
||||
</div>
|
||||
<div class="tm-head tm-filterhead">
|
||||
<div class="tm-head tm-ctlrow">
|
||||
<div id="tm-filter-wrap" class="dd-wrap">
|
||||
<button id="tm-filter-btn" class="btn dd-btn" title="filter & sort">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
|
||||
filter
|
||||
</button>
|
||||
<div id="tm-filter-menu" class="dd-menu" hidden>
|
||||
<label class="t-label">env</label>
|
||||
<select id="tm-env"><option value="">all envs</option></select>
|
||||
<label class="t-label">sort</label>
|
||||
<select id="tm-sort">
|
||||
<option value="line:asc">order: arrival</option>
|
||||
<option value="reward:desc">reward ↓</option>
|
||||
<option value="reward:asc">reward ↑</option>
|
||||
<option value="advantage:desc">advantage ↓</option>
|
||||
<option value="advantage:asc">advantage ↑</option>
|
||||
<option value="output_tokens:desc">tokens ↓</option>
|
||||
<option value="group:asc">group</option>
|
||||
</select>
|
||||
<label class="toggle"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tm-head tm-ctlrow" id="tm-kind-row">
|
||||
<div class="seg" id="tm-kind">
|
||||
<button data-kind="train">Train</button>
|
||||
<button data-kind="eval">Eval</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tm-head tm-ctlrow" id="tm-subset-row">
|
||||
<div class="seg" id="tm-subset">
|
||||
<button data-subset="all">All</button>
|
||||
<button data-subset="effective">Effective</button>
|
||||
@@ -160,22 +198,28 @@
|
||||
<div class="tm-head">
|
||||
<span class="t-label">episodes</span>
|
||||
<span id="tm-count" class="badge"></span>
|
||||
<div class="spacer"></div>
|
||||
<button id="tm-prev" class="btn tm-nav" title="previous episode">↑</button>
|
||||
<button id="tm-next" class="btn tm-nav" title="next episode">↓</button>
|
||||
</div>
|
||||
<div id="tm-list"></div>
|
||||
</aside>
|
||||
<section id="tm-main">
|
||||
<div class="tm-head">
|
||||
<span class="tm-title">Trace Viewer</span>
|
||||
<button id="tm-back" class="btn" hidden title="back to the report">← report</button>
|
||||
<div class="seg" id="tm-view">
|
||||
<button data-view="transcript" class="active">Transcript</button>
|
||||
<button data-view="timeline">Timeline</button>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<select id="token-signal">
|
||||
<option value="">text view</option>
|
||||
<option value="advantage">tokens: advantage</option>
|
||||
<option value="logprob">tokens: logprob</option>
|
||||
<option value="mask">tokens: mask</option>
|
||||
<option value="is_content">tokens: is_content</option>
|
||||
<div class="seg" id="trace-view-mode">
|
||||
<button data-mode="messages" class="active">Messages</button>
|
||||
<button data-mode="rendered">Rendered</button>
|
||||
</div>
|
||||
<select id="token-signal" title="Choose the token signal for either view. Text is uncolored; other options color recorded tokens by advantage, log probability, training mask, or message-content membership.">
|
||||
<option value="">Text</option>
|
||||
<option value="advantage">Advantage</option>
|
||||
<option value="logprob">Logprob</option>
|
||||
<option value="mask">Mask</option>
|
||||
<option value="is_content">Content</option>
|
||||
</select>
|
||||
<button id="tm-collapse" class="btn">collapse</button>
|
||||
<button id="tm-expand" class="btn">expand</button>
|
||||
@@ -186,6 +230,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>
|
||||
|
||||
@@ -570,6 +570,8 @@ mark.hit {
|
||||
#step-blocks { flex: 1; display: flex; gap: 2px; height: 16px; min-width: 0; margin-bottom: 4px; }
|
||||
.sb-cell { position: relative; flex: 1; min-width: 0; background: var(--grey-2); border: 1px solid var(--hairline); cursor: pointer; }
|
||||
.sb-cell:hover { border-color: var(--grey-6); }
|
||||
.sb-cell.placeholder { cursor: default; }
|
||||
.sb-cell.placeholder:hover { border-color: var(--hairline); }
|
||||
.sb-cell.on { background: var(--accent); border-color: var(--accent); }
|
||||
/* eval steps carry a small dot under the block (same mark as the step label) */
|
||||
.sb-cell.eval::after {
|
||||
@@ -613,6 +615,9 @@ mark.hit {
|
||||
#episode-table td { padding: 5px 10px; border-bottom: 1px solid var(--hairline-faint); white-space: nowrap; }
|
||||
#episode-table tbody tr { cursor: pointer; }
|
||||
#episode-table tbody tr:hover { background: var(--grey-2); }
|
||||
#episode-table tr.empty { cursor: default; }
|
||||
#episode-table tr.empty:hover { background: none; }
|
||||
#episode-table tr.empty td { border-bottom: 0; }
|
||||
.r-pos { color: var(--positive); }
|
||||
.r-neg { color: var(--negative); }
|
||||
.r-zero { color: var(--grey-4); }
|
||||
@@ -638,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; }
|
||||
@@ -659,13 +670,14 @@ mark.hit {
|
||||
.tm-item .tm-reward { flex-shrink: 0; }
|
||||
.tm-item:hover { background: var(--grey-2); }
|
||||
.tm-item.active { background: var(--grey-2); border-color: var(--grey-3); color: var(--grey-6); }
|
||||
.tm-item.err { background: rgba(255, 69, 57, 0.08); border-color: var(--negative); }
|
||||
.tm-item.err:hover, .tm-item.err.active { background: rgba(255, 69, 57, 0.16); }
|
||||
.tm-item .tm-reward { margin-left: auto; }
|
||||
.tm-nav { padding: 0 8px; height: 24px; }
|
||||
.tm-stephead { justify-content: space-between; background: var(--grey-2); min-height: 40px; }
|
||||
#step-label, #tm-step-label { white-space: nowrap; }
|
||||
#tm-step-label { color: var(--grey-6); }
|
||||
.tm-filterhead { gap: 8px; }
|
||||
.tm-filterhead .seg button { height: 22px; padding: 0 9px; font-size: 10px; }
|
||||
.tm-ctlrow { min-height: 0; padding: 8px 14px; }
|
||||
#tm-step-label {
|
||||
font-size: 11px;
|
||||
letter-spacing: var(--track-caps);
|
||||
@@ -678,10 +690,112 @@ mark.hit {
|
||||
#tm-step-label .muted { text-transform: none; letter-spacing: var(--track-mono); }
|
||||
|
||||
#tm-main { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
|
||||
#tm-messages { flex: 1; overflow-y: auto; padding: 14px 16px; }
|
||||
#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);
|
||||
background: rgba(255, 69, 57, 0.08);
|
||||
color: var(--grey-6);
|
||||
}
|
||||
.trace-error-banner + .trace-error-banner { margin-top: 8px; }
|
||||
.trace-error-message { padding: 10px 12px; font-size: 12px; white-space: pre-wrap; word-break: break-word; }
|
||||
.trace-error-type { font-weight: 500; color: var(--negative); }
|
||||
.trace-error-tb > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 12px;
|
||||
border-top: 1px solid rgba(255, 69, 57, 0.2);
|
||||
color: var(--grey-4);
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.trace-error-tb > summary:hover { color: var(--grey-6); }
|
||||
.trace-error-tb[open] .entry-chev { transform: rotate(90deg); }
|
||||
.trace-error-tb > pre {
|
||||
margin: 0;
|
||||
padding: 10px 12px;
|
||||
border-top: 1px solid rgba(255, 69, 57, 0.2);
|
||||
color: var(--grey-5);
|
||||
font: 400 11px/1.5 var(--font-mono);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
/* numbered collapsible message entries */
|
||||
details.entry { border: 1px solid var(--hairline); margin-bottom: 8px; }
|
||||
details.entry > summary {
|
||||
@@ -749,6 +863,43 @@ details.sub > summary {
|
||||
details.sub .sub-name { font-weight: 500; color: var(--grey-6); }
|
||||
details.sub > .entry-body { border-top: 1px solid var(--hairline); }
|
||||
|
||||
/* tool definitions are model context, but deliberately sit outside numbered messages */
|
||||
details.tool-definitions, details.rendered-transcript {
|
||||
border: 1px solid var(--grey-3);
|
||||
margin-bottom: 12px;
|
||||
background: rgba(183, 166, 250, 0.025);
|
||||
}
|
||||
details.tool-definitions > summary, details.rendered-transcript > summary,
|
||||
details.tool-definition > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
padding: 7px 12px;
|
||||
background: var(--grey-2);
|
||||
}
|
||||
details.tool-definitions[open] > summary, details.rendered-transcript[open] > summary,
|
||||
details.tool-definition[open] > summary { border-bottom: 1px solid var(--hairline); }
|
||||
details.tool-definitions[open] > summary .entry-chev,
|
||||
details.rendered-transcript[open] > summary .entry-chev,
|
||||
details.tool-definition[open] > summary .entry-chev { transform: rotate(90deg); }
|
||||
.context-label, .tool-def-name { color: var(--chart-2); font-size: 10px; font-weight: 500; letter-spacing: var(--track-caps); text-transform: uppercase; }
|
||||
details.tool-definition { margin: 8px 12px; border: 1px solid var(--hairline); }
|
||||
.tool-description { padding: 10px 12px; color: var(--grey-5); font-size: 12px; white-space: pre-wrap; word-break: break-word; }
|
||||
.schema-head { display: flex; align-items: center; padding: 6px 12px; border-top: 1px solid var(--hairline); color: var(--grey-4); font-size: 10px; letter-spacing: var(--track-caps); text-transform: uppercase; }
|
||||
.schema-head .icon-btn { margin-left: auto; }
|
||||
.tool-schema, .rendered-text {
|
||||
margin: 0;
|
||||
padding: 12px 14px;
|
||||
overflow: auto;
|
||||
color: var(--grey-5);
|
||||
font: 400 11px/1.55 var(--font-mono);
|
||||
tab-size: 2;
|
||||
}
|
||||
.tool-schema { max-height: 380px; border-top: 1px solid var(--hairline); white-space: pre; }
|
||||
.rendered-text { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
#trace-view-mode button { white-space: nowrap; }
|
||||
|
||||
/* right pane: overview metadata */
|
||||
.tm-reward-big { color: var(--positive); }
|
||||
.tm-reward-big.neg { color: var(--negative); }
|
||||
@@ -801,3 +952,114 @@ pre.json { background: var(--grey-2); border: 1px solid var(--hairline); padding
|
||||
::-webkit-scrollbar-thumb { background: var(--grey-3); }
|
||||
::-webkit-scrollbar-thumb:hover { background: var(--grey-4); }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
/* ---------------------------------------------------------------- report */
|
||||
/* two toggles share the topbar: only the first one pushes right */
|
||||
#topbar .toggle + .toggle { margin-left: 0; }
|
||||
|
||||
#report-wrap { flex: 1; min-height: 0; overflow-y: auto; }
|
||||
#report-body {
|
||||
max-width: 820px;
|
||||
margin: 0 auto;
|
||||
padding: 8px 0 80px;
|
||||
font-size: 13px;
|
||||
line-height: 1.7;
|
||||
color: var(--grey-5);
|
||||
}
|
||||
#report-body h1, #report-body h2, #report-body h3, #report-body h4, #report-body h5, #report-body h6 {
|
||||
color: var(--grey-6);
|
||||
font-weight: 400;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
margin: 28px 0 10px;
|
||||
}
|
||||
#report-body h1 { font-size: 16px; }
|
||||
#report-body h2 { font-size: 13px; border-bottom: 1px solid var(--hairline); padding-bottom: 6px; }
|
||||
#report-body h3, #report-body h4, #report-body h5, #report-body h6 { font-size: 11px; color: var(--grey-5); }
|
||||
#report-body .report-title { margin-top: 8px; }
|
||||
#report-body p { margin: 10px 0; }
|
||||
#report-body hr { border: none; border-top: 1px solid var(--hairline); margin: 20px 0; }
|
||||
#report-body ul, #report-body ol { margin: 10px 0; padding-left: 22px; }
|
||||
#report-body li { margin: 4px 0; }
|
||||
#report-body blockquote {
|
||||
margin: 12px 0;
|
||||
padding: 2px 14px;
|
||||
border-left: 2px solid var(--grey-3);
|
||||
color: var(--grey-4);
|
||||
}
|
||||
#report-body code { background: var(--grey-2); padding: 1px 5px; font-size: 12px; color: var(--grey-6); }
|
||||
#report-body .md-code {
|
||||
background: var(--grey-2);
|
||||
border: 1px solid var(--hairline);
|
||||
padding: 12px 14px;
|
||||
overflow-x: auto;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
margin: 12px 0;
|
||||
}
|
||||
#report-body .md-code code { background: none; padding: 0; color: var(--grey-5); }
|
||||
#report-body a { color: var(--infra); text-decoration: none; }
|
||||
#report-body a:hover { text-decoration: underline; }
|
||||
#report-body strong { color: var(--grey-6); font-weight: 600; }
|
||||
.md-table-wrap { overflow-x: auto; margin: 12px 0; }
|
||||
.md-table { border-collapse: collapse; font-size: 12px; width: 100%; }
|
||||
.md-table th, .md-table td { border: 1px solid var(--hairline); padding: 6px 10px; text-align: left; }
|
||||
.md-table th {
|
||||
color: var(--grey-4);
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
/* citation chips: numbered, colored by verification against the trace files */
|
||||
.cite-chip {
|
||||
display: inline-block;
|
||||
min-width: 16px;
|
||||
padding: 0 4px;
|
||||
margin: 0 1px;
|
||||
text-align: center;
|
||||
font-size: 10px;
|
||||
line-height: 15px;
|
||||
border: 1px solid var(--grey-3);
|
||||
color: var(--grey-5);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
vertical-align: super;
|
||||
}
|
||||
.cite-chip:hover { border-color: var(--grey-6); color: var(--grey-6); }
|
||||
.cite-chip.ok { border-color: rgba(182, 255, 60, 0.5); color: var(--accent); }
|
||||
.cite-chip.bad, .cite-chip.missing { border-color: rgba(255, 69, 57, 0.6); color: var(--negative); }
|
||||
|
||||
/* agent highlights inside the trace viewer; the citation note rides the mark
|
||||
as a hover tooltip */
|
||||
mark.hl-quote {
|
||||
background: rgba(182, 255, 60, 0.22);
|
||||
color: var(--grey-6);
|
||||
outline: 1px solid rgba(182, 255, 60, 0.45);
|
||||
}
|
||||
mark.hl-quote[data-tip] { cursor: help; }
|
||||
.tok-tip.note { max-width: 420px; white-space: normal; }
|
||||
details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pulse 1.6s ease-out 2; }
|
||||
@keyframes hl-pulse {
|
||||
0% { box-shadow: 0 0 0 0 rgba(182, 255, 60, 0.45); }
|
||||
70% { box-shadow: 0 0 0 6px rgba(182, 255, 60, 0); }
|
||||
100% { box-shadow: 0 0 0 0 rgba(182, 255, 60, 0); }
|
||||
}
|
||||
|
||||
/* agent view-command toast (shown when follow is off, or on errors) */
|
||||
#view-toast {
|
||||
position: fixed;
|
||||
right: 16px;
|
||||
bottom: 16px;
|
||||
z-index: 70;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
padding: 10px 12px;
|
||||
max-width: 60vw;
|
||||
font-size: 12px;
|
||||
}
|
||||
#view-toast .toast-text { color: var(--grey-6); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Launcher-side dashboard auto-start.
|
||||
|
||||
Every launcher registers its output dir in a shared registry and makes sure one
|
||||
dashboard is running: every dashboard instance serves its own dirs plus the
|
||||
registry (re-read live), so each new run shows up on one URL - one dashboard
|
||||
per host per user. If a live daemon already exists, its URL is reused instead
|
||||
of starting another. Discovery goes through
|
||||
``~/.cache/prime-rl/dashboard/daemon.json`` (pid + actual url), which survives
|
||||
port spillover. The daemon also carries the process title ``PRL::Dashboard``.
|
||||
|
||||
Kept free of ``dashboard``-extra imports on purpose: the launcher must work
|
||||
without the extra (then it registers the dir and points at the missing extra
|
||||
instead of spawning). ``main`` is the ``dashboard`` console script, delegating
|
||||
to the actual server.
|
||||
"""
|
||||
|
||||
import fcntl
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.utils.pathing import CACHE_DIR
|
||||
|
||||
STATE_DIR = CACHE_DIR / "dashboard"
|
||||
DAEMON_FILE = STATE_DIR / "daemon.json"
|
||||
DIRS_FILE = STATE_DIR / "dirs.json"
|
||||
DAEMON_LOG = STATE_DIR / "daemon.log"
|
||||
SPAWN_TIMEOUT_S = 10.0
|
||||
|
||||
|
||||
@contextmanager
|
||||
def registry_lock():
|
||||
"""Serialize read-modify-write cycles on the shared registry files: concurrent
|
||||
launchers (or dashboard starts) must not drop each other's entries."""
|
||||
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with open(STATE_DIR / ".lock", "w") as lock_file:
|
||||
fcntl.flock(lock_file, fcntl.LOCK_EX)
|
||||
yield
|
||||
|
||||
|
||||
def register_output_dir(output_dir: Path) -> None:
|
||||
"""Add the dir to the daemon's registry (idempotent, atomic)."""
|
||||
with registry_lock():
|
||||
try:
|
||||
dirs = json.loads(DIRS_FILE.read_text())
|
||||
except (OSError, ValueError):
|
||||
dirs = []
|
||||
entry = str(output_dir.resolve())
|
||||
if entry in dirs:
|
||||
return
|
||||
dirs.append(entry)
|
||||
tmp = DIRS_FILE.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(dirs))
|
||||
tmp.replace(DIRS_FILE)
|
||||
|
||||
|
||||
def find_daemon(timeout: float = 1.0) -> dict | None:
|
||||
"""The live daemon's record ({pid, url, ...}), or None."""
|
||||
try:
|
||||
info = json.loads(DAEMON_FILE.read_text())
|
||||
os.kill(info["pid"], 0)
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return None
|
||||
try:
|
||||
with urllib.request.urlopen(f"{info['url']}/api/runs", timeout=timeout):
|
||||
return info
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def ensure_dashboard(output_dir: Path, logger) -> str | None:
|
||||
"""Register the run's output dir and make sure one dashboard daemon serves it.
|
||||
|
||||
Returns the dashboard URL (log it with ``log_dashboard_url``), or None when no
|
||||
daemon could be found or started (missing extra, non-interactive session, or
|
||||
startup failure).
|
||||
"""
|
||||
# The dir may not exist yet on a first run: create it up front, because the
|
||||
# daemon only serves registered dirs that exist (and refuses to start with none).
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
register_output_dir(output_dir)
|
||||
daemon = find_daemon()
|
||||
if daemon is not None:
|
||||
return daemon["url"]
|
||||
if not sys.stdout.isatty():
|
||||
logger.warning("Non-interactive session - not auto-starting a dashboard (the output dir stays registered)")
|
||||
return None
|
||||
# The console script exists even without the extra, so check the actual imports.
|
||||
if importlib.util.find_spec("fastapi") is None or importlib.util.find_spec("uvicorn") is None:
|
||||
logger.warning("Dashboard extra not installed - install with `uv sync --extra dashboard`")
|
||||
return None
|
||||
binary = shutil.which("dashboard")
|
||||
if binary is None:
|
||||
logger.warning("Dashboard entry point not found - install with `uv sync --extra dashboard`")
|
||||
return None
|
||||
with open(DAEMON_LOG, "ab") as log_file:
|
||||
process = subprocess.Popen([binary], stdout=log_file, stderr=log_file, start_new_session=True)
|
||||
deadline = time.monotonic() + SPAWN_TIMEOUT_S
|
||||
while time.monotonic() < deadline:
|
||||
daemon = find_daemon()
|
||||
if daemon is not None:
|
||||
return daemon["url"]
|
||||
if process.poll() is not None:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
logger.warning(f"Dashboard daemon did not come up - see {DAEMON_LOG}")
|
||||
return None
|
||||
|
||||
|
||||
def log_dashboard_url(logger, url: str | None) -> None:
|
||||
"""Banner pointing at the dashboard - meant as the launcher's last startup log."""
|
||||
if url is None:
|
||||
return
|
||||
logger.opt(raw=True, colors=True).info(f"\n <b>Dashboard</b> · <green><u>{url}</u></green>\n\n")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from prime_rl.dashboard.server import main as server_main
|
||||
|
||||
server_main()
|
||||
@@ -6,18 +6,25 @@ lives in ``prime_rl.evals.evals``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
|
||||
from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("Evals")
|
||||
config = cli(EvalsConfig)
|
||||
from prime_rl.utils.pathing import write_launch_toml
|
||||
from prime_rl.utils.pathing import prepare_attempt_dirs, write_launch_toml
|
||||
|
||||
write_launch_toml(config.output_dir, "evals")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
|
||||
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
|
||||
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
|
||||
os.environ["PRL_LOG_DIR"] = str(log_dir)
|
||||
write_launch_toml(config_dir, "evals")
|
||||
(config_dir / "evals.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
|
||||
from prime_rl.evals.evals import run_evals
|
||||
|
||||
asyncio.run(run_evals(config))
|
||||
|
||||
@@ -10,7 +10,13 @@ from typing import Any
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, latest_log_dir
|
||||
from prime_rl.utils.pathing import (
|
||||
format_log_message,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
prepare_attempt_dirs,
|
||||
write_launch_toml,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
@@ -51,7 +57,7 @@ def write_config(
|
||||
return config_path
|
||||
|
||||
|
||||
def write_slurm_script(config: InferenceConfig, config_path: Path, script_path: Path) -> None:
|
||||
def write_slurm_script(config: InferenceConfig, config_path: Path, log_dir: Path, script_path: Path) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
@@ -70,7 +76,10 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
template_vars = dict(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.output_dir,
|
||||
launcher_log_dir=get_launcher_log_dir(config.output_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
dp_per_node=dp_per_node,
|
||||
num_nodes=getattr(config.deployment, "num_nodes", 1),
|
||||
@@ -116,6 +125,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
script = template.render(**template_vars)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.output_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -125,17 +135,17 @@ def inference_slurm(config: InferenceConfig):
|
||||
|
||||
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = get_config_dir(config.output_dir)
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
|
||||
write_launch_toml(config_dir, "inference")
|
||||
is_multi_node = config.deployment.type in ("multi_node", "disaggregated")
|
||||
exclude = {"deployment", "slurm", "dry_run"} if is_multi_node else {"slurm", "dry_run"}
|
||||
config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
script_path = config.output_dir / INFERENCE_SBATCH
|
||||
write_slurm_script(config, config_path, script_path)
|
||||
script_path = get_launcher_dir(config.output_dir) / INFERENCE_SBATCH
|
||||
write_slurm_script(config, config_path, log_dir, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
log_dir = latest_log_dir(config.output_dir)
|
||||
num_nodes = getattr(config.deployment, "num_nodes", 1)
|
||||
log_message = format_log_message(log_dir=log_dir, inference=True, job_log=True, num_infer_nodes=num_nodes)
|
||||
|
||||
|
||||
@@ -14,16 +14,17 @@ from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
from prime_rl.configs.inference import VllmRouterConfig
|
||||
from prime_rl.configs.orchestrator import EnvConfig
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
|
||||
from prime_rl.entrypoints.inference import vllm_overrides_fragment
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_log_dir,
|
||||
format_log_message,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
latest_log_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
prepare_attempt_dirs,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
write_launch_toml,
|
||||
@@ -120,8 +121,8 @@ def rl_local(config: RLConfig):
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
write_launch_toml(config.run_dir, "rl")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_toml(config_dir, "rl")
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
@@ -129,6 +130,8 @@ def rl_local(config: RLConfig):
|
||||
logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
# Derive launcher-local GPU IDs from deployment config
|
||||
gpu_offset = 0
|
||||
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
|
||||
@@ -174,9 +177,6 @@ def rl_local(config: RLConfig):
|
||||
f"Update the base_url to use port {expected_port} to match the inference server."
|
||||
)
|
||||
|
||||
# Per-attempt log dir: a resume never overwrites an earlier attempt's logs
|
||||
log_dir = create_attempt_log_dir(config.run_dir)
|
||||
|
||||
# Start processes
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
@@ -367,17 +367,12 @@ def rl_local(config: RLConfig):
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Monitor all processes for failures
|
||||
logger.success("Startup complete. Showing orchestrator logs...")
|
||||
logger.success("Launcher complete")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
tail_process = Popen(
|
||||
f"tail -F '{log_dir / 'orchestrator.log'}'",
|
||||
shell=True,
|
||||
)
|
||||
processes.append(tail_process)
|
||||
|
||||
# Check for errors from monitor threads
|
||||
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
|
||||
# Trainer and orchestrator completion is the successful stop condition.
|
||||
completion_events = (stop_events["trainer"], stop_events["orchestrator"])
|
||||
while not all(event.is_set() for event in completion_events):
|
||||
if error_queue:
|
||||
error = error_queue[0]
|
||||
logger.error(f"Error: {error}")
|
||||
@@ -420,7 +415,7 @@ def rl_local(config: RLConfig):
|
||||
raise
|
||||
|
||||
|
||||
def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) -> None:
|
||||
def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script_path: Path) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
@@ -463,7 +458,11 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_dir / RL_CONFIG,
|
||||
config_dir=config_dir,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
elif config.inference is not None and config.inference.deployment.type == "disaggregated":
|
||||
@@ -474,7 +473,10 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
is_disaggregated=True,
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
|
||||
nodes_per_infer_replica=infer_deploy.num_nodes,
|
||||
@@ -515,7 +517,10 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
is_disaggregated=False,
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir, # TODO: should prob have each subconfig path separately
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.total_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
|
||||
@@ -548,6 +553,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -558,9 +564,8 @@ def rl_slurm(config: RLConfig):
|
||||
config.log.level or os.environ.get("PRIME_LOG_LEVEL", "info"), json_logging=config.log.json_logging
|
||||
)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
write_launch_toml(config.run_dir, "rl")
|
||||
log_dir = latest_log_dir(config.run_dir)
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_toml(config_dir, "rl")
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean"})
|
||||
@@ -596,14 +601,16 @@ def rl_slurm(config: RLConfig):
|
||||
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
|
||||
)
|
||||
|
||||
script_path = config.run_dir / RL_SBATCH
|
||||
write_slurm_script(config, config_dir, script_path)
|
||||
script_path = get_launcher_dir(config.run_dir) / RL_SBATCH
|
||||
write_slurm_script(config, config_dir, log_dir, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
if config.dry_run:
|
||||
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
|
||||
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
@@ -611,6 +618,7 @@ def rl_slurm(config: RLConfig):
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
|
||||
def rl(config: RLConfig):
|
||||
|
||||
+86
-144
@@ -12,17 +12,17 @@ from prime_rl.configs.evals import EvalsConfig, OnlineConfig
|
||||
from prime_rl.configs.orchestrator import EvalSourceConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
|
||||
from prime_rl.utils.config import cli, dump_resolved_config, find_package_resource
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_log_dir,
|
||||
format_log_message,
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_log_dir,
|
||||
latest_log_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
prepare_attempt_dirs,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
write_launch_toml,
|
||||
@@ -40,8 +40,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"
|
||||
@@ -141,14 +139,20 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
|
||||
json.dump(env_server_dict, f, indent=2)
|
||||
|
||||
|
||||
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path, prl_run_id: str | None = None) -> None:
|
||||
def write_slurm_script(
|
||||
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str | None = None
|
||||
) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
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 = {
|
||||
@@ -161,191 +165,130 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
else:
|
||||
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=config_path.parent,
|
||||
log_dir=log_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)
|
||||
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,
|
||||
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")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_toml(config_dir, "sft")
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
exclude = (
|
||||
{"deployment", "slurm", "dry_run", "clean"}
|
||||
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"]
|
||||
|
||||
script_path = config.run_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:
|
||||
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}")
|
||||
eval_script_path = config.run_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]
|
||||
script_path = launcher_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, log_dir, script_path, prl_run_id)
|
||||
logger.info(f"Wrote SLURM script to {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),
|
||||
log_dir=log_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
|
||||
|
||||
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}")
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
logger.success(log_message)
|
||||
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(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
|
||||
def sft_local(config: SFTConfig):
|
||||
@@ -354,8 +297,8 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
write_launch_toml(config.run_dir, "sft")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_toml(config_dir, "sft")
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
write_config(config, config_path)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
@@ -368,7 +311,7 @@ def sft_local(config: SFTConfig):
|
||||
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
log_dir = create_attempt_log_dir(config.run_dir)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
|
||||
# launcher must partition GPUs between processes; plain SFT leaves them to torchrun.
|
||||
@@ -467,6 +410,9 @@ def sft_local(config: SFTConfig):
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
"PRL_ATTEMPT_CONFIG_DIR": str(config_dir),
|
||||
"PRL_ATTEMPT_LOG_DIR": str(log_dir),
|
||||
"PRL_LOG_DIR": str(log_dir),
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "evals",
|
||||
},
|
||||
@@ -506,12 +452,8 @@ def sft_local(config: SFTConfig):
|
||||
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
|
||||
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
|
||||
|
||||
logger.success("Startup complete. Showing trainer logs...")
|
||||
tail_process = Popen(
|
||||
f"tail -F '{log_dir / 'trainer.log'}' | sed -u 's/^\\[[a-zA-Z]*[0-9]*\\]://'",
|
||||
shell=True,
|
||||
)
|
||||
processes.append(tail_process)
|
||||
logger.success("Launcher complete")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
# Wait for the trainer (and the evals process, which drains its final evals after
|
||||
# the trainer's last checkpoint) while surfacing any process failure.
|
||||
|
||||
@@ -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__":
|
||||
|
||||
@@ -42,6 +42,9 @@ class WandbMonitor(Monitor):
|
||||
self.logger.debug(f"Found WANDB_ARGS in environment variables {wandb_args}")
|
||||
sys.argv = json.loads(wandb_args)
|
||||
|
||||
# W&B advertises Weave on every init when it sees openai/verifiers imported.
|
||||
os.environ.setdefault("WANDB_DISABLE_WEAVE", "1")
|
||||
|
||||
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
|
||||
# requires a server connection and can't work offline.
|
||||
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1" and os.environ.get("WANDB_MODE") not in (
|
||||
|
||||
@@ -210,6 +210,8 @@ class Dispatcher:
|
||||
# *why* — the orchestrator toggles this based on step / policy lead.
|
||||
self.dispatch_allowed = asyncio.Event()
|
||||
self.dispatch_allowed.set()
|
||||
self.policy_update_pending = False
|
||||
self.scheduling_lock = asyncio.Lock()
|
||||
|
||||
self.stopped = asyncio.Event()
|
||||
self.task: asyncio.Task | None = None
|
||||
@@ -371,6 +373,12 @@ class Dispatcher:
|
||||
the resulting aborts are processed while the engine is still stepping —
|
||||
otherwise the orphaned KV transfers crash the decode engine on resume
|
||||
(see ``WeightWatcher.apply_policy_update``)."""
|
||||
self.policy_update_pending = True
|
||||
# Wait for a scheduling call that started before the pending update.
|
||||
# No rollout can cross the inference weight swap after this barrier.
|
||||
async with self.scheduling_lock:
|
||||
pass
|
||||
|
||||
if self.train_envs is None or self.progress is None:
|
||||
return
|
||||
min_version = min_fresh_version(self.progress.step, self.max_off_policy_steps)
|
||||
@@ -392,7 +400,8 @@ class Dispatcher:
|
||||
)
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""No-op: the dispatcher drains in ``on_version_pending`` (pre-pause)."""
|
||||
"""Resume rollout scheduling after inference applies the new policy."""
|
||||
self.policy_update_pending = False
|
||||
|
||||
async def fill_inflight(self) -> None:
|
||||
"""Schedule new rollouts up to ``max_inflight``, honoring
|
||||
@@ -401,28 +410,33 @@ class Dispatcher:
|
||||
respects it. When ``PREFER_EVAL``'s source exhausts we flip back to
|
||||
``PREFER_TRAIN`` so the eval tail drains alongside fresh train."""
|
||||
while True:
|
||||
if self.policy_update_pending:
|
||||
return
|
||||
if self.available_permits <= 0 or self.admission_budget() <= 0:
|
||||
return
|
||||
|
||||
if self.mode == DispatcherMode.PREFER_EVAL:
|
||||
# PREFER_EVAL is only entered when the orchestrator triggers
|
||||
# eval, which requires ``eval_source`` to be configured
|
||||
assert self.eval_source is not None
|
||||
if not self.eval_has_work:
|
||||
# Eval source + all eval groups fully dispatched. Flip
|
||||
# to PREFER_TRAIN so any remaining permits go to train
|
||||
# while the in-flight eval tail completes naturally
|
||||
self.switch_mode(DispatcherMode.PREFER_TRAIN, reason="the eval queue drained")
|
||||
continue
|
||||
scheduled = await self.try_schedule("eval")
|
||||
if not scheduled:
|
||||
return
|
||||
else: # PREFER_TRAIN — respects the orchestrator's dispatch gate
|
||||
if not self.dispatch_allowed.is_set():
|
||||
return
|
||||
scheduled = await self.try_schedule("train")
|
||||
if not scheduled:
|
||||
async with self.scheduling_lock:
|
||||
if self.policy_update_pending:
|
||||
return
|
||||
if self.mode == DispatcherMode.PREFER_EVAL:
|
||||
# PREFER_EVAL is only entered when the orchestrator triggers
|
||||
# eval, which requires ``eval_source`` to be configured
|
||||
assert self.eval_source is not None
|
||||
if not self.eval_has_work:
|
||||
# Eval source + all eval groups fully dispatched. Flip
|
||||
# to PREFER_TRAIN so any remaining permits go to train
|
||||
# while the in-flight eval tail completes naturally
|
||||
self.switch_mode(DispatcherMode.PREFER_TRAIN, reason="the eval queue drained")
|
||||
continue
|
||||
scheduled = await self.try_schedule("eval")
|
||||
if not scheduled:
|
||||
return
|
||||
else: # PREFER_TRAIN — respects the orchestrator's dispatch gate
|
||||
if not self.dispatch_allowed.is_set():
|
||||
return
|
||||
scheduled = await self.try_schedule("train")
|
||||
if not scheduled:
|
||||
return
|
||||
|
||||
def switch_mode(self, new_mode: DispatcherMode, *, reason: str) -> None:
|
||||
if new_mode == self.mode:
|
||||
|
||||
@@ -179,6 +179,13 @@ class Envs(Generic[EnvT]):
|
||||
async def start(self) -> None:
|
||||
"""Connect to all env servers in parallel — every address is known up front,
|
||||
so there's nothing to serialize on."""
|
||||
# When several env.start()s load_dataset() concurrently, datasets' parallel arrow read
|
||||
# (tqdm thread_map) races in ensure_lock's `del tqdm_class._lock` and crashes with
|
||||
# `AttributeError: type object 'tqdm' has no attribute '_lock'`. Pre-seed the lock so it
|
||||
# isn't created-and-deleted per call.
|
||||
from datasets.utils import tqdm as hf_tqdm
|
||||
|
||||
hf_tqdm.set_lock(hf_tqdm.get_lock())
|
||||
await asyncio.gather(*(env.start() for env in self))
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""EvalSource: trigger-driven, finite-per-epoch pull of eval examples.
|
||||
|
||||
The orchestrator pokes ``trigger(step)`` after each ship + once at
|
||||
startup; the dispatcher pulls via ``next_task()`` until
|
||||
The policy watcher calls ``trigger(step)`` after each applied policy,
|
||||
including startup. The dispatcher pulls via ``next_task()`` until
|
||||
``bool(source) == False``. Constructed only when eval is configured."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,8 +37,8 @@ class EvalSource:
|
||||
|
||||
self.queue: deque[TaskRequest] = deque()
|
||||
|
||||
# On resume we skip the startup eval; on fresh start the first
|
||||
# trigger fires every env (subject to ``skip_first_step``)
|
||||
# A fresh run evaluates the base policy. Resumed runs apply interval
|
||||
# rules to the loaded checkpoint and later policies.
|
||||
self.first_trigger = not is_resumed
|
||||
|
||||
def trigger(self, step: int, *, force: bool = False) -> list[str]:
|
||||
|
||||
@@ -78,11 +78,7 @@ from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, s
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_broadcast_dir
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
final_broadcast_version,
|
||||
resolve_latest_ckpt_step,
|
||||
)
|
||||
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
|
||||
|
||||
monkey_patch_oai_iterable_types()
|
||||
monkey_patch_chat_completion_logprobs()
|
||||
@@ -166,9 +162,10 @@ class Orchestrator:
|
||||
self.eval_triggered_at = {}
|
||||
self.consecutive_empty_batches = 0
|
||||
self.gate_closed_at = None
|
||||
# Pulsed by the version hooks so a held ship can re-check ``policy.version``
|
||||
# Pulsed after inference applies a policy so held work can re-check it.
|
||||
self.version_advanced = asyncio.Event()
|
||||
self.wait_for_policy_time = 0.0
|
||||
self.eval_triggered_steps: set[int] = set()
|
||||
self.component_tasks = []
|
||||
|
||||
# Always assigned by ``setup()``; None-initialized so teardown can run
|
||||
@@ -320,14 +317,9 @@ class Orchestrator:
|
||||
# scratch). The startup broadcast is always coming, so wait for it rather
|
||||
# than failing immediately when it is not there yet.
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
|
||||
t0 = time.perf_counter()
|
||||
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
)
|
||||
await self.receiver.sync_startup(sync_version, timeout=wait_timeout)
|
||||
self.policy.version = sync_version
|
||||
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
self.eval_source: EvalSource | None = (
|
||||
EvalSource(
|
||||
@@ -390,9 +382,12 @@ class Orchestrator:
|
||||
self.watcher = WeightWatcher(
|
||||
self.receiver,
|
||||
policy=self.policy,
|
||||
observers=[self.dispatcher, self],
|
||||
ckpt_step=self.policy.version,
|
||||
observers=[self.dispatcher],
|
||||
ckpt_step=sync_version,
|
||||
)
|
||||
if self.eval_source is not None:
|
||||
self.watcher.on_update(self.trigger_eval)
|
||||
self.watcher.on_update(self.on_policy_update)
|
||||
# Single periodic logger for the whole pipeline. It's the only
|
||||
# consumer of ``dispatcher.metrics.drained()`` (which clears on read)
|
||||
self.lag_monitor = EventLoopLagMonitor()
|
||||
@@ -419,6 +414,11 @@ class Orchestrator:
|
||||
wandb_enabled=wandb_enabled,
|
||||
)
|
||||
|
||||
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
|
||||
t0 = time.perf_counter()
|
||||
await self.watcher.sync_startup(sync_version, timeout=wait_timeout)
|
||||
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Run the orchestrator until shutdown. Drives setup, spawns the
|
||||
background tasks, runs the main loop in this task, then cleans up."""
|
||||
@@ -438,14 +438,6 @@ class Orchestrator:
|
||||
asyncio.create_task(self.watcher.start(), name="watcher"),
|
||||
]
|
||||
|
||||
# Base-model eval (policy v0) — fires before any train rollouts, logged at the first
|
||||
# step, unless ``eval.skip_first_step=True``. On resume, defaults to assuming a clean
|
||||
# exit (evals already completed); set ``eval.retrigger_on_resume=True`` to also re-fire
|
||||
# interval-aligned evals at the checkpoint step (e.g. after a crash).
|
||||
if config.eval is not None and config.eval.retrigger_on_resume and self.resume_step is not None:
|
||||
self.maybe_trigger_eval(self.resume_step)
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
|
||||
# Anchor step-time clock so the first step measures startup → first batch
|
||||
self.last_batch_at = time.perf_counter()
|
||||
|
||||
@@ -484,18 +476,11 @@ class Orchestrator:
|
||||
get_logger().warning("Orchestrator cleanup complete (forced)")
|
||||
trim_process_memory()
|
||||
|
||||
@property
|
||||
def final_version(self) -> int | None:
|
||||
"""Newest policy version the trainer will ever broadcast."""
|
||||
if self.config.max_steps is None:
|
||||
return None
|
||||
return final_broadcast_version(self.config.max_steps, self.config.weight_broadcast.broadcast_final)
|
||||
|
||||
async def wait_for_version(self, version: int, reason: str) -> None:
|
||||
"""Bounded wait until the watcher has applied v{version}."""
|
||||
if self.policy.version >= version:
|
||||
return
|
||||
get_logger().info(f"Waiting for the trainer to broadcast v{version} {reason}")
|
||||
get_logger().info(f"Waiting for inference to apply policy v{version} {reason}")
|
||||
|
||||
async def wait() -> None:
|
||||
while self.policy.version < version:
|
||||
@@ -514,15 +499,15 @@ class Orchestrator:
|
||||
try:
|
||||
await asyncio.wait_for(wait(), timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
get_logger().warning(f"Trainer did not broadcast v{version} within {timeout}s — proceeding anyway")
|
||||
get_logger().warning(f"Inference did not apply policy v{version} within {timeout}s — proceeding anyway")
|
||||
|
||||
async def wait_for_final_broadcast(self) -> None:
|
||||
"""Stay alive for the trainer's last broadcast. Every broadcast is a
|
||||
blocking rendezvous — tearing down the watcher before it would strand
|
||||
the trainer inside the handshake."""
|
||||
if self.final_version is None:
|
||||
if self.config.max_steps is None:
|
||||
return
|
||||
await self.wait_for_version(self.final_version, reason="before shutdown")
|
||||
await self.wait_for_version(self.config.max_steps, reason="before shutdown")
|
||||
|
||||
async def main_loop(self) -> None:
|
||||
"""Consume dispatcher results and route them to the train / eval sink.
|
||||
@@ -644,16 +629,16 @@ class Orchestrator:
|
||||
f"({n_trainable / effective.num_traces:.1%}) — consider reviewing task difficulty"
|
||||
)
|
||||
|
||||
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
|
||||
# Ship batch ``step`` only once inference has applied v{step-1-TARGET_LAG}.
|
||||
# Without this, fast envs fill batches from buffered rollouts and the
|
||||
# orchestrator races arbitrarily far ahead of the trainer. Always
|
||||
# satisfiable: the trainer broadcasts every version except v{max_steps},
|
||||
# and ``wait_for_final_broadcast`` keeps the watcher alive through the
|
||||
# last rendezvous after the pipeline drains.
|
||||
# satisfiable: the trainer broadcasts every version, and
|
||||
# ``wait_for_final_broadcast`` keeps the watcher alive through the last
|
||||
# rendezvous after the pipeline drains.
|
||||
required_version = step - 1 - TARGET_LAG
|
||||
if self.policy.version < required_version:
|
||||
get_logger().info(
|
||||
f"Holding batch {step} until the trainer publishes policy v{required_version} "
|
||||
f"Holding batch {step} until inference applies policy v{required_version} "
|
||||
f"(currently v{self.policy.version})"
|
||||
)
|
||||
hold_start = time.perf_counter()
|
||||
@@ -757,14 +742,8 @@ class Orchestrator:
|
||||
|
||||
self.log_train_batch(batch, step=step, step_time=step_time)
|
||||
|
||||
# The final eval must measure the final weights: hold until the
|
||||
# trainer's last broadcast (v{max_steps} when evals consume it) has
|
||||
# been applied before triggering it. Satisfiable — the trainer
|
||||
# broadcasts right after consuming the batch this call just shipped.
|
||||
if config.eval is not None and config.max_steps is not None and step >= config.max_steps:
|
||||
assert self.final_version is not None
|
||||
await self.wait_for_version(self.final_version, reason="for the final eval")
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
if config.max_steps is not None and step >= config.max_steps:
|
||||
await self.wait_for_version(step, reason="before shutdown")
|
||||
# Drain right after shipping the final batch. Waiting for a further
|
||||
# batch to fill would burn inference on data that can never train —
|
||||
# and with a tight ``max_off_policy_steps`` it never fills at all (the
|
||||
@@ -784,14 +763,18 @@ class Orchestrator:
|
||||
f"train episode(s); any in-flight evals will complete)"
|
||||
)
|
||||
|
||||
def maybe_trigger_eval(self, step: int) -> None:
|
||||
async def trigger_eval(self, step: int) -> None:
|
||||
"""Fire eligible eval epochs and flip to ``PREFER_EVAL`` if anything
|
||||
fires. No-op when eval is not configured."""
|
||||
if self.eval_source is None:
|
||||
if self.eval_source is None or step in self.eval_triggered_steps:
|
||||
return
|
||||
fired = self.eval_source.trigger(step)
|
||||
if self.resume_step == step and self.config.eval is not None and not self.config.eval.retrigger_on_resume:
|
||||
return
|
||||
is_final = self.config.max_steps is not None and step >= self.config.max_steps
|
||||
fired = self.eval_source.trigger(step, force=is_final)
|
||||
if not fired:
|
||||
return
|
||||
self.eval_triggered_steps.add(step)
|
||||
reason = f"eval was triggered at step {step}"
|
||||
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=reason)
|
||||
now = time.perf_counter()
|
||||
@@ -942,10 +925,6 @@ class Orchestrator:
|
||||
policy_versions = {span.start for span in policy_spans if span is not None}
|
||||
policy_versions.update(failure.policy_version for failure in batch.failures)
|
||||
policy_version = min(policy_versions)
|
||||
if len(policy_versions) > 1:
|
||||
get_logger().warning(
|
||||
f"Eval {batch.env_name} step {batch.step} had mixed policy versions: {sorted(policy_versions)}"
|
||||
)
|
||||
# Episode metrics over {all,effective} (eval batches are per-env, so no `agg` axis).
|
||||
# ``effective`` = non-errored; pass@k / pass^k only over the effective set.
|
||||
episodes = batch.episodes
|
||||
@@ -969,7 +948,7 @@ class Orchestrator:
|
||||
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
|
||||
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"Evaluated {batch.env_name} | "
|
||||
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
@@ -1006,7 +985,7 @@ class Orchestrator:
|
||||
if lead > TARGET_LAG:
|
||||
if was_set:
|
||||
get_logger().info(
|
||||
f"Pausing dispatcher until the trainer publishes policy v{self.progress.step - 1 - TARGET_LAG} "
|
||||
f"Pausing dispatcher until inference applies policy v{self.progress.step - 1 - TARGET_LAG} "
|
||||
f"(currently v{self.policy.version})"
|
||||
)
|
||||
self.gate_closed_at = time.perf_counter()
|
||||
@@ -1019,15 +998,10 @@ class Orchestrator:
|
||||
self.gate_closed_at = None
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook, fired at publish confirmation (pre-apply):
|
||||
``policy.version`` already carries the new version, so wake a held ship."""
|
||||
self.version_advanced.set()
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook: the weight update completed;
|
||||
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
|
||||
async def on_policy_update(self, _step: int) -> None:
|
||||
"""Refresh policy-dependent state after inference applies new weights."""
|
||||
self.update_dispatch_gate()
|
||||
self.version_advanced.set()
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Bounded best-effort teardown of all components. Has a global
|
||||
|
||||
@@ -6,6 +6,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable
|
||||
|
||||
from prime_rl.orchestrator.types import Policy, VersionObserver
|
||||
from prime_rl.transports.weights import WeightReceiver
|
||||
@@ -38,6 +39,19 @@ class WeightWatcher:
|
||||
self.task: asyncio.Task | None = None
|
||||
self.update_lock = asyncio.Lock()
|
||||
self.stopped = asyncio.Event()
|
||||
self.update_hooks: list[Callable[[int], Awaitable[None]]] = []
|
||||
|
||||
def on_update(self, hook: Callable[[int], Awaitable[None]]) -> None:
|
||||
"""Register an async hook that runs after inference applies new weights."""
|
||||
self.update_hooks.append(hook)
|
||||
|
||||
async def sync_startup(self, step: int, timeout: float) -> None:
|
||||
"""Apply the startup policy and notify the registered update hooks."""
|
||||
async with self.update_lock:
|
||||
await self.receiver.sync_startup(step, timeout)
|
||||
self.ckpt_step = step
|
||||
self.policy.version = step
|
||||
await self._notify_update(step)
|
||||
|
||||
async def start(self) -> None:
|
||||
self.task = asyncio.current_task()
|
||||
@@ -72,12 +86,9 @@ class WeightWatcher:
|
||||
await self.receiver.wait_published(next_step, cancelled=self.stopped.is_set)
|
||||
self.last_wait_for_ckpt_time = time.perf_counter() - t0
|
||||
|
||||
# Publish confirmed: the policy version advances here, before the
|
||||
# apply — inference pauses during the update, so nothing can generate
|
||||
# under the new number from the old weights, and a ship held on this
|
||||
# version releases without waiting out the inference weight reload.
|
||||
# Record the published version before notifying pending observers.
|
||||
# ``policy.version`` advances only after inference applies it.
|
||||
self.ckpt_step = next_step
|
||||
self.policy.version = next_step
|
||||
|
||||
# Drain stale rollouts BEFORE pausing the inference engines.
|
||||
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
|
||||
@@ -102,17 +113,22 @@ class WeightWatcher:
|
||||
await self.receiver.receive(next_step)
|
||||
self.last_update_weights_time = time.perf_counter() - t1
|
||||
self.update_count += 1
|
||||
self.policy.version = next_step
|
||||
get_logger().debug(
|
||||
f"Updated inference weights to policy v{next_step} in {format_time(self.last_update_weights_time)}"
|
||||
)
|
||||
|
||||
for observer in self.observers:
|
||||
try:
|
||||
await observer.on_new_version(next_step)
|
||||
except Exception as exc:
|
||||
get_logger().warning(
|
||||
f"Observer {type(observer).__name__}.on_new_version({next_step}) raised: {exc!r}"
|
||||
)
|
||||
await self._notify_update(next_step)
|
||||
|
||||
async def _notify_update(self, step: int) -> None:
|
||||
for observer in self.observers:
|
||||
try:
|
||||
await observer.on_new_version(step)
|
||||
except Exception as exc:
|
||||
get_logger().warning(f"Observer {type(observer).__name__}.on_new_version({step}) raised: {exc!r}")
|
||||
|
||||
for hook in self.update_hooks:
|
||||
await hook(step)
|
||||
|
||||
def gauges(self) -> dict[str, float]:
|
||||
return {
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately on any failed command so a crash anywhere releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
@@ -52,13 +52,12 @@ export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
# Paths
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_PATH={{ config_path }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
# Per-attempt log dir: a relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
|
||||
export LOG_DIR={{ log_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR=$CONFIG_DIR
|
||||
export PRL_ATTEMPT_LOG_DIR=$LOG_DIR
|
||||
mkdir -p $LOG_DIR/inference
|
||||
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
|
||||
# Setup environment
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately on any failed command so a crash anywhere releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
@@ -58,15 +58,24 @@ export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parall
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
# 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
|
||||
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
export LOG_DIR={{ log_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR=$CONFIG_DIR
|
||||
export PRL_ATTEMPT_LOG_DIR=$LOG_DIR
|
||||
mkdir -p $LOG_DIR/trainer $LOG_DIR/inference
|
||||
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
|
||||
# Clean exits do not trigger srun --kill-on-bad-exit. Each terminal component
|
||||
# publishes its successful exit through the shared launcher directory. Every node
|
||||
# uses the same completion condition before it tears down support processes.
|
||||
export TRAINER_DONE=$LAUNCHER_DIR/.trainer.done
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
export ORCHESTRATOR_DONE=$LAUNCHER_DIR/.orchestrator.done
|
||||
{% endif -%}
|
||||
mkdir -p "$LAUNCHER_DIR"
|
||||
rm -f "$TRAINER_DONE"{% if num_infer_nodes > 0 %} "$ORCHESTRATOR_DONE"{% endif %}
|
||||
|
||||
export PRL_RUN_ID=${PRL_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")}
|
||||
export PRL_RUN_NAME={{ run_name }}
|
||||
export WANDB_RUN_ID=$PRL_RUN_ID
|
||||
@@ -400,21 +409,28 @@ else
|
||||
|
||||
echo $HOSTNAMES_STR | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
|
||||
WANDB_SHARED_LABEL=trainer uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.json \
|
||||
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log &
|
||||
(
|
||||
WANDB_SHARED_LABEL=trainer uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.json \
|
||||
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ] && [ "$TRAIN_NODE_RANK" -eq 0 ]; then
|
||||
touch "$TRAINER_DONE" || exit $?
|
||||
fi
|
||||
exit "$COMPONENT_CODE"
|
||||
) &
|
||||
{% if num_infer_nodes > 0 %} fi{% endif %}
|
||||
{% if num_infer_nodes > 0 %}
|
||||
# Launch the orchestrator on the node ORCH_ADDR points at (see the ORCH_PROCID
|
||||
@@ -450,19 +466,41 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $LOG_DIR/orchestrator.log &
|
||||
(
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $LOG_DIR/orchestrator.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ]; then
|
||||
touch "$ORCHESTRATOR_DONE" || exit $?
|
||||
fi
|
||||
exit "$COMPONENT_CODE"
|
||||
) &
|
||||
fi
|
||||
{% endif %}
|
||||
|
||||
# Wait for the first background job to exit and propagate its exit code. This
|
||||
# turns background process crashes (router, orchestrator) into task failures
|
||||
# that --kill-on-bad-exit=1 can broadcast to the other nodes so the whole job
|
||||
# tears down instead of leaving zombies holding the allocation.
|
||||
wait -n
|
||||
EXIT_CODE=$?
|
||||
# Every node watches the terminal components for successful completion.
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
# Inference runs stop after both the trainer and orchestrator finish.
|
||||
( until [ -f "$TRAINER_DONE" ] && [ -f "$ORCHESTRATOR_DONE" ]; do sleep 10; done ) &
|
||||
{% else -%}
|
||||
# Trainer-only runs stop when the trainer finishes.
|
||||
( until [ -f "$TRAINER_DONE" ]; do sleep 10; done ) &
|
||||
{% endif -%}
|
||||
COMPLETION_PID=$!
|
||||
|
||||
# A clean component exit is not enough to stop the run. Keep waiting for the
|
||||
# shared completion condition. Propagate any failure through
|
||||
# --kill-on-bad-exit=1 so every node tears down.
|
||||
while true; do
|
||||
wait -n -p FINISHED_PID
|
||||
EXIT_CODE=$?
|
||||
if [ "$EXIT_CODE" -ne 0 ] || [ "${FINISHED_PID:-}" = "$COMPLETION_PID" ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
REMAINING_PIDS=$(jobs -p)
|
||||
{%- if cleanup_grace_period %}
|
||||
# Cross-node teardown is driven by `srun --kill-on-bad-exit=1`, which reaps peer
|
||||
|
||||
@@ -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 }}
|
||||
@@ -18,94 +18,119 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately on any failed command so a crash on any node releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
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 }}
|
||||
# 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
|
||||
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
export LOG_DIR={{ log_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR=$CONFIG_DIR
|
||||
export PRL_ATTEMPT_LOG_DIR=$LOG_DIR
|
||||
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" > "$OUTPUT_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
|
||||
@@ -115,53 +140,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={{ output_dir }}/eval_job_%j.log
|
||||
#SBATCH --error={{ output_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 }}
|
||||
# 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 job-scoped sentinel and the
|
||||
# other nodes watch for it to release their engines. Stale sentinels from other job
|
||||
# IDs are inert, so only this job's own path needs clearing.
|
||||
export EVAL_DONE=$OUTPUT_DIR/.eval_done_$SLURM_JOB_ID
|
||||
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="$OUTPUT_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
|
||||
@@ -18,14 +18,16 @@
|
||||
{%- if exclude %}
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately if any setup command or the launcher fails so the SLURM job
|
||||
# releases its allocation instead of holding nodes after a crash.
|
||||
set -e
|
||||
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR={{ config_dir }}
|
||||
export PRL_ATTEMPT_LOG_DIR={{ log_dir }}
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
|
||||
@@ -18,14 +18,16 @@
|
||||
{%- if exclude %}
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately if any setup command or the launcher fails so the SLURM job
|
||||
# releases its allocation instead of holding nodes after a crash.
|
||||
set -e
|
||||
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR={{ config_dir }}
|
||||
export PRL_ATTEMPT_LOG_DIR={{ log_dir }}
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
|
||||
@@ -67,7 +67,7 @@ from prime_rl.utils.metrics_server import HealthServer, MetricsServer
|
||||
from prime_rl import monitors
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.utils import clean_exit, final_broadcast_version, resolve_latest_ckpt_step
|
||||
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
|
||||
from ring_flash_attn import substitute_hf_flash_attn
|
||||
|
||||
|
||||
@@ -590,26 +590,23 @@ def train(config: TrainerConfig):
|
||||
current_lr = optimizer.param_groups[0]["lr"]
|
||||
forward_backward_time = time.perf_counter() - forward_backward_start_time
|
||||
|
||||
# Broadcast the model just produced (policy v{progress.step}) so the orchestrator can
|
||||
# sample its next step from it. Every broadcast is a handshake with the consumer, so
|
||||
# versions past the last consumed one are skipped (``final_broadcast_version``:
|
||||
# training never samples v{max_steps}, but a configured final eval measures it).
|
||||
# Broadcast the model just produced (policy v{progress.step}). The final
|
||||
# broadcast keeps inference synchronized with the completed trainer.
|
||||
if weight_sender is None:
|
||||
broadcast_weights_time = 0
|
||||
else:
|
||||
broadcast_unused = config.max_steps is not None and progress.step > final_broadcast_version(
|
||||
config.max_steps, config.weight_broadcast.broadcast_final
|
||||
)
|
||||
if not broadcast_unused:
|
||||
broadcast_weights_start_time = time.perf_counter()
|
||||
# The per-layer gather + fp8 conversion peaks ~50 GiB above the
|
||||
# resident weights; release cached blocks (incl. offload-stream
|
||||
# pools) so the broadcast gets the full headroom.
|
||||
torch.cuda.empty_cache()
|
||||
weight_sender.broadcast(model, step=progress.step)
|
||||
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
|
||||
else:
|
||||
broadcast_weights_time = 0
|
||||
broadcast_weights_start_time = time.perf_counter()
|
||||
# The per-layer gather + fp8 conversion peaks ~50 GiB above the
|
||||
# resident weights; release cached blocks (incl. offload-stream
|
||||
# pools) so the broadcast gets the full headroom. Drain all
|
||||
# pending work first: empty_cache returns blocks to the driver,
|
||||
# so a still-running kernel holding a cached block (e.g. the
|
||||
# optimizer step's tail) faults with an illegal memory access
|
||||
# once its block is freed under it.
|
||||
torch.cuda.synchronize()
|
||||
torch.cuda.empty_cache()
|
||||
weight_sender.broadcast(model, step=progress.step)
|
||||
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
|
||||
|
||||
# Checkpoint the step we just finished (model = policy v{progress.step}).
|
||||
if (
|
||||
|
||||
@@ -12,26 +12,67 @@ def get_log_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "logs"
|
||||
|
||||
|
||||
def create_attempt_log_dir(run_dir: Path) -> Path:
|
||||
"""Create ``logs/attempt_<n>`` for this launch attempt and repoint ``logs/latest`` to it.
|
||||
def _attempt_numbers(parent: Path) -> set[int]:
|
||||
return {
|
||||
int(path.name.removeprefix("attempt_"))
|
||||
for path in parent.glob("attempt_*")
|
||||
if path.name.removeprefix("attempt_").isdigit()
|
||||
}
|
||||
|
||||
Every launch — fresh or resumed — gets its own numbered log directory, so a resume
|
||||
never overwrites an earlier attempt's logs. Returns the attempt directory."""
|
||||
logs_dir = get_log_dir(run_dir)
|
||||
logs_dir.mkdir(parents=True, exist_ok=True)
|
||||
attempts = (
|
||||
int(p.name.removeprefix("attempt_"))
|
||||
for p in logs_dir.glob("attempt_*")
|
||||
if p.name.removeprefix("attempt_").isdigit()
|
||||
)
|
||||
attempt_dir = logs_dir / f"attempt_{1 + max(attempts, default=0)}"
|
||||
attempt_dir.mkdir()
|
||||
# Atomically repoint the relative ``latest`` symlink: create a temp link, then rename.
|
||||
tmp_link = logs_dir / f".{attempt_dir.name}"
|
||||
|
||||
def _point_latest(parent: Path, attempt_dir: Path) -> None:
|
||||
"""Atomically point ``parent/latest`` at a relative attempt directory."""
|
||||
tmp_link = parent / f".{attempt_dir.name}"
|
||||
if tmp_link.is_symlink() or tmp_link.exists():
|
||||
tmp_link.unlink()
|
||||
os.symlink(attempt_dir.name, tmp_link)
|
||||
os.replace(tmp_link, logs_dir / "latest")
|
||||
os.replace(tmp_link, parent / "latest")
|
||||
|
||||
|
||||
def create_attempt_dirs(run_dir: Path) -> tuple[Path, Path]:
|
||||
"""Create matching config and log directories for one launch attempt.
|
||||
|
||||
Returns the concrete resolved-config and log directories. The ``latest``
|
||||
symlink under each artifact root points to the new attempt.
|
||||
"""
|
||||
configs_dir = run_dir / "configs"
|
||||
logs_dir = get_log_dir(run_dir)
|
||||
configs_dir.mkdir(parents=True, exist_ok=True)
|
||||
logs_dir.mkdir(parents=True, exist_ok=True)
|
||||
attempts = _attempt_numbers(configs_dir) | _attempt_numbers(logs_dir)
|
||||
attempt_name = f"attempt_{1 + max(attempts, default=0)}"
|
||||
config_attempt_dir = configs_dir / attempt_name
|
||||
log_dir = logs_dir / attempt_name
|
||||
config_dir = config_attempt_dir / "resolved"
|
||||
config_dir.mkdir(parents=True)
|
||||
log_dir.mkdir()
|
||||
_point_latest(configs_dir, config_attempt_dir)
|
||||
_point_latest(logs_dir, log_dir)
|
||||
return config_dir, log_dir
|
||||
|
||||
|
||||
def prepare_attempt_dirs(run_dir: Path) -> tuple[Path, Path]:
|
||||
"""Reuse a launcher-pinned attempt or allocate a new one."""
|
||||
config_dir = os.environ.get("PRL_ATTEMPT_CONFIG_DIR")
|
||||
log_dir = os.environ.get("PRL_ATTEMPT_LOG_DIR")
|
||||
if config_dir is None and log_dir is None:
|
||||
return create_attempt_dirs(run_dir)
|
||||
if config_dir is None or log_dir is None:
|
||||
raise RuntimeError("PRL_ATTEMPT_CONFIG_DIR and PRL_ATTEMPT_LOG_DIR must be set together")
|
||||
resolved_config_dir = Path(config_dir)
|
||||
attempt_log_dir = Path(log_dir)
|
||||
resolved_config_dir.mkdir(parents=True, exist_ok=True)
|
||||
attempt_log_dir.mkdir(parents=True, exist_ok=True)
|
||||
return resolved_config_dir, attempt_log_dir
|
||||
|
||||
|
||||
def create_attempt_log_dir(run_dir: Path) -> Path:
|
||||
"""Create a log-only attempt for standalone processes without config dumps."""
|
||||
logs_dir = get_log_dir(run_dir)
|
||||
logs_dir.mkdir(parents=True, exist_ok=True)
|
||||
attempt_dir = logs_dir / f"attempt_{1 + max(_attempt_numbers(logs_dir), default=0)}"
|
||||
attempt_dir.mkdir()
|
||||
_point_latest(logs_dir, attempt_dir)
|
||||
return attempt_dir
|
||||
|
||||
|
||||
@@ -61,7 +102,7 @@ def format_log_message(
|
||||
|
||||
log_lines: list[str] = []
|
||||
if job_log:
|
||||
log_lines.append(f"{i1}{'Job:':<{col}}tail -F {log_dir.parent.parent}/job_*.log")
|
||||
log_lines.append(f"{i1}{'Job:':<{col}}tail -F {get_launcher_log_dir(log_dir.parent.parent)}/*job_*.log")
|
||||
if trainer:
|
||||
log_lines.append(f"{i1}{'Trainer:':<{col}}tail -F {log_dir}/trainer.log")
|
||||
if num_train_nodes > 1:
|
||||
@@ -104,13 +145,21 @@ CACHE_DIR = home_dir() / ".cache" / "prime-rl"
|
||||
|
||||
|
||||
def get_config_dir(output_dir: Path) -> Path:
|
||||
"""Resolved per-component config dumps (JSON). The launch TOML copy lives one
|
||||
level up, at `configs/<entrypoint>.toml`."""
|
||||
return output_dir / "configs" / "resolved"
|
||||
"""Return the current attempt's resolved config directory.
|
||||
|
||||
The environment override pins child processes to their launch attempt. The
|
||||
legacy path keeps tools compatible with runs created before config attempts.
|
||||
"""
|
||||
if config_dir := os.environ.get("PRL_ATTEMPT_CONFIG_DIR"):
|
||||
return Path(config_dir)
|
||||
configs_dir = output_dir / "configs"
|
||||
latest = configs_dir / "latest" / "resolved"
|
||||
legacy = configs_dir / "resolved"
|
||||
return legacy if legacy.is_dir() and not latest.exists() else latest
|
||||
|
||||
|
||||
def write_launch_toml(run_dir: Path, name: str) -> None:
|
||||
"""Copy the launch `@` TOML file(s) verbatim to `configs/<name>.toml`."""
|
||||
def write_launch_toml(config_dir: Path, name: str) -> None:
|
||||
"""Copy the launch `@` TOML file(s) to the current config attempt."""
|
||||
import sys
|
||||
|
||||
argv = sys.argv[1:]
|
||||
@@ -124,9 +173,17 @@ def write_launch_toml(run_dir: Path, name: str) -> None:
|
||||
if not tomls:
|
||||
return
|
||||
texts = [text for _, text in tomls] if len(tomls) == 1 else [f"# @ {p}\n{text}" for p, text in tomls]
|
||||
config_dir = run_dir / "configs"
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
(config_dir / f"{name}.toml").write_text("\n".join(texts))
|
||||
attempt_dir = config_dir.parent
|
||||
attempt_dir.mkdir(parents=True, exist_ok=True)
|
||||
(attempt_dir / f"{name}.toml").write_text("\n".join(texts))
|
||||
|
||||
|
||||
def get_launcher_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "launcher"
|
||||
|
||||
|
||||
def get_launcher_log_dir(output_dir: Path) -> Path:
|
||||
return get_launcher_dir(output_dir) / "logs"
|
||||
|
||||
|
||||
def get_ckpt_dir(output_dir: Path) -> Path:
|
||||
@@ -174,10 +231,9 @@ def has_checkpoints(output_dir: Path) -> bool:
|
||||
return ckpt_dir.exists() and any(ckpt_dir.iterdir())
|
||||
|
||||
|
||||
# Launcher artifacts that may exist in a run directory before training starts: resolved
|
||||
# configs and the SLURM script/job log (a submitted job re-invokes the entrypoint inside
|
||||
# the run directory). Everything else is treated as artifacts of a previous run.
|
||||
LAUNCHER_ARTIFACTS = ("configs", "rl.sbatch", "sft.sbatch", "job_*.log")
|
||||
# Launcher artifacts may exist before training starts. Everything else is treated as
|
||||
# artifacts of a previous run.
|
||||
LAUNCHER_ARTIFACTS = ("configs", "launcher")
|
||||
|
||||
|
||||
def has_run_artifacts(run_dir: Path) -> bool:
|
||||
@@ -185,7 +241,13 @@ def has_run_artifacts(run_dir: Path) -> bool:
|
||||
if not run_dir.exists():
|
||||
return False
|
||||
launcher_entries = {entry for pattern in LAUNCHER_ARTIFACTS for entry in run_dir.glob(pattern)}
|
||||
return any(entry not in launcher_entries for entry in run_dir.iterdir())
|
||||
for entry in run_dir.iterdir():
|
||||
if entry in launcher_entries:
|
||||
continue
|
||||
if entry.name == "logs" and entry.is_dir() and not any(path.is_file() for path in entry.rglob("*")):
|
||||
continue
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def validate_run_dir(
|
||||
@@ -229,17 +291,17 @@ def validate_run_dir(
|
||||
|
||||
|
||||
def clean_future_steps(output_dir: Path, resume_step: int) -> None:
|
||||
"""Remove stale rollouts, broadcasts, and traces past ``resume_step``.
|
||||
"""Remove stale rollouts past ``resume_step`` and broadcasts from it onward.
|
||||
|
||||
Pass ``resume_step=-1`` to wipe every step directory (fresh runs).
|
||||
"""
|
||||
dirs = [
|
||||
get_rollout_dir(output_dir),
|
||||
get_broadcast_dir(output_dir),
|
||||
cleanup_rules = [
|
||||
(get_rollout_dir(output_dir), lambda step: step > resume_step),
|
||||
(get_broadcast_dir(output_dir), lambda step: step >= resume_step),
|
||||
]
|
||||
|
||||
for directory in dirs:
|
||||
steps_to_delete = [step for step in get_all_ckpt_steps(directory) if step > resume_step]
|
||||
for directory, should_delete in cleanup_rules:
|
||||
steps_to_delete = [step for step in get_all_ckpt_steps(directory) if should_delete(step)]
|
||||
if not steps_to_delete:
|
||||
continue
|
||||
get_logger().info(
|
||||
|
||||
@@ -163,13 +163,6 @@ def get_free_port() -> int:
|
||||
return port
|
||||
|
||||
|
||||
def final_broadcast_version(max_steps: int, broadcast_final: bool) -> int:
|
||||
"""Newest policy version the trainer will ever broadcast: v{max_steps} when
|
||||
something consumes it (a configured final eval), else v{max_steps - 1} -
|
||||
training never samples from the final version."""
|
||||
return max_steps if broadcast_final else max_steps - 1
|
||||
|
||||
|
||||
@contextmanager
|
||||
def default_dtype(dtype):
|
||||
prev = torch.get_default_dtype()
|
||||
|
||||
@@ -86,7 +86,18 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
|
||||
# resolved concatenated document renders as a tree
|
||||
page.click("#tabs [data-tab=config]")
|
||||
page.wait_for_timeout(1500)
|
||||
assert page.locator("#config-attempt-select").input_value() == "latest"
|
||||
assert page.locator("#config-attempt-select option:checked").inner_text().startswith("latest (attempt ")
|
||||
assert page.eval_on_selector("#config-view", "e => e.innerText.length") > 100, "config view did not render"
|
||||
if page.locator("#config-attempt-select option").count() > 2:
|
||||
latest_config = page.locator("#config-view").inner_text()
|
||||
first_attempt = page.locator("#config-attempt-select option").nth(1).get_attribute("value")
|
||||
page.locator("#config-attempt-select").select_option(first_attempt, force=True)
|
||||
page.wait_for_timeout(1000)
|
||||
assert page.locator("#config-attempt-select").input_value() == first_attempt
|
||||
assert page.locator("#config-view").inner_text() != latest_config
|
||||
page.locator("#config-attempt-select").select_option("latest", force=True)
|
||||
page.wait_for_timeout(1000)
|
||||
page.click("#config-format [data-fmt=json]")
|
||||
page.wait_for_timeout(1500)
|
||||
assert page.locator("#config-view .j-line").count() > 10, "resolved config tree did not render"
|
||||
@@ -111,6 +122,8 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
|
||||
# logs: the merged pane shows lines
|
||||
page.click("#tabs [data-tab=logs]")
|
||||
page.wait_for_timeout(PAGE_SETTLE_MS)
|
||||
assert page.locator("#attempt-select").input_value() == "latest"
|
||||
assert page.locator("#attempt-select option:checked").inner_text().startswith("latest (attempt ")
|
||||
log_lines = page.locator(".log-pane .ll").count()
|
||||
assert log_lines > 10, f"log pane rendered only {log_lines} lines"
|
||||
|
||||
|
||||
@@ -2,14 +2,18 @@ from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.utils.weights import load_state_dict
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.integration.dashboard_smoke import make_dashboard_test
|
||||
from tests.utils import (
|
||||
check_avg_mismatch_kl_in_range,
|
||||
check_hf_load,
|
||||
check_no_error,
|
||||
check_reward_goes_up,
|
||||
check_reward_in_range,
|
||||
convert_checkpoint,
|
||||
strip_escape_codes,
|
||||
)
|
||||
|
||||
@@ -129,4 +133,24 @@ def test_reward_in_range_resume(rl_resume_process: ProcessResult, test_no_error_
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.6)
|
||||
|
||||
|
||||
def test_convert_final_checkpoint(rl_resume_process: ProcessResult, run_dir: Path, tmp_path: Path):
|
||||
"""The final DCP checkpoint converts to bf16 and fp8 (direct == chained), and the exports reload in HF."""
|
||||
assert rl_resume_process.returncode == 0
|
||||
step_dir = run_dir / "checkpoints" / "step_20"
|
||||
convert_checkpoint("dcp_to_bf16", step_dir)
|
||||
convert_checkpoint("dcp_to_fp8", step_dir)
|
||||
check_hf_load(step_dir / "weights")
|
||||
|
||||
# Quantizing the bf16 export reproduces the direct dcp->fp8 export byte-for-byte.
|
||||
convert_checkpoint("bf16_to_fp8", step_dir / "weights", tmp_path / "fp8-chained")
|
||||
direct = load_state_dict(step_dir / "weights-FP8")
|
||||
chained = load_state_dict(tmp_path / "fp8-chained")
|
||||
assert set(direct) == set(chained)
|
||||
for key in direct:
|
||||
assert torch.equal(direct[key].view(torch.uint8), chained[key].view(torch.uint8)), key
|
||||
|
||||
convert_checkpoint("fp8_to_bf16", step_dir / "weights-FP8", tmp_path / "dequant")
|
||||
check_hf_load(tmp_path / "dequant")
|
||||
|
||||
|
||||
test_dashboard = make_dashboard_test("rl_process", RUN_NAME)
|
||||
|
||||
@@ -7,7 +7,7 @@ from torch.distributed.checkpoint.format_utils import dcp_to_torch_save
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.integration.dashboard_smoke import make_dashboard_test
|
||||
from tests.utils import check_loss_goes_down, strip_escape_codes
|
||||
from tests.utils import check_hf_load, check_loss_goes_down, convert_checkpoint, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
|
||||
|
||||
@@ -173,4 +173,15 @@ def test_full_offload_model_only_resume_preserves_weights(
|
||||
)
|
||||
|
||||
|
||||
def test_convert_final_checkpoint(sft_resume_process: ProcessResult, run_dir: Path, tmp_path: Path):
|
||||
"""The final DCP checkpoint converts to bf16 and fp8, and the exports reload in HF."""
|
||||
assert sft_resume_process.returncode == 0
|
||||
step_dir = run_dir / "checkpoints" / "step_10"
|
||||
convert_checkpoint("dcp_to_bf16", step_dir)
|
||||
convert_checkpoint("dcp_to_fp8", step_dir)
|
||||
check_hf_load(step_dir / "weights")
|
||||
convert_checkpoint("fp8_to_bf16", step_dir / "weights-FP8", tmp_path / "dequant")
|
||||
check_hf_load(tmp_path / "dequant")
|
||||
|
||||
|
||||
test_dashboard = make_dashboard_test("sft_process", RUN_NAME)
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import pytest
|
||||
|
||||
from prime_rl.utils.pathing import validate_run_dir
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_dirs,
|
||||
get_broadcast_dir,
|
||||
get_rollout_dir,
|
||||
get_step_path,
|
||||
validate_run_dir,
|
||||
)
|
||||
|
||||
|
||||
def test_nonexistent_dir_passes(tmp_path):
|
||||
@@ -17,10 +24,19 @@ def test_empty_dir_passes(tmp_path):
|
||||
def test_dir_with_launcher_artifacts_passes(tmp_path):
|
||||
run_dir = tmp_path / "submitted"
|
||||
run_dir.mkdir()
|
||||
(run_dir / "configs").mkdir()
|
||||
(run_dir / "configs" / "trainer.toml").touch()
|
||||
(run_dir / "rl.sbatch").touch()
|
||||
(run_dir / "job_1234.log").touch()
|
||||
config_dir, log_dir = create_attempt_dirs(run_dir)
|
||||
(config_dir / "trainer.json").touch()
|
||||
next_config_dir, next_log_dir = create_attempt_dirs(run_dir)
|
||||
assert next_config_dir.parent.name == "attempt_2"
|
||||
assert next_log_dir.name == "attempt_2"
|
||||
assert (run_dir / "configs" / "latest").resolve() == next_config_dir.parent
|
||||
assert (run_dir / "logs" / "latest").resolve() == next_log_dir
|
||||
(run_dir / "launcher").mkdir()
|
||||
(run_dir / "launcher" / "rl.sbatch").touch()
|
||||
(run_dir / "launcher" / ".trainer.done").touch()
|
||||
(run_dir / "launcher" / ".orchestrator.done").touch()
|
||||
(run_dir / "launcher" / "logs").mkdir()
|
||||
(run_dir / "launcher" / "logs" / "job_1234.log").touch()
|
||||
validate_run_dir(run_dir, output_dir=tmp_path, resuming=False, clean=False)
|
||||
|
||||
|
||||
@@ -84,3 +100,20 @@ def test_clean_outside_output_dir_raises(tmp_path):
|
||||
with pytest.raises(ValueError, match="remain under output_dir"):
|
||||
validate_run_dir(escaped, output_dir=tmp_path / "outputs", resuming=False, clean=True)
|
||||
assert escaped.exists()
|
||||
|
||||
|
||||
def test_clean_future_steps_rebuilds_resume_broadcast(tmp_path):
|
||||
rollout_dir = get_rollout_dir(tmp_path)
|
||||
broadcast_dir = get_broadcast_dir(tmp_path)
|
||||
for parent in (rollout_dir, broadcast_dir):
|
||||
for step in (1, 2, 3):
|
||||
get_step_path(parent, step).mkdir(parents=True)
|
||||
|
||||
clean_future_steps(tmp_path, resume_step=2)
|
||||
|
||||
assert get_step_path(rollout_dir, 1).exists()
|
||||
assert get_step_path(rollout_dir, 2).exists()
|
||||
assert not get_step_path(rollout_dir, 3).exists()
|
||||
assert get_step_path(broadcast_dir, 1).exists()
|
||||
assert not get_step_path(broadcast_dir, 2).exists()
|
||||
assert not get_step_path(broadcast_dir, 3).exists()
|
||||
|
||||
+21
-1
@@ -108,7 +108,7 @@ def check_loss_goes_down(lines: list[str]):
|
||||
|
||||
|
||||
def check_final_eval_reward_above(lines: list[str], env_name: str, min_threshold: float):
|
||||
"""Assert the LAST `Evaluated {env_name} (Step N) | ... | Reward X.XXXX`
|
||||
"""Assert the last `Evaluated {env_name} | ... | Reward X.XXXX`
|
||||
line reports a reward above ``min_threshold``.
|
||||
|
||||
Robust for short distill smokes: until the policy converges, eval reward is
|
||||
@@ -223,3 +223,23 @@ def check_mismatch_kl_in_range(
|
||||
min_threshold=min_threshold,
|
||||
max_threshold=max_threshold,
|
||||
)
|
||||
|
||||
|
||||
def convert_checkpoint(converter: str, *args: Path) -> None:
|
||||
"""Run ``tools/convert_<converter>.py`` on a checkpoint."""
|
||||
import subprocess
|
||||
|
||||
cmd = ["uv", "run", "python", f"tools/convert_{converter}.py", *[str(arg) for arg in args]]
|
||||
subprocess.run(cmd, check=True, timeout=600)
|
||||
|
||||
|
||||
def check_hf_load(weights_dir: Path) -> None:
|
||||
"""Helper to assert that an exported checkpoint loads as an HF model with no missing/unexpected tensors"""
|
||||
import torch
|
||||
from transformers import AutoModelForCausalLM
|
||||
|
||||
model, loading_info = AutoModelForCausalLM.from_pretrained(weights_dir, output_loading_info=True)
|
||||
assert not loading_info["missing_keys"], f"missing keys: {loading_info['missing_keys'][:5]}"
|
||||
assert not loading_info["unexpected_keys"], f"unexpected keys: {loading_info['unexpected_keys'][:5]}"
|
||||
assert not loading_info["mismatched_keys"], f"mismatched keys: {loading_info['mismatched_keys'][:5]}"
|
||||
assert all(torch.isfinite(param).all() for param in model.parameters())
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Quantize a bf16 HF safetensors checkpoint to blockwise FP8 (DeepSeek/GLM format).
|
||||
|
||||
2D linear weights are quantized to e4m3 with per-128x128-block fp32 scales
|
||||
stored under ``<name>.weight_scale_inv``; norms, embeddings, lm_head, router
|
||||
gates and other sensitive modules stay in the source dtype. The output dir gets
|
||||
the quantized shards, a rewritten index, all non-weight assets, and a
|
||||
``quantization_config`` block in ``config.json`` that vLLM loads natively.
|
||||
|
||||
Usage (from the prime-rl repo):
|
||||
uv run python tools/convert_bf16_to_fp8.py <model_dir> [output_dir] [--block-size 128]
|
||||
|
||||
Writes to ``<model_dir>-FP8`` by default.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from safetensors import safe_open
|
||||
from safetensors.torch import save_file
|
||||
|
||||
from prime_rl.trainer.models.fp8 import quantize_to_fp8_blockwise
|
||||
|
||||
# Module-name substrings that stay unquantized: norms, embeddings, output head,
|
||||
# MoE router gates, GatedDeltaNet low-rank projections, MTP/indexer projections,
|
||||
# vision tower. Mirrors the trainer's _DEFAULT_FP8_IGNORE_PATTERNS
|
||||
# (configs/trainer.py), adapted to HF checkpoint names.
|
||||
SKIP_SUBSTRINGS = (
|
||||
"norm",
|
||||
"embed",
|
||||
"lm_head",
|
||||
"shared_expert_gate",
|
||||
"in_proj_a",
|
||||
"in_proj_b",
|
||||
"eh_proj",
|
||||
"weights_proj",
|
||||
"visual.",
|
||||
"router",
|
||||
)
|
||||
|
||||
|
||||
def should_quantize(name: str, tensor: torch.Tensor) -> bool:
|
||||
return (
|
||||
name.endswith(".weight")
|
||||
and tensor.ndim == 2
|
||||
and tensor.is_floating_point()
|
||||
and tensor.element_size() > 1
|
||||
and not name.endswith(".gate.weight")
|
||||
and not any(substring in name for substring in SKIP_SUBSTRINGS)
|
||||
)
|
||||
|
||||
|
||||
def quantize_state_dict(
|
||||
tensors: dict[str, torch.Tensor], block_size: int, device: str
|
||||
) -> tuple[dict[str, torch.Tensor], list[str]]:
|
||||
"""Quantize the quantizable tensors of one CPU state-dict slice; returns (out, modules kept in bf16).
|
||||
|
||||
Tensors move to ``device`` one at a time (and are popped from the input as they
|
||||
are consumed), so peak device memory stays near the largest single weight.
|
||||
"""
|
||||
out: dict[str, torch.Tensor] = {}
|
||||
modules_to_not_convert: list[str] = []
|
||||
for name in list(tensors):
|
||||
tensor = tensors.pop(name)
|
||||
if should_quantize(name, tensor):
|
||||
quantized, scales = quantize_to_fp8_blockwise(tensor.to(device), block_size)
|
||||
out[name] = quantized.cpu()
|
||||
out[name + "_scale_inv"] = scales.cpu()
|
||||
else:
|
||||
if name.endswith(".weight") and tensor.ndim == 2 and tensor.is_floating_point():
|
||||
modules_to_not_convert.append(name.removesuffix(".weight"))
|
||||
if name.endswith(".weight") and tensor.ndim > 2 and tensor.numel() > 1_000_000:
|
||||
print(f"Warning: leaving large {tensor.ndim}D tensor unquantized: {name} {tuple(tensor.shape)}")
|
||||
out[name] = tensor.cpu()
|
||||
return out, modules_to_not_convert
|
||||
|
||||
|
||||
def quantization_config(modules_to_not_convert: list[str], block_size: int) -> dict:
|
||||
return {
|
||||
"quant_method": "fp8",
|
||||
"fmt": "e4m3",
|
||||
"activation_scheme": "dynamic",
|
||||
"weight_block_size": [block_size, block_size],
|
||||
"modules_to_not_convert": sorted(set(modules_to_not_convert)),
|
||||
}
|
||||
|
||||
|
||||
def list_shards(model_dir: Path) -> list[str]:
|
||||
index_path = model_dir / "model.safetensors.index.json"
|
||||
if index_path.exists():
|
||||
weight_map = json.loads(index_path.read_text())["weight_map"]
|
||||
return sorted(set(weight_map.values()))
|
||||
if (model_dir / "model.safetensors").exists():
|
||||
return ["model.safetensors"]
|
||||
raise FileNotFoundError(f"No safetensors checkpoint found in {model_dir}")
|
||||
|
||||
|
||||
def convert(input_dir: Path, output_dir: Path | None = None, block_size: int = 128) -> Path:
|
||||
input_dir = input_dir.resolve()
|
||||
output_dir = output_dir or input_dir.with_name(input_dir.name + "-FP8")
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
|
||||
weight_map: dict[str, str] = {}
|
||||
total_size = 0
|
||||
modules_to_not_convert: list[str] = []
|
||||
num_quantized = 0
|
||||
|
||||
for shard_name in list_shards(input_dir):
|
||||
# Shards land in host memory; quantize_state_dict streams them through the
|
||||
# device tensor-by-tensor so a whole shard never sits on the GPU at once.
|
||||
with safe_open(input_dir / shard_name, framework="pt", device="cpu") as f:
|
||||
tensors = {name: f.get_tensor(name) for name in f.keys()}
|
||||
out_shard, shard_modules = quantize_state_dict(tensors, block_size, device)
|
||||
modules_to_not_convert.extend(shard_modules)
|
||||
num_quantized += sum(1 for name in out_shard if name.endswith("_scale_inv"))
|
||||
for name, tensor in out_shard.items():
|
||||
weight_map[name] = shard_name
|
||||
total_size += tensor.nbytes
|
||||
save_file(out_shard, output_dir / shard_name, metadata={"format": "pt"})
|
||||
print(f"Quantized {shard_name} ({num_quantized} tensors so far)")
|
||||
|
||||
if num_quantized == 0:
|
||||
raise ValueError(f"No quantizable weights found in {input_dir} - is this a bf16 checkpoint?")
|
||||
|
||||
index = {"metadata": {"total_size": total_size}, "weight_map": weight_map}
|
||||
(output_dir / "model.safetensors.index.json").write_text(json.dumps(index, indent=2, sort_keys=True) + "\n")
|
||||
|
||||
for path in input_dir.iterdir():
|
||||
if path.is_file() and path.suffix != ".safetensors" and path.name != "model.safetensors.index.json":
|
||||
shutil.copyfile(path, output_dir / path.name)
|
||||
|
||||
config_path = input_dir / "config.json"
|
||||
config = json.loads(config_path.read_text())
|
||||
config["quantization_config"] = quantization_config(modules_to_not_convert, block_size)
|
||||
(output_dir / "config.json").write_text(json.dumps(config, indent=2) + "\n")
|
||||
print(f"Done: {num_quantized} weights quantized -> {output_dir}")
|
||||
return output_dir
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("input_dir", type=Path, help="HF safetensors model dir (bf16/fp16/fp32)")
|
||||
parser.add_argument("output_dir", type=Path, nargs="?", default=None, help="default: <input_dir>-FP8")
|
||||
parser.add_argument("--block-size", type=int, default=128)
|
||||
args = parser.parse_args()
|
||||
convert(args.input_dir, args.output_dir, args.block_size)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Convert a DCP trainer checkpoint into bf16 HF-format weights offline.
|
||||
|
||||
The trainer saves only DCP checkpoints; every HF export goes through this
|
||||
script. It mirrors the trainer's broadcast save path: build the model, DCP-load
|
||||
the checkpoint's model state, gather rank-parallel, convert to HF format, and
|
||||
write sharded safetensors plus config/tokenizer assets.
|
||||
|
||||
The model and tokenizer configs are read from the run's resolved config
|
||||
(``<run>/configs/latest/resolved/trainer.json`` or ``sft.json``). LoRA checkpoints are not
|
||||
supported — the script exports full fine-tunes only.
|
||||
|
||||
Usage (from the prime-rl repo; more ranks = faster gathers and writes, and
|
||||
models too big for one GPU need enough ranks to shard across):
|
||||
uv run python tools/convert_dcp_to_bf16.py <run>/checkpoints/step_{n} [output_dir]
|
||||
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_bf16.py \
|
||||
<run>/checkpoints/step_{n} [output_dir]
|
||||
|
||||
Writes to ``<ckpt_dir>/weights`` by default.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch.distributed.checkpoint import FileSystemReader
|
||||
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
|
||||
|
||||
from prime_rl.configs.trainer import ModelConfig, TokenizerConfig
|
||||
from prime_rl.trainer.ckpt import AppState
|
||||
from prime_rl.trainer.model import setup_model, setup_processor, setup_tokenizer
|
||||
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
|
||||
from prime_rl.trainer.utils import setup_torch_distributed
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_config_dir
|
||||
from prime_rl.utils.weights import (
|
||||
convert_state_dict_to_hf,
|
||||
gather_weights_parallel,
|
||||
save_state_dict_parallel,
|
||||
)
|
||||
|
||||
# Training kernels and parallelism settings do not apply to an offline export.
|
||||
# Resolve parallelism for the converter's world size and use portable kernels.
|
||||
CONVERSION_OVERRIDES = {
|
||||
"compile": None,
|
||||
"ac": None,
|
||||
"dp_replicate": 1,
|
||||
"cp": 1,
|
||||
"ep": "auto",
|
||||
"ep_comm_backend": "torch",
|
||||
"attn": "flash_attention_2",
|
||||
"moe_fused_kernel": False,
|
||||
}
|
||||
|
||||
RUN_CONFIG_NAMES = ("trainer.json", "sft.json")
|
||||
|
||||
|
||||
def resolve_dcp_dir(ckpt_dir: Path) -> Path:
|
||||
"""The DCP checkpoint id for a step dir (``step_{n}``) or its ``trainer`` subdir."""
|
||||
if (ckpt_dir / "trainer" / ".metadata").exists():
|
||||
return ckpt_dir / "trainer"
|
||||
if (ckpt_dir / ".metadata").exists():
|
||||
return ckpt_dir
|
||||
raise FileNotFoundError(f"No DCP checkpoint found at {ckpt_dir} (expected {ckpt_dir}/trainer/.metadata)")
|
||||
|
||||
|
||||
def resolve_run_configs(step_dir: Path) -> tuple[ModelConfig, TokenizerConfig]:
|
||||
"""Model/tokenizer configs from the run's resolved config."""
|
||||
logger = get_logger()
|
||||
config_dir = get_config_dir(step_dir.parent.parent)
|
||||
for name in RUN_CONFIG_NAMES:
|
||||
path = config_dir / name
|
||||
if path.exists():
|
||||
logger.info(f"Reading model config from {path}")
|
||||
run_config = json.loads(path.read_text())
|
||||
break
|
||||
else:
|
||||
raise FileNotFoundError(
|
||||
f"No resolved run config ({' or '.join(RUN_CONFIG_NAMES)}) found under {config_dir} "
|
||||
"- the checkpoint must live in its run directory"
|
||||
)
|
||||
|
||||
model = ModelConfig(**run_config["model"])
|
||||
tokenizer = TokenizerConfig(**run_config["tokenizer"])
|
||||
return model.model_copy(update=CONVERSION_OVERRIDES), tokenizer
|
||||
|
||||
|
||||
def check_not_lora(model_config: ModelConfig, dcp_dir: Path) -> None:
|
||||
if model_config.lora is not None:
|
||||
raise ValueError("LoRA checkpoints are not supported - dcp_to_bf16 exports full fine-tunes only")
|
||||
metadata = FileSystemReader(dcp_dir).read_metadata()
|
||||
lora_keys = [k for k in metadata.state_dict_metadata if "lora_A" in k or "lora_B" in k or ".base_layer." in k]
|
||||
if lora_keys:
|
||||
raise ValueError(
|
||||
f"Checkpoint contains LoRA keys (e.g. {lora_keys[0]}) - dcp_to_bf16 exports full fine-tunes only"
|
||||
)
|
||||
|
||||
|
||||
def setup_single_process_env() -> None:
|
||||
"""Default the torchrun env vars so the script also runs under plain ``python``."""
|
||||
if "RANK" in os.environ:
|
||||
return
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("localhost", 0))
|
||||
free_port = sock.getsockname()[1]
|
||||
os.environ["MASTER_ADDR"] = "localhost"
|
||||
os.environ["MASTER_PORT"] = str(free_port)
|
||||
os.environ["RANK"] = "0"
|
||||
os.environ["WORLD_SIZE"] = "1"
|
||||
os.environ["LOCAL_RANK"] = "0"
|
||||
os.environ["LOCAL_WORLD_SIZE"] = "1"
|
||||
|
||||
|
||||
def save_model_assets(model, model_config: ModelConfig, tokenizer_config: TokenizerConfig, output_dir: Path) -> None:
|
||||
"""Save model config, generation config, processor and tokenizer next to the weights."""
|
||||
model.config.save_pretrained(output_dir)
|
||||
if model.generation_config:
|
||||
# training sets use_cache=False which can conflict with cache_implementation —
|
||||
# save with use_cache=True without mutating the model's config
|
||||
gen_config = deepcopy(model.generation_config)
|
||||
gen_config.use_cache = True
|
||||
gen_config.save_pretrained(output_dir)
|
||||
# Processor first: it saves its own (unmodified) tokenizer, which the configured
|
||||
# tokenizer (pad token, custom chat template) must override.
|
||||
processor = setup_processor(model_config)
|
||||
if processor is not None:
|
||||
processor.save_pretrained(output_dir)
|
||||
if tokenizer_config.name is None:
|
||||
tokenizer_config = tokenizer_config.model_copy(update={"name": model_config.name})
|
||||
setup_tokenizer(tokenizer_config).save_pretrained(output_dir)
|
||||
# Local trust_remote_code models localize auto_map to plain module names, so the
|
||||
# custom code files must travel with the weights.
|
||||
source_dir = Path(model_config.name)
|
||||
if source_dir.is_dir():
|
||||
for path in source_dir.glob("*.py"):
|
||||
shutil.copyfile(path, output_dir / path.name)
|
||||
|
||||
|
||||
def load_and_convert(ckpt_dir: Path):
|
||||
"""DCP-load a checkpoint and gather it as a rank-partial HF-format bf16 state dict.
|
||||
|
||||
Returns ``(model, model_config, tokenizer_config, state_dict, step_dir)``.
|
||||
"""
|
||||
logger = setup_logger("info")
|
||||
|
||||
dcp_dir = resolve_dcp_dir(ckpt_dir)
|
||||
step_dir = dcp_dir.parent
|
||||
model_config, tokenizer_config = resolve_run_configs(step_dir)
|
||||
check_not_lora(model_config, dcp_dir)
|
||||
|
||||
setup_single_process_env()
|
||||
setup_torch_distributed()
|
||||
|
||||
resolve_ep(model_config)
|
||||
parallel_dims = get_parallel_dims(model_config)
|
||||
model = setup_model(model_config, parallel_dims, loading_from_checkpoint_later=True)
|
||||
|
||||
logger.info(f"Loading DCP checkpoint from {dcp_dir}")
|
||||
dcp_load(state_dict={"app": AppState(model, [], None, None)}, checkpoint_id=dcp_dir)
|
||||
|
||||
logger.info("Gathering and converting weights")
|
||||
state_dict = gather_weights_parallel(model, dtype=torch.bfloat16)
|
||||
if getattr(model.config, "tie_word_embeddings", False):
|
||||
for key in getattr(model, "_tied_weights_keys", []):
|
||||
state_dict.pop(key, None)
|
||||
state_dict = convert_state_dict_to_hf(model, state_dict)
|
||||
return model, model_config, tokenizer_config, state_dict, step_dir
|
||||
|
||||
|
||||
def convert(ckpt_dir: Path, output_dir: Path | None = None) -> Path:
|
||||
logger = get_logger()
|
||||
model, model_config, tokenizer_config, state_dict, step_dir = load_and_convert(ckpt_dir)
|
||||
output_dir = output_dir if output_dir is not None else step_dir / "weights"
|
||||
|
||||
logger.info(f"Writing HF weights to {output_dir}")
|
||||
save_state_dict_parallel(state_dict, output_dir)
|
||||
if get_world().is_master:
|
||||
save_model_assets(model, model_config, tokenizer_config, output_dir)
|
||||
logger.info(f"Done: {output_dir}")
|
||||
return output_dir
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument(
|
||||
"ckpt_dir", type=Path, help="the DCP checkpoint (<run>/checkpoints/step_{n} or .../step_{n}/trainer)"
|
||||
)
|
||||
parser.add_argument("output_dir", type=Path, nargs="?", default=None, help="default: <ckpt_dir>/weights")
|
||||
args = parser.parse_args()
|
||||
convert(args.ckpt_dir, args.output_dir)
|
||||
dist.destroy_process_group()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Convert a DCP trainer checkpoint into blockwise-FP8 HF weights.
|
||||
|
||||
Same gather as ``dcp_to_bf16``, but each rank quantizes its slice on GPU and
|
||||
only the fp8 shards are written — no intermediate bf16 export on disk.
|
||||
|
||||
Usage (from the prime-rl repo; more ranks = faster gathers, quantization and writes):
|
||||
uv run python tools/convert_dcp_to_fp8.py <run>/checkpoints/step_{n} [output_dir]
|
||||
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_fp8.py \
|
||||
<run>/checkpoints/step_{n} [output_dir]
|
||||
|
||||
Writes to ``<ckpt_dir>/weights-FP8`` by default.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from convert_bf16_to_fp8 import quantization_config, quantize_state_dict
|
||||
from convert_dcp_to_bf16 import load_and_convert, save_model_assets
|
||||
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.weights import save_state_dict_parallel
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument(
|
||||
"ckpt_dir", type=Path, help="the DCP checkpoint (<run>/checkpoints/step_{n} or .../step_{n}/trainer)"
|
||||
)
|
||||
parser.add_argument("output_dir", type=Path, nargs="?", default=None, help="default: <ckpt_dir>/weights-FP8")
|
||||
parser.add_argument("--block-size", type=int, default=128)
|
||||
args = parser.parse_args()
|
||||
|
||||
model, model_config, tokenizer_config, state_dict, step_dir = load_and_convert(args.ckpt_dir)
|
||||
output_dir = args.output_dir if args.output_dir is not None else step_dir / "weights-FP8"
|
||||
logger = get_logger()
|
||||
world = get_world()
|
||||
|
||||
logger.info("Quantizing weights to blockwise fp8")
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
state_dict, modules_to_not_convert = quantize_state_dict(state_dict, args.block_size, device)
|
||||
|
||||
logger.info(f"Writing fp8 weights to {output_dir}")
|
||||
save_state_dict_parallel(state_dict, output_dir)
|
||||
|
||||
all_modules: list[list[str] | None] = [None] * world.world_size
|
||||
dist.all_gather_object(all_modules, modules_to_not_convert)
|
||||
dist.destroy_process_group()
|
||||
|
||||
if world.is_master:
|
||||
save_model_assets(model, model_config, tokenizer_config, output_dir)
|
||||
config_path = output_dir / "config.json"
|
||||
config = json.loads(config_path.read_text())
|
||||
config["quantization_config"] = quantization_config(
|
||||
[module for modules in all_modules for module in modules or []], args.block_size
|
||||
)
|
||||
config_path.write_text(json.dumps(config, indent=2) + "\n")
|
||||
logger.info(f"Done: {output_dir}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Dequantize a blockwise-FP8 HF checkpoint (DeepSeek/GLM format) to bf16.
|
||||
|
||||
The inverse of ``tools/convert_bf16_to_fp8.py``, and works on official fp8-only
|
||||
releases (e.g. GLM-5-FP8): every e4m3 tensor is multiplied by its
|
||||
``<name>_scale_inv`` per-block scales and stored as bf16, scale tensors are
|
||||
dropped, and ``quantization_config`` is stripped from ``config.json``.
|
||||
|
||||
Usage (from the prime-rl repo):
|
||||
uv run python tools/convert_fp8_to_bf16.py <model_dir> [output_dir]
|
||||
|
||||
Writes to ``<model_dir>-BF16`` by default.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from safetensors import safe_open
|
||||
from safetensors.torch import save_file
|
||||
|
||||
|
||||
def dequantize_blockwise(weight: torch.Tensor, scales: torch.Tensor, block_size: tuple[int, int]) -> torch.Tensor:
|
||||
rows, cols = weight.shape
|
||||
block_rows, block_cols = block_size
|
||||
expanded = scales.repeat_interleave(block_rows, dim=0)[:rows].repeat_interleave(block_cols, dim=1)[:, :cols]
|
||||
return (weight.to(torch.float32) * expanded).to(torch.bfloat16)
|
||||
|
||||
|
||||
def list_shards(model_dir: Path) -> list[str]:
|
||||
index_path = model_dir / "model.safetensors.index.json"
|
||||
if index_path.exists():
|
||||
weight_map = json.loads(index_path.read_text())["weight_map"]
|
||||
return sorted(set(weight_map.values()))
|
||||
if (model_dir / "model.safetensors").exists():
|
||||
return ["model.safetensors"]
|
||||
raise FileNotFoundError(f"No safetensors checkpoint found in {model_dir}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("input_dir", type=Path, help="HF safetensors model dir with blockwise-fp8 weights")
|
||||
parser.add_argument("output_dir", type=Path, nargs="?", default=None, help="default: <input_dir>-BF16")
|
||||
args = parser.parse_args()
|
||||
|
||||
input_dir = args.input_dir.resolve()
|
||||
output_dir = args.output_dir or input_dir.with_name(input_dir.name + "-BF16")
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
|
||||
config = json.loads((input_dir / "config.json").read_text())
|
||||
quantization_config = config.pop("quantization_config", {})
|
||||
if quantization_config.get("scale_fmt") == "ue8m0":
|
||||
raise ValueError("ue8m0 scales are not supported - only plain float weight_scale_inv checkpoints")
|
||||
block_size = tuple(quantization_config.get("weight_block_size", [128, 128]))
|
||||
|
||||
index_path = input_dir / "model.safetensors.index.json"
|
||||
scale_to_shard = json.loads(index_path.read_text())["weight_map"] if index_path.exists() else {}
|
||||
|
||||
# Scales can live in a different shard than their weight; cache the most
|
||||
# recently opened shards to avoid re-reading them per tensor.
|
||||
shard_cache: dict[str, dict[str, torch.Tensor]] = {}
|
||||
|
||||
def get_scales(name: str, current_shard: str) -> torch.Tensor:
|
||||
shard_name = scale_to_shard.get(name, current_shard)
|
||||
if shard_name not in shard_cache:
|
||||
with safe_open(input_dir / shard_name, framework="pt", device=device) as f:
|
||||
shard_cache[shard_name] = {key: f.get_tensor(key) for key in f.keys()}
|
||||
while len(shard_cache) > 2:
|
||||
shard_cache.pop(next(iter(shard_cache)))
|
||||
if name not in shard_cache[shard_name]:
|
||||
raise KeyError(f"Missing {name} for fp8 tensor {name.removesuffix('_scale_inv')}")
|
||||
return shard_cache[shard_name][name]
|
||||
|
||||
weight_map: dict[str, str] = {}
|
||||
total_size = 0
|
||||
num_dequantized = 0
|
||||
|
||||
for shard_name in list_shards(input_dir):
|
||||
out_shard: dict[str, torch.Tensor] = {}
|
||||
with safe_open(input_dir / shard_name, framework="pt", device=device) as f:
|
||||
for name in f.keys():
|
||||
if name.endswith("_scale_inv"):
|
||||
continue
|
||||
tensor = f.get_tensor(name)
|
||||
if tensor.element_size() == 1:
|
||||
scales = get_scales(name + "_scale_inv", shard_name)
|
||||
out_shard[name] = dequantize_blockwise(tensor, scales, block_size).cpu()
|
||||
num_dequantized += 1
|
||||
else:
|
||||
out_shard[name] = tensor.cpu()
|
||||
for name, tensor in out_shard.items():
|
||||
weight_map[name] = shard_name
|
||||
total_size += tensor.nbytes
|
||||
save_file(out_shard, output_dir / shard_name, metadata={"format": "pt"})
|
||||
print(f"Dequantized {shard_name} ({num_dequantized} tensors so far)")
|
||||
|
||||
if num_dequantized == 0:
|
||||
raise ValueError(f"No fp8 weights found in {input_dir} - is this an fp8 checkpoint?")
|
||||
|
||||
index = {"metadata": {"total_size": total_size}, "weight_map": weight_map}
|
||||
(output_dir / "model.safetensors.index.json").write_text(json.dumps(index, indent=2, sort_keys=True) + "\n")
|
||||
|
||||
for path in input_dir.iterdir():
|
||||
if (
|
||||
path.is_file()
|
||||
and path.suffix != ".safetensors"
|
||||
and path.name not in ("model.safetensors.index.json", "config.json")
|
||||
):
|
||||
shutil.copyfile(path, output_dir / path.name)
|
||||
(output_dir / "config.json").write_text(json.dumps(config, indent=2) + "\n")
|
||||
print(f"Done: {num_dequantized} weights dequantized -> {output_dir}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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()
|
||||
@@ -4964,7 +4964,7 @@ dev = [
|
||||
|
||||
[[package]]
|
||||
name = "prime-rl"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "aiolimiter" },
|
||||
@@ -4980,6 +4980,7 @@ dependencies = [
|
||||
{ name = "prime" },
|
||||
{ name = "prime-pydantic-config" },
|
||||
{ name = "prime-rl-configs" },
|
||||
{ name = "psutil" },
|
||||
{ name = "pyarrow" },
|
||||
{ name = "pybase64" },
|
||||
{ name = "pyzmq" },
|
||||
@@ -5139,6 +5140,7 @@ requires-dist = [
|
||||
{ name = "prime-rl", extras = ["gpu"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
|
||||
{ name = "psutil", specifier = ">=7.0.0" },
|
||||
{ name = "pyarrow", specifier = ">=21.0.0" },
|
||||
{ name = "pybase64", specifier = ">=1.4.2" },
|
||||
{ name = "pyzmq", specifier = ">=27.1.0" },
|
||||
|
||||
Reference in New Issue
Block a user