Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b3364d1a8 | ||
|
|
544bd6205a | ||
|
|
3460245d63 | ||
|
|
3758321f08 | ||
|
|
01dc127b1a | ||
|
|
663b53bbc2 | ||
|
|
f96a46f090 | ||
|
|
01994b8168 | ||
|
|
e6b5e4de5d | ||
|
|
a5853ce9ab | ||
|
|
38582b2bf1 | ||
|
|
a266325605 | ||
|
|
b9de4a0f7a | ||
|
|
75663f0d4c | ||
|
|
a975cab86d | ||
|
|
9aa5f1f2c8 | ||
|
|
c09bb0b30c | ||
|
|
3e93371dad | ||
|
|
f53e4d9c63 |
@@ -170,7 +170,7 @@ jobs:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync
|
||||
run: uv sync --all-extras
|
||||
- name: Download all benchmark artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --extra flash-attn --all-packages --locked
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
|
||||
+2
-2
@@ -96,7 +96,7 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
|
||||
# mount here: .git would bust the cache every commit.
|
||||
COPY --from=manifests /manifests /app
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
|
||||
--no-install-workspace \
|
||||
--no-install-package prime-rl-configs \
|
||||
--no-install-package verifiers \
|
||||
@@ -132,7 +132,7 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
|
||||
&& \
|
||||
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
|
||||
&& \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
|
||||
|
||||
|
||||
Vendored
+1
-1
Submodule deps/prime-envs updated: b30aad3637...26dafdc958
Vendored
+1
-1
Submodule deps/renderers updated: 2846a3dcd2...cb82439137
Vendored
+1
-1
Submodule deps/verifiers updated: d4f3d5a8c6...b2e4e81577
@@ -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/
|
||||
ls /tmp/reverse-dry/check/configs/resolved/
|
||||
# rl.json trainer.json orchestrator.json inference.json
|
||||
```
|
||||
|
||||
Each per-process TOML 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/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/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.
|
||||
|
||||
+9
-6
@@ -43,19 +43,20 @@ uv run rl @ rl.toml \
|
||||
|
||||
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
|
||||
|
||||
For quick A/B ablations on the same node, run two RL instances side-by-side in separate tmux sessions, each pinned to half the GPUs and a separate inference port:
|
||||
For quick A/B ablations on the same node, run two RL instances side-by-side in separate shells, each pinned to half the GPUs and a separate inference port, and track both in one dashboard:
|
||||
|
||||
```bash
|
||||
# session 1, GPUs 0–1, default port 8000
|
||||
bash scripts/tmux.sh -s exp1 -o outputs/exp1
|
||||
# shell 1, GPUs 0–1, default port 8000
|
||||
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --run.name exp1
|
||||
|
||||
# session 2, GPUs 2–3, port 8001
|
||||
bash scripts/tmux.sh -s exp2 -o outputs/exp2
|
||||
# shell 2, GPUs 2–3, port 8001
|
||||
CUDA_VISIBLE_DEVICES=2,3 uv run rl @ rl.toml \
|
||||
--inference.server.port 8001 \
|
||||
--orchestrator.model.client.base-url http://localhost:8001/v1 \
|
||||
--run.name exp2
|
||||
|
||||
# watch both side by side
|
||||
uv run dashboard outputs
|
||||
```
|
||||
|
||||
#### SFT and Torchrun
|
||||
@@ -193,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:
|
||||
|
||||
+5
-11
@@ -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 TOMLs to `<run_dir>/configs/`, 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/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
|
||||
|
||||
### Algorithms
|
||||
|
||||
@@ -327,17 +327,11 @@ tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
|
||||
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
|
||||
```
|
||||
|
||||
### Console Output
|
||||
### Dashboard
|
||||
|
||||
`scripts/tmux.sh` opens a 4-pane tmux session that follows `trainer.log`, `orchestrator.log`, `inference.log`, and the union of env worker logs. Start it before launching:
|
||||
`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.
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh -o outputs/my-run
|
||||
# then in the Launcher window:
|
||||
uv run rl @ ... --run.name my-run
|
||||
```
|
||||
|
||||
Pass `-s <session>` and `-o <run_dir>` (the run directory, `<output_dir>/<run_name>`) to run multiple parallel experiments side-by-side in different sessions. The helper also works on a SLURM head node — `bash scripts/tmux.sh my-rl-job /shared/outputs/my-rl-job`.
|
||||
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
|
||||
|
||||
|
||||
@@ -12,9 +12,10 @@ The taskset is included through the Verifiers workspace. After syncing the repos
|
||||
uv run python -c "import alphabet_sort"
|
||||
```
|
||||
|
||||
Start the tmux session:
|
||||
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh
|
||||
uv run dashboard
|
||||
```
|
||||
|
||||
## Task
|
||||
@@ -31,13 +32,13 @@ We use non-default settings to balance the difficulty: 3 fixed turns (instead of
|
||||
|
||||
Start the inference server:
|
||||
```bash
|
||||
# In the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507
|
||||
```
|
||||
|
||||
Evaluate the base model:
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval alphabet-sort --harness.id null \
|
||||
-m Qwen/Qwen3-4B-Instruct-2507 \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
@@ -91,7 +92,7 @@ We train with LoRA (rank 32, alpha 64) for 100 steps.
|
||||
|
||||
*Check out the logs on [W&B](https://wandb.ai/primeintellect/alphabet-sort-4b-lora/workspace?nw=nwuserandrewpi).*
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run rl @ examples/basic/alphabet-sort/rl.toml \
|
||||
--run.name rl \
|
||||
--monitors.wandb.project ... \
|
||||
@@ -106,12 +107,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetS
|
||||
|
||||
Let's see how our final RL checkpoint performs on the eval set.
|
||||
```bash
|
||||
# In the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
|
||||
```
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval alphabet-sort --harness.id null \
|
||||
-m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
|
||||
@@ -12,21 +12,21 @@ The `reverse-text` taskset is included through the Verifiers workspace. After sy
|
||||
uv run python -c "import reverse_text"
|
||||
```
|
||||
|
||||
First, let's start a `tmux` session which we will use throughout the experiment.
|
||||
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh
|
||||
uv run dashboard
|
||||
```
|
||||
|
||||
Let's check how well `Qwen3-0.6B` does out-of-the-box on the `reverse-text` environment.
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.model Qwen/Qwen3-0.6B
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval reverse-text --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
```
|
||||
|
||||
@@ -41,7 +41,7 @@ We will fine-tune `PrimeIntellect/Qwen3-0.6B` ([HF](https://huggingface.co/Prime
|
||||
To train on a single GPU, run
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run sft @ examples/basic/reverse-text/sft.toml \
|
||||
--run.name sft \
|
||||
--monitors.wandb.project ... \
|
||||
@@ -51,7 +51,7 @@ uv run sft @ examples/basic/reverse-text/sft.toml \
|
||||
To train on multiple GPUs, run
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run torchrun \
|
||||
--local-ranks-filter 0 \
|
||||
--nproc-per-node ... \
|
||||
@@ -71,7 +71,7 @@ For the RL we will only do 20 steps at 8x16 rollouts, for a total batch size of
|
||||
*Check out the logs of the RL run on [W&B](https://wandb.ai/primeintellect/examples?nw=yxjwjc556do).*
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run rl @ examples/basic/reverse-text/rl.toml \
|
||||
--model.name ... \
|
||||
--run.name rl \
|
||||
@@ -88,12 +88,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL`
|
||||
Let's see how our final RL checkpoints perform on the `reverse-text` environment.
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval reverse-text --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
```
|
||||
|
||||
|
||||
@@ -25,10 +25,10 @@ Set up the credentials for the configured reference judge:
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
|
||||
Start the tmux session:
|
||||
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh
|
||||
uv run dashboard
|
||||
```
|
||||
|
||||
## Task
|
||||
@@ -69,14 +69,14 @@ Key configuration highlights:
|
||||
Start the inference server:
|
||||
|
||||
```bash
|
||||
# In the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507 --vllm.tool-call-parser hermes
|
||||
```
|
||||
|
||||
Evaluate the base model:
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval wiki-search --harness.id null \
|
||||
-m Qwen/Qwen3-4B-Instruct-2507 \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
@@ -91,7 +91,7 @@ uv run eval wiki-search --harness.id null \
|
||||
Train with the unified config file:
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run rl @ examples/basic/wiki-search/rl.toml \
|
||||
--run.name rl \
|
||||
--monitors.wandb.project your-project-name \
|
||||
@@ -110,12 +110,12 @@ This will write DCP checkpoints in `outputs/rl/checkpoints/step_*`.
|
||||
Evaluate your trained model:
|
||||
|
||||
```bash
|
||||
# In the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSearch-RL --vllm.tool-call-parser hermes
|
||||
```
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval wiki-search --harness.id null \
|
||||
-m <user>/Qwen3-4B-Instruct-WikiSearch-RL \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
|
||||
@@ -12,23 +12,23 @@ The taskset is included through the Verifiers workspace. After syncing the repos
|
||||
uv run python -c "import wordle"
|
||||
```
|
||||
|
||||
Start the pre-layouted `tmux` session which we will use to run all experiments and view logs conveniently
|
||||
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh
|
||||
uv run dashboard
|
||||
```
|
||||
|
||||
Before training, we want to get a baseline score and test how well `Qwen3-1.7B` does out-of-the-box in the `wordle` environment so that we quantify our training effect. To do so, first start a local inference server to serve `Qwen3-1.7B`.
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.model Qwen/Qwen3-1.7B
|
||||
```
|
||||
|
||||
Then, use the `eval` entrypoint to evaluate the model in the `wordle` environment. We evaluate on the 20 evaluation examples which are distinct words not appearing in the training set of the environment. We constrain the response length to 1024 tokens as this should be more than enough to play a full game.
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval wordle --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
```
|
||||
|
||||
@@ -43,7 +43,7 @@ We will fine-tune `PrimeIntellect/Qwen3-1.7B` ([HF](https://huggingface.co/Prime
|
||||
To train on a single GPU, run
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run sft @ examples/basic/wordle/sft.toml \
|
||||
--run.name sft \
|
||||
--monitors.wandb.project ... \
|
||||
@@ -53,7 +53,7 @@ uv run sft @ examples/basic/wordle/sft.toml \
|
||||
To train on multiple GPUs, run
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run torchrun \
|
||||
--local-ranks-filter 0 \
|
||||
--nproc-per-node ... \
|
||||
@@ -74,7 +74,7 @@ Finally, we will do multi-turn RL against the `wordle` environment using the mod
|
||||
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run rl @ examples/basic/wordle/rl.toml \
|
||||
--model.name ... \
|
||||
--run.name rl \
|
||||
@@ -91,12 +91,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](http
|
||||
Let's see how our final RL checkpoint performs on the eval set.
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.model PrimeIntellect/Qwen3-1.7B-Wordle-RL
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval wordle --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
```
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"pydantic>=1.10.13",
|
||||
"prime-pydantic-config>=0.4.3",
|
||||
"renderers>=0.1.9",
|
||||
"renderers>=0.1.10",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.3.0",
|
||||
|
||||
@@ -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):
|
||||
@@ -233,8 +233,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 +285,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."""
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
+41
-30
@@ -13,38 +13,25 @@ dependencies = [
|
||||
"loguru>=0.7.3",
|
||||
"pyarrow>=21.0.0",
|
||||
"numpy>=2.2.6",
|
||||
"torch>=2.9.0",
|
||||
"torchvision",
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers==5.6.2",
|
||||
"vllm>=0.26.0",
|
||||
"mooncake-transfer-engine>=0.3.10.post2",
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.6.19",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"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",
|
||||
"torchtitan",
|
||||
"verifiers[harbor]>=0.3.1.dev59",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
"flash-linear-attention",
|
||||
"nvidia-ml-py>=12.575.51",
|
||||
"verifiers[harbor]>=0.3.1",
|
||||
"renderers>=0.1.10",
|
||||
"pybase64>=1.4.2",
|
||||
"orjson>=3.10",
|
||||
"pandas>=2.0",
|
||||
"msgspec>=0.18",
|
||||
"torchao>=0.17.0",
|
||||
"modelexpress==0.3.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
@@ -55,11 +42,32 @@ 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.entrypoints.dashboard:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
|
||||
|
||||
[project.optional-dependencies]
|
||||
gpu = [
|
||||
"torch>=2.9.0 ; sys_platform == 'linux'",
|
||||
"torchvision ; sys_platform == 'linux'",
|
||||
"torchaudio ; sys_platform == 'linux'",
|
||||
"torchdata>=0.11.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.26.0 ; sys_platform == 'linux'",
|
||||
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
|
||||
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
|
||||
"torchtitan ; sys_platform == 'linux'",
|
||||
"dion ; sys_platform == 'linux'",
|
||||
"tilelang>=0.1.8 ; sys_platform == 'linux'",
|
||||
"flash-linear-attention ; sys_platform == 'linux'",
|
||||
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
|
||||
"torchao>=0.17.0 ; sys_platform == 'linux'",
|
||||
"modelexpress==0.3.0 ; sys_platform == 'linux'",
|
||||
]
|
||||
dashboard = [
|
||||
"fastapi>=0.115",
|
||||
"uvicorn>=0.30",
|
||||
]
|
||||
# Both wheels are the same flash-attn 2.8.3 / cu128 / torch 2.11 / cp312 build and carry
|
||||
# sm_80 / sm_90 / sm_100 / sm_120 cubins. `attn="auto"` picks FA4 on sm_100 and FA3 on
|
||||
# sm_90, so FA2 is the resolved backend on sm_120 (see `_resolve_attn_impl` in
|
||||
@@ -68,30 +76,31 @@ flash-attn = [
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.22/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
|
||||
]
|
||||
flash-attn-3 = ["flash_attn_3"]
|
||||
flash-attn-3 = ["flash_attn_3 ; sys_platform == 'linux'"]
|
||||
|
||||
flash-attn-cute = [
|
||||
"flash-attn-4",
|
||||
"flash-attn-4 ; sys_platform == 'linux'",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64' or platform_machine == 'aarch64'",
|
||||
"deep-gemm",
|
||||
"nixl",
|
||||
"nixl-cu12 ; platform_machine == 'x86_64'",
|
||||
"vllm-router",
|
||||
"deep-ep ; sys_platform == 'linux'",
|
||||
"deep-gemm ; sys_platform == 'linux'",
|
||||
"nixl ; sys_platform == 'linux'",
|
||||
"nixl-cu12 ; sys_platform == 'linux' and platform_machine == 'x86_64'",
|
||||
"vllm-router ; sys_platform == 'linux'",
|
||||
]
|
||||
gpt-oss = [
|
||||
"kernels",
|
||||
"kernels ; sys_platform == 'linux'",
|
||||
]
|
||||
quack = [
|
||||
"quack-kernels>=0.4.1",
|
||||
"quack-kernels>=0.4.1 ; sys_platform == 'linux'",
|
||||
]
|
||||
# Prebuilt `prime-kernels` wheels from a release (see the `kernels` skill). Compiled for
|
||||
# sm_100a; on other GPUs the package installs fine and reports its kernels unavailable.
|
||||
kernels = [
|
||||
"prime-kernels",
|
||||
"prime-kernels ; sys_platform == 'linux'",
|
||||
]
|
||||
all = [
|
||||
"prime-rl[gpu]",
|
||||
"prime-rl[flash-attn]",
|
||||
"prime-rl[disagg]",
|
||||
"prime-rl[quack]",
|
||||
@@ -101,12 +110,13 @@ all = [
|
||||
|
||||
[dependency-groups]
|
||||
mamba-ssm = [
|
||||
"mamba-ssm>=2.3.0",
|
||||
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
|
||||
]
|
||||
dev = [
|
||||
"ipykernel>=6.29.5",
|
||||
"ipywidgets>=8.1.7",
|
||||
"pre-commit>=4.2.0",
|
||||
"playwright>=1.49",
|
||||
"pytest>=8.4.1",
|
||||
"pytest-asyncio>=0.23",
|
||||
"ruff>=0.12.1",
|
||||
@@ -123,6 +133,7 @@ no-build-isolation-package = ["flash-attn"]
|
||||
environments = [
|
||||
"sys_platform == 'linux' and platform_machine == 'x86_64'",
|
||||
"sys_platform == 'linux' and platform_machine == 'aarch64'",
|
||||
"sys_platform == 'darwin' and platform_machine == 'arm64'",
|
||||
]
|
||||
# Override torch's pinned cuDNN to fix Conv3d performance regression (torch 2.9 + cuDNN 9.8-9.14)
|
||||
# See: https://github.com/pytorch/pytorch/issues/166122
|
||||
@@ -210,9 +221,9 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
verifiers = { path = "deps/verifiers", editable = true }
|
||||
renderers = { path = "deps/renderers", editable = true }
|
||||
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
torch = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
|
||||
torchvision = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
|
||||
torchaudio = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
|
||||
torchao = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
|
||||
@@ -53,16 +53,10 @@ if [ -n "$PRIME_RL_REF" ]; then
|
||||
cp -a /app/.venv "$DEST/.venv"
|
||||
fi
|
||||
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
|
||||
# Mirror the image's uv sync extras — explicit instead
|
||||
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
|
||||
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
|
||||
# startup. --inexact keeps the seeded venv's pre-built wheels
|
||||
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
|
||||
# override's lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev --all-packages \
|
||||
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
|
||||
--extra gpt-oss \
|
||||
--group mamba-ssm )
|
||||
# --inexact keeps the seeded venv's pre-built wheels (flash-attn-3,
|
||||
# deep-ep, mamba-ssm) in place; uv only rebuilds them if the override's
|
||||
# lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev --all-packages --all-extras --group mamba-ssm )
|
||||
export VIRTUAL_ENV="$DEST/.venv"
|
||||
export PATH="$DEST/.venv/bin:$PATH"
|
||||
cd "$DEST"
|
||||
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
SESSION_NAME="prime-rl"
|
||||
OUTPUT_DIR="outputs"
|
||||
AGENT="claude"
|
||||
|
||||
# Optional CLI parsing
|
||||
# Supports:
|
||||
# -s|--session-name NAME
|
||||
# -o|--output-dir DIR
|
||||
# -a|--agent AGENT (claude|codex, default: claude)
|
||||
# Positional: [SESSION_NAME [OUTPUT_DIR]]
|
||||
POSITIONAL=()
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
-s|--session-name)
|
||||
if [[ -z "$2" ]]; then
|
||||
echo "Error: --session-name requires a value" >&2
|
||||
exit 1
|
||||
fi
|
||||
SESSION_NAME="$2"
|
||||
shift 2
|
||||
;;
|
||||
-o|--output-dir)
|
||||
if [[ -z "$2" ]]; then
|
||||
echo "Error: --output-dir requires a value" >&2
|
||||
exit 1
|
||||
fi
|
||||
OUTPUT_DIR="$2"
|
||||
shift 2
|
||||
;;
|
||||
-a|--agent)
|
||||
if [[ -z "$2" ]]; then
|
||||
echo "Error: --agent requires a value (claude|codex)" >&2
|
||||
exit 1
|
||||
fi
|
||||
AGENT="$2"
|
||||
shift 2
|
||||
;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 [-s SESSION_NAME] [-o OUTPUT_DIR] [-a AGENT] [SESSION_NAME [OUTPUT_DIR]]" >&2
|
||||
echo " -a, --agent claude|codex (default: claude)" >&2
|
||||
exit 0
|
||||
;;
|
||||
--)
|
||||
shift
|
||||
break
|
||||
;;
|
||||
*)
|
||||
POSITIONAL+=("$1")
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ ${#POSITIONAL[@]} -ge 1 ]]; then
|
||||
SESSION_NAME="${POSITIONAL[0]}"
|
||||
fi
|
||||
if [[ ${#POSITIONAL[@]} -ge 2 ]]; then
|
||||
OUTPUT_DIR="${POSITIONAL[1]}"
|
||||
fi
|
||||
|
||||
LOG_DIR="${OUTPUT_DIR}/logs/latest"
|
||||
|
||||
if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
|
||||
echo "Attaching to tmux session: $SESSION_NAME"
|
||||
exec tmux attach-session -t "$SESSION_NAME"
|
||||
fi
|
||||
|
||||
echo "Creating new tmux session: $SESSION_NAME"
|
||||
|
||||
# Window 0: Launcher - empty shell
|
||||
tmux new-session -d -s "$SESSION_NAME" -n "Launcher"
|
||||
|
||||
# Window 1: Logs - 4 vertical panes
|
||||
tmux new-window -t "$SESSION_NAME" -n "Logs"
|
||||
|
||||
tmux split-window -v -t "$SESSION_NAME:Logs.0"
|
||||
tmux split-window -v -t "$SESSION_NAME:Logs.1"
|
||||
tmux split-window -v -t "$SESSION_NAME:Logs.2"
|
||||
tmux select-layout -t "$SESSION_NAME:Logs" even-vertical
|
||||
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.0" -T "Trainer"
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.1" -T "Orchestrator"
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.2" -T "Envs"
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.3" -T "Inference"
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.0" \
|
||||
"tail -F ${LOG_DIR}/trainer.log 2>/dev/null" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.1" \
|
||||
"tail -F ${LOG_DIR}/orchestrator.log 2>/dev/null" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.2" \
|
||||
"tail -F ${LOG_DIR}/envs/*/*.log 2>/dev/null" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.3" \
|
||||
"tail -F ${LOG_DIR}/inference.log 2>/dev/null" C-m
|
||||
|
||||
# Window 2: SUCCESS - grep SUCCESS on orch and trainer logs (two stacked panes)
|
||||
tmux new-window -t "$SESSION_NAME" -n "SUCCESS"
|
||||
|
||||
tmux split-window -v -t "$SESSION_NAME:SUCCESS.0"
|
||||
tmux select-layout -t "$SESSION_NAME:SUCCESS" even-vertical
|
||||
|
||||
tmux select-pane -t "$SESSION_NAME:SUCCESS.0" -T "Orchestrator"
|
||||
tmux select-pane -t "$SESSION_NAME:SUCCESS.1" -T "Trainer"
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:SUCCESS.0" "tail -F ${LOG_DIR}/orchestrator.log 2>/dev/null | grep --line-buffered SUCCESS" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:SUCCESS.1" "tail -F ${LOG_DIR}/trainer.log 2>/dev/null | grep --line-buffered SUCCESS" C-m
|
||||
|
||||
# Window 3: Agent (claude code or codex) with log context
|
||||
tmux new-window -t "$SESSION_NAME" -n "Agent"
|
||||
|
||||
AGENT_PROMPT="You are monitoring a prime-rl training run. The output directory is ${OUTPUT_DIR}. Log paths:
|
||||
Trainer: ${LOG_DIR}/trainer.log
|
||||
All nodes: ${LOG_DIR}/trainer/node_*.log
|
||||
All ranks: ${LOG_DIR}/trainer/torchrun/*/*/*/*.log
|
||||
Orchestrator: ${LOG_DIR}/orchestrator.log
|
||||
Inference: ${LOG_DIR}/inference.log
|
||||
Envs: ${LOG_DIR}/envs/*/*.log
|
||||
Train envs: ${LOG_DIR}/envs/train/*.log
|
||||
You are running inside tmux session \"${SESSION_NAME}\". The Launcher window (window 0) is where the user runs launch commands. You can read its contents with: tmux capture-pane -t ${SESSION_NAME}:Launcher -p
|
||||
Help the user monitor and debug this run."
|
||||
|
||||
case "$AGENT" in
|
||||
claude)
|
||||
tmux send-keys -t "$SESSION_NAME:Agent" \
|
||||
"claude --permission-mode auto --append-system-prompt \"${AGENT_PROMPT}\"" C-m
|
||||
;;
|
||||
codex)
|
||||
tmux send-keys -t "$SESSION_NAME:Agent" \
|
||||
"codex --yolo \"${AGENT_PROMPT}\"" C-m
|
||||
;;
|
||||
*)
|
||||
echo "Error: unknown agent '$AGENT' (expected claude|codex)" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
# Pane title styling
|
||||
tmux set-option -t "$SESSION_NAME" -g pane-border-status top
|
||||
tmux set-option -t "$SESSION_NAME" -g pane-border-format " #{pane_title} "
|
||||
|
||||
# Focus launcher window and attach
|
||||
tmux select-window -t "$SESSION_NAME:Launcher"
|
||||
exec tmux attach-session -t "$SESSION_NAME"
|
||||
@@ -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`).
|
||||
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
---
|
||||
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.
|
||||
|
||||
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."}
|
||||
```
|
||||
|
||||
Each citation requires `step`, `kind`, `subset`, `episode`, `quote`, and `note`.
|
||||
Use the episode `id`, 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.
|
||||
|
||||
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.
|
||||
@@ -22,13 +22,15 @@ git submodule update --init --recursive
|
||||
## Sync
|
||||
|
||||
```bash
|
||||
uv sync # core only
|
||||
uv sync # slim
|
||||
uv sync --group dev # + pytest, ruff, pre-commit
|
||||
uv sync --all-extras # + extras (flash-attn, flash-attn-cute, …)
|
||||
uv sync --all-extras --all-packages # + all env packages (needed to train on them)
|
||||
uv sync --package prime-rl --package gsm8k # core + just one env
|
||||
```
|
||||
|
||||
`uv sync --group dev` installs the `pre-commit` package but leaves the git hook inert until it's wired up — run `uv run pre-commit install` once per clone (see `README.md`'s Development section).
|
||||
|
||||
Environment packages are uv **workspace members**. Those under `deps/prime-envs/environments/*/*` are auto-discovered — adding a new env there needs no `pyproject.toml` change. verifiers' example envs are enumerated explicitly in `[tool.uv.workspace].members` (only the ones prime-rl trains or tests on) — to use another, add its path to the list. Members are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
|
||||
|
||||
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
|
||||
|
||||
@@ -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/` (start with `rl.json`). 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/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.
|
||||
2. Confirm all processes are alive and the run is making progress.
|
||||
3. Write the initial summary into `{run_dir}/STATUS.md`.
|
||||
|
||||
@@ -40,14 +40,7 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
|
||||
|
||||
**Never restart unless the researcher explicitly asked.** Confirm the exact restart command and the conditions that warrant one.
|
||||
|
||||
**Never** run kill or launch commands from your own shell. Dispatch them to the tmux **Launcher** window so the researcher sees what was executed:
|
||||
|
||||
```bash
|
||||
SESSION=$(tmux display-message -p '#S')
|
||||
tmux send-keys -t "$SESSION:Launcher" 'your command here' Enter
|
||||
```
|
||||
|
||||
After a restart, verify all processes are back up and progress resumed before the next check-in.
|
||||
**Never** run kill or launch commands yourself. Hand the researcher the exact command and let them run it; after a restart, verify all processes are back up and progress resumed before the next check-in.
|
||||
|
||||
---
|
||||
|
||||
@@ -55,11 +48,34 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
|
||||
### Where to find things
|
||||
|
||||
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the run dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
|
||||
- `{run_dir}/configs/` — resolved configs, written as JSON so explicit None settings round-trip (`rl.json` has the full picture).
|
||||
- `{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}/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).
|
||||
|
||||
### Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR` if set; several dirs can be tracked at
|
||||
once) serves a local web dashboard at `http://localhost:7788` with four views per run:
|
||||
metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved 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
|
||||
free one, so several dashboards run side by side without coordination. GPU deps live
|
||||
behind the `gpu` extra, so `uv sync --extra dashboard && uv run dashboard` works
|
||||
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
|
||||
|
||||
```
|
||||
@@ -77,6 +93,8 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
└── 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:
|
||||
@@ -180,13 +198,13 @@ A few warnings are normal. Escalate when errors are persistent, growing, or hit
|
||||
All processes use `setproctitle` so they're visible in `ps`/`htop`/`pstree`:
|
||||
|
||||
```
|
||||
PRIME-RL::Launcher
|
||||
├── PRIME-RL::Inference (vLLM server, GPU 0)
|
||||
├── PRIME-RL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
|
||||
PRL::Launcher
|
||||
├── PRL::Inference (vLLM server, GPU 0)
|
||||
├── PRL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
|
||||
│ └── Verifiers::EnvWorker0..N
|
||||
├── PRIME-RL::Orchestrator (CPU-only; connects to each env server)
|
||||
├── PRL::Orchestrator (CPU-only; connects to each env server)
|
||||
├── torchrun
|
||||
│ └── PRIME-RL::Trainer (GPU 1+)
|
||||
│ └── PRL::Trainer (GPU 1+)
|
||||
└── tail trainer.log
|
||||
```
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ description: How to launch prime-rl training runs — the `rl`, `sft`, `inferenc
|
||||
|
||||
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
|
||||
|
||||
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory.
|
||||
|
||||
## Run directories
|
||||
|
||||
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, broadcasts, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
|
||||
@@ -43,6 +45,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
|
||||
- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
|
||||
- SLURM: single- and multi-node
|
||||
- Multi-node SLURM stops after `.trainer.done` for trainer-only fake-data runs. Runs with inference stop after both `.trainer.done` and `.orchestrator.done`.
|
||||
- Environment packages: before launching a config with a non-core verifier env id,
|
||||
verify the package imports under `uv run` (for example
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
|
||||
@@ -139,3 +142,12 @@ 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.
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
|
||||
directories (metrics, resolved configs, rollout traces, cited reports,
|
||||
component logs) at
|
||||
http://localhost:7788. Needs the `dashboard` extra. Every instance also serves
|
||||
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.
|
||||
|
||||
GPU dependencies live behind the `gpu` extra, so this works anywhere — a
|
||||
cluster head node, a laptop against a mounted outputs dir:
|
||||
|
||||
```bash
|
||||
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).
|
||||
Executable
+1285
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 7.4 KiB |
@@ -0,0 +1,237 @@
|
||||
<!-- 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. -->
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>prime-rl dashboard</title>
|
||||
<link rel="icon" href="/static/butterfly-white.svg">
|
||||
<link rel="stylesheet" href="/static/vendor/uPlot.min.css">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<header id="topbar">
|
||||
<div class="brand">
|
||||
<img src="/static/butterfly-white.svg" alt="Prime Intellect">
|
||||
</div>
|
||||
<select id="run-select" title="run"></select>
|
||||
<div id="compare-wrap" class="dd-wrap">
|
||||
<button id="compare-btn" class="btn dd-btn">compare</button>
|
||||
<div id="compare-menu" class="dd-menu" hidden></div>
|
||||
</div>
|
||||
<nav id="tabs">
|
||||
<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>
|
||||
|
||||
<div id="run-overview"></div>
|
||||
|
||||
<main>
|
||||
<section id="tab-metrics">
|
||||
<div class="controls">
|
||||
<div class="seg" id="metrics-mode">
|
||||
<button data-mode="overview" class="active">Overview</button>
|
||||
<button data-mode="all">All</button>
|
||||
</div>
|
||||
<input id="metrics-search" class="search" type="search" placeholder="regex filter, e.g. ^entropy/ or reward">
|
||||
<label class="ctl">smooth <input id="smooth-range" type="range" min="1" max="50" value="1"><span id="smooth-val">off</span></label>
|
||||
<span id="metrics-status" class="muted"></span>
|
||||
<div class="spacer"></div>
|
||||
<div class="seg" id="all-layout" hidden>
|
||||
<button data-layout="flat">Flat</button>
|
||||
<button data-layout="nested">Nested</button>
|
||||
</div>
|
||||
<button id="metrics-collapse" class="btn">collapse</button>
|
||||
<button id="metrics-expand" class="btn">expand</button>
|
||||
</div>
|
||||
<div id="metrics-body"></div>
|
||||
</section>
|
||||
|
||||
<section id="tab-config" hidden>
|
||||
<div class="controls">
|
||||
<div class="seg" id="config-format">
|
||||
<button data-fmt="toml">TOML</button>
|
||||
<button data-fmt="json">JSON</button>
|
||||
</div>
|
||||
<input id="config-search" class="search" type="search" placeholder="regex search, e.g. lora|lr">
|
||||
<span id="config-hits" class="muted"></span>
|
||||
</div>
|
||||
<pre id="config-view"></pre>
|
||||
</section>
|
||||
|
||||
<section id="tab-traces" hidden>
|
||||
<div class="controls" id="step-bar">
|
||||
<button id="step-prev" class="btn tm-nav" title="previous step">‹</button>
|
||||
<div id="step-blocks"></div>
|
||||
<button id="step-next" class="btn tm-nav" title="next step">›</button>
|
||||
<span id="step-label" class="t-label"></span>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<div id="trace-filter-wrap" class="dd-wrap">
|
||||
<button id="trace-filter-btn" class="btn dd-btn" title="filter & sort">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
|
||||
filter
|
||||
</button>
|
||||
<div id="trace-filter-menu" class="dd-menu" hidden>
|
||||
<label class="t-label">env</label>
|
||||
<select id="trace-env"><option value="">all envs</option></select>
|
||||
<label class="t-label">sort</label>
|
||||
<select id="trace-sort">
|
||||
<option value="line:asc">order: arrival</option>
|
||||
<option value="reward:desc">reward ↓</option>
|
||||
<option value="reward:asc">reward ↑</option>
|
||||
<option value="advantage:desc">advantage ↓</option>
|
||||
<option value="advantage:asc">advantage ↑</option>
|
||||
<option value="output_tokens:desc">tokens ↓</option>
|
||||
<option value="group:asc">group</option>
|
||||
</select>
|
||||
<label class="toggle"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="seg" id="trace-kind">
|
||||
<button data-kind="train" class="active">Train</button>
|
||||
<button data-kind="eval">Eval</button>
|
||||
</div>
|
||||
<div class="seg" id="trace-subset">
|
||||
<button data-subset="all">All</button>
|
||||
<button data-subset="effective" class="active">Effective</button>
|
||||
</div>
|
||||
<span id="trace-status" class="muted"></span>
|
||||
</div>
|
||||
<div id="episode-table-wrap">
|
||||
<table id="episode-table">
|
||||
<thead><tr>
|
||||
<th>#</th><th>env</th><th>group</th><th>reward</th><th>adv</th>
|
||||
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>status</th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
</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>
|
||||
<select id="attempt-select"></select>
|
||||
<div id="log-comp-wrap" class="dd-wrap">
|
||||
<button id="log-comp-btn" class="btn dd-btn">components</button>
|
||||
<div id="log-comp-menu" class="dd-menu" hidden></div>
|
||||
</div>
|
||||
<div class="seg" id="log-view">
|
||||
<button data-view="merge" class="active">Merge</button>
|
||||
<button data-view="split">Split</button>
|
||||
</div>
|
||||
<div class="stepper" id="log-level" title="minimum log level">
|
||||
<button id="log-level-down" title="more verbose">‹</button>
|
||||
<span id="log-level-label">all</span>
|
||||
<button id="log-level-up" title="less verbose">›</button>
|
||||
</div>
|
||||
<input id="log-search" class="search" type="search" placeholder="regex filter, e.g. ERROR|WARN">
|
||||
<button id="log-older" class="btn">load older</button>
|
||||
</div>
|
||||
<div id="log-panes"></div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<div id="drawer-backdrop" hidden></div>
|
||||
<div id="trace-modal" hidden>
|
||||
<aside id="tm-left">
|
||||
<div class="tm-head tm-stephead">
|
||||
<button id="tm-step-prev" class="btn tm-nav" title="previous step">‹</button>
|
||||
<span id="tm-step-label"></span>
|
||||
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
|
||||
</div>
|
||||
<div class="tm-head tm-ctlrow">
|
||||
<div id="tm-filter-wrap" class="dd-wrap">
|
||||
<button id="tm-filter-btn" class="btn dd-btn" title="filter & 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>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tm-head">
|
||||
<span class="t-label">episodes</span>
|
||||
<span id="tm-count" class="badge"></span>
|
||||
</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="spacer"></div>
|
||||
<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>
|
||||
<button id="drawer-close" class="btn">✕</button>
|
||||
</div>
|
||||
<div class="tm-head tm-tabs-row" id="tm-tabs-row" hidden>
|
||||
<div id="tm-trace-tabs" class="seg" hidden></div>
|
||||
<div id="tm-branch-tabs" class="seg" hidden></div>
|
||||
</div>
|
||||
<div id="tm-messages"></div>
|
||||
</section>
|
||||
<aside id="tm-right">
|
||||
<div class="tm-head"><span class="tm-title">Overview</span></div>
|
||||
<div id="tm-meta"></div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<script src="/static/vendor/uPlot.iife.min.js"></script>
|
||||
<script src="/static/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,990 @@
|
||||
/* 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.
|
||||
|
||||
Prime Intellect design language (prime-context: colors_and_type.css / brand.md).
|
||||
Mono dominant, #111 canvas, lime accent used categorically, hairline dividers,
|
||||
border-radius 0 everywhere, no shadows or gradients. ABC Favorit Mono is licensed
|
||||
and not vendored here; the stack falls back to JetBrains Mono / system mono. */
|
||||
|
||||
:root {
|
||||
--grey-1: #111111;
|
||||
--grey-2: #1c1c1c;
|
||||
--grey-3: #3a3a3a;
|
||||
--grey-4: #767676;
|
||||
--grey-5: #bcbcbc;
|
||||
--grey-6: #ffffff;
|
||||
|
||||
--accent: #b6ff3c;
|
||||
--negative: #ff4539;
|
||||
--positive: #b6ff3c;
|
||||
--infra: #4a9eff;
|
||||
--risk: #ff6b4a;
|
||||
|
||||
--chart-1: #78f8a5;
|
||||
--chart-2: #b7a6fa;
|
||||
--chart-3: #fcdaa4;
|
||||
|
||||
--hairline: rgba(255, 255, 255, 0.1);
|
||||
--hairline-faint: rgba(255, 255, 255, 0.06);
|
||||
|
||||
--font-mono: "ABC Favorit Mono", "JetBrains Mono", ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;
|
||||
|
||||
--track-mono: 0.04em;
|
||||
--track-caps: 0.12em;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
summary { list-style: none; cursor: pointer; user-select: none; }
|
||||
summary::-webkit-details-marker { display: none; }
|
||||
html, body { height: 100%; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--grey-1);
|
||||
color: var(--grey-5);
|
||||
font: 400 13px/1.5 var(--font-mono);
|
||||
letter-spacing: var(--track-mono);
|
||||
font-variant-numeric: tabular-nums lining-nums;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.muted { color: var(--grey-4); font-size: 11px; }
|
||||
.spacer { flex: 1; }
|
||||
|
||||
/* mono caps label — the house label style */
|
||||
.t-label {
|
||||
font-size: 11px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-4);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- topbar */
|
||||
#topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 0 20px;
|
||||
height: 52px;
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
background: var(--grey-1);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 20;
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: 10px; user-select: none; }
|
||||
.brand img { height: 18px; display: block; }
|
||||
#tabs { display: flex; gap: 2px; margin-left: 8px; align-self: stretch; }
|
||||
#tabs button {
|
||||
background: none;
|
||||
border: none;
|
||||
border-bottom: 1px solid transparent;
|
||||
margin-bottom: -1px;
|
||||
color: var(--grey-4);
|
||||
font: 400 11px var(--font-mono);
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
padding: 0 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
#tabs button:hover { color: var(--grey-6); }
|
||||
#tabs button.active { color: var(--accent); border-bottom-color: var(--accent); }
|
||||
#topbar .toggle { margin-left: auto; }
|
||||
|
||||
select, .search, .btn {
|
||||
background: transparent;
|
||||
color: var(--grey-5);
|
||||
border: 1px solid var(--grey-3);
|
||||
border-radius: 0;
|
||||
height: 28px;
|
||||
padding: 0 10px;
|
||||
font: 400 12px var(--font-mono);
|
||||
letter-spacing: var(--track-mono);
|
||||
outline: none;
|
||||
}
|
||||
/* flat selects: no native chrome, hairline chevron */
|
||||
select {
|
||||
appearance: none;
|
||||
-webkit-appearance: none;
|
||||
background-color: var(--grey-1);
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='5' viewBox='0 0 8 5'%3E%3Cpath d='M1 1l3 3 3-3' fill='none' stroke='%23767676' stroke-width='1.2'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 9px center;
|
||||
padding-right: 26px;
|
||||
cursor: pointer;
|
||||
}
|
||||
select:hover { border-color: var(--grey-6); color: var(--grey-6); }
|
||||
option { background: var(--grey-1); color: var(--grey-5); }
|
||||
select:focus, .search:focus { border-color: var(--grey-6); }
|
||||
|
||||
/* dropdown-opening buttons carry a caret; menus share one flat panel style */
|
||||
.dd-btn { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.dd-btn::after {
|
||||
content: "";
|
||||
width: 8px;
|
||||
height: 5px;
|
||||
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='5' viewBox='0 0 8 5'%3E%3Cpath d='M1 1l3 3 3-3' fill='none' stroke='%23767676' stroke-width='1.2'/%3E%3C/svg%3E") no-repeat center;
|
||||
}
|
||||
.dd-wrap { position: relative; }
|
||||
.dd-btn.active { color: var(--accent); border-color: var(--accent); }
|
||||
/* selects dressed as dropdowns: lowercase label with ellipsis, scrollable options */
|
||||
.dd-select .dd-btn { text-transform: none; letter-spacing: var(--track-mono); font-size: 12px; max-width: 340px; }
|
||||
.dd-select .dd-btn span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.dd-optlist { min-width: 100%; max-height: 320px; overflow-y: auto; padding: 4px 0; white-space: nowrap; }
|
||||
.dd-opt { padding: 5px 12px; font-size: 12px; cursor: pointer; color: var(--grey-5); }
|
||||
.dd-opt:hover { background: var(--grey-2); color: var(--grey-6); }
|
||||
.dd-opt.active { color: var(--accent); }
|
||||
.dd-opt.disabled { color: var(--grey-3); cursor: default; }
|
||||
.dd-menu {
|
||||
position: absolute;
|
||||
top: 34px;
|
||||
z-index: 40;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
padding: 8px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
.btn {
|
||||
cursor: pointer;
|
||||
text-transform: uppercase;
|
||||
font-size: 11px;
|
||||
letter-spacing: var(--track-caps);
|
||||
color: var(--grey-5);
|
||||
}
|
||||
.btn:hover { border-color: var(--grey-6); color: var(--grey-6); }
|
||||
.btn:active { background: rgba(255, 255, 255, 0.04); }
|
||||
#run-select { max-width: 340px; font-size: 12px; }
|
||||
|
||||
.badge {
|
||||
font: 400 10px var(--font-mono);
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
padding: 3px 8px;
|
||||
border: 1px solid var(--grey-3);
|
||||
border-radius: 0;
|
||||
color: var(--grey-5);
|
||||
}
|
||||
|
||||
/* run overview card — platform-style run header shown on every tab */
|
||||
#run-overview {
|
||||
padding: 16px 20px 14px;
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
.ov-top { display: flex; align-items: flex-end; gap: 48px; flex-wrap: wrap; }
|
||||
.ov-field { display: flex; flex-direction: column; gap: 6px; }
|
||||
.ov-field .lbl {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-4);
|
||||
}
|
||||
.ov-field .val {
|
||||
font-size: 13px;
|
||||
color: var(--grey-6);
|
||||
max-width: 280px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.st-running { color: var(--accent); border-color: rgba(182, 255, 60, 0.5); background: rgba(182, 255, 60, 0.08); }
|
||||
.st-completed { color: var(--chart-1); border-color: rgba(120, 248, 165, 0.4); }
|
||||
.st-stopped { color: var(--grey-4); }
|
||||
/* slider controls (smoothing, pane size) */
|
||||
.ctl {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-4);
|
||||
}
|
||||
.ctl input[type="range"] { width: 110px; accent-color: var(--accent); }
|
||||
.ctl span { color: var(--grey-5); min-width: 24px; }
|
||||
|
||||
.toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
color: var(--grey-4);
|
||||
font-size: 11px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
user-select: none;
|
||||
}
|
||||
.toggle input { display: none; }
|
||||
.toggle .dot { width: 10px; height: 10px; border: 1px solid var(--grey-3); background: transparent; }
|
||||
.toggle input:checked + .dot { background: var(--accent); border-color: var(--accent); }
|
||||
|
||||
/* the LIVE indicator is a pulsing circle */
|
||||
#topbar .toggle .dot { width: 7px; height: 7px; border-radius: 50%; }
|
||||
#topbar .toggle input:checked + .dot { animation: live-pulse 2s ease-out infinite; }
|
||||
@keyframes live-pulse {
|
||||
0% { box-shadow: 0 0 0 0 rgba(182, 255, 60, 0.55); }
|
||||
70% { box-shadow: 0 0 0 5px rgba(182, 255, 60, 0); }
|
||||
100% { box-shadow: 0 0 0 0 rgba(182, 255, 60, 0); }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ main */
|
||||
main { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
main > section { flex: 1; min-height: 0; display: flex; flex-direction: column; padding: 16px 20px; gap: 12px; }
|
||||
.controls { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||
|
||||
.seg { display: inline-flex; border: 1px solid var(--grey-3); flex-shrink: 0; }
|
||||
/* arrow stepper (log level): ‹ label › */
|
||||
.stepper { display: inline-flex; align-items: center; border: 1px solid var(--grey-3); height: 28px; }
|
||||
.stepper button { background: none; border: none; color: var(--grey-4); width: 24px; height: 100%; cursor: pointer; font: 400 13px var(--font-mono); }
|
||||
.stepper button:hover:not(:disabled) { color: var(--grey-6); }
|
||||
.stepper button:disabled { opacity: 0.3; cursor: default; }
|
||||
.stepper span {
|
||||
font-size: 11px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-5);
|
||||
min-width: 52px;
|
||||
text-align: center;
|
||||
}
|
||||
.seg button {
|
||||
white-space: nowrap;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--grey-4);
|
||||
height: 26px;
|
||||
padding: 0 12px;
|
||||
font: 400 11px var(--font-mono);
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
cursor: pointer;
|
||||
}
|
||||
.seg button + button { border-left: 1px solid var(--grey-3); }
|
||||
.seg button.active { background: var(--grey-2); color: var(--accent); }
|
||||
.seg button:disabled { opacity: 0.35; cursor: default; }
|
||||
|
||||
/* checkbox rows (compare menu, filter menus) */
|
||||
.file-item { display: flex; align-items: center; gap: 8px; padding: 3px 4px; cursor: pointer; font-size: 11px; }
|
||||
.file-item:hover { background: var(--grey-2); }
|
||||
.file-item input { appearance: none; width: 9px; height: 9px; border: 1px solid var(--grey-3); margin: 0; flex-shrink: 0; }
|
||||
.file-item input:checked { background: var(--accent); border-color: var(--accent); }
|
||||
|
||||
/* multi-run compare menu */
|
||||
#compare-menu {
|
||||
left: 0;
|
||||
min-width: 320px;
|
||||
max-height: 50vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- metrics */
|
||||
/* stable gutter: no layout shift when collapsing sections hides the scrollbar */
|
||||
#metrics-body { flex: 1; overflow-y: auto; scrollbar-gutter: stable; min-height: 0; padding-right: 10px; }
|
||||
.chart-card.dragging { opacity: 0.45; }
|
||||
/* one 12px rhythm everywhere: section-to-section, header-to-panes, pane-to-pane */
|
||||
details.section { margin-bottom: 12px; }
|
||||
/* nested sections (all-mode key tree) indent one step */
|
||||
details.section details.section { margin-left: 14px; }
|
||||
details.section:not([open]) > summary { margin-bottom: 0; }
|
||||
/* section headers are full-width bars so the clickable region is obvious */
|
||||
details.section > summary {
|
||||
font: 400 11px var(--font-mono);
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-5);
|
||||
margin: 0 0 12px;
|
||||
padding: 7px 12px;
|
||||
background: var(--grey-2);
|
||||
border: 1px solid var(--hairline);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
details.section > summary:hover { color: var(--grey-6); border-color: var(--grey-3); }
|
||||
details.section .sec-chev { margin-left: auto; transition: transform 0.12s; font-size: 10px; color: var(--grey-4); }
|
||||
details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
.chart-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(var(--pane-min, 260px), 1fr)); gap: 12px; }
|
||||
/* eval runs: running-average stat cards instead of x/y chart panes */
|
||||
.stat-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; }
|
||||
.stat-card { background: var(--grey-2); border: 1px solid var(--hairline); padding: 12px 14px; min-width: 0; }
|
||||
.stat-card:hover { border-color: var(--grey-3); }
|
||||
.stat-label {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-4);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.stat-value { font-size: 20px; color: var(--grey-6); margin: 6px 0 0; }
|
||||
.eval-progress { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
|
||||
.ep-bar { flex: 1; height: 6px; background: var(--grey-2); border: 1px solid var(--hairline); }
|
||||
.ep-fill { height: 100%; background: var(--accent); }
|
||||
.ep-label {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-4);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.chart-card {
|
||||
position: relative;
|
||||
background: var(--grey-2);
|
||||
border: 1px solid var(--hairline);
|
||||
padding: 8px 10px 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.chart-card:hover { border-color: var(--grey-3); }
|
||||
.chart-head { display: flex; align-items: baseline; gap: 10px; margin-bottom: 2px; cursor: grab; }
|
||||
.chart-title {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-mono);
|
||||
color: var(--grey-4);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
flex: 1;
|
||||
}
|
||||
.chart-last { font-size: 12px; font-weight: 500; color: var(--grey-6); }
|
||||
.chart-empty {
|
||||
height: 120px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--grey-4);
|
||||
font-size: 11px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
/* minimal empty state, shared by every "nothing here" case: just dim text */
|
||||
.empty-box {
|
||||
margin: 64px auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
text-align: center;
|
||||
white-space: normal;
|
||||
}
|
||||
.empty-title {
|
||||
font-size: 11px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-4);
|
||||
}
|
||||
.empty-detail {
|
||||
font-size: 11px;
|
||||
letter-spacing: var(--track-mono);
|
||||
color: var(--grey-4);
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.u-cursor-pt { display: none !important; }
|
||||
/* hover highlight dot on the snapped data point */
|
||||
.u-dot {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
pointer-events: none;
|
||||
will-change: transform;
|
||||
}
|
||||
/* drag-to-zoom selection highlight */
|
||||
.u-select { background: rgba(182, 255, 60, 0.1); outline: 1px solid rgba(182, 255, 60, 0.35); }
|
||||
|
||||
/* hover popover with x/y values */
|
||||
.u-tip {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 5;
|
||||
pointer-events: none;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
padding: 6px 9px;
|
||||
font: 10.5px var(--font-mono);
|
||||
letter-spacing: var(--track-mono);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.u-tip-x {
|
||||
color: var(--grey-4);
|
||||
font-size: 9.5px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: var(--track-caps);
|
||||
margin-bottom: 3px;
|
||||
}
|
||||
.u-tip-row { display: flex; align-items: center; gap: 6px; padding: 1px 0; }
|
||||
.u-tip-row .sw { width: 7px; height: 7px; flex-shrink: 0; }
|
||||
.u-tip-row .sw-band { border: 1px dotted; background: transparent; }
|
||||
.u-tip-l { color: var(--grey-4); }
|
||||
.u-tip-v { color: var(--grey-6); margin-left: auto; padding-left: 10px; }
|
||||
|
||||
|
||||
/* metrics regex filter (overview + all) */
|
||||
#metrics-search, #config-search, #log-search { flex: 1; max-width: 460px; }
|
||||
|
||||
/* wandb-style resize handles on every chart card: right edge = width, bottom
|
||||
edge = height, corner = both. Resizing one pane resizes all of them. */
|
||||
.rz { position: absolute; opacity: 0; }
|
||||
.chart-card:hover .rz { opacity: 1; }
|
||||
.rz-e { top: 0; right: 0; bottom: 16px; width: 6px; cursor: ew-resize; }
|
||||
.rz-s { left: 0; right: 16px; bottom: 0; height: 6px; cursor: ns-resize; }
|
||||
.rz-e:hover, .rz-s:hover { background: rgba(255, 255, 255, 0.08); }
|
||||
.rz-se {
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
cursor: nwse-resize;
|
||||
background:
|
||||
linear-gradient(135deg, transparent 0 50%, var(--grey-3) 50% calc(50% + 1px), transparent calc(50% + 1px) 100%) no-repeat 3px 3px / 10px 10px,
|
||||
linear-gradient(135deg, transparent 0 50%, var(--grey-3) 50% calc(50% + 1px), transparent calc(50% + 1px) 100%) no-repeat 7px 7px / 10px 10px;
|
||||
}
|
||||
body.resizing { user-select: none; }
|
||||
|
||||
/* ---------------------------------------------------------------- config */
|
||||
#config-view {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
background: var(--grey-2);
|
||||
border: 1px solid var(--hairline);
|
||||
padding: 14px 16px;
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
white-space: normal;
|
||||
}
|
||||
/* collapsible JSON tree */
|
||||
#config-view .j-line { white-space: pre; padding: 0 6px; }
|
||||
/* TOML (launch config) lines: whitespace preserved, minimal highlighting */
|
||||
#config-view .t-line { white-space: pre-wrap; padding: 0 6px; min-height: 1.55em; }
|
||||
#config-view .t-line:hover { background: rgba(255, 255, 255, 0.05); }
|
||||
.t-section { color: var(--accent); }
|
||||
#config-view div.j-line:hover, #config-view summary.j-line:hover { background: rgba(255, 255, 255, 0.05); }
|
||||
.j-ellip { color: var(--grey-4); }
|
||||
details.j-fold[open] > summary .j-ellip { display: none; }
|
||||
mark.hit {
|
||||
background: rgba(182, 255, 60, 0.22);
|
||||
color: var(--grey-6);
|
||||
outline: 1px solid rgba(182, 255, 60, 0.4);
|
||||
}
|
||||
.j-key { color: var(--grey-6); }
|
||||
.j-str { color: var(--chart-1); }
|
||||
.j-num { color: var(--chart-2); }
|
||||
.j-lit { color: var(--chart-3); }
|
||||
.j-punc { color: var(--grey-4); }
|
||||
|
||||
/* ------------------------------------------------------------------ logs */
|
||||
/* vertical stack of component panes (trainer / orchestrator / inference / envs) */
|
||||
/* split view always fills the tab: panes share the height equally */
|
||||
#log-panes { flex: 1; display: flex; flex-direction: column; gap: 10px; min-height: 0; }
|
||||
.log-pane {
|
||||
flex: 1 1 0;
|
||||
min-height: 80px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border: 1px solid var(--hairline);
|
||||
background: var(--grey-1);
|
||||
min-width: 0;
|
||||
}
|
||||
#log-panes.maxed { overflow: hidden; }
|
||||
#log-panes.maxed .log-pane { display: none; }
|
||||
#log-panes.maxed .log-pane.maximized { display: flex; flex: 1; height: auto; }
|
||||
#log-comp-menu {
|
||||
left: 0;
|
||||
min-width: 220px;
|
||||
}
|
||||
.log-pane-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 5px 10px;
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
background: var(--grey-2);
|
||||
}
|
||||
.lp-title {
|
||||
font-size: 10px;
|
||||
font-weight: 500;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-5);
|
||||
}
|
||||
.lp-file { height: 24px; font-size: 11px; max-width: 280px; }
|
||||
.lp-count { font-size: 10px; color: var(--grey-4); }
|
||||
.lp-max { height: 24px; padding: 0 8px; }
|
||||
.log-pane-stream {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
padding: 8px 12px;
|
||||
font-size: 11.5px;
|
||||
line-height: 1.55;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
.ll { display: flex; gap: 8px; }
|
||||
.ll:hover { background: var(--grey-2); }
|
||||
.ll .ltext { flex: 1; min-width: 0; }
|
||||
/* merge view: right-aligned component badge column */
|
||||
.ll .lgb {
|
||||
flex-shrink: 0;
|
||||
width: 112px;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: flex-start;
|
||||
padding-top: 1px;
|
||||
user-select: none;
|
||||
}
|
||||
.ll .lgb-badge {
|
||||
font-size: 9px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-4);
|
||||
background: var(--grey-2);
|
||||
border: 1px solid var(--hairline);
|
||||
padding: 0 5px;
|
||||
line-height: 14px;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ANSI — mapped onto the PI palette */
|
||||
.a-bold { font-weight: 500; color: var(--grey-6); }
|
||||
.a-dim { opacity: 0.55; }
|
||||
.fg30 { color: var(--grey-3); } .fg31 { color: var(--negative); } .fg32 { color: var(--chart-1); }
|
||||
.fg33 { color: var(--chart-3); } .fg34 { color: var(--infra); } .fg35 { color: var(--chart-2); }
|
||||
.fg36 { color: #7adfff; } .fg37 { color: var(--grey-5); }
|
||||
.fg90 { color: var(--grey-4); } .fg91 { color: var(--risk); } .fg92 { color: var(--chart-1); }
|
||||
.fg93 { color: var(--chart-3); } .fg94 { color: var(--infra); } .fg95 { color: var(--chart-2); }
|
||||
.fg96 { color: #7adfff; } .fg97 { color: var(--grey-6); }
|
||||
|
||||
/* ---------------------------------------------------------------- traces */
|
||||
/* step selector: one block per rollout step, filled up to the selection */
|
||||
#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 {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: -6px;
|
||||
width: 3px;
|
||||
height: 3px;
|
||||
margin-left: -1.5px;
|
||||
border-radius: 50%;
|
||||
background: var(--grey-5);
|
||||
}
|
||||
.sb-cell.eval:hover::after { background: var(--grey-6); }
|
||||
#trace-filter-menu {
|
||||
right: 0;
|
||||
min-width: 240px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
#step-label { display: inline-flex; align-items: center; gap: 7px; color: var(--grey-5); }
|
||||
.eval-dot { display: inline-block; width: 4px; height: 4px; border-radius: 50%; background: var(--grey-5); }
|
||||
|
||||
#episode-table-wrap { flex: 1; overflow: auto; border: 1px solid var(--hairline); background: var(--grey-1); min-height: 0; }
|
||||
#episode-table .vpad td { padding: 0; border: 0; }
|
||||
#episode-table { width: 100%; border-collapse: collapse; font-size: 11.5px; }
|
||||
#episode-table th {
|
||||
text-align: left;
|
||||
font: 400 10px var(--font-mono);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: var(--track-caps);
|
||||
color: var(--grey-4);
|
||||
padding: 9px 10px;
|
||||
border-bottom: 1px solid var(--grey-3);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--grey-1);
|
||||
z-index: 1;
|
||||
}
|
||||
#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); }
|
||||
.status-ok { color: var(--positive); }
|
||||
.status-err { color: var(--negative); }
|
||||
|
||||
/* ----------------------------------------------------- trace viewer modal */
|
||||
#drawer-backdrop { position: fixed; inset: 0; background: rgba(17, 17, 17, 0.8); z-index: 30; }
|
||||
#trace-modal {
|
||||
position: fixed;
|
||||
inset: 3vh 2vw;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
z-index: 31;
|
||||
display: grid;
|
||||
grid-template-columns: 280px minmax(0, 1fr) 320px;
|
||||
}
|
||||
.tm-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 14px;
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
min-height: 48px;
|
||||
}
|
||||
.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; }
|
||||
#tm-list { flex: 1; overflow-y: auto; padding: 4px 8px 10px; }
|
||||
.tm-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 5px 10px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
font-size: 11.5px;
|
||||
color: var(--grey-5);
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
.tm-item .tm-num { flex-shrink: 0; }
|
||||
/* env names never wrap - they clip with an ellipsis so every row is one line */
|
||||
.tm-item .tm-env { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.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-ctlrow { min-height: 0; padding: 8px 14px; }
|
||||
#tm-step-label {
|
||||
font-size: 11px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-6);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
#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 { display: flex; flex: 1; flex-direction: column; overflow-y: auto; padding: 14px 16px; }
|
||||
#tm-messages > * { flex-shrink: 0; }
|
||||
#tm-right { border-left: 1px solid var(--hairline); overflow-y: auto; min-height: 0; }
|
||||
#tm-meta { padding: 12px 14px; }
|
||||
|
||||
.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 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 7px 12px;
|
||||
background: var(--grey-2);
|
||||
min-width: 0;
|
||||
}
|
||||
details.entry[open] > summary { border-bottom: 1px solid var(--hairline); }
|
||||
.entry-num { font-size: 10px; color: var(--grey-4); letter-spacing: var(--track-mono); }
|
||||
.entry-role {
|
||||
font-size: 10px;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: var(--track-caps);
|
||||
color: var(--accent);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.entry-preview {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--grey-4);
|
||||
font-size: 11px;
|
||||
}
|
||||
details.entry[open] > summary > .entry-preview { visibility: hidden; }
|
||||
.entry-chev { color: var(--grey-4); font-size: 10px; transition: transform 0.12s; }
|
||||
details.entry[open] .entry-chev { transform: rotate(90deg); }
|
||||
.entry-body { padding: 10px 14px; font-size: 12px; white-space: pre-wrap; word-break: break-word; color: var(--grey-5); }
|
||||
.chip {
|
||||
font-size: 10px;
|
||||
border: 1px solid var(--grey-3);
|
||||
padding: 1px 7px;
|
||||
color: var(--grey-4);
|
||||
letter-spacing: var(--track-mono);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.icon-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--grey-4);
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
padding: 2px 4px;
|
||||
line-height: 1;
|
||||
}
|
||||
.icon-btn:hover { color: var(--grey-6); }
|
||||
.icon-btn.copied { color: var(--accent); }
|
||||
|
||||
/* nested sub-blocks (reasoning) */
|
||||
details.sub { border: 1px solid var(--hairline); margin: 8px 12px; }
|
||||
details.sub > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 5px 10px;
|
||||
font-size: 10.5px;
|
||||
color: var(--grey-5);
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
}
|
||||
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); }
|
||||
.tm-reward-big.na { color: var(--grey-4); }
|
||||
.meta-sec {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--accent);
|
||||
margin: 16px 0 6px;
|
||||
}
|
||||
.meta-row { display: flex; align-items: center; gap: 8px; padding: 3px 0; font-size: 11.5px; }
|
||||
.meta-row .k { color: var(--grey-4); }
|
||||
.meta-row .k .tree { color: var(--grey-3); }
|
||||
.meta-row .v { margin-left: auto; color: var(--grey-6); text-align: right; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 60%; }
|
||||
.meta-row .v.id { font-size: 10.5px; color: var(--grey-5); border: 1px solid var(--hairline); padding: 2px 6px; }
|
||||
details.meta-fold { border: 1px solid var(--hairline); margin: 8px 0; }
|
||||
details.meta-fold > summary { padding: 6px 10px; font-size: 10.5px; color: var(--grey-5); }
|
||||
details.meta-fold > pre { margin: 0; border: none; border-top: 1px solid var(--hairline); }
|
||||
|
||||
/* tool calls: green-terminal block */
|
||||
.tool-call {
|
||||
margin: 8px 12px 10px;
|
||||
padding: 7px 10px;
|
||||
background: #0b1403;
|
||||
border: 1px solid rgba(182, 255, 60, 0.22);
|
||||
color: var(--accent);
|
||||
font-size: 12px;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.tok { padding: 0 1px; }
|
||||
.tok:hover { outline: 1px solid var(--grey-6); }
|
||||
.tok-tip {
|
||||
position: fixed;
|
||||
z-index: 100;
|
||||
pointer-events: none;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
padding: 4px 8px;
|
||||
font: 400 11px var(--font-mono);
|
||||
color: var(--grey-5);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
pre.json { background: var(--grey-2); border: 1px solid var(--hairline); padding: 12px; font-size: 11px; overflow-x: auto; }
|
||||
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-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; }
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
.uplot, .uplot *, .uplot *::before, .uplot *::after {box-sizing: border-box;}.uplot {font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";line-height: 1.5;width: min-content;}.u-title {text-align: center;font-size: 18px;font-weight: bold;}.u-wrap {position: relative;user-select: none;}.u-over, .u-under {position: absolute;}.u-under {overflow: hidden;}.uplot canvas {display: block;position: relative;width: 100%;height: 100%;}.u-axis {position: absolute;}.u-legend {font-size: 14px;margin: auto;text-align: center;}.u-inline {display: block;}.u-inline * {display: inline-block;}.u-inline tr {margin-right: 16px;}.u-legend th {font-weight: 600;}.u-legend th > * {vertical-align: middle;display: inline-block;}.u-legend .u-marker {width: 1em;height: 1em;margin-right: 4px;background-clip: padding-box !important;}.u-inline.u-live th::after {content: ":";vertical-align: middle;}.u-inline:not(.u-live) .u-value {display: none;}.u-series > * {padding: 4px;}.u-series th {cursor: pointer;}.u-legend .u-off > * {opacity: 0.3;}.u-select {background: rgba(0,0,0,0.07);position: absolute;pointer-events: none;}.u-cursor-x, .u-cursor-y {position: absolute;left: 0;top: 0;pointer-events: none;will-change: transform;}.u-hz .u-cursor-x, .u-vt .u-cursor-y {height: 100%;border-right: 1px dashed #607D8B;}.u-hz .u-cursor-y, .u-vt .u-cursor-x {width: 100%;border-bottom: 1px dashed #607D8B;}.u-cursor-pt {position: absolute;top: 0;left: 0;border-radius: 50%;border: 0 solid;pointer-events: none;will-change: transform;/*this has to be !important since we set inline "background" shorthand */background-clip: padding-box !important;}.u-axis.u-off, .u-select.u-off, .u-cursor-x.u-off, .u-cursor-y.u-off, .u-cursor-pt.u-off {display: none;}
|
||||
@@ -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()
|
||||
@@ -15,6 +15,9 @@ 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
|
||||
|
||||
write_launch_toml(config.output_dir, "evals")
|
||||
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_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
latest_log_dir,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
@@ -71,6 +77,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.output_dir,
|
||||
launcher_log_dir=get_launcher_log_dir(config.output_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
dp_per_node=dp_per_node,
|
||||
num_nodes=getattr(config.deployment, "num_nodes", 1),
|
||||
@@ -116,6 +123,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
script = template.render(**template_vars)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.output_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -131,7 +139,7 @@ def inference_slurm(config: InferenceConfig):
|
||||
config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
script_path = config.output_dir / INFERENCE_SBATCH
|
||||
script_path = get_launcher_dir(config.output_dir) / INFERENCE_SBATCH
|
||||
write_slurm_script(config, config_path, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ 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
|
||||
@@ -23,9 +24,12 @@ from prime_rl.utils.pathing import (
|
||||
format_log_message,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
latest_log_dir,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
write_launch_toml,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -120,6 +124,7 @@ def rl_local(config: RLConfig):
|
||||
)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
write_launch_toml(config.run_dir, "rl")
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
@@ -127,6 +132,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
|
||||
@@ -365,17 +372,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}")
|
||||
@@ -462,6 +464,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_dir / RL_CONFIG,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
elif config.inference is not None and config.inference.deployment.type == "disaggregated":
|
||||
@@ -473,6 +477,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
|
||||
nodes_per_infer_replica=infer_deploy.num_nodes,
|
||||
@@ -514,6 +520,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir, # TODO: should prob have each subconfig path separately
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.total_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
|
||||
@@ -546,6 +554,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -557,6 +566,7 @@ def rl_slurm(config: RLConfig):
|
||||
)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
write_launch_toml(config.run_dir, "rl")
|
||||
log_dir = latest_log_dir(config.run_dir)
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
@@ -593,7 +603,7 @@ def rl_slurm(config: RLConfig):
|
||||
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
|
||||
)
|
||||
|
||||
script_path = config.run_dir / RL_SBATCH
|
||||
script_path = get_launcher_dir(config.run_dir) / RL_SBATCH
|
||||
write_slurm_script(config, config_dir, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
@@ -601,6 +611,8 @@ def rl_slurm(config: RLConfig):
|
||||
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:
|
||||
@@ -608,6 +620,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):
|
||||
|
||||
@@ -12,6 +12,7 @@ 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 (
|
||||
@@ -21,10 +22,13 @@ from prime_rl.utils.pathing import (
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
get_log_dir,
|
||||
latest_log_dir,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
write_launch_toml,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -161,6 +165,8 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
else:
|
||||
@@ -168,6 +174,8 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
num_nodes=config.deployment.num_train_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
@@ -182,6 +190,7 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -216,6 +225,8 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
|
||||
**config.slurm.template_vars,
|
||||
config_dir=config_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router=config.inference.router,
|
||||
@@ -233,6 +244,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -248,6 +260,7 @@ def sft_slurm(config: SFTConfig):
|
||||
decoupled_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_path = config_dir / SFT_CONFIG
|
||||
exclude = (
|
||||
{"deployment", "slurm", "dry_run", "clean"}
|
||||
@@ -267,7 +280,8 @@ def sft_slurm(config: SFTConfig):
|
||||
if decoupled_eval and config.monitors.wandb is not None:
|
||||
prl_run_id = os.environ["PRL_RUN_ID"]
|
||||
|
||||
script_path = config.run_dir / SFT_SBATCH
|
||||
launcher_dir = get_launcher_dir(config.run_dir)
|
||||
script_path = launcher_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, script_path, prl_run_id)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
@@ -279,7 +293,7 @@ def sft_slurm(config: SFTConfig):
|
||||
if decoupled_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(f"Wrote eval subconfigs to {config_dir}")
|
||||
eval_script_path = config.run_dir / EVAL_SBATCH
|
||||
eval_script_path = launcher_dir / EVAL_SBATCH
|
||||
write_eval_slurm_script(config, config_dir, eval_script_path, prl_run_id)
|
||||
logger.info(f"Wrote eval SLURM script to {eval_script_path}")
|
||||
script_paths = [script_path, eval_script_path]
|
||||
@@ -320,6 +334,8 @@ def sft_slurm(config: SFTConfig):
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n{submit}{note}\n\n{log_message}")
|
||||
return
|
||||
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
submitted_job_ids: list[str] = []
|
||||
for path in script_paths:
|
||||
# --parsable prints ``<job_id>[;<cluster>]`` — the human-readable format varies
|
||||
@@ -344,6 +360,7 @@ def sft_slurm(config: SFTConfig):
|
||||
logger.success(f"Submitted batch job {job_id}")
|
||||
|
||||
logger.success(log_message)
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
|
||||
def sft_local(config: SFTConfig):
|
||||
@@ -353,6 +370,7 @@ 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_path = config_dir / SFT_CONFIG
|
||||
write_config(config, config_path)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
@@ -365,6 +383,8 @@ def sft_local(config: SFTConfig):
|
||||
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
log_dir = create_attempt_log_dir(config.run_dir)
|
||||
|
||||
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
|
||||
@@ -503,12 +523,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.
|
||||
|
||||
+23
-10
@@ -40,12 +40,13 @@ from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.metrics import dispatch_failure_metrics
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
monkey_patch_oai_iterable_types,
|
||||
)
|
||||
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.types import EvalBatch, Policy
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
|
||||
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
|
||||
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
|
||||
from prime_rl.utils.config import dump_resolved_config
|
||||
@@ -93,6 +94,7 @@ class Evals:
|
||||
|
||||
get_logger().info(f"Initializing monitors ({config.monitors})")
|
||||
await monitors.setup(
|
||||
producer="evals",
|
||||
wandb=config.monitors.wandb,
|
||||
file=config.monitors.file,
|
||||
output_dir=config.output_dir,
|
||||
@@ -167,11 +169,10 @@ class Evals:
|
||||
get_inflight=lambda: self.dispatcher.current_inflight,
|
||||
)
|
||||
# The collector always polls — it feeds the concurrency controller;
|
||||
# W&B mirroring is gated on the registered monitor.
|
||||
# metrics fan out to every registered monitor.
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.admin_clients.clients,
|
||||
on_load=self.concurrency.observe,
|
||||
log_to_wandb=wandb_enabled,
|
||||
)
|
||||
# Fail fast when adaptivity has no signal: external API endpoints
|
||||
# (e.g. Prime Inference) expose no vLLM /metrics, so without a probe
|
||||
@@ -375,10 +376,15 @@ class Evals:
|
||||
# An env with no examples emits no episodes, so its epoch can never finalize.
|
||||
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
|
||||
while pending:
|
||||
episode = await self.dispatcher.out_q.get()
|
||||
step = eval_work(episode).step
|
||||
await monitors.log([episode], step, "eval", "all")
|
||||
eval_batch = self.eval_sink.add(episode)
|
||||
item = await self.dispatcher.out_q.get()
|
||||
if isinstance(item, GroupCancellation):
|
||||
raise RuntimeError("Eval dispatcher emitted a group cancellation")
|
||||
if isinstance(item, DispatchFailure):
|
||||
eval_batch = self.eval_sink.fail(item)
|
||||
else:
|
||||
step = eval_work(item).step
|
||||
await monitors.log([item], step, "eval", "all")
|
||||
eval_batch = self.eval_sink.add(item)
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
pending.discard(eval_batch.env_name)
|
||||
@@ -386,17 +392,24 @@ class Evals:
|
||||
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
|
||||
"""Persist + log one completed eval epoch through the monitors, mirroring the
|
||||
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
|
||||
if not batch.episodes:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no episodes returned, skipping log")
|
||||
if not batch.episodes and not batch.failures:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
|
||||
return
|
||||
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
if batch.episodes.effective:
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
|
||||
episodes = batch.episodes
|
||||
effective = episodes.effective
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", episodes), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
|
||||
total_attempts = len(episodes) + len(batch.failures)
|
||||
metrics |= dispatch_failure_metrics(
|
||||
batch.failures,
|
||||
prefix=f"eval/{batch.env_name}/all",
|
||||
total_attempts=total_attempts,
|
||||
)
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
|
||||
metrics["step"] = float(batch.step)
|
||||
await monitors.log(metrics, step=batch.step)
|
||||
|
||||
@@ -51,7 +51,7 @@ def receive_state_dict(communicator: PyNcclCommunicator) -> Generator[tuple[str,
|
||||
# Split concatenated tensor back into individual tensors
|
||||
offset = 0
|
||||
for key, shape, numel in tensor_info_list:
|
||||
tensor = concatenated[offset : offset + numel].view(shape).clone()
|
||||
tensor = concatenated[offset : offset + numel].view(shape)
|
||||
offset += numel
|
||||
try:
|
||||
yield key, tensor
|
||||
|
||||
@@ -45,6 +45,7 @@ async def setup(
|
||||
file: FileMonitorConfig | None = None,
|
||||
*,
|
||||
output_dir: Path,
|
||||
producer: str | None = None,
|
||||
run_config: BaseConfig | None = None,
|
||||
train_env_names: list[str] | None = None,
|
||||
eval_env_names: list[str] | None = None,
|
||||
@@ -79,7 +80,7 @@ async def setup(
|
||||
)
|
||||
)
|
||||
if file is not None:
|
||||
monitors.append(("file", FileMonitor(file), dict(output_dir=output_dir)))
|
||||
monitors.append(("file", FileMonitor(file), dict(output_dir=output_dir, producer=producer)))
|
||||
if not monitors:
|
||||
return
|
||||
|
||||
@@ -99,7 +100,7 @@ def get(monitor_cls: type[Monitor]) -> Monitor | None:
|
||||
|
||||
|
||||
@overload
|
||||
async def log(data: dict[str, Any], step: int) -> None: ...
|
||||
async def log(data: dict[str, Any], step: int | None) -> None: ...
|
||||
|
||||
|
||||
@overload
|
||||
@@ -108,7 +109,7 @@ async def log(data: vf.Episode | list[vf.Episode], step: int, kind: Kind, subset
|
||||
|
||||
async def log(
|
||||
data: dict[str, Any] | vf.Episode | list[vf.Episode],
|
||||
step: int,
|
||||
step: int | None,
|
||||
kind: Kind = "train",
|
||||
subset: Subset = "effective",
|
||||
) -> None:
|
||||
|
||||
@@ -24,7 +24,7 @@ class Monitor(ABC):
|
||||
"""Initialize run. Overrides name their own kwargs."""
|
||||
|
||||
@overload
|
||||
async def log(self, data: dict[str, Any], step: int) -> None: ...
|
||||
async def log(self, data: dict[str, Any], step: int | None) -> None: ...
|
||||
|
||||
@overload
|
||||
async def log(self, data: vf.Episode | list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None: ...
|
||||
@@ -32,7 +32,7 @@ class Monitor(ABC):
|
||||
async def log(
|
||||
self,
|
||||
data: dict[str, Any] | vf.Episode | list[vf.Episode],
|
||||
step: int,
|
||||
step: int | None,
|
||||
kind: Kind = "train",
|
||||
subset: Subset = "effective",
|
||||
) -> None:
|
||||
@@ -41,11 +41,13 @@ class Monitor(ABC):
|
||||
await self.log_metrics(data, step=step)
|
||||
else:
|
||||
episodes = data if isinstance(data, list) else [data]
|
||||
assert step is not None
|
||||
await self.log_episodes(episodes, step=step, kind=kind, subset=subset)
|
||||
|
||||
@abstractmethod
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
"""Log scalar metrics."""
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
"""Log scalar metrics. ``step=None`` logs a time-keyed row (e.g. inference
|
||||
metrics, which are sampled on wall time rather than the training step)."""
|
||||
|
||||
@abstractmethod
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
|
||||
@@ -22,15 +22,18 @@ class FileMonitor(Monitor):
|
||||
config: FileMonitorConfig
|
||||
file: TextIO
|
||||
|
||||
async def init(self, output_dir: Path) -> None:
|
||||
async def init(self, output_dir: Path, producer: str | None = None) -> None:
|
||||
self.output_dir = output_dir
|
||||
self.producer = producer
|
||||
self.path = output_dir / self.config.path
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Line-buffered append so a concurrently-running dashboard can tail the file.
|
||||
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
|
||||
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
"""``step=None`` logs a time-keyed row (e.g. inference metrics, which are
|
||||
sampled on wall time rather than the training step)."""
|
||||
sanitized, dropped = sanitize(metrics)
|
||||
if dropped:
|
||||
self.logger.warning(
|
||||
@@ -38,6 +41,8 @@ class FileMonitor(Monitor):
|
||||
)
|
||||
|
||||
row = {"step": step, "time": time.time(), **sanitized}
|
||||
if self.producer is not None:
|
||||
row["producer"] = self.producer
|
||||
self.file.write(json.dumps(row) + "\n")
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
|
||||
@@ -5,6 +5,7 @@ import atexit
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Coroutine
|
||||
|
||||
@@ -87,10 +88,13 @@ class PrimeMonitor(Monitor):
|
||||
)
|
||||
await self.run.create(name=self.config.name, **run_fields)
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
metrics, dropped = sanitize(metrics)
|
||||
if dropped:
|
||||
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
|
||||
# every monitor stamps its own wall time; without it, step=None rows
|
||||
# (e.g. inference metrics) reach the platform with no time anchor
|
||||
metrics["_timestamp"] = time.time()
|
||||
self.run.submit("metrics upload", self.run.log_metrics(metrics))
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
|
||||
@@ -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 (
|
||||
@@ -113,6 +116,9 @@ class WandbMonitor(Monitor):
|
||||
self.wandb = init_wandb(max_retries)
|
||||
|
||||
wandb.define_metric("*", step_metric="step")
|
||||
# key prefixes that arrived via step=None (wall-time rows); their time axis
|
||||
# is defined lazily on first sight in log_metrics
|
||||
self._time_prefixes: set[str] = set()
|
||||
|
||||
# Provision the curated "overview" saved view once per project (the run's primary process
|
||||
# in shared mode, else the single master). Best-effort: a workspaces/API failure must never
|
||||
@@ -133,8 +139,18 @@ class WandbMonitor(Monitor):
|
||||
|
||||
self.logger.info(f"Logging metrics to W&B ({self.wandb.url})")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
wandb.log({**metrics, "step": step})
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
# every log carries the monitor's own wall-time stamp
|
||||
if step is None:
|
||||
# time-keyed rows chart against wall time; whichever key prefixes show
|
||||
# up this way get their time axis defined on first sight
|
||||
for prefix in {key.split("/")[0] for key in metrics}:
|
||||
if prefix not in self._time_prefixes:
|
||||
self._time_prefixes.add(prefix)
|
||||
wandb.define_metric(f"{prefix}/*", step_metric="_timestamp")
|
||||
wandb.log({**metrics, "_timestamp": time.time()})
|
||||
else:
|
||||
wandb.log({**metrics, "step": step, "_timestamp": time.time()})
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
pass
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
"""Curated "overview" W&B saved view.
|
||||
|
||||
The dashboard mirrors these sections in `prime_rl/dashboard/static/app.js`
|
||||
(buildSections + the *_METRICS/INFERENCE_PANELS constants) — keep the two in
|
||||
sync when editing panels here.
|
||||
|
||||
prime-rl logs many metrics; the default workspace auto-generates a panel per key, which buries the
|
||||
few that matter. These build a named saved view grouping the important metrics into sections, so a
|
||||
new project gets a usable overview without hand-picking panels. Panels are untitled — each shows
|
||||
@@ -29,6 +33,7 @@ OVERVIEW_NAME = "overview"
|
||||
# agent. Only the score metric differs — train scores with "reward/mean", eval with "avg@k" (its k
|
||||
# dynamic, so also a regex) — and each section builder prepends its own.
|
||||
COMMON_METRICS = [
|
||||
"all/dispatch_failure/mean",
|
||||
"effective/num_total_tokens/mean",
|
||||
"effective/num_turns/mean",
|
||||
"effective/num_branches/mean",
|
||||
|
||||
@@ -97,7 +97,14 @@ class AdminClients:
|
||||
self._wait_for_ready_timeout = client_config.wait_for_ready_timeout
|
||||
|
||||
async def wait_for_ready(self, model_name: str) -> None:
|
||||
await check_health(self.clients + self._router_clients, timeout=self._wait_for_ready_timeout)
|
||||
# The engines are waited on even when a router fronts them: the llm-d
|
||||
# router (Envoy) 404s /health, which check_health treats as "no health
|
||||
# route", so the router alone is not a readiness signal. The router
|
||||
# owns the info-level waiting log; the per-engine waits log at debug.
|
||||
await asyncio.gather(
|
||||
check_health(self.clients, timeout=self._wait_for_ready_timeout, quiet=bool(self._router_clients)),
|
||||
check_health(self._router_clients, timeout=self._wait_for_ready_timeout),
|
||||
)
|
||||
await maybe_check_has_model(self.clients, model_name, skip_model_check=self._skip_model_check)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
@@ -190,8 +197,15 @@ async def maybe_check_has_model(
|
||||
|
||||
|
||||
async def check_health(
|
||||
admin_clients: list[AsyncClient], interval: int = 1, log_interval: int = 30, timeout: int = 1800
|
||||
admin_clients: list[AsyncClient],
|
||||
interval: int = 1,
|
||||
log_interval: int = 30,
|
||||
timeout: int = 1800,
|
||||
quiet: bool = False,
|
||||
) -> None:
|
||||
"""Wait until every client's /health responds. With ``quiet``, the periodic
|
||||
waiting lines log at debug instead of info - used for engines fronted by a
|
||||
router, so startup logs one waiting line instead of one per engine."""
|
||||
logger = get_logger()
|
||||
|
||||
async def _check_health(admin_client: AsyncClient) -> None:
|
||||
@@ -208,9 +222,8 @@ async def check_health(
|
||||
return
|
||||
except Exception as e:
|
||||
if wait_time % log_interval == 0 and wait_time > 0:
|
||||
logger.info(
|
||||
f"Waiting for inference server at {admin_client.base_url} to start up ({wait_time}s elapsed)"
|
||||
)
|
||||
log = logger.debug if quiet else logger.info
|
||||
log(f"Waiting for inference server at {admin_client.base_url} to start up ({wait_time}s elapsed)")
|
||||
logger.debug(f"Inference server at {admin_client.base_url} not reachable: {e!r}")
|
||||
await asyncio.sleep(interval)
|
||||
wait_time += interval
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
burst-capped so a raised (or drained) cap never lands all its prefills at
|
||||
once.
|
||||
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
|
||||
- Emit-everything invariant: every dispatched episode eventually reaches
|
||||
``out_q`` exactly once — as a native episode, or covered by its group's
|
||||
single ``GroupCancellation`` message when the group is dropped. Failures
|
||||
remain episode errors; sinks decide drop / partial-train policy.
|
||||
- Every dispatched attempt reaches ``out_q`` exactly once: as the native
|
||||
episode returned by the environment, as a ``DispatchFailure`` when no
|
||||
episode was produced, or under the group's ``GroupCancellation`` when the
|
||||
orchestrator abandons it.
|
||||
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
|
||||
schedule next. Transitions are level-triggered (driven by the eval
|
||||
source's emptiness), so in-flight episodes of the opposite kind drain
|
||||
@@ -44,6 +44,7 @@ from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import (
|
||||
CancelReason,
|
||||
DispatchFailure,
|
||||
DispatchResult,
|
||||
GroupCancellation,
|
||||
GroupState,
|
||||
@@ -121,15 +122,6 @@ class DispatcherMetrics:
|
||||
return keys
|
||||
|
||||
|
||||
def _trace_task(task: vf.Task) -> vf.TraceTask:
|
||||
return vf.TraceTask(
|
||||
type=type(task).__name__,
|
||||
data=task.data,
|
||||
key=task.key,
|
||||
hash=task.hash,
|
||||
)
|
||||
|
||||
|
||||
def _validate_episode_task(episode: vf.WireEpisode, task: vf.Task) -> None:
|
||||
expected = (task.key, task.hash)
|
||||
actual = (episode.task.key, episode.task.hash)
|
||||
@@ -202,7 +194,8 @@ class Dispatcher:
|
||||
# Bounded so the dispatcher backpressures on a slow sink (unbounded
|
||||
# when no hard ceiling is configured — the dynamic cap still bounds
|
||||
# in-flight work). One entry per episode — the sinks count episodes,
|
||||
# never loose traces — plus one ``GroupCancellation`` per dropped group.
|
||||
# never loose traces — plus terminal dispatcher events for attempts
|
||||
# that produced no episode.
|
||||
maxsize = max(8, max_inflight_ceiling) if max_inflight_ceiling is not None else 0
|
||||
self.out_q: asyncio.Queue[DispatchResult] = asyncio.Queue(maxsize=maxsize)
|
||||
|
||||
@@ -217,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
|
||||
@@ -353,7 +348,7 @@ class Dispatcher:
|
||||
timeout=0.5, # wake periodically to re-check fill (mode flips)
|
||||
)
|
||||
for task in done:
|
||||
await self.handle_completed_episode(task)
|
||||
await self.handle_completed_request(task)
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
|
||||
@@ -378,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)
|
||||
@@ -399,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
|
||||
@@ -408,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:
|
||||
@@ -558,34 +565,40 @@ class Dispatcher:
|
||||
if refund_admission:
|
||||
self.admissions_in_window = max(0, self.admissions_in_window - 1)
|
||||
|
||||
async def handle_completed_episode(self, task: asyncio.Task) -> None:
|
||||
"""Emit every dispatched episode exactly once to ``out_q``."""
|
||||
async def handle_completed_request(self, task: asyncio.Task) -> None:
|
||||
"""Emit the terminal result of one dispatched environment request."""
|
||||
meta = self.inflight.pop(task, None)
|
||||
if meta is None:
|
||||
return # already handled by drop_group / cancel_inflight_episodes
|
||||
self.release(refund_admission=True)
|
||||
group = self.groups.get(meta.group_id)
|
||||
|
||||
is_synth_exception = False
|
||||
try:
|
||||
episode: vf.WireEpisode = task.result()
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
except Exception as exc:
|
||||
get_logger().warning(f"Episode task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
|
||||
episode = vf.WireEpisode(
|
||||
env=vf.EnvInfo(id=meta.env_name),
|
||||
task=_trace_task(meta.task),
|
||||
ok=False,
|
||||
errors=[
|
||||
vf.Error(
|
||||
get_logger().warning(f"Environment request failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
policy_version = self.complete_group_member(meta, group)
|
||||
await self.out_q.put(
|
||||
DispatchFailure(
|
||||
kind=meta.kind,
|
||||
env_name=meta.env_name,
|
||||
group_id=str(meta.group_id),
|
||||
step=meta.step,
|
||||
policy_version=policy_version,
|
||||
task_type=type(meta.task).__name__,
|
||||
task_key=meta.task.key,
|
||||
task_hash=meta.task.hash,
|
||||
error=vf.Error(
|
||||
type=type(exc).__name__,
|
||||
message=str(exc),
|
||||
traceback="".join(traceback.format_exception(exc)),
|
||||
)
|
||||
],
|
||||
),
|
||||
)
|
||||
)
|
||||
is_synth_exception = True
|
||||
return
|
||||
|
||||
if not episode.traces and episode.ok:
|
||||
episode.ok = False
|
||||
@@ -601,19 +614,29 @@ class Dispatcher:
|
||||
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
|
||||
if trace.has_error:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if not is_synth_exception and trace.last_error is not None:
|
||||
if trace.last_error is not None:
|
||||
get_logger().warning(
|
||||
f"Trace failed in group {meta.group_id} ({meta.env_name}) — "
|
||||
f"{trace.last_error.type}: {trace.last_error.message}"
|
||||
)
|
||||
if not episode.ok and not episode.traces:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if not is_synth_exception and self.on_episode_complete is not None and meta.started_at > 0:
|
||||
if self.on_episode_complete is not None and meta.started_at > 0:
|
||||
self.on_episode_complete(
|
||||
meta.env_name, meta.kind, episode.num_total_tokens, time.monotonic() - meta.started_at
|
||||
)
|
||||
await self.emit_episode(meta, group, episode)
|
||||
|
||||
def complete_group_member(self, meta: InflightEpisode, group: GroupState | None) -> int:
|
||||
"""Advance group accounting and return the attempt's pinned policy version."""
|
||||
policy_version = meta.policy_version
|
||||
if group is not None:
|
||||
policy_version = group.policy_version_at_start
|
||||
group.emitted += 1
|
||||
if group.emitted >= group.target_episodes:
|
||||
self.groups.pop(meta.group_id, None)
|
||||
return policy_version
|
||||
|
||||
async def emit_episode(
|
||||
self,
|
||||
meta: InflightEpisode,
|
||||
@@ -622,12 +645,7 @@ class Dispatcher:
|
||||
) -> None:
|
||||
"""Stamp one completed episode with its dispatch provenance and emit it."""
|
||||
_validate_episode_task(episode, meta.task)
|
||||
policy_version = meta.policy_version
|
||||
if group is not None:
|
||||
policy_version = group.policy_version_at_start
|
||||
group.emitted += 1
|
||||
if group.emitted >= group.target_episodes:
|
||||
self.groups.pop(meta.group_id, None)
|
||||
policy_version = self.complete_group_member(meta, group)
|
||||
|
||||
episode.env.name = meta.env_name
|
||||
episode.group = vf.GroupInfo(id=str(meta.group_id))
|
||||
@@ -654,7 +672,7 @@ class Dispatcher:
|
||||
# Sync claim phase: pop matching tasks from ``self.inflight`` and
|
||||
# release their permits in one non-yielding sweep. After this loop
|
||||
# the dropped tasks are no longer reachable from ``self.inflight``,
|
||||
# so ``handle_completed_episode``'s existing None-guard makes the
|
||||
# so ``handle_completed_request``'s existing None-guard makes the
|
||||
# subsequent async emit phase race-free.
|
||||
claimed: list[tuple[asyncio.Task, InflightEpisode]] = []
|
||||
for task, meta in list(self.inflight.items()):
|
||||
|
||||
@@ -8,7 +8,7 @@ import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.metrics import EvalEpisodes
|
||||
from prime_rl.orchestrator.types import EvalBatch
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch
|
||||
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, eval_work
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -19,7 +19,9 @@ class EvalSink:
|
||||
def __init__(self, *, eval_envs: EvalEnvs) -> None:
|
||||
self.eval_envs = eval_envs
|
||||
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
|
||||
self.pending_group_failures: dict[str, list[DispatchFailure]] = defaultdict(list)
|
||||
self.pending_batches: dict[tuple[str, int], list[vf.Episode]] = defaultdict(list)
|
||||
self.pending_batch_failures: dict[tuple[str, int], list[DispatchFailure]] = defaultdict(list)
|
||||
|
||||
def add(self, episode: vf.Episode) -> EvalBatch | None:
|
||||
env_name = episode_env_name(episode)
|
||||
@@ -28,12 +30,32 @@ class EvalSink:
|
||||
bkey = (env_name, eval_step)
|
||||
group = self.pending_groups[group_id]
|
||||
group.append(episode)
|
||||
if len(group) >= self.group_size_for(env_name):
|
||||
if self._group_size(group_id) >= self.group_size_for(env_name):
|
||||
self.process_group(group_id)
|
||||
if len(self.pending_batches[bkey]) >= self.batch_size_for(env_name):
|
||||
if self._batch_size(bkey) >= self.batch_size_for(env_name):
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
def fail(self, failure: DispatchFailure) -> EvalBatch | None:
|
||||
"""Count a request failure toward its group and eval epoch without
|
||||
manufacturing a verifier episode."""
|
||||
if failure.kind != "eval":
|
||||
raise ValueError(f"EvalSink cannot process a {failure.kind} dispatch failure")
|
||||
group_id = failure.group_id
|
||||
bkey = (failure.env_name, failure.step)
|
||||
self.pending_group_failures[group_id].append(failure)
|
||||
if self._group_size(group_id) >= self.group_size_for(failure.env_name):
|
||||
self.process_group(group_id)
|
||||
if self._batch_size(bkey) >= self.batch_size_for(failure.env_name):
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
def _group_size(self, group_id: str) -> int:
|
||||
return len(self.pending_groups[group_id]) + len(self.pending_group_failures[group_id])
|
||||
|
||||
def _batch_size(self, key: tuple[str, int]) -> int:
|
||||
return len(self.pending_batches[key]) + len(self.pending_batch_failures[key])
|
||||
|
||||
def group_size_for(self, env_name: str) -> int:
|
||||
return self.eval_envs.get(env_name).config.group_size
|
||||
|
||||
@@ -42,15 +64,23 @@ class EvalSink:
|
||||
return len(env.examples) * env.config.group_size
|
||||
|
||||
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
|
||||
batch_counts = {key: len(runs) for key, runs in self.pending_batches.items()}
|
||||
keys = set(self.pending_batches) | set(self.pending_batch_failures)
|
||||
batch_counts = {key: self._batch_size(key) for key in keys}
|
||||
buffered: dict[tuple[str, int], int] = {}
|
||||
for group in self.pending_groups.values():
|
||||
if not group:
|
||||
group_ids = set(self.pending_groups) | set(self.pending_group_failures)
|
||||
for group_id in group_ids:
|
||||
group = self.pending_groups[group_id]
|
||||
failures = self.pending_group_failures[group_id]
|
||||
if not group and not failures:
|
||||
continue
|
||||
episode = group[0]
|
||||
eval_step = eval_work(episode).step
|
||||
key = (episode_env_name(episode), eval_step)
|
||||
buffered[key] = buffered.get(key, 0) + len(group)
|
||||
if group:
|
||||
env_name = episode_env_name(group[0])
|
||||
eval_step = eval_work(group[0]).step
|
||||
else:
|
||||
env_name = failures[0].env_name
|
||||
eval_step = failures[0].step
|
||||
key = (env_name, eval_step)
|
||||
buffered[key] = buffered.get(key, 0) + len(group) + len(failures)
|
||||
return [
|
||||
(
|
||||
env_name,
|
||||
@@ -64,12 +94,18 @@ class EvalSink:
|
||||
|
||||
def process_group(self, group_id: str) -> None:
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
if not group:
|
||||
failures = self.pending_group_failures.pop(group_id, [])
|
||||
if not group and not failures:
|
||||
return
|
||||
episode = group[0]
|
||||
env_name = episode_env_name(episode)
|
||||
eval_step = eval_work(episode).step
|
||||
self.pending_batches[(env_name, eval_step)].extend(group)
|
||||
if group:
|
||||
env_name = episode_env_name(group[0])
|
||||
eval_step = eval_work(group[0]).step
|
||||
else:
|
||||
env_name = failures[0].env_name
|
||||
eval_step = failures[0].step
|
||||
key = (env_name, eval_step)
|
||||
self.pending_batches[key].extend(group)
|
||||
self.pending_batch_failures[key].extend(failures)
|
||||
|
||||
traces = [trace for episode in group for trace in episode.traces]
|
||||
survivors = [trace for trace in traces if not trace.has_error]
|
||||
@@ -79,15 +115,17 @@ class EvalSink:
|
||||
task_idx = next((trace.task.data.idx for trace in traces), None)
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} "
|
||||
f"eval_step={eval_step} | episodes={len(group)} traces={len(traces)} "
|
||||
f"(errored={num_errored}) | reward={avg_reward:.4f}"
|
||||
f"eval_step={eval_step} | episodes={len(group)} dispatch_failures={len(failures)} "
|
||||
f"traces={len(traces)} (errored={num_errored + len(failures)}) | reward={avg_reward:.4f}"
|
||||
)
|
||||
|
||||
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
|
||||
env_name, step = key
|
||||
episodes = self.pending_batches.pop(key, [])
|
||||
failures = self.pending_batch_failures.pop(key, [])
|
||||
return EvalBatch(
|
||||
env_name=env_name,
|
||||
step=step,
|
||||
episodes=EvalEpisodes(episodes, group_size=self.group_size_for(env_name)),
|
||||
failures=failures,
|
||||
)
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -7,10 +7,10 @@ from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from statistics import mean, median
|
||||
|
||||
import wandb
|
||||
from httpx import AsyncClient
|
||||
from prometheus_client.parser import text_string_to_metric_families
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.orchestrator.concurrency import EngineLoadSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -279,7 +279,7 @@ class InferenceMetricsCollector:
|
||||
admin_clients: list[AsyncClient],
|
||||
roles: list[str | None] | None = None,
|
||||
on_load: Callable[[list[EngineLoadSample]], None] | None = None,
|
||||
log_to_wandb: bool = True,
|
||||
log_metrics: bool = True,
|
||||
):
|
||||
self.endpoints = build_metrics_endpoints(admin_clients, roles=roles)
|
||||
self.previous: dict[tuple[str, str], TimedSnapshot] = {}
|
||||
@@ -287,16 +287,13 @@ class InferenceMetricsCollector:
|
||||
self.task: asyncio.Task | None = None
|
||||
self.has_pd_roles = {endpoint.role for endpoint in self.endpoints if endpoint.role is not None} == PD_ROLES
|
||||
self.on_load = on_load
|
||||
self.log_to_wandb = log_to_wandb
|
||||
self.log_metrics = log_metrics
|
||||
get_logger().info(
|
||||
"Collecting inference metrics from "
|
||||
+ ", ".join(f"{endpoint.name}={endpoint.key}" for endpoint in self.endpoints)
|
||||
)
|
||||
|
||||
async def start(self):
|
||||
if self.log_to_wandb:
|
||||
wandb.define_metric("inference/*", step_metric="_timestamp")
|
||||
|
||||
async def poll_loop():
|
||||
while True:
|
||||
try:
|
||||
@@ -346,7 +343,7 @@ class InferenceMetricsCollector:
|
||||
return
|
||||
|
||||
await asyncio.gather(*[self.fetch_max_model_len(endpoint) for endpoint in self.endpoints])
|
||||
metrics = self.build_metrics(samples) if self.log_to_wandb else {}
|
||||
metrics = self.build_metrics(samples) if self.log_metrics else {}
|
||||
load_samples = [self.build_load_sample(sample) for sample in samples]
|
||||
for sample in samples:
|
||||
self.previous[sample.key] = TimedSnapshot(timestamp=sample.timestamp, snapshot=sample.snapshot)
|
||||
@@ -355,8 +352,10 @@ class InferenceMetricsCollector:
|
||||
self.on_load(load_samples)
|
||||
|
||||
if metrics:
|
||||
metrics["_timestamp"] = time.time()
|
||||
wandb.log(metrics)
|
||||
# Time-keyed rows (step=None): inference metrics are sampled on wall
|
||||
# time, not the training step. Fans out to every registered monitor;
|
||||
# each monitor stamps its own timestamp.
|
||||
await monitors.log(metrics, step=None)
|
||||
|
||||
async def fetch_max_model_len(self, endpoint: MetricsEndpoint) -> None:
|
||||
"""Cache the engine's max context length from ``/v1/models`` (set
|
||||
|
||||
@@ -9,11 +9,25 @@ from typing import Any, Literal
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.algo.routing import is_trainable, scalar_advantage
|
||||
from prime_rl.orchestrator.types import DispatchFailure
|
||||
from prime_rl.orchestrator.utils import compute_pass_metrics, episode_env_name, episode_group_id
|
||||
|
||||
Subset = Literal["all", "effective"]
|
||||
|
||||
|
||||
def dispatch_failure_metrics(failures: list[DispatchFailure], *, prefix: str, total_attempts: int) -> dict[str, float]:
|
||||
"""Metrics for requests that failed outside the verifier episode boundary."""
|
||||
if total_attempts == 0:
|
||||
return {}
|
||||
out = {f"{prefix}/dispatch_failure/mean": len(failures) / total_attempts}
|
||||
error_types = [failure.error.type for failure in failures]
|
||||
out |= {
|
||||
f"{prefix}/dispatch_failure/{error_type}": float(error_types.count(error_type))
|
||||
for error_type in sorted(set(error_types))
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TraceRecord:
|
||||
"""A trace joined with its episode and training selection state.
|
||||
@@ -317,8 +331,7 @@ class EpisodeMetrics:
|
||||
def cancelled(self) -> Stat:
|
||||
"""Per-episode pipeline-cancellation rate — same denominator as
|
||||
``has_error``. Read from the id-set, not the trace records, so
|
||||
trace-less episodes (synthetic error episodes inside a voided group)
|
||||
still count."""
|
||||
trace-less episodes still count."""
|
||||
return Stat([float(episode.id in self.cancelled_ids) for episode in self.episodes])
|
||||
|
||||
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
|
||||
|
||||
@@ -45,7 +45,7 @@ from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
|
||||
from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.metrics import TrainEpisodes
|
||||
from prime_rl.orchestrator.metrics import TrainEpisodes, dispatch_failure_metrics
|
||||
from prime_rl.orchestrator.packing import BatchPacker
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
@@ -55,6 +55,7 @@ from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.train_sink import TrainSink
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import (
|
||||
DispatchFailure,
|
||||
EvalBatch,
|
||||
GroupCancellation,
|
||||
Policy,
|
||||
@@ -77,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()
|
||||
@@ -165,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
|
||||
@@ -212,6 +210,7 @@ class Orchestrator:
|
||||
self.admin_clients = AdminClients(config.model.client)
|
||||
|
||||
await monitors.setup(
|
||||
producer="orch",
|
||||
wandb=config.monitors.wandb,
|
||||
prime=config.monitors.prime,
|
||||
file=config.monitors.file,
|
||||
@@ -318,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(
|
||||
@@ -363,13 +357,12 @@ class Orchestrator:
|
||||
on_overload=self.dispatcher.cancel_inflight,
|
||||
)
|
||||
# The collector always polls — it feeds the concurrency controller;
|
||||
# W&B mirroring is gated on the registered monitor (the collector logs
|
||||
# to the global W&B session, which only exists when init succeeded).
|
||||
# metrics fan out to every registered monitor when collection is on.
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.admin_clients.clients,
|
||||
roles=config.inference_metrics_roles,
|
||||
on_load=self.concurrency.observe,
|
||||
log_to_wandb=wandb_enabled and config.collect_inference_metrics,
|
||||
log_metrics=config.collect_inference_metrics,
|
||||
)
|
||||
await self.inference_metrics.start()
|
||||
# One awaited scrape so the concurrency controller derives (and logs) its
|
||||
@@ -389,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()
|
||||
@@ -418,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."""
|
||||
@@ -437,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()
|
||||
|
||||
@@ -483,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:
|
||||
@@ -513,20 +499,24 @@ 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 completed episodes and ``GroupCancellation`` events from the
|
||||
dispatcher and route them to the train / eval sink. The sinks return a
|
||||
finalized batch (or ``None``); we just dispatch on the result."""
|
||||
"""Consume dispatcher results and route them to the train / eval sink.
|
||||
|
||||
Native episodes are persisted as verifier artifacts. Dispatch failures
|
||||
and group cancellations remain internal accounting events.
|
||||
|
||||
The sinks return a finalized batch (or ``None``); we just dispatch on
|
||||
the result."""
|
||||
while not self.stopped.is_set():
|
||||
self._raise_if_component_stopped()
|
||||
if self.draining and self.dispatcher.is_idle:
|
||||
@@ -546,6 +536,17 @@ class Orchestrator:
|
||||
if train_batch is not None and not self.draining and not self.stopped.is_set():
|
||||
await self.finalize_train_batch(train_batch)
|
||||
continue
|
||||
if isinstance(item, DispatchFailure):
|
||||
if item.kind == "eval":
|
||||
assert self.eval_sink is not None
|
||||
eval_batch = self.eval_sink.fail(item)
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
else:
|
||||
train_batch = await self.train_sink.fail(item)
|
||||
if train_batch is not None and not self.draining and not self.stopped.is_set():
|
||||
await self.finalize_train_batch(train_batch)
|
||||
continue
|
||||
episode = item
|
||||
|
||||
# Every completed rollout — errored, rejected, or never batched — lands in the
|
||||
@@ -628,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()
|
||||
@@ -669,6 +670,20 @@ class Orchestrator:
|
||||
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
|
||||
for env_name, env_pool in pool.by_env().items():
|
||||
metrics |= env_pool.metrics.to_wandb(prefix=f"train/{env_name}", subset=subset)
|
||||
total_attempts = len(batch.episodes) + len(batch.failures)
|
||||
metrics |= dispatch_failure_metrics(batch.failures, prefix="train/agg/all", total_attempts=total_attempts)
|
||||
failures_by_env: dict[str, list[DispatchFailure]] = {}
|
||||
for failure in batch.failures:
|
||||
failures_by_env.setdefault(failure.env_name, []).append(failure)
|
||||
episodes_by_env = batch.episodes.by_env()
|
||||
for env_name in set(episodes_by_env) | set(failures_by_env):
|
||||
env_failures = failures_by_env.get(env_name, [])
|
||||
env_attempts = len(episodes_by_env.get(env_name, TrainEpisodes())) + len(env_failures)
|
||||
metrics |= dispatch_failure_metrics(
|
||||
env_failures,
|
||||
prefix=f"train/{env_name}/all",
|
||||
total_attempts=env_attempts,
|
||||
)
|
||||
|
||||
# Progress / timing / env-share accounting (assembled here, not in the metrics
|
||||
# objects). ``num_tokens`` is over the full arrival window; the input/output breakdown is over
|
||||
@@ -678,7 +693,9 @@ class Orchestrator:
|
||||
num_input = sum(record.trace.num_input_tokens for record in effective.records)
|
||||
num_output = sum(record.trace.num_output_tokens for record in effective.records)
|
||||
num_rollouts = batch.episodes.num_traces
|
||||
num_unique_examples = len({episode_group_id(episode) for episode in batch.episodes})
|
||||
group_ids = {episode_group_id(episode) for episode in batch.episodes}
|
||||
group_ids.update(failure.group_id for failure in batch.failures)
|
||||
num_unique_examples = len(group_ids)
|
||||
metrics |= {
|
||||
"progress/tokens": num_tokens,
|
||||
"progress/input_tokens": num_input,
|
||||
@@ -725,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
|
||||
@@ -752,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()
|
||||
@@ -839,10 +854,10 @@ class Orchestrator:
|
||||
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
|
||||
Every quality metric (Reward, Trainable, Turns, Branches, Max Off-Policy, Truncation) is
|
||||
computed over exactly the traces shipped to the trainer this step (``batch.cohort``).
|
||||
``Error``, ``Cancelled``, and ``Ratio`` are rates over the step's full arrival window —
|
||||
``Error``, ``Dispatch Failure``, ``Cancelled``, and ``Ratio`` describe the step's full arrival window —
|
||||
over the shipped set they are 0/0/share-of-shipped by construction, so the window is the
|
||||
only scope where they carry signal (and they stay disjoint: a cancellation is a pipeline
|
||||
decision, not a rollout failure)."""
|
||||
decision, an episode error came from the environment, and a dispatch failure produced no episode)."""
|
||||
episodes = batch.episodes
|
||||
effective = batch.cohort.effective
|
||||
eff = effective.metrics
|
||||
@@ -851,13 +866,16 @@ class Orchestrator:
|
||||
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
|
||||
trainable_rate = (n_trainable / n_effective) if n_effective else 0.0
|
||||
max_off_policy_steps = max((episode_staleness(episode, step)[0] for episode in effective), default=0)
|
||||
num_attempts = len(episodes) + len(batch.failures)
|
||||
dispatch_failure_rate = len(batch.failures) / num_attempts if num_attempts else 0.0
|
||||
|
||||
head = (
|
||||
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Trainable {n_trainable}/{n_effective} ({trainable_rate:.1%}) | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max_off_policy_steps} | "
|
||||
f"Error {episodes.metrics.has_error.mean():.1%} | Cancelled {episodes.metrics.cancelled.mean():.1%} | "
|
||||
f"Error {episodes.metrics.has_error.mean():.1%} | Dispatch Failure {dispatch_failure_rate:.1%} | "
|
||||
f"Cancelled {episodes.metrics.cancelled.mean():.1%} | "
|
||||
f"Truncation {eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
if len(self.train_envs) <= 1:
|
||||
@@ -866,7 +884,10 @@ class Orchestrator:
|
||||
|
||||
window_by_env = episodes.by_env()
|
||||
shipped_by_env = effective.by_env()
|
||||
env_names = sorted(set(window_by_env) | set(shipped_by_env))
|
||||
failures_by_env: dict[str, list[DispatchFailure]] = {}
|
||||
for failure in batch.failures:
|
||||
failures_by_env.setdefault(failure.env_name, []).append(failure)
|
||||
env_names = sorted(set(window_by_env) | set(shipped_by_env) | set(failures_by_env))
|
||||
name_width = max((len(name) for name in env_names), default=0)
|
||||
lines = [head]
|
||||
for env_name in env_names:
|
||||
@@ -874,34 +895,36 @@ class Orchestrator:
|
||||
env_eff_pool = shipped_by_env.get(env_name, TrainEpisodes())
|
||||
env_eff = env_eff_pool.metrics
|
||||
ratio = (pool.num_traces / n_generated) if n_generated else 0.0
|
||||
env_failures = failures_by_env.get(env_name, [])
|
||||
env_attempts = len(pool) + len(env_failures)
|
||||
env_failure_rate = len(env_failures) / env_attempts if env_attempts else 0.0
|
||||
lines.append(
|
||||
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_eff.reward.mean():.4f} | "
|
||||
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max((episode_staleness(episode, step)[0] for episode in env_eff_pool), default=0)} | "
|
||||
f"Error {pool.metrics.has_error.mean():.1%} | Cancelled {pool.metrics.cancelled.mean():.1%} | "
|
||||
f"Error {pool.metrics.has_error.mean():.1%} | Dispatch Failure {env_failure_rate:.1%} | "
|
||||
f"Cancelled {pool.metrics.cancelled.mean():.1%} | "
|
||||
f"Truncation {env_eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
get_logger().success("\n\t\t ".join(lines))
|
||||
|
||||
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
|
||||
"""Persist + log one completed eval epoch through the monitors."""
|
||||
if not batch.episodes:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no episodes returned, skipping log")
|
||||
if not batch.episodes and not batch.failures:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
|
||||
return
|
||||
|
||||
# The non-errored subset is logged on epoch completion (multiple eval envs share the
|
||||
# step's trace file — each epoch appends its cohort once, and every record carries
|
||||
# ``env_name``); the full returned cohort already streamed into ``all`` on arrival.
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
if batch.episodes.effective:
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
policy_spans = [eval_work(episode).policy for episode in batch.episodes]
|
||||
if any(span is None for span in policy_spans):
|
||||
raise ValueError(f"Eval {batch.env_name} step {batch.step} is missing policy provenance")
|
||||
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
|
||||
@@ -909,6 +932,12 @@ class Orchestrator:
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", episodes), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
|
||||
total_attempts = len(episodes) + len(batch.failures)
|
||||
metrics |= dispatch_failure_metrics(
|
||||
batch.failures,
|
||||
prefix=f"eval/{batch.env_name}/all",
|
||||
total_attempts=total_attempts,
|
||||
)
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(policy_version)
|
||||
metrics["step"] = float(batch.step)
|
||||
await monitors.log(metrics, step=batch.step)
|
||||
@@ -919,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%}"
|
||||
@@ -956,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()
|
||||
@@ -969,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
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""Training-side episode, group, and batch assembly.
|
||||
|
||||
``add()`` takes one completed episode and ``cancel()`` a dropped group's
|
||||
``GroupCancellation``; both return ``TrainBatch | None``. Before every readiness
|
||||
check the sink sweeps ``pending_batch`` for traces past ``max_off_policy_steps`` —
|
||||
this sweep, not the dispatcher's in-flight cancel, is what guarantees nothing
|
||||
stale ships."""
|
||||
``add()`` takes one completed episode, ``fail()`` a request that produced no
|
||||
episode, and ``cancel()`` a dropped group's ``GroupCancellation``. Before every
|
||||
readiness check the sink sweeps ``pending_batch`` for traces past
|
||||
``max_off_policy_steps`` — this sweep, not the dispatcher's in-flight cancel,
|
||||
is what guarantees nothing stale ships."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -20,7 +20,7 @@ from prime_rl.orchestrator.algo.routing import stamp_loss_routing
|
||||
from prime_rl.orchestrator.envs import TrainEnvs
|
||||
from prime_rl.orchestrator.metrics import TrainEpisodes
|
||||
from prime_rl.orchestrator.trajectories import trace_to_samples
|
||||
from prime_rl.orchestrator.types import GroupCancellation, Progress, TrainBatch
|
||||
from prime_rl.orchestrator.types import DispatchFailure, GroupCancellation, Progress, TrainBatch
|
||||
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, min_fresh_version, train_work
|
||||
from prime_rl.transports.batch import TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
@@ -87,7 +87,9 @@ class TrainSink:
|
||||
self.on_result = on_result
|
||||
|
||||
self.pending_episodes = TrainEpisodes()
|
||||
self.pending_failures: list[DispatchFailure] = []
|
||||
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
|
||||
self.pending_group_failures: dict[str, list[DispatchFailure]] = defaultdict(list)
|
||||
# A dropped group's terminal marker; its ``count`` fills in for the
|
||||
# episodes the group will never deliver.
|
||||
self.pending_group_cancellations: dict[str, GroupCancellation] = {}
|
||||
@@ -113,7 +115,9 @@ class TrainSink:
|
||||
return self.pending_tokens, self.token_batch_size, "tokens"
|
||||
|
||||
def buffered_count(self) -> int:
|
||||
return sum(len(group) for group in self.pending_groups.values())
|
||||
episodes = sum(len(group) for group in self.pending_groups.values())
|
||||
failures = sum(len(group) for group in self.pending_group_failures.values())
|
||||
return episodes + failures
|
||||
|
||||
def pending_batch_by_env(self) -> dict[str, int]:
|
||||
counts: dict[str, int] = defaultdict(int)
|
||||
@@ -145,10 +149,22 @@ class TrainSink:
|
||||
await self.process_group(cancellation.group_id)
|
||||
return self._maybe_batch()
|
||||
|
||||
async def fail(self, failure: DispatchFailure) -> TrainBatch | None:
|
||||
"""Count a request failure toward its group without presenting it as
|
||||
an episode to the algorithm or curriculum."""
|
||||
if failure.kind != "train":
|
||||
raise ValueError(f"TrainSink cannot process a {failure.kind} dispatch failure")
|
||||
self.pending_group_failures[failure.group_id].append(failure)
|
||||
if not self._group_complete(failure.group_id, failure.env_name):
|
||||
return None
|
||||
await self.process_group(failure.group_id)
|
||||
return self._maybe_batch()
|
||||
|
||||
def _group_complete(self, group_id: str, env_name: str) -> bool:
|
||||
cancellation = self.pending_group_cancellations.get(group_id)
|
||||
cancelled = cancellation.count if cancellation is not None else 0
|
||||
return len(self.pending_groups[group_id]) + cancelled >= self.group_size_for(env_name)
|
||||
failed = len(self.pending_group_failures[group_id])
|
||||
return len(self.pending_groups[group_id]) + failed + cancelled >= self.group_size_for(env_name)
|
||||
|
||||
def _maybe_batch(self) -> TrainBatch | None:
|
||||
"""Sweep stale queued traces, then cut a batch if the survivors still
|
||||
@@ -209,18 +225,24 @@ class TrainSink:
|
||||
|
||||
async def process_group(self, group_id: str) -> None:
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
failures = self.pending_group_failures.pop(group_id, [])
|
||||
cancellation = self.pending_group_cancellations.pop(group_id, None)
|
||||
if not group and cancellation is None:
|
||||
if not group and not failures and cancellation is None:
|
||||
return
|
||||
|
||||
env_name = episode_env_name(group[0]) if group else cancellation.env_name
|
||||
env_name = (
|
||||
episode_env_name(group[0]) if group else (failures[0].env_name if failures else cancellation.env_name)
|
||||
)
|
||||
env = self.train_envs.get(env_name)
|
||||
traces = [trace for episode in group for trace in episode.traces]
|
||||
task_idx = next((trace.task.data.idx for trace in traces), None)
|
||||
num_errored = sum(trace.has_error for trace in traces) + sum(
|
||||
not episode.ok for episode in group if not episode.traces
|
||||
num_errored = (
|
||||
sum(trace.has_error for trace in traces)
|
||||
+ sum(not episode.ok for episode in group if not episode.traces)
|
||||
+ len(failures)
|
||||
)
|
||||
n_owed = len(group) + (cancellation.count if cancellation is not None else 0)
|
||||
n_owed = len(group) + len(failures) + (cancellation.count if cancellation is not None else 0)
|
||||
self.pending_failures.extend(failures)
|
||||
|
||||
# A stale drop voids the whole group: every member shares the dispatch
|
||||
# version, so the arrived episodes are exactly as stale as the
|
||||
@@ -367,6 +389,8 @@ class TrainSink:
|
||||
cohort = TrainEpisodes(cohort_episodes, sampled_trace_ids=shipped_ids)
|
||||
|
||||
episodes = self.pending_episodes
|
||||
failures = self.pending_failures
|
||||
if samples:
|
||||
self.pending_episodes = TrainEpisodes()
|
||||
return TrainBatch(episodes=episodes, cohort=cohort, samples=samples)
|
||||
self.pending_failures = []
|
||||
return TrainBatch(episodes=episodes, cohort=cohort, samples=samples, failures=failures)
|
||||
|
||||
@@ -52,7 +52,22 @@ class GroupCancellation:
|
||||
reason: CancelReason
|
||||
|
||||
|
||||
DispatchResult: TypeAlias = vf.WireEpisode | GroupCancellation
|
||||
@dataclass(frozen=True)
|
||||
class DispatchFailure:
|
||||
"""An environment request that failed before producing an episode."""
|
||||
|
||||
kind: WorkKind
|
||||
env_name: str
|
||||
group_id: str
|
||||
step: int
|
||||
policy_version: int
|
||||
task_type: str
|
||||
task_key: str
|
||||
task_hash: str
|
||||
error: vf.Error
|
||||
|
||||
|
||||
DispatchResult: TypeAlias = vf.WireEpisode | DispatchFailure | GroupCancellation
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -96,21 +111,26 @@ class GroupState:
|
||||
|
||||
@dataclass
|
||||
class TrainBatch:
|
||||
"""Observation and shipped-cohort reports plus the trainer payload."""
|
||||
"""Returned episodes, dispatch failures, shipped cohort, and trainer payload."""
|
||||
|
||||
episodes: TrainEpisodes
|
||||
cohort: TrainEpisodes
|
||||
samples: list[TrainingSample]
|
||||
failures: list[DispatchFailure]
|
||||
|
||||
|
||||
@dataclass
|
||||
class EvalBatch:
|
||||
"""One env's eval epoch. ``episodes`` is the full returned cohort (errored included); its
|
||||
``.effective`` / ``.metrics`` views drive logging."""
|
||||
"""One env's eval epoch.
|
||||
|
||||
``episodes`` is the full returned cohort (errored included), while
|
||||
``failures`` accounts for requests that returned no verifier artifact.
|
||||
"""
|
||||
|
||||
env_name: str
|
||||
step: int
|
||||
episodes: EvalEpisodes
|
||||
failures: list[DispatchFailure]
|
||||
|
||||
|
||||
class VersionObserver(Protocol):
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately on any failed command so a crash anywhere releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
@@ -58,6 +58,7 @@ export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parall
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
@@ -67,6 +68,16 @@ ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
|
||||
# Clean exits do not trigger srun --kill-on-bad-exit. Each terminal component
|
||||
# publishes its successful exit through the shared launcher directory. Every node
|
||||
# uses the same completion condition before it tears down support processes.
|
||||
export TRAINER_DONE=$LAUNCHER_DIR/.trainer.done
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
export ORCHESTRATOR_DONE=$LAUNCHER_DIR/.orchestrator.done
|
||||
{% endif -%}
|
||||
mkdir -p "$LAUNCHER_DIR"
|
||||
rm -f "$TRAINER_DONE"{% if num_infer_nodes > 0 %} "$ORCHESTRATOR_DONE"{% endif %}
|
||||
|
||||
export PRL_RUN_ID=${PRL_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")}
|
||||
export PRL_RUN_NAME={{ run_name }}
|
||||
export WANDB_RUN_ID=$PRL_RUN_ID
|
||||
@@ -400,21 +411,28 @@ else
|
||||
|
||||
echo $HOSTNAMES_STR | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
|
||||
WANDB_SHARED_LABEL=trainer uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.json \
|
||||
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log &
|
||||
(
|
||||
WANDB_SHARED_LABEL=trainer uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.json \
|
||||
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ] && [ "$TRAIN_NODE_RANK" -eq 0 ]; then
|
||||
touch "$TRAINER_DONE" || exit $?
|
||||
fi
|
||||
exit "$COMPONENT_CODE"
|
||||
) &
|
||||
{% if num_infer_nodes > 0 %} fi{% endif %}
|
||||
{% if num_infer_nodes > 0 %}
|
||||
# Launch the orchestrator on the node ORCH_ADDR points at (see the ORCH_PROCID
|
||||
@@ -450,19 +468,41 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $LOG_DIR/orchestrator.log &
|
||||
(
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $LOG_DIR/orchestrator.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ]; then
|
||||
touch "$ORCHESTRATOR_DONE" || exit $?
|
||||
fi
|
||||
exit "$COMPONENT_CODE"
|
||||
) &
|
||||
fi
|
||||
{% endif %}
|
||||
|
||||
# Wait for the first background job to exit and propagate its exit code. This
|
||||
# turns background process crashes (router, orchestrator) into task failures
|
||||
# that --kill-on-bad-exit=1 can broadcast to the other nodes so the whole job
|
||||
# tears down instead of leaving zombies holding the allocation.
|
||||
wait -n
|
||||
EXIT_CODE=$?
|
||||
# Every node watches the terminal components for successful completion.
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
# Inference runs stop after both the trainer and orchestrator finish.
|
||||
( until [ -f "$TRAINER_DONE" ] && [ -f "$ORCHESTRATOR_DONE" ]; do sleep 10; done ) &
|
||||
{% else -%}
|
||||
# Trainer-only runs stop when the trainer finishes.
|
||||
( until [ -f "$TRAINER_DONE" ]; do sleep 10; done ) &
|
||||
{% endif -%}
|
||||
COMPLETION_PID=$!
|
||||
|
||||
# A clean component exit is not enough to stop the run. Keep waiting for the
|
||||
# shared completion condition. Propagate any failure through
|
||||
# --kill-on-bad-exit=1 so every node tears down.
|
||||
while true; do
|
||||
wait -n -p FINISHED_PID
|
||||
EXIT_CODE=$?
|
||||
if [ "$EXIT_CODE" -ne 0 ] || [ "${FINISHED_PID:-}" = "$COMPLETION_PID" ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
REMAINING_PIDS=$(jobs -p)
|
||||
{%- if cleanup_grace_period %}
|
||||
# Cross-node teardown is driven by `srun --kill-on-bad-exit=1`, which reaps peer
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately on any failed command so a crash on any node releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
@@ -33,6 +33,7 @@ export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_PATH={{ config_path }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
@@ -65,7 +66,7 @@ echo "MASTER_PORT=${MASTER_PORT}"
|
||||
{% if use_nccl_broadcast %}
|
||||
# The eval job has a separate allocation. Publish the trainer's NCCL host through
|
||||
# the shared run directory under this job ID.
|
||||
printf '%s\n' "$MASTER_ADDR" > "$OUTPUT_DIR/.sft_nccl_host_$SLURM_JOB_ID"
|
||||
printf '%s\n' "$MASTER_ADDR" > "$LAUNCHER_DIR/.sft_nccl_host_$SLURM_JOB_ID"
|
||||
{% endif %}
|
||||
|
||||
# Install environment
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/eval_job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/eval_job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/eval_job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/eval_job_%j.log
|
||||
|
||||
# Online-eval job for a decoupled SFT run: the inference pool (one vLLM engine per
|
||||
# DP rank behind a single router) plus the evals process and its env servers. The trainer
|
||||
@@ -42,6 +42,7 @@ export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export CONFIG_PATH=$CONFIG_DIR/inference.json
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Move a previous job's inference logs aside instead of deleting them: rm of log
|
||||
# files another job's processes still hold open can wedge in the NFS client and
|
||||
# hang the whole job before srun even runs.
|
||||
@@ -50,10 +51,9 @@ mkdir -p $OUTPUT_DIR/logs/inference
|
||||
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
|
||||
# A clean evals exit cannot trip srun --kill-on-bad-exit (which only propagates
|
||||
# failures), so node 0 publishes completion through this job-scoped sentinel and the
|
||||
# other nodes watch for it to release their engines. Stale sentinels from other job
|
||||
# IDs are inert, so only this job's own path needs clearing.
|
||||
export EVAL_DONE=$OUTPUT_DIR/.eval_done_$SLURM_JOB_ID
|
||||
# failures), so node 0 publishes completion through this sentinel and the other nodes
|
||||
# watch for it to release their engines.
|
||||
export EVAL_DONE=$LAUNCHER_DIR/.eval.done
|
||||
rm -f "$EVAL_DONE"
|
||||
{% if prl_run_id %}
|
||||
# Trainer (separate SLURM job) and evals log to a single shared W&B run whose id
|
||||
@@ -72,7 +72,7 @@ export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
export HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
{% if use_nccl_broadcast %}
|
||||
: "${TRAIN_JOB_ID:?TRAIN_JOB_ID is required for NCCL weight broadcast}"
|
||||
TRAIN_HOST_FILE="$OUTPUT_DIR/.sft_nccl_host_$TRAIN_JOB_ID"
|
||||
TRAIN_HOST_FILE="$LAUNCHER_DIR/.sft_nccl_host_$TRAIN_JOB_ID"
|
||||
until [ -s "$TRAIN_HOST_FILE" ]; do sleep 1; done
|
||||
export TRAIN_HOST=$(<"$TRAIN_HOST_FILE")
|
||||
rm -f "$TRAIN_HOST_FILE"
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
{%- if exclude %}
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately if any setup command or the launcher fails so the SLURM job
|
||||
# releases its allocation instead of holding nodes after a crash.
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
{%- if exclude %}
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
|
||||
|
||||
# Exit immediately if any setup command or the launcher fails so the SLURM job
|
||||
# releases its allocation instead of holding nodes after a crash.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -84,7 +84,11 @@ def train(config: TrainerConfig):
|
||||
# Setup the monitors
|
||||
asyncio.run(
|
||||
monitors.setup(
|
||||
wandb=config.monitors.wandb, file=config.monitors.file, output_dir=config.output_dir, run_config=config
|
||||
producer="trainer",
|
||||
wandb=config.monitors.wandb,
|
||||
file=config.monitors.file,
|
||||
output_dir=config.output_dir,
|
||||
run_config=config,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -586,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 (
|
||||
|
||||
@@ -76,6 +76,7 @@ def train(config: SFTConfig):
|
||||
# Setup the monitors
|
||||
asyncio.run(
|
||||
monitors.setup(
|
||||
producer="trainer",
|
||||
wandb=config.monitors.wandb,
|
||||
file=config.monitors.file,
|
||||
output_dir=config.run_dir,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import asyncio
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
@@ -60,7 +61,7 @@ def format_log_message(
|
||||
|
||||
log_lines: list[str] = []
|
||||
if job_log:
|
||||
log_lines.append(f"{i1}{'Job:':<{col}}tail -F {log_dir.parent.parent}/job_*.log")
|
||||
log_lines.append(f"{i1}{'Job:':<{col}}tail -F {get_launcher_log_dir(log_dir.parent.parent)}/*job_*.log")
|
||||
if trainer:
|
||||
log_lines.append(f"{i1}{'Trainer:':<{col}}tail -F {log_dir}/trainer.log")
|
||||
if num_train_nodes > 1:
|
||||
@@ -90,8 +91,50 @@ def format_log_message(
|
||||
return "Logs:\n" + "\n".join(log_lines)
|
||||
|
||||
|
||||
def home_dir() -> Path:
|
||||
"""Best-effort home directory; fall back to the temp dir so import never fails."""
|
||||
try:
|
||||
return Path.home()
|
||||
except RuntimeError:
|
||||
return Path(tempfile.gettempdir())
|
||||
|
||||
|
||||
CACHE_DIR = home_dir() / ".cache" / "prime-rl"
|
||||
"""User-scoped cache root."""
|
||||
|
||||
|
||||
def get_config_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "configs"
|
||||
"""Resolved per-component config dumps (JSON). The launch TOML copy lives one
|
||||
level up, at `configs/<entrypoint>.toml`."""
|
||||
return output_dir / "configs" / "resolved"
|
||||
|
||||
|
||||
def write_launch_toml(run_dir: Path, name: str) -> None:
|
||||
"""Copy the launch `@` TOML file(s) verbatim to `configs/<name>.toml`."""
|
||||
import sys
|
||||
|
||||
argv = sys.argv[1:]
|
||||
paths = []
|
||||
for i, arg in enumerate(argv):
|
||||
# root config references only: `@ file`; a `--flag @ file` / `--flag @file`
|
||||
# is a nested reference and belongs under its flag, not in the launch copy
|
||||
if arg == "@" and i + 1 < len(argv) and (i == 0 or not argv[i - 1].startswith("--")):
|
||||
paths.append(Path(argv[i + 1]))
|
||||
tomls = [(p, p.read_text()) for p in paths if p.suffix == ".toml" and p.is_file()]
|
||||
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))
|
||||
|
||||
|
||||
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:
|
||||
@@ -139,10 +182,9 @@ def has_checkpoints(output_dir: Path) -> bool:
|
||||
return ckpt_dir.exists() and any(ckpt_dir.iterdir())
|
||||
|
||||
|
||||
# Launcher artifacts that may exist in a run directory before training starts: resolved
|
||||
# configs and the SLURM script/job log (a submitted job re-invokes the entrypoint inside
|
||||
# the run directory). Everything else is treated as artifacts of a previous run.
|
||||
LAUNCHER_ARTIFACTS = ("configs", "rl.sbatch", "sft.sbatch", "job_*.log")
|
||||
# Launcher artifacts may exist before training starts. Everything else is treated as
|
||||
# artifacts of a previous run.
|
||||
LAUNCHER_ARTIFACTS = ("configs", "launcher")
|
||||
|
||||
|
||||
def has_run_artifacts(run_dir: Path) -> bool:
|
||||
@@ -194,17 +236,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(
|
||||
|
||||
@@ -10,7 +10,7 @@ import setproctitle
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
PRIME_RL_PROC_PREFIX = "PRIME-RL"
|
||||
PRIME_RL_PROC_PREFIX = "PRL"
|
||||
|
||||
|
||||
# Applied to every launched component (trainer, orchestrator, inference).
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Browser smoke test for the run dashboard, run against real integration-run artifacts.
|
||||
|
||||
Launched at the end of each integration test so that any change to the on-disk
|
||||
artifacts (metrics.jsonl rows, Episode records, config JSONs, log layout) that
|
||||
breaks the dashboard fails the same CI run that produced them.
|
||||
"""
|
||||
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
DASHBOARD_STARTUP_TIMEOUT_S = 30
|
||||
PAGE_SETTLE_MS = 4000
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return sock.getsockname()[1]
|
||||
|
||||
|
||||
def _install_browser() -> None:
|
||||
subprocess.run(
|
||||
["uv", "run", "playwright", "install", "--with-deps", "--only-shell", "chromium"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
timeout=600,
|
||||
)
|
||||
|
||||
|
||||
def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
|
||||
"""Serve ``output_dir`` and assert the dashboard renders the run end to end."""
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
_install_browser()
|
||||
port = _free_port()
|
||||
server = subprocess.Popen(
|
||||
["uv", "run", "dashboard", output_dir.as_posix(), "--port", str(port)],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.STDOUT,
|
||||
)
|
||||
try:
|
||||
deadline = time.monotonic() + DASHBOARD_STARTUP_TIMEOUT_S
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=1):
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
raise AssertionError("dashboard did not start listening")
|
||||
|
||||
errors: list[str] = []
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch()
|
||||
page = browser.new_page(viewport={"width": 1600, "height": 1000})
|
||||
page.on("console", lambda m: errors.append(f"console: {m.text}") if m.type == "error" else None)
|
||||
page.on("pageerror", lambda e: errors.append(f"page: {e}"))
|
||||
base = f"http://127.0.0.1:{port}"
|
||||
|
||||
# metrics: the run resolves and the overview renders charts with data
|
||||
page.goto(f"{base}/#run={run_name}&tab=metrics")
|
||||
page.wait_for_timeout(PAGE_SETTLE_MS)
|
||||
status = page.locator("#run-overview .badge").first.inner_text()
|
||||
assert status, "overview card did not render a status"
|
||||
fields = page.evaluate(
|
||||
"""() => Object.fromEntries([...document.querySelectorAll('#run-overview .ov-field')]
|
||||
.map(f => [f.querySelector('.lbl').innerText, f.querySelector('.val, .badge').innerText]))"""
|
||||
)
|
||||
run_type = fields.get("TYPE")
|
||||
assert run_type in ("RL", "SFT", "EVAL"), f"overview type field did not render: {fields!r}"
|
||||
if run_type == "EVAL":
|
||||
assert fields.get("EPISODES", "").isdigit(), f"overview episodes field did not render: {fields!r}"
|
||||
cards = page.locator(".stat-card").count()
|
||||
assert cards >= 5, f"expected >=5 stat cards, got {cards}"
|
||||
else:
|
||||
assert "/" in fields.get("STEP", ""), f"overview step field did not render: {fields!r}"
|
||||
charts = page.locator(".chart-card").count()
|
||||
assert charts >= 5, f"expected >=5 metric panels, got {charts}"
|
||||
with_data = page.evaluate("""() => [...document.querySelectorAll('.chart-card .u-wrap')].length""")
|
||||
assert with_data >= 5, f"expected >=5 mounted charts, got {with_data}"
|
||||
|
||||
# config: the default view renders (launch TOML on new runs), and the
|
||||
# resolved concatenated document renders as a tree
|
||||
page.click("#tabs [data-tab=config]")
|
||||
page.wait_for_timeout(1500)
|
||||
assert page.eval_on_selector("#config-view", "e => e.innerText.length") > 100, "config view did not render"
|
||||
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"
|
||||
|
||||
# traces: when the run saved rollouts, episodes must render and open
|
||||
rollout_steps = page.evaluate(
|
||||
f"""fetch('{base}/api/runs/{run_name}/rollouts').then(r => r.json()).then(d => d.steps.length)"""
|
||||
)
|
||||
if rollout_steps:
|
||||
page.click("#tabs [data-tab=traces]")
|
||||
page.wait_for_timeout(3000)
|
||||
rows = page.locator("#episode-table tbody tr").count()
|
||||
assert rows > 0, "traces table rendered no episodes"
|
||||
page.click("#episode-table tbody tr >> nth=0")
|
||||
page.wait_for_timeout(3000)
|
||||
entries = page.locator("#tm-messages details.entry").count()
|
||||
assert entries > 0, "episode viewer rendered no messages"
|
||||
reward = page.locator(".tm-reward-big").first.inner_text()
|
||||
assert reward not in ("", "n/a"), f"episode reward did not render: {reward!r}"
|
||||
page.keyboard.press("Escape")
|
||||
|
||||
# logs: the merged pane shows lines
|
||||
page.click("#tabs [data-tab=logs]")
|
||||
page.wait_for_timeout(PAGE_SETTLE_MS)
|
||||
log_lines = page.locator(".log-pane .ll").count()
|
||||
assert log_lines > 10, f"log pane rendered only {log_lines} lines"
|
||||
|
||||
browser.close()
|
||||
|
||||
assert not errors, f"dashboard raised browser errors: {errors[:5]}"
|
||||
finally:
|
||||
server.terminate()
|
||||
try:
|
||||
server.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
server.kill()
|
||||
print(f"Dashboard smoke passed for {run_name} ({output_dir})", file=sys.stderr)
|
||||
|
||||
|
||||
def make_dashboard_test(process_fixture: str, run_name: str):
|
||||
"""The per-file dashboard smoke: `test_dashboard = make_dashboard_test("rl_process", RUN_NAME)`.
|
||||
Depends on the module's (module-scoped) training-process fixture, so it runs
|
||||
against the artifacts that run just produced."""
|
||||
import pytest
|
||||
|
||||
@pytest.mark.usefixtures(process_fixture)
|
||||
def test_dashboard(output_dir: Path) -> None:
|
||||
check_dashboard_smoke(output_dir, run_name)
|
||||
|
||||
return test_dashboard
|
||||
@@ -4,6 +4,7 @@ from typing import Callable
|
||||
import pytest
|
||||
|
||||
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_no_error,
|
||||
@@ -83,3 +84,6 @@ def test_mismatch_kl_in_range(rl_process: ProcessResult, test_no_error, run_dir:
|
||||
with open(run_dir / "logs" / "latest" / "trainer.log", "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_avg_mismatch_kl_in_range(trainer_stdout, last_n_steps=5, max_threshold=0.15)
|
||||
|
||||
|
||||
test_dashboard = make_dashboard_test("rl_process", RUN_NAME)
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Callable
|
||||
import pytest
|
||||
|
||||
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_no_error,
|
||||
@@ -126,3 +127,6 @@ def test_reward_in_range_resume(rl_resume_process: ProcessResult, test_no_error_
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.6)
|
||||
|
||||
|
||||
test_dashboard = make_dashboard_test("rl_process", RUN_NAME)
|
||||
|
||||
@@ -10,6 +10,7 @@ import pytest
|
||||
|
||||
from prime_rl.utils.process import cleanup_process
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.integration.dashboard_smoke import make_dashboard_test
|
||||
from tests.utils import check_final_eval_reward_above, check_no_error, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
@@ -122,3 +123,6 @@ def test_eval_reward_converges(rl_opd_process: ProcessResult, test_no_error, run
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_final_eval_reward_above(orchestrator_stdout, env_name="reverse-text", min_threshold=0.5)
|
||||
|
||||
|
||||
test_dashboard = make_dashboard_test("rl_opd_process", RUN_NAME)
|
||||
|
||||
@@ -10,6 +10,7 @@ import pytest
|
||||
|
||||
from prime_rl.utils.process import cleanup_process
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.integration.dashboard_smoke import make_dashboard_test
|
||||
from tests.utils import check_final_eval_reward_above, check_no_error, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
@@ -121,3 +122,6 @@ def test_eval_reward_converges(rl_sft_process: ProcessResult, test_no_error, run
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_final_eval_reward_above(orchestrator_stdout, env_name="reverse-text", min_threshold=0.5)
|
||||
|
||||
|
||||
test_dashboard = make_dashboard_test("rl_sft_process", RUN_NAME)
|
||||
|
||||
@@ -6,6 +6,7 @@ import torch
|
||||
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
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
|
||||
@@ -170,3 +171,6 @@ def test_full_offload_model_only_resume_preserves_weights(
|
||||
assert torch.equal(before[key].to(torch.bfloat16), after[key].to(torch.bfloat16)), (
|
||||
f"Weight mismatch after model-only resume: {key}"
|
||||
)
|
||||
|
||||
|
||||
test_dashboard = make_dashboard_test("sft_process", RUN_NAME)
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Callable
|
||||
import pytest
|
||||
|
||||
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
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
|
||||
@@ -112,3 +113,6 @@ def test_loss_goes_down_resume(sft_lora_resume_process: ProcessResult, run_dir:
|
||||
with open(trainer_log_path, "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_loss_goes_down(trainer_stdout)
|
||||
|
||||
|
||||
test_dashboard = make_dashboard_test("sft_lora_process", RUN_NAME)
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import pytest
|
||||
|
||||
from prime_rl.utils.pathing import validate_run_dir
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
get_broadcast_dir,
|
||||
get_rollout_dir,
|
||||
get_step_path,
|
||||
validate_run_dir,
|
||||
)
|
||||
|
||||
|
||||
def test_nonexistent_dir_passes(tmp_path):
|
||||
@@ -19,8 +25,12 @@ def test_dir_with_launcher_artifacts_passes(tmp_path):
|
||||
run_dir.mkdir()
|
||||
(run_dir / "configs").mkdir()
|
||||
(run_dir / "configs" / "trainer.toml").touch()
|
||||
(run_dir / "rl.sbatch").touch()
|
||||
(run_dir / "job_1234.log").touch()
|
||||
(run_dir / "launcher").mkdir()
|
||||
(run_dir / "launcher" / "rl.sbatch").touch()
|
||||
(run_dir / "launcher" / ".trainer.done").touch()
|
||||
(run_dir / "launcher" / ".orchestrator.done").touch()
|
||||
(run_dir / "launcher" / "logs").mkdir()
|
||||
(run_dir / "launcher" / "logs" / "job_1234.log").touch()
|
||||
validate_run_dir(run_dir, output_dir=tmp_path, resuming=False, clean=False)
|
||||
|
||||
|
||||
@@ -84,3 +94,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()
|
||||
|
||||
+1
-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
|
||||
|
||||
Reference in New Issue
Block a user