Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9975d8868d | ||
|
|
de626e934e | ||
|
|
e56a8df198 | ||
|
|
68e0c50f6c | ||
|
|
e26b505039 | ||
|
|
70caa7c61f | ||
|
|
5a005de2d6 | ||
|
|
756afd40eb | ||
|
|
c1674ac93c | ||
|
|
b1d4f2fa6c | ||
|
|
d43e0f329b | ||
|
|
8c1f196dd3 | ||
|
|
753a3fec0a | ||
|
|
3ad13dd0bc | ||
|
|
ee06d333e4 | ||
|
|
91d4b92597 | ||
|
|
82acb12ed7 | ||
|
|
124f9694a6 | ||
|
|
4308fe3aba | ||
|
|
da53d4c064 |
@@ -174,7 +174,7 @@ jobs:
|
||||
run: |
|
||||
if [ -f .gitmodules ]; then
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/pydantic-config deps/verifiers deps/renderers deps/research-environments
|
||||
git submodule update --init --recursive -- deps/pydantic-config deps/verifiers deps/renderers deps/prime-envs
|
||||
fi
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
|
||||
@@ -32,7 +32,7 @@ jobs:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
- name: Install dependencies
|
||||
@@ -100,7 +100,7 @@ jobs:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
- name: Install dependencies
|
||||
|
||||
@@ -79,7 +79,7 @@ jobs:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
|
||||
@@ -17,6 +17,7 @@ configs/endpoints.py
|
||||
**/rollouts
|
||||
**/logs
|
||||
**/wandb
|
||||
!src/prime_rl/monitors/wandb/
|
||||
**/evals
|
||||
**/run_*/
|
||||
!configs/**/evals
|
||||
|
||||
+3
-3
@@ -4,9 +4,9 @@
|
||||
[submodule "renderers"]
|
||||
path = deps/renderers
|
||||
url = git@github.com:PrimeIntellect-ai/renderers.git
|
||||
[submodule "research-environments"]
|
||||
path = deps/research-environments
|
||||
url = git@github.com:PrimeIntellect-ai/research-environments.git
|
||||
[submodule "prime-envs"]
|
||||
path = deps/prime-envs
|
||||
url = git@github.com:PrimeIntellect-ai/prime-envs.git
|
||||
[submodule "pydantic-config"]
|
||||
path = deps/pydantic-config
|
||||
url = https://github.com/PrimeIntellect-ai/pydantic-config
|
||||
|
||||
@@ -95,7 +95,7 @@ cd prime-rl
|
||||
2. Initialize submodules
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
```
|
||||
|
||||
3. Install [uv](https://docs.astral.sh/uv/)
|
||||
|
||||
@@ -2,15 +2,18 @@
|
||||
"""
|
||||
Run a single benchmark configuration and output JSON results.
|
||||
|
||||
This script wraps the prime-rl training with --bench.output-json to get
|
||||
metrics directly without parsing console output.
|
||||
This script runs a normal short training (--max-steps) with the file monitor
|
||||
enabled and aggregates throughput / MFU / step time / peak memory from the
|
||||
run's metrics.jsonl.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
@@ -83,6 +86,8 @@ class BenchmarkConfig(BaseConfig):
|
||||
|
||||
timeout: Annotated[int, Field(description="Timeout in seconds")] = 3600
|
||||
|
||||
max_steps: Annotated[int, Field(ge=2, description="Training steps to run. The first step is warmup.")] = 4
|
||||
|
||||
micro_batches: Annotated[int, Field(ge=1, description="Number of micro batches")] = 2
|
||||
|
||||
ep: Annotated[int, Field(ge=1, description="Expert parallelism size (1 = no EP)")] = 1
|
||||
@@ -115,7 +120,7 @@ class BenchmarkConfig(BaseConfig):
|
||||
] = None
|
||||
|
||||
|
||||
def build_command(config: BenchmarkConfig) -> list[str]:
|
||||
def build_command(config: BenchmarkConfig, output_dir: Path) -> list[str]:
|
||||
"""Build the benchmark command from config."""
|
||||
# Determine training script
|
||||
if config.type == "rl":
|
||||
@@ -137,12 +142,18 @@ def build_command(config: BenchmarkConfig) -> list[str]:
|
||||
str(config.seq_len),
|
||||
"--model.attn",
|
||||
config.attention,
|
||||
"--bench.output-json",
|
||||
str(config.output),
|
||||
"--max-steps",
|
||||
str(config.max_steps),
|
||||
"--output-dir",
|
||||
str(output_dir),
|
||||
"--monitors.file.path",
|
||||
"metrics.jsonl",
|
||||
"--model.compile",
|
||||
"--dist-timeout-seconds",
|
||||
str(config.timeout),
|
||||
]
|
||||
if config.type == "sft":
|
||||
cmd.extend(["--run.name", "bench"])
|
||||
|
||||
# Add activation checkpointing if enabled
|
||||
if config.ac == "Recompute":
|
||||
@@ -198,14 +209,61 @@ def dummy_metrics() -> dict:
|
||||
}
|
||||
|
||||
|
||||
def aggregate_metrics(metrics_path: Path) -> dict:
|
||||
"""Aggregate per-step metrics from a run's metrics.jsonl.
|
||||
|
||||
Each metrics.jsonl line is one monitor.log call (``{"step": N, ...}``);
|
||||
merge the lines per step, drop the first (warmup) step, and compute
|
||||
mean/std/min/max per metric like the old --bench JSON export did.
|
||||
"""
|
||||
per_step: dict[int, dict] = {}
|
||||
with open(metrics_path) as f:
|
||||
for line in f:
|
||||
row = json.loads(line)
|
||||
per_step.setdefault(row["step"], {}).update(row)
|
||||
|
||||
steps = sorted(per_step)[1:] # Exclude first warmup step
|
||||
columns = {
|
||||
"perf/mfu": "mfu",
|
||||
"perf/throughput": "throughput",
|
||||
"time/step": "step_time",
|
||||
"perf/peak_memory": "peak_memory",
|
||||
}
|
||||
series = {name: [per_step[step][key] for step in steps] for key, name in columns.items()}
|
||||
|
||||
def stats(values: list[float]) -> dict:
|
||||
return {
|
||||
"mean": statistics.mean(values),
|
||||
"std": statistics.stdev(values) if len(values) > 1 else 0.0,
|
||||
"min": min(values),
|
||||
"max": max(values),
|
||||
}
|
||||
|
||||
total_memory_gib = torch.cuda.mem_get_info()[1] / 1024**3
|
||||
peak_memory_gib = statistics.mean(series["peak_memory"])
|
||||
return {
|
||||
"mfu": stats(series["mfu"]),
|
||||
"throughput": stats(series["throughput"]),
|
||||
"step_time": stats(series["step_time"]),
|
||||
"peak_memory": {
|
||||
"gib": peak_memory_gib,
|
||||
"pct": peak_memory_gib / total_memory_gib * 100,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def run_benchmark(config: BenchmarkConfig) -> None:
|
||||
"""Run a single benchmark and write results to output path."""
|
||||
cmd = build_command(config)
|
||||
output_dir = Path(tempfile.mkdtemp(prefix="benchmark-run-"))
|
||||
cmd = build_command(config, output_dir)
|
||||
print(f"Running: {' '.join(cmd)}")
|
||||
|
||||
if config.dry_run:
|
||||
return
|
||||
|
||||
# The SFT entrypoint writes to output_dir/<run.name>, the RL trainer to output_dir directly
|
||||
metrics_path = output_dir / "bench" / "metrics.jsonl" if config.type == "sft" else output_dir / "metrics.jsonl"
|
||||
|
||||
start_time = time.perf_counter()
|
||||
try:
|
||||
config.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -221,14 +279,13 @@ def run_benchmark(config: BenchmarkConfig) -> None:
|
||||
config.success = False
|
||||
config.error_reason = extract_oom_error_reason(output) or f"Non-zero exit code: {result.returncode}"
|
||||
print(f"Process exited with code {result.returncode}: {output}")
|
||||
if not config.output.exists():
|
||||
if not metrics_path.exists():
|
||||
config.success = False
|
||||
config.error_reason = config.error_reason or extract_oom_error_reason(output) or "No JSON output written"
|
||||
config.error_reason = config.error_reason or extract_oom_error_reason(output) or "No metrics.jsonl written"
|
||||
print(f"Process exited with code {result.returncode}: {output}")
|
||||
print("Benchmark completed but no JSON output was written")
|
||||
print("Benchmark completed but no metrics.jsonl was written")
|
||||
else:
|
||||
with open(config.output) as f:
|
||||
metrics = json.load(f)
|
||||
metrics = aggregate_metrics(metrics_path)
|
||||
lines = output.splitlines()
|
||||
print("\n".join(lines))
|
||||
except subprocess.TimeoutExpired:
|
||||
|
||||
@@ -11,7 +11,7 @@ num_infer_gpus = 1
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ num_infer_gpus = 1
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "hendrycks-sanity"
|
||||
name = "hendrycks-sanity"
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ num_infer_gpus = 1
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text"
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ num_infer_gpus = 1
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "wiki-search"
|
||||
name = "wiki-search"
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ seq_len = 8192
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "wordle"
|
||||
name = "wordle"
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@ max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
resume_step = 15
|
||||
|
||||
[resume]
|
||||
step = 15
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
@@ -16,7 +16,7 @@ type = "filesystem"
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "reverse-text-ci"
|
||||
name = "ci-rl-opd"
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ type = "filesystem"
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "reverse-text-ci"
|
||||
name = "ci-rl-sft"
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
max_steps = 10
|
||||
|
||||
[ckpt]
|
||||
resume_step = 5
|
||||
|
||||
[resume]
|
||||
step = 5
|
||||
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
max_steps = 10
|
||||
|
||||
[ckpt]
|
||||
resume_step = 5
|
||||
|
||||
[resume]
|
||||
step = 5
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
@@ -8,7 +8,9 @@ seq_len = 2048
|
||||
type = "filesystem"
|
||||
|
||||
[ckpt]
|
||||
resume_step = 15
|
||||
|
||||
[resume]
|
||||
step = 15
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
@@ -5,7 +5,7 @@ seq_len = 2048
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ max_steps = 5000
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "hendrycks-sanity"
|
||||
name = "hendrycks-sanity"
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ seq_len = 2048
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text"
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ seq_len = 4096
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "wiki-search"
|
||||
name = "wiki-search"
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ seq_len = 8192
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "wordle"
|
||||
name = "wordle"
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
|
||||
## Run the debug configs
|
||||
|
||||
Every config writes to the default `outputs/` directory, so running two back-to-back — or re-running one — fails with `FileExistsError`. Pass a distinct `--output-dir outputs/<algo>` per config (recommended for a sweep) or `--clean-output-dir` to wipe and restart.
|
||||
Every config writes to the default `outputs/` directory, so running two back-to-back — or re-running one — fails with `FileExistsError`. Pass a distinct `--output-dir outputs/<algo>` per config (recommended for a sweep) or `--clean` to wipe and restart.
|
||||
|
||||
```bash
|
||||
# GRPO (no frozen model)
|
||||
|
||||
@@ -8,7 +8,7 @@ seq_len = 4096
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-echo"
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ seq_len = 2048
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-rl"
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ seq_len = 2048
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-max-rl"
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ seq_len = 2048
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-mixed-grpo-opd"
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ seq_len = 2048
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-opd"
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ seq_len = 2048
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-opd-lora"
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ seq_len = 4096
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-rae"
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ seq_len = 2048
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-self-distill"
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ seq_len = 2048
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-sft"
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ seq_len = 2048
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-sft-lora"
|
||||
|
||||
|
||||
+1
Submodule deps/prime-envs added at b30aad3637
Vendored
+1
-1
Submodule deps/renderers updated: 2a7e77eb14...2846a3dcd2
Vendored
-1
Submodule deps/research-environments deleted from c0a0d1d7ac
Vendored
+1
-1
Submodule deps/verifiers updated: d53ab56f0c...91a267616d
+2
-2
@@ -234,7 +234,7 @@ The knobs (under `[trainer.loss]` with `type = "default"`):
|
||||
|
||||
| Knob | Default | What it does |
|
||||
|---|---|---|
|
||||
| `dppo_mask_low` / `dppo_mask_high` | 0.1 / 0.1 | Lower / upper thresholds for DPPO-style token-level masking. |
|
||||
| `dppo_mask_low` / `dppo_mask_high` | 0.2 / 0.2 | Lower / upper thresholds for DPPO-style token-level masking. |
|
||||
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
|
||||
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
|
||||
|
||||
@@ -477,7 +477,7 @@ type = "repetition"
|
||||
threshold = 0.4
|
||||
```
|
||||
|
||||
Filtered rollouts still appear in W&B distributions, just not in the trainer batch — useful for spotting whether filtering is doing its job.
|
||||
Filtered rollouts still appear in the W&B metrics, just not in the trainer batch — useful for spotting whether filtering is doing its job.
|
||||
|
||||
## Multi-Turn Trajectories
|
||||
|
||||
|
||||
+10
-9
@@ -61,7 +61,7 @@ CLI flags mirror the TOML tree using dots:
|
||||
|
||||
```bash
|
||||
uv run rl --help # full schema
|
||||
uv run rl @ rl.toml --dry-run --output-dir /tmp/check # write resolved configs
|
||||
uv run rl @ rl.toml --dry-run --output-dir /tmp --run.name check # write resolved configs (JSON) to /tmp/check/configs
|
||||
```
|
||||
|
||||
## Syntax
|
||||
@@ -71,12 +71,12 @@ uv run rl @ rl.toml --dry-run --output-dir /tmp/check # write resolved configs
|
||||
CLI uses paired flags: bare `--flag` sets `True`, `--no-flag` sets `False`. TOML must be explicit:
|
||||
|
||||
```bash
|
||||
uv run rl @ rl.toml --clean-output-dir # True
|
||||
uv run rl @ rl.toml --no-clean-output-dir # False
|
||||
uv run rl @ rl.toml --clean # True
|
||||
uv run rl @ rl.toml --no-clean # False
|
||||
```
|
||||
|
||||
```toml
|
||||
clean_output_dir = true
|
||||
clean = true
|
||||
```
|
||||
|
||||
### Lists
|
||||
@@ -218,7 +218,7 @@ PYTORCH_CUDA_ALLOC_CONF = "expandable_segments:False"
|
||||
VLLM_USE_DEEP_GEMM = "1"
|
||||
|
||||
[orchestrator.env_vars]
|
||||
PI_USAGE_BASE_URL = "https://..."
|
||||
PRIME_LOG_LEVEL = "debug"
|
||||
```
|
||||
|
||||
The `rl` launcher applies these the same way in both single-node and multi-node (SLURM) runs. Precedence, low to high:
|
||||
@@ -257,17 +257,18 @@ Start from a shipped base config, override two fields on the CLI, and dry-run:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/basic/reverse-text/rl.toml \
|
||||
--wandb.name my-experiment \
|
||||
--monitors.wandb.name my-experiment \
|
||||
--trainer.optim.lr 5e-6 \
|
||||
--output-dir /tmp/reverse-dry \
|
||||
--run.name check \
|
||||
--dry-run
|
||||
```
|
||||
|
||||
Then inspect the resolved config:
|
||||
|
||||
```bash
|
||||
ls /tmp/reverse-dry/configs/
|
||||
# rl.toml trainer.toml orchestrator.toml inference.toml
|
||||
ls /tmp/reverse-dry/check/configs/
|
||||
# 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/configs/trainer.toml`, 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 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.
|
||||
|
||||
+2
-2
@@ -20,7 +20,7 @@ The three processes communicate through configurable transports — by default t
|
||||
curl -sSL https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`research-environments`](https://github.com/PrimeIntellect-ai/research-environments) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
|
||||
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`prime-envs`](https://github.com/PrimeIntellect-ai/prime-envs) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
|
||||
|
||||
You need at least one NVIDIA GPU (RTX 3090/4090/5090, A100, H100, H200, or B200). Single-GPU runs are supported for debugging; production RL is typically 1× inference node + 1+ trainer nodes.
|
||||
|
||||
@@ -32,7 +32,7 @@ Train an SFT-warmed `Qwen3-0.6B` on the `reverse-text` task — the env is bundl
|
||||
uv run rl @ examples/basic/reverse-text/rl.toml
|
||||
```
|
||||
|
||||
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into `outputs/logs/{trainer,orchestrator,inference}.log`. Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes and final HF-compatible weights land at `outputs/weights/step_20`.
|
||||
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into the run directory at `outputs/<run_name>/logs/{trainer,orchestrator,inference}.log` (`run.name` auto-generates as `<envs>--<model>--<short-id>`; pass `--run.name <name>` for a predictable path). Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes and final HF-compatible weights land at `outputs/<run_name>/weights/step_20`.
|
||||
|
||||
## Documentation
|
||||
|
||||
|
||||
+7
-15
@@ -48,14 +48,14 @@ For quick A/B ablations on the same node, run two RL instances side-by-side in s
|
||||
```bash
|
||||
# session 1, GPUs 0–1, default port 8000
|
||||
bash scripts/tmux.sh -s exp1 -o outputs/exp1
|
||||
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --output-dir outputs/exp1
|
||||
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
|
||||
CUDA_VISIBLE_DEVICES=2,3 uv run rl @ rl.toml \
|
||||
--inference.server.port 8001 \
|
||||
--orchestrator.model.client.base-url http://localhost:8001/v1 \
|
||||
--output-dir outputs/exp2
|
||||
--run.name exp2
|
||||
```
|
||||
|
||||
#### SFT and Torchrun
|
||||
@@ -69,7 +69,7 @@ uv run torchrun \
|
||||
src/prime_rl/trainer/sft/train.py @ sft.toml
|
||||
```
|
||||
|
||||
`--local-ranks-filter 0` keeps console output to rank 0 only; per-rank stdout/stderr is still captured in `<output_dir>/logs/trainer/torchrun/`.
|
||||
`--local-ranks-filter 0` keeps console output to rank 0 only; per-rank stdout/stderr is still captured in `<run_dir>/logs/latest/trainer/torchrun/`.
|
||||
|
||||
### Multi-Node
|
||||
|
||||
@@ -245,22 +245,14 @@ The default templates live under [`src/prime_rl/templates/`](https://github.com/
|
||||
|
||||
## Benchmarking
|
||||
|
||||
Every entrypoint supports a `--bench` flag that runs a few warm-up + measurement steps with fake data and prints a rich-formatted throughput / MFU table:
|
||||
To benchmark a parallelism config before committing a multi-day run, run a short training with fake data and a step cap, and read throughput / MFU / step time / peak memory from the logs:
|
||||
|
||||
```bash
|
||||
# SFT trainer alone
|
||||
uv run sft @ sft.toml --bench
|
||||
uv run sft ... --data.type fake --data.length variable --bench # variable-length fake data
|
||||
uv run sft @ sft.toml --data.type fake --max-steps 4
|
||||
|
||||
# RL trainer alone (no inference involved)
|
||||
uv run trainer @ train.toml --data.fake --bench
|
||||
|
||||
# Inference alone — start the server normally, then bench the orchestrator
|
||||
uv run inference @ infer.toml
|
||||
uv run orchestrator @ orch.toml --bench
|
||||
|
||||
# Full RL stack (trainer with fake data, inference with real data from orchestrator)
|
||||
uv run rl @ rl.toml --bench
|
||||
uv run trainer @ train.toml --data.fake --max-steps 4
|
||||
```
|
||||
|
||||
Persist results with `--bench.output-json`. Use this to compare parallelism configs before committing a multi-day run.
|
||||
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, enable the file monitor (`--file-monitor.filename metrics.jsonl`) and aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
|
||||
|
||||
+44
-42
@@ -70,17 +70,18 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
|---|---|
|
||||
| `log.level` | Process log level for trainer + orchestrator (`info` default; falls back to `$PRIME_LOG_LEVEL`). Set per-process via `trainer.log.level` / `orchestrator.log.level`, or globally on the `rl` entrypoint to propagate to both. |
|
||||
| `orchestrator.log.vf_level` | Env-worker / [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) log level (`info` default; `debug` is noisy but useful for env debugging). |
|
||||
| `--wandb` (+ `--wandb.project`, `--wandb.name`) | Enable Weights & Biases logging. See [Weights & Biases](#weights--biases). |
|
||||
| `--orchestrator.prime-monitor` | Stream metrics to the Prime Intellect platform (Prime Lab). See [Platform monitoring](#platform-monitoring). |
|
||||
| `--monitors.wandb` (+ `--monitors.wandb.project`, `--monitors.wandb.name`) | Enable Weights & Biases logging. See [Weights & Biases](#weights--biases). |
|
||||
| `--monitors.prime` | Stream metrics and episodes to the Prime Intellect platform (Prime Lab). See [Platform monitoring](#platform-monitoring). |
|
||||
|
||||
**Run management:**
|
||||
|
||||
| Knob | What it does |
|
||||
|---|---|
|
||||
| `--clean-output-dir` | Wipe `<output_dir>` before starting. Useful when re-running an experiment with the same name during iteration. |
|
||||
| `--output-dir outputs/<name>` | Per-run output directory. Always set this when running more than one experiment in parallel. |
|
||||
| `--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). |
|
||||
| `--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 `<output_dir>/configs/`, and exit without launching. The fastest way to debug a misbehaving config. |
|
||||
| `--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. |
|
||||
|
||||
### Algorithms
|
||||
|
||||
@@ -170,7 +171,7 @@ See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectorie
|
||||
The minimal SFT run trains `Qwen3-0.6B` on the `reverse-text` SFT dataset:
|
||||
|
||||
```bash
|
||||
uv run sft @ examples/basic/reverse-text/sft.toml --wandb
|
||||
uv run sft @ examples/basic/reverse-text/sft.toml --monitors.wandb
|
||||
```
|
||||
|
||||
Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manages this for you — see [Scaling § SFT and Torchrun](scaling.md#sft-and-torchrun) for non-default layouts; multi-node SFT goes through [SLURM](scaling.md#slurm)).
|
||||
@@ -199,7 +200,7 @@ Pulled from the console log and mirrored to W&B.
|
||||
**Stability and optimization:**
|
||||
|
||||
- `optim/grad_norm` — spikes precede divergence.
|
||||
- `optim/lr`, `optim/zero_grad_ratio` — LR schedule and the fraction of params that received zero gradients (high → dead path or wrong loss masking).
|
||||
- `optim/lr` — LR schedule.
|
||||
- For MoE: `max_vio/mean` (load-balancing violation), `routing_confidence/mean` — both are logged when non-zero.
|
||||
|
||||
**Performance:**
|
||||
@@ -217,10 +218,10 @@ Checkpointing is split across processes because the orchestrator and trainer can
|
||||
|
||||
| Process | What's saved | Where |
|
||||
|---|---|---|
|
||||
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<output_dir>/checkpoints/step_N/trainer/` |
|
||||
| Orchestrator | Progress, per-env data state | `<output_dir>/checkpoints/step_N/orchestrator/` |
|
||||
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_N/trainer/` |
|
||||
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_N/orchestrator/` |
|
||||
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
|
||||
| Trainer (HF weights) | HF-compatible weight snapshot for serving | `<output_dir>/weights/step_N/` |
|
||||
| Trainer (HF weights) | HF-compatible weight snapshot for serving | `<run_dir>/weights/step_N/` |
|
||||
|
||||
### Enabling Checkpoints
|
||||
|
||||
@@ -235,22 +236,29 @@ uv run rl @ rl.toml --ckpt.interval 25 --ckpt.keep-interval 100 # …plus perma
|
||||
|
||||
### Resuming a Run
|
||||
|
||||
Re-run the same launch command and pass `--ckpt.resume-step <N>` (or `-1` for "latest"). Make sure `--max-steps` is at least the target final step, not the remaining delta:
|
||||
Re-run the same launch command and pass `--resume` (latest checkpoint) or `--resume.step <N>`. Resuming reuses the run directory, so the run needs a name you can point back at — launch with `--run.name` (or pass the first run's auto-generated name). Make sure `--max-steps` is at least the target final step, not the remaining delta:
|
||||
|
||||
```bash
|
||||
# First run: steps 1–10
|
||||
uv run rl @ rl.toml --max-steps 10 --ckpt
|
||||
uv run rl @ rl.toml --max-steps 10 --ckpt --run.name my-run
|
||||
|
||||
# Resume: continue to step 20
|
||||
uv run rl @ rl.toml --max-steps 20 --ckpt.resume-step 10
|
||||
# Resume from the latest checkpoint: continue to step 20
|
||||
uv run rl @ rl.toml --max-steps 20 --ckpt --resume --run.name my-run
|
||||
|
||||
# ...or from a specific step
|
||||
uv run rl @ rl.toml --max-steps 20 --ckpt --resume.step 10 --run.name my-run
|
||||
|
||||
# ...or fork another run's checkpoint into a fresh run
|
||||
uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
|
||||
--resume.dir outputs/my-run/checkpoints/step_10
|
||||
```
|
||||
|
||||
### Serving Checkpoints
|
||||
|
||||
HF-compatible weight snapshots are written under `<output_dir>/weights/step_N/` whenever a full checkpoint runs (or you can write weights-only via `--ckpt.weights-only` for cheaper snapshots). Upload directly:
|
||||
HF-compatible weight snapshots are written under `<run_dir>/weights/step_N/` whenever a full checkpoint runs (or you can write weights-only via `--ckpt.weights-only` for cheaper snapshots). Upload directly:
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/<model>-RL outputs/weights/step_100
|
||||
uv run hf upload <user>/<model>-RL outputs/<run_name>/weights/step_100
|
||||
```
|
||||
|
||||
For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write the raw adapter alongside the merged weights — useful when serving the adapter through a separate `/load_lora_adapter` call.
|
||||
@@ -259,10 +267,10 @@ For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write t
|
||||
|
||||
### Log Files
|
||||
|
||||
The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
|
||||
The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>/` — every launch (fresh or resumed) gets its own numbered attempt directory, and `logs/latest` symlinks to the current one. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
|
||||
|
||||
```
|
||||
<output_dir>/logs/
|
||||
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
|
||||
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
|
||||
├── orchestrator.log # single instance, single file
|
||||
├── inference.log # symlink → inference/node_0.log on multi-node
|
||||
@@ -280,9 +288,9 @@ Env logs are the first place to look for env-side errors (most user code lives t
|
||||
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
|
||||
|
||||
```bash
|
||||
tail -F <output_dir>/logs/{trainer,orchestrator,inference}.log
|
||||
tail -F <output_dir>/logs/trainer/node_*.log # multi-node only
|
||||
tail -F <output_dir>/logs/inference/router.log # multi-node only
|
||||
tail -F <run_dir>/logs/latest/{trainer,orchestrator,inference}.log
|
||||
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
|
||||
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
|
||||
```
|
||||
|
||||
### Console Output
|
||||
@@ -290,50 +298,44 @@ tail -F <output_dir>/logs/inference/router.log # multi-node only
|
||||
`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:
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh
|
||||
bash scripts/tmux.sh -o outputs/my-run
|
||||
# then in the Launcher window:
|
||||
uv run rl @ ... --output-dir outputs/my-run
|
||||
uv run rl @ ... --run.name my-run
|
||||
```
|
||||
|
||||
Pass `-s <session>` and `-o <output_dir>` 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`.
|
||||
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`.
|
||||
|
||||
### Weights & Biases
|
||||
|
||||
W&B is off by default. Enable with `--wandb`:
|
||||
W&B is off by default (the file monitor, which writes `metrics.jsonl` and the per-step trace files to the run directory, is on by default):
|
||||
|
||||
```bash
|
||||
uv run rl @ rl.toml --wandb # default project, random name
|
||||
uv run rl @ rl.toml --wandb.project my-proj --wandb.name run-42
|
||||
uv run rl @ rl.toml --no-wandb # force-disable even if the TOML enables it
|
||||
uv run rl @ rl.toml --monitors.wandb # default project, random name
|
||||
uv run rl @ rl.toml --monitors.wandb.project my-proj --monitors.wandb.name run-42
|
||||
uv run rl @ rl.toml --no-monitors.file # disable the local metric/trace files
|
||||
```
|
||||
|
||||
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `wandb.offline = true`.
|
||||
|
||||
By default, every 10 steps each process also logs a sample of prompts/completions (with rewards and advantages) and reward/advantage/entropy distributions as W&B tables. Tune via `--wandb.log-extras.interval` and `--wandb.log-extras.sample-ratio`, or disable subsets:
|
||||
|
||||
```bash
|
||||
uv run rl @ rl.toml --wandb \
|
||||
--orchestrator.wandb.log-extras.interval 50 \
|
||||
--no-trainer.wandb.log-extras.distributions
|
||||
```
|
||||
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `monitors.wandb.offline = true`.
|
||||
|
||||
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, W&B mode **auto-creates an `overview` saved view** on the first run into a project — curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
|
||||
|
||||
### Platform Monitoring
|
||||
|
||||
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics, samples, and distributions to the platform dashboard. Bare flag uses defaults:
|
||||
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics and episodes to the platform dashboard. Bare flag uses defaults:
|
||||
|
||||
```bash
|
||||
uv run rl @ rl.toml --orchestrator.prime-monitor
|
||||
uv run rl @ rl.toml --monitors.prime
|
||||
```
|
||||
|
||||
Or set it in TOML:
|
||||
|
||||
```toml
|
||||
[orchestrator.prime_monitor]
|
||||
run_name = "my-experiment"
|
||||
[monitors.prime]
|
||||
name = "my-experiment"
|
||||
```
|
||||
|
||||
Every 10th step the orchestrator uploads the step's episodes (full conversations with rewards and advantages) to the run's sample viewer.
|
||||
|
||||
Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted team. Currently internal-only.
|
||||
|
||||
## Rules of Thumb
|
||||
@@ -341,5 +343,5 @@ Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted t
|
||||
- **Start small.** Run `examples/basic/reverse-text/rl.toml` end-to-end on 2 GPUs before scaling. If the smoke run finishes cleanly, your install is good.
|
||||
- **Batch size ≥ 64.** Smaller batches give noisy gradient estimates and the trainer's overhead-per-step dominates throughput. 64 is the practical floor; 128–512 is the range for quick ablations; production RL often runs at 1024+.
|
||||
- **Group size ≥ 8.** Bigger groups (`orchestrator.group_size`) make it more likely that a task produces a mix of high- and low-reward rollouts, which is what gives the trainer a usable signal — if all rollouts in a group succeed or all fail, the within-group advantage collapses to zero and the trainer learns nothing from that task. Bigger groups also tighten advantage normalization. 8 is the floor; 16–32 is common.
|
||||
- **Pin `output_dir` per run.** Sharing a directory across runs will mix rollouts and break resumes. `--output-dir outputs/<unique-name>` is the simplest discipline.
|
||||
- **Runs never share a directory.** Every launch writes to its own run directory `<output_dir>/<run_name>`, auto-named `<envs>--<model>--<short-id>` by default. Name runs you want to find again or resume with `--run.name <name>`; re-using a name blocks unless you resume or pass `--clean`.
|
||||
- **Use `--dry-run` before SLURM.** Validators (e.g. CP needs flash-attention) fail fast in dry-run and slow in queue.
|
||||
|
||||
@@ -21,7 +21,7 @@ num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "search-ablations"
|
||||
name = "glm45air-search"
|
||||
|
||||
@@ -32,7 +32,8 @@ timeout = 3600
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[resume]
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
@@ -86,7 +87,7 @@ num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.0
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
[monitors.prime]
|
||||
|
||||
# --- Train: the search envs with usable training data (rlm `search` skill, prime sandbox) ---
|
||||
|
||||
@@ -103,9 +104,6 @@ forward_env = ["SERPER_API_KEY"]
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-search"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
@@ -122,7 +120,7 @@ choices = ["A", "B"]
|
||||
# [[orchestrator.train.source.env.taskset.task.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# path = "deps/prime-envs/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
@@ -136,9 +134,6 @@ forward_env = ["SERPER_API_KEY"]
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-search"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
@@ -155,7 +150,7 @@ choices = ["A", "B"]
|
||||
# [[orchestrator.train.source.env.taskset.task.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# path = "deps/prime-envs/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
@@ -175,9 +170,6 @@ forward_env = ["SERPER_API_KEY"]
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-search"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
@@ -193,7 +185,7 @@ model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
# [[orchestrator.eval.source.env.taskset.task.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# path = "deps/prime-envs/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "swe-ablations"
|
||||
name = "glm45air-scaleswe"
|
||||
|
||||
@@ -43,7 +43,8 @@ timeout = 3600
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[resume]
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
@@ -108,12 +109,9 @@ id = "rlm"
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-swe"]
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
[monitors.prime]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
|
||||
|
||||
@@ -131,9 +129,6 @@ id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-swe"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
|
||||
@@ -22,7 +22,7 @@ num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "terminal-ablations"
|
||||
name = "glm45air-terminal"
|
||||
|
||||
@@ -33,7 +33,8 @@ timeout = 3600
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[resume]
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
@@ -87,7 +88,7 @@ num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
[monitors.prime]
|
||||
|
||||
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
|
||||
|
||||
@@ -99,9 +100,6 @@ id = "rlm"
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-terminal"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
@@ -111,14 +109,14 @@ id = "tmax"
|
||||
# [[orchestrator.train.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# path = "deps/prime-envs/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.train.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# path = "deps/prime-envs/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
@@ -135,9 +133,6 @@ id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-terminal"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
@@ -149,14 +144,14 @@ id = "swebench-verified"
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# path = "deps/prime-envs/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# path = "deps/prime-envs/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
@@ -169,9 +164,6 @@ id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-terminal"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
@@ -183,14 +175,14 @@ id = "terminal-bench-2"
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# path = "deps/prime-envs/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# path = "deps/prime-envs/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
max_steps = 10000000
|
||||
seq_len = 131072
|
||||
output_dir = "/shared/outputs/glm5-llmd" # FILL IN: point at your shared filesystem
|
||||
clean_output_dir = true
|
||||
output_dir = "/shared/outputs" # FILL IN: point at your shared filesystem
|
||||
clean = true
|
||||
|
||||
[run]
|
||||
name = "glm5-llmd"
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "glm5-llmd"
|
||||
name = "base"
|
||||
|
||||
@@ -137,7 +140,6 @@ id = "r2e-gym"
|
||||
id = "rlm"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["glm5-llmd"]
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -3,7 +3,7 @@ seq_len = 131072
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "glm5-pd-disag"
|
||||
|
||||
[weight_broadcast]
|
||||
@@ -85,7 +85,6 @@ id = "swebench-verified"
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["glm5-pd-disag", "swe-bench-verified"]
|
||||
|
||||
[[orchestrator.post_batch_filters]]
|
||||
|
||||
@@ -20,7 +20,7 @@ job_name = "swe-qwen30b"
|
||||
[ckpt]
|
||||
interval = 100
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "intellect-3.1"
|
||||
|
||||
[trainer.model]
|
||||
@@ -58,7 +58,6 @@ id = "r2e-gym"
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["intellect-3.1", "swe"]
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
@@ -74,7 +73,6 @@ skills = ["search"]
|
||||
forward_env = ["SERPER_API_KEY"]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["intellect-3.1", "deepdive"]
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
@@ -136,7 +134,6 @@ id = "swebench-verified"
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["intellect-3.1", "swe-bench-verified"]
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
|
||||
@@ -20,7 +20,7 @@ job_name = "swe-minimax"
|
||||
[ckpt]
|
||||
interval = 100
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "minimax-swe"
|
||||
|
||||
[trainer.model]
|
||||
@@ -58,7 +58,6 @@ id = "r2e-gym"
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["minimax-swe", "swe"]
|
||||
|
||||
[orchestrator.eval]
|
||||
@@ -74,7 +73,6 @@ id = "swebench-verified"
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["minimax-swe", "swe-bench-verified"]
|
||||
|
||||
[inference.vllm]
|
||||
|
||||
@@ -18,7 +18,7 @@ num_train_nodes = 4
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "nemotron-3-super"
|
||||
name = "nemotron-3-super-swe"
|
||||
|
||||
@@ -29,7 +29,8 @@ timeout = 3600
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[resume]
|
||||
|
||||
[model]
|
||||
name = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
|
||||
@@ -92,12 +93,9 @@ id = "rlm"
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["nemotron-3-super-swe"]
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
[monitors.prime]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
@@ -113,9 +111,6 @@ id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["nemotron-3-super-swe"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
|
||||
@@ -20,7 +20,7 @@ job_name = "math-qwen30b"
|
||||
[ckpt]
|
||||
interval = 100
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "qwen30b-math"
|
||||
|
||||
[trainer.model]
|
||||
|
||||
@@ -20,7 +20,7 @@ job_name = "swe-qwen30b"
|
||||
[ckpt]
|
||||
interval = 100
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "qwen30b-swe"
|
||||
|
||||
[trainer.model]
|
||||
@@ -56,7 +56,6 @@ id = "r2e-gym"
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["qwen30b-swe", "swe"]
|
||||
|
||||
[orchestrator.eval]
|
||||
@@ -72,7 +71,6 @@ id = "swebench-verified"
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["qwen30b-swe", "swe-bench-verified"]
|
||||
|
||||
[inference.vllm]
|
||||
|
||||
@@ -9,7 +9,7 @@ type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "general-agent-debug"
|
||||
name = "qwen3-30b-a3b-rlm"
|
||||
|
||||
|
||||
@@ -93,14 +93,15 @@ We train with LoRA (rank 32, alpha 64) for 100 steps.
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
uv run rl @ examples/basic/alphabet-sort/rl.toml \
|
||||
--run.name rl \
|
||||
--wandb.project ... \
|
||||
--wandb.name ...
|
||||
```
|
||||
|
||||
This will write a weight checkpoint in `outputs/weights/step_100`. Upload it to HF to be able to use it as the final model for evaluation.
|
||||
This will write a weight checkpoint in `outputs/rl/weights/step_100`. Upload it to HF to be able to use it as the final model for evaluation.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-4B-Instruct-AlphabetSort-RL outputs/weights/step_100
|
||||
uv run hf upload <user>/Qwen3-4B-Instruct-AlphabetSort-RL outputs/rl/weights/step_100
|
||||
```
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL`](https://huggingface.co/PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL).
|
||||
|
||||
@@ -7,7 +7,7 @@ seq_len = 2048
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
max_steps = 5000
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "hendrycks-sanity"
|
||||
name = "hendrycks-sanity"
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ To train on a single GPU, run
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
uv run sft @ examples/basic/reverse-text/sft.toml \
|
||||
--run.name sft \
|
||||
--wandb.project ... \
|
||||
--wandb.name ...
|
||||
```
|
||||
@@ -59,10 +60,10 @@ uv run torchrun \
|
||||
--wandb.name ...
|
||||
```
|
||||
|
||||
This should write a weight checkpoint in `outputs/weights/step_100`. Upload it to HF to be able to use it as the base model for RL.
|
||||
This should write a weight checkpoint in `outputs/sft/weights/step_100`. Upload it to HF to be able to use it as the base model for RL.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT outputs/weights/step_100
|
||||
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT outputs/sft/weights/step_100
|
||||
```
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT).
|
||||
@@ -77,14 +78,15 @@ For the RL we will only do 20 steps at 8x16 rollouts, for a total batch size of
|
||||
# Run this in the `Trainer` pane
|
||||
uv run rl @ examples/basic/reverse-text/rl.toml \
|
||||
--model.name ... \
|
||||
--run.name rl \
|
||||
--wandb.project ... \
|
||||
--wandb.name ...
|
||||
```
|
||||
|
||||
This will write a weight checkpoint in `outputs/weights/step_20`. As before, let's upload it to HF.
|
||||
This will write a weight checkpoint in `outputs/rl/weights/step_20`. As before, let's upload it to HF.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-RL outputs/weights/step_20
|
||||
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-RL outputs/rl/weights/step_20
|
||||
```
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL).
|
||||
@@ -131,18 +133,18 @@ Exec into the trainer pod and run SFT:
|
||||
|
||||
```bash
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs
|
||||
# This will save checkpoints to /data/outputs/weights/step_100
|
||||
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs --run.name sft
|
||||
# This will save checkpoints to /data/outputs/sft/weights/step_100
|
||||
```
|
||||
|
||||
Upload the checkpoint to HuggingFace or use it directly from shared storage:
|
||||
|
||||
```bash
|
||||
# Option 1: Upload to HuggingFace (from within the pod)
|
||||
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT /data/outputs/weights/step_100
|
||||
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT /data/outputs/sft/weights/step_100
|
||||
|
||||
# Option 2: Use local checkpoint path in RL config
|
||||
# Update the model.name in the RL configs to point to /data/outputs/weights/step_100
|
||||
# Update the model.name in the RL configs to point to /data/outputs/sft/weights/step_100
|
||||
```
|
||||
|
||||
### Step 3: Deploy RL Training
|
||||
@@ -223,8 +225,8 @@ uv run eval reverse-text --harness.id null \
|
||||
|
||||
```bash
|
||||
helm uninstall my-exp
|
||||
# Optionally delete shared data:
|
||||
kubectl delete pvc prime-rl-shared-data
|
||||
# Optionally delete shared data. The PVC is named <release-name>-shared-data:
|
||||
kubectl delete pvc my-exp-shared-data
|
||||
```
|
||||
|
||||
**What the Helm chart provides:**
|
||||
|
||||
@@ -4,7 +4,7 @@ seq_len = 2048
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text"
|
||||
|
||||
|
||||
@@ -93,6 +93,7 @@ Train with the unified config file:
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
uv run rl @ examples/basic/wiki-search/rl.toml \
|
||||
--run.name rl \
|
||||
--wandb.project your-project-name \
|
||||
--wandb.name your-run-name
|
||||
```
|
||||
@@ -102,10 +103,10 @@ The unified config file automatically configures:
|
||||
- **Orchestrator**: Rollout generation with tool calling enabled
|
||||
- **Inference**: vLLM server for Qwen3-4B-Instruct-2507 with tool parsing enabled
|
||||
|
||||
This will write weight checkpoints in `outputs/weights/step_*`. Upload the final checkpoint to HuggingFace:
|
||||
This will write weight checkpoints in `outputs/rl/weights/step_*`. Upload the final checkpoint to HuggingFace:
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-4B-Instruct-WikiSearch-RL outputs/weights/step_500
|
||||
uv run hf upload <user>/Qwen3-4B-Instruct-WikiSearch-RL outputs/rl/weights/step_500
|
||||
```
|
||||
|
||||
## Evaluation
|
||||
|
||||
@@ -8,7 +8,7 @@ num_infer_gpus = 6
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "wiki-search"
|
||||
name = "wiki-search"
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ To train on a single GPU, run
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
uv run sft @ examples/basic/wordle/sft.toml \
|
||||
--run.name sft \
|
||||
--wandb.project ... \
|
||||
--wandb.name ...
|
||||
```
|
||||
@@ -61,10 +62,10 @@ uv run torchrun \
|
||||
--wandb.name ...
|
||||
```
|
||||
|
||||
After training completes, you will find the final weight checkpoint in `outputs/weights/step_20`. Upload it to HF to be able to use it as the base model for RL we will do in the next section.
|
||||
After training completes, you will find the final weight checkpoint in `outputs/sft/weights/step_20`. Upload it to HF to be able to use it as the base model for RL we will do in the next section.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-1.7B-Wordle-SFT outputs/weights/step_20
|
||||
uv run hf upload <user>/Qwen3-1.7B-Wordle-SFT outputs/sft/weights/step_20
|
||||
```
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-SFT).
|
||||
@@ -80,14 +81,15 @@ Finally, we will do multi-turn RL against the `wordle` environment using the mod
|
||||
# Run this in the `Trainer` pane
|
||||
uv run rl @ examples/basic/wordle/rl.toml \
|
||||
--model.name ... \
|
||||
--run.name rl \
|
||||
--wandb.project ... \
|
||||
--wandb.name ...
|
||||
```
|
||||
|
||||
This will write a weight checkpoint in `outputs/weights/step_100`. As before, let's upload it to HF.
|
||||
This will write a weight checkpoint in `outputs/rl/weights/step_100`. As before, let's upload it to HF.
|
||||
|
||||
```bash
|
||||
uv run hf upload <user>/Qwen3-1.7B-Wordle-RL outputs/weights/step_100
|
||||
uv run hf upload <user>/Qwen3-1.7B-Wordle-RL outputs/rl/weights/step_100
|
||||
```
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-RL).
|
||||
|
||||
@@ -5,7 +5,7 @@ seq_len = 8192
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "wordle"
|
||||
name = "wordle"
|
||||
|
||||
|
||||
+4
-6
@@ -2,8 +2,6 @@
|
||||
|
||||
This directory contains a Helm chart for deploying prime-rl training infrastructure on Kubernetes clusters.
|
||||
|
||||
For complete documentation, see the [Kubernetes guide](https://docs.primeintellect.ai/prime-rl/kubernetes).
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
@@ -64,11 +62,11 @@ helm install my-exp ./prime-rl \
|
||||
|
||||
```bash
|
||||
helm uninstall my-exp
|
||||
kubectl delete pvc prime-rl-shared-data # Warning: deletes data!
|
||||
|
||||
# The PVC is named <release-name>-shared-data (see templates/pvc.yaml)
|
||||
kubectl delete pvc my-exp-shared-data # Warning: deletes data!
|
||||
```
|
||||
|
||||
## Learn More
|
||||
|
||||
- [Full Kubernetes documentation](https://docs.primeintellect.ai/prime-rl/kubernetes) - Architecture, configuration, distributed training
|
||||
- [Deployment guide](https://docs.primeintellect.ai/prime-rl/deployment) - Non-Kubernetes deployments
|
||||
- [Troubleshooting](https://docs.primeintellect.ai/prime-rl/troubleshooting) - Common issues
|
||||
- [Scaling guide](https://docs.primeintellect.ai/prime-rl/scaling) - Non-Kubernetes multi-node deployment (SLURM), parallelism, benchmarking
|
||||
|
||||
@@ -6,7 +6,7 @@ group_size = 16
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text"
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ max_steps = 20
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
seq_len = 2048
|
||||
|
||||
[wandb]
|
||||
[monitors.wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text"
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class WandbMonitorConfig(BaseConfig):
|
||||
project: str = "prime-rl"
|
||||
"""W&B project to log to."""
|
||||
|
||||
entity: str | None = None
|
||||
"""W&B entity to log to."""
|
||||
|
||||
name: str | None = None
|
||||
"""W&B run name. Inherits ``run.name`` when unset."""
|
||||
|
||||
group: str | None = None
|
||||
"""W&B group."""
|
||||
|
||||
tags: list[str] | None = None
|
||||
"""W&B tags attached to the run."""
|
||||
|
||||
offline: bool = False
|
||||
"""Run W&B in offline mode."""
|
||||
|
||||
|
||||
class FileMonitorConfig(BaseConfig):
|
||||
path: Path = Path("metrics.jsonl")
|
||||
"""Path of the JSONL file, relative to the component's ``output_dir`` (absolute paths win)."""
|
||||
|
||||
|
||||
class PrimeMonitorConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""Run name shown on the platform. Inherits ``run.name`` when unset."""
|
||||
|
||||
|
||||
class MonitorsConfig(BaseConfig):
|
||||
wandb: WandbMonitorConfig | None = None
|
||||
"""Log metrics to Weights & Biases. Off by default; enable with ``--monitors.wandb``."""
|
||||
|
||||
file: FileMonitorConfig | None = FileMonitorConfig()
|
||||
"""Log metrics and episode traces to the run's output directory. On by default; disable with ``--no-monitors.file``."""
|
||||
|
||||
|
||||
class OrchestratorMonitorsConfig(MonitorsConfig):
|
||||
prime: PrimeMonitorConfig | None = None
|
||||
"""Log metrics and episodes to the Prime Intellect platform. If None, disabled."""
|
||||
@@ -9,16 +9,15 @@ from prime_rl.configs.algorithm import (
|
||||
AlgoConfig,
|
||||
GRPOAlgoConfig,
|
||||
)
|
||||
from prime_rl.configs.monitors import OrchestratorMonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
ClientConfig,
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
PrimeMonitorConfig,
|
||||
ResumeConfig,
|
||||
TransportConfig,
|
||||
WandbWithExtrasConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import TokenizerConfig
|
||||
@@ -286,11 +285,8 @@ class CheckpointConfig(BaseConfig):
|
||||
interval: int | None = Field(None, ge=1)
|
||||
"""Step interval at which to save the orchestrator checkpoint."""
|
||||
|
||||
resume_step: int | None = Field(None, ge=-1)
|
||||
"""Step to resume the orchestrator from. None starts from scratch; ``-1`` resumes from the latest checkpoint available."""
|
||||
|
||||
wait_for_weights_timeout: int | None = Field(None, ge=1)
|
||||
"""Wait up to this many seconds for the startup weight directory to appear (the trainer broadcasts the incoming policy — v0 from scratch, v{resume_step} on resume — before the first step). If None, fall back to a default timeout. Raise this for large models on slow shared filesystems."""
|
||||
"""Wait up to this many seconds for the startup weight directory to appear (the trainer broadcasts the incoming policy — v0 from scratch, the resumed step's version on resume — before the first step). If None, fall back to a default timeout. Raise this for large models on slow shared filesystems."""
|
||||
|
||||
keep_last: int | None = Field(None, ge=1)
|
||||
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
|
||||
@@ -439,12 +435,8 @@ class OrchestratorConfig(BaseConfig):
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for the orchestrator process(es). Merged on top of the launcher defaults."""
|
||||
|
||||
wandb: WandbWithExtrasConfig | None = None
|
||||
|
||||
prime_monitor: PrimeMonitorConfig | None = None
|
||||
|
||||
file_monitor: FileMonitorConfig | None = None
|
||||
"""Local JSONL metric sink. If set, orchestrator metrics are appended to ``<output_dir>/metrics.jsonl``."""
|
||||
monitors: OrchestratorMonitorsConfig = OrchestratorMonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
|
||||
|
||||
collect_inference_metrics: bool = True
|
||||
"""Collect inference-server metrics (requires wandb)."""
|
||||
@@ -453,6 +445,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
"""Role for each policy admin client when collecting P/D inference metrics."""
|
||||
|
||||
ckpt: CheckpointConfig | None = None
|
||||
|
||||
resume: ResumeConfig | None = None
|
||||
"""Resume the orchestrator from a checkpoint. None starts from scratch; an empty block resumes from the latest checkpoint, ``resume.step`` from that step, ``resume.dir`` from an external checkpoint step directory. Without ``ckpt`` the run loads but saves no new checkpoints."""
|
||||
"""Checkpoint configuration."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
|
||||
@@ -500,9 +495,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
max_off_policy_steps: int = Field(8, ge=0)
|
||||
"""Maximum policies allowed to generate a single rollout. Rollouts generated more than ``max_off_policy_steps`` ahead of training are discarded. Higher values yield better throughput at the cost of off-policy noise."""
|
||||
|
||||
bench: bool = False
|
||||
"""Benchmark mode. Sets ``max_steps`` to 5 and disables W&B."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
@@ -521,13 +513,13 @@ class OrchestratorConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_prime_monitor_run_name(self):
|
||||
"""Default ``prime_monitor.run_name`` to the W&B run name when monitoring
|
||||
is enabled and the user hasn't named the prime-monitor run explicitly."""
|
||||
if self.prime_monitor is None or self.prime_monitor.run_name is not None:
|
||||
def auto_setup_prime_monitor_name(self):
|
||||
"""Default ``monitors.prime.name`` to the W&B run name when monitoring
|
||||
is enabled and the user hasn't named the platform run explicitly."""
|
||||
if self.monitors.prime is None or self.monitors.prime.name is not None:
|
||||
return self
|
||||
if self.wandb is not None and self.wandb.name:
|
||||
self.prime_monitor.run_name = self.wandb.name
|
||||
if self.monitors.wandb is not None and self.monitors.wandb.name:
|
||||
self.monitors.prime.name = self.monitors.wandb.name
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -638,20 +630,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench:
|
||||
self.max_steps = 4 # Run for 1 warmup step + 3 evaluation steps
|
||||
|
||||
# Disable evaluation
|
||||
self.eval = None
|
||||
if self.wandb:
|
||||
self.wandb.log_extras = None
|
||||
if self.prime_monitor:
|
||||
self.prime_monitor.log_extras = None
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_config(self):
|
||||
"""Set vLLM sampling defaults on each train env from top-level fields."""
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import uuid
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
@@ -6,6 +7,7 @@ from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig
|
||||
from prime_rl.configs.orchestrator import (
|
||||
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
|
||||
)
|
||||
@@ -20,17 +22,12 @@ from prime_rl.configs.orchestrator import (
|
||||
)
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
ResumeConfig,
|
||||
RunConfig,
|
||||
SlurmConfig,
|
||||
TransportConfig,
|
||||
VLMConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
BenchConfig,
|
||||
FakeDataLoaderConfig,
|
||||
TokenizerConfig,
|
||||
TrainerConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig,
|
||||
)
|
||||
@@ -40,13 +37,16 @@ from prime_rl.configs.trainer import (
|
||||
from prime_rl.configs.trainer import (
|
||||
NIXLWeightBroadcastConfig as TrainerNIXLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
TokenizerConfig,
|
||||
TrainerConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
from prime_rl.utils.validation import (
|
||||
propagate_shared_fields,
|
||||
validate_shared_ckpt_config,
|
||||
validate_shared_max_steps,
|
||||
validate_shared_model_name,
|
||||
validate_shared_output_dir,
|
||||
validate_shared_seq_len,
|
||||
validate_shared_tokenizer,
|
||||
validate_shared_wandb_config,
|
||||
@@ -70,7 +70,7 @@ class SharedWandbConfig(BaseConfig):
|
||||
"""W&B entity."""
|
||||
|
||||
name: str | None = None
|
||||
"""W&B run name."""
|
||||
"""W&B run name. Inherits ``run.name`` when unset."""
|
||||
|
||||
group: str | None = None
|
||||
"""W&B group."""
|
||||
@@ -86,13 +86,26 @@ class SharedWandbConfig(BaseConfig):
|
||||
if self.offline:
|
||||
raise ValueError(
|
||||
"W&B shared mode is always on for the rl entrypoint and requires server "
|
||||
"connectivity; wandb.offline = true is not supported. Use offline mode "
|
||||
"via the sub-config wandb blocks (trainer.wandb.offline, "
|
||||
"orchestrator.wandb.offline) if you really need it per-process."
|
||||
"connectivity; monitors.wandb.offline = true is not supported. Use offline mode "
|
||||
"via the sub-config wandb blocks (trainer.monitors.wandb.offline, "
|
||||
"orchestrator.monitors.wandb.offline) if you really need it per-process."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class SharedMonitorsConfig(BaseConfig):
|
||||
"""The ``rl`` entrypoint's shared monitor configs, propagated to trainer and orchestrator."""
|
||||
|
||||
wandb: SharedWandbConfig | None = None
|
||||
"""Shared W&B config. Propagated to trainer and orchestrator."""
|
||||
|
||||
file: FileMonitorConfig | None = None
|
||||
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/metrics.jsonl`` on both trainer and orchestrator."""
|
||||
|
||||
prime: PrimeMonitorConfig | None = None
|
||||
"""Prime platform monitor. Propagated to the orchestrator only — the trainer has no platform integration."""
|
||||
|
||||
|
||||
class SharedCheckpointConfig(BaseConfig):
|
||||
output_dir: Path | None = None
|
||||
"""Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer ``output_dir``."""
|
||||
@@ -100,9 +113,6 @@ class SharedCheckpointConfig(BaseConfig):
|
||||
interval: int | None = None
|
||||
"""Interval at which to save checkpoints."""
|
||||
|
||||
resume_step: int | None = None
|
||||
"""Step to resume from. If None, does not resume from a checkpoint."""
|
||||
|
||||
keep_last: int | None = Field(None, ge=1)
|
||||
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
|
||||
|
||||
@@ -227,11 +237,29 @@ class RLConfig(BaseConfig):
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for every launched RL component. Component-specific env_vars override these."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Output directory. Should be unique per experiment."""
|
||||
run: RunConfig = Field(default_factory=RunConfig)
|
||||
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
|
||||
|
||||
clean_output_dir: bool = False
|
||||
"""Delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming."""
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory that groups related runs. Each run writes its artifacts to ``output_dir / run.name``."""
|
||||
|
||||
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."""
|
||||
|
||||
@property
|
||||
def run_dir(self) -> Path:
|
||||
assert self.run.dir is not None # resolved at construction
|
||||
return self.output_dir / self.run.dir
|
||||
|
||||
def _resolve_run_name(self) -> None:
|
||||
"""Fill the auto-generated run name and directory (idempotent — called by every
|
||||
validator that reads them, so it does not depend on validator ordering)."""
|
||||
if self.run.name is None:
|
||||
envs = "+".join(dict.fromkeys(source.resolved_name for source in self.orchestrator.train.source))
|
||||
model = self.trainer.model.name.split("/")[-1]
|
||||
self.run.name = f"{envs or 'no-env'}--{model}--{uuid.uuid4().hex[:8]}".lower()
|
||||
if self.run.dir is None:
|
||||
self.run.dir = self.run.name
|
||||
|
||||
### Shared configurations
|
||||
|
||||
@@ -241,11 +269,11 @@ class RLConfig(BaseConfig):
|
||||
ckpt: SharedCheckpointConfig | None = None
|
||||
"""Shared checkpoint config. If None, falls back to the sub-config checkpoint settings."""
|
||||
|
||||
wandb: SharedWandbConfig | None = None
|
||||
"""Shared W&B config. If None, falls back to the sub-config W&B settings."""
|
||||
resume: ResumeConfig | None = None
|
||||
"""Resume the run from a checkpoint (point at it with the previous run's ``run.name``). Without ``[ckpt]`` the run loads the checkpoint but saves no new ones. If None, does not resume."""
|
||||
|
||||
file_monitor: FileMonitorConfig | None = None
|
||||
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/metrics.jsonl`` on both trainer and orchestrator. If None, falls back to the sub-config settings."""
|
||||
monitors: SharedMonitorsConfig = SharedMonitorsConfig()
|
||||
"""Shared monitor configs (``monitors.wandb``, ``monitors.file``). Propagated to trainer and orchestrator; ``[orchestrator.monitors.prime]`` configures the platform monitor."""
|
||||
|
||||
model: SharedModelConfig | None = None
|
||||
"""Shared model config. If None, falls back to the sub-config model settings."""
|
||||
@@ -263,9 +291,6 @@ class RLConfig(BaseConfig):
|
||||
|
||||
rollout_transport: TransportConfig | None = None
|
||||
|
||||
bench: bool = False
|
||||
"""Benchmark mode. Sets trainer and orchestrator to benchmark mode and, when set, suffixes the W&B project with ``-bench``."""
|
||||
|
||||
deployment: DeploymentConfig = SingleNodeDeploymentConfig()
|
||||
|
||||
slurm: SlurmConfig | None = None
|
||||
@@ -316,9 +341,9 @@ class RLConfig(BaseConfig):
|
||||
"Cannot configure inference with num_infer_nodes = 0. "
|
||||
"Either set num_infer_nodes > 0 or remove the inference config."
|
||||
)
|
||||
if num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
|
||||
if num_infer_nodes == 0 and not self.trainer.data.fake:
|
||||
raise ValueError(
|
||||
"Must use fake data (trainer.data.fake or bench = true) when num_infer_nodes = 0, "
|
||||
"Must use fake data (trainer.data.fake) when num_infer_nodes = 0, "
|
||||
"since no orchestrator or inference server will be running."
|
||||
)
|
||||
return self
|
||||
@@ -360,12 +385,58 @@ class RLConfig(BaseConfig):
|
||||
"""
|
||||
return propagate_shared_fields(data)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_dir(self):
|
||||
"""Point trainer and orchestrator at the run directory (``output_dir / run.name``).
|
||||
|
||||
The sub-configs' ``output_dir`` is fully derived here: sub-processes spawned by
|
||||
the launcher receive the resolved run directory and never re-derive it.
|
||||
"""
|
||||
self._resolve_run_name()
|
||||
run_dir = self.run_dir
|
||||
for sub in (self.trainer, self.orchestrator):
|
||||
if "output_dir" in sub.model_fields_set and sub.output_dir != run_dir:
|
||||
raise ValueError(
|
||||
f"{type(sub).__name__}.output_dir ({sub.output_dir}) conflicts with the run directory "
|
||||
f"({run_dir}). Under the rl entrypoint, sub-config output directories are derived from "
|
||||
"output_dir / run.name — set those instead."
|
||||
)
|
||||
sub.output_dir = run_dir
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_resume(self):
|
||||
"""Propagate the top-level resume onto the sub-configs."""
|
||||
if self.resume is None:
|
||||
return self
|
||||
self.trainer.resume = self.resume.model_copy()
|
||||
self.orchestrator.resume = self.resume.model_copy()
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_identity(self):
|
||||
"""Default the W&B and Prime platform run names to ``run.name``.
|
||||
|
||||
Explicit names always win: only unset names inherit. Runs after the
|
||||
orchestrator's own ``auto_setup_prime_monitor_name``, so an explicitly
|
||||
set W&B name still takes precedence for the platform run name. The run
|
||||
identity itself is runtime-only ($PRL_RUN_ID / $PRL_RUN_NAME, set by the
|
||||
``rl`` entrypoint), never sub-config.
|
||||
"""
|
||||
self._resolve_run_name()
|
||||
for wandb in (self.monitors.wandb, self.trainer.monitors.wandb, self.orchestrator.monitors.wandb):
|
||||
if wandb is not None and wandb.name is None:
|
||||
wandb.name = self.run.name
|
||||
for prime in (self.monitors.prime, self.orchestrator.monitors.prime):
|
||||
if prime is not None and prime.name is None:
|
||||
prime.name = self.run.name
|
||||
return self
|
||||
|
||||
### Validate shared configs (after sub-config construction)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_shared_configs(self):
|
||||
"""Validate consistency of shared configs across trainer, orchestrator, and inference."""
|
||||
validate_shared_output_dir(self.trainer, self.orchestrator)
|
||||
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
|
||||
validate_shared_tokenizer(self.trainer, self.orchestrator, self.inference)
|
||||
validate_shared_max_steps(self.trainer, self.orchestrator)
|
||||
@@ -463,24 +534,6 @@ class RLConfig(BaseConfig):
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench:
|
||||
self.trainer.bench = BenchConfig()
|
||||
self.orchestrator.bench = True
|
||||
self.trainer.data.fake = FakeDataLoaderConfig(
|
||||
batch_size=self.orchestrator.batch_size or 32,
|
||||
)
|
||||
|
||||
trainer_bench_enabled = self.trainer.bench is not None
|
||||
if trainer_bench_enabled != self.orchestrator.bench:
|
||||
raise ValueError(
|
||||
f"Trainer benchmark mode ({self.trainer.bench}) and orchestrator benchmark mode "
|
||||
f"({self.orchestrator.bench}) must match. Use the top-level bench = true to set both."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_lora(self):
|
||||
if self.trainer.model.lora is not None:
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import uuid
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
@@ -6,17 +7,17 @@ from pydantic import Field, model_validator
|
||||
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
HeartbeatConfig,
|
||||
ResumeConfig,
|
||||
RunConfig,
|
||||
SlurmConfig,
|
||||
TrainerLogConfig,
|
||||
WandbConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
AdamWConfig,
|
||||
BenchConfig,
|
||||
CheckpointConfig,
|
||||
ConstantSchedulerConfig,
|
||||
GCConfig,
|
||||
@@ -188,18 +189,42 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
ckpt: CheckpointConfig | None = None
|
||||
|
||||
resume: ResumeConfig | None = None
|
||||
"""Resume the run from a checkpoint (point at it with the previous run's ``run.name``). Without ``[ckpt]`` the run loads the checkpoint but saves no new ones. If None, does not resume."""
|
||||
|
||||
log: TrainerLogConfig = TrainerLogConfig()
|
||||
|
||||
wandb: WandbConfig | None = None
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
|
||||
file_monitor: FileMonitorConfig | None = None
|
||||
"""Local JSONL metric sink. If set, metrics are appended to ``<output_dir>/metrics.jsonl``."""
|
||||
run: RunConfig = Field(default_factory=RunConfig)
|
||||
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — checkpoints and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
"""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."""
|
||||
|
||||
clean_output_dir: bool = False
|
||||
"""Delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming."""
|
||||
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."""
|
||||
|
||||
@property
|
||||
def run_dir(self) -> Path:
|
||||
assert self.run.dir is not None # resolved at construction
|
||||
return self.output_dir / self.run.dir
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_identity(self):
|
||||
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
|
||||
default the run directory and W&B run name to it when not set explicitly."""
|
||||
if self.run.name is None:
|
||||
dataset = str(getattr(self.data, "name", "")).split("/")[-1]
|
||||
model = self.model.name.split("/")[-1]
|
||||
parts = [part for part in (dataset, model) if part]
|
||||
self.run.name = "--".join([*parts, uuid.uuid4().hex[:8]]).lower()
|
||||
if self.run.dir is None:
|
||||
self.run.dir = self.run.name
|
||||
if self.monitors.wandb is not None and self.monitors.wandb.name is None:
|
||||
self.monitors.wandb.name = self.run.name
|
||||
return self
|
||||
|
||||
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``."""
|
||||
@@ -210,9 +235,6 @@ class SFTConfig(BaseConfig):
|
||||
memory_profiler_path: Path | None = None
|
||||
"""Path to write the memory profile to."""
|
||||
|
||||
bench: BenchConfig | None = None
|
||||
"""Benchmark-mode configuration. When set, ``max_steps`` is forced to 4 and fake data is used."""
|
||||
|
||||
gc: GCConfig | None = GCConfig()
|
||||
"""Garbage collection config. Disables automatic GC and runs deterministic collections every N steps to avoid stragglers. Set to null to use Python's default GC behavior."""
|
||||
|
||||
@@ -365,14 +387,6 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
### Auto-setup and validate shared configs
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench is not None:
|
||||
self.max_steps = 4 # 1 Warmup + 3 Benchmark
|
||||
if self.ckpt: # Do not checkpoint
|
||||
self.ckpt = None
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_tokenizer(self):
|
||||
if self.tokenizer.name is None:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
@@ -10,7 +11,7 @@ from prime_rl.utils.config import BaseConfig
|
||||
# and the single shared W&B run. The launcher always sets these last, so allowing them in
|
||||
# `env_vars` would be a silent no-op (or, on multi-node, a footgun) — reject them instead.
|
||||
PROTECTED_ENV_VARS = frozenset(
|
||||
{"CUDA_VISIBLE_DEVICES", "WANDB_SHARED_MODE", "WANDB_SHARED_RUN_ID", "WANDB_SHARED_LABEL"}
|
||||
{"CUDA_VISIBLE_DEVICES", "PRL_RUN_ID", "PRL_RUN_NAME", "WANDB_RUN_ID", "WANDB_SHARED_MODE", "WANDB_SHARED_LABEL"}
|
||||
)
|
||||
|
||||
|
||||
@@ -27,6 +28,41 @@ EnvVars: TypeAlias = Annotated[dict[str, str], AfterValidator(reject_protected_e
|
||||
"""A per-component `env_vars` mapping, validated to not clobber `PROTECTED_ENV_VARS`."""
|
||||
|
||||
|
||||
class RunConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""Run name. Auto-generated as ``<envs>--<model>--<short-id>`` when unset, so every launch gets a fresh, readable run directory; set an explicit name (e.g. an experiment name) to get a predictable run directory, which is also required to resume a previous run. Unless set explicitly, the W&B run name and the Prime platform run name inherit it."""
|
||||
|
||||
dir: str | None = None
|
||||
"""Run directory name — the run writes all its artifacts to ``output_dir / dir``. Defaults to ``run.name``; set it only when the directory should differ from the display name."""
|
||||
|
||||
|
||||
class ResumeConfig(BaseConfig):
|
||||
"""Resume the run from a checkpoint. A bare ``--resume`` (or empty ``[resume]`` block)
|
||||
resumes from the latest checkpoint."""
|
||||
|
||||
step: int | None = Field(None, ge=1)
|
||||
"""Checkpoint step to resume from. None resumes from the latest checkpoint."""
|
||||
|
||||
dir: Path | None = None
|
||||
"""External checkpoint step directory to resume from (e.g. ``other/run/checkpoints/step_50``) — forks another run's checkpoint into this run. Mutually exclusive with ``step``."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_step_xor_dir(self):
|
||||
if self.step is not None and self.dir is not None:
|
||||
raise ValueError(
|
||||
"resume.step and resume.dir are mutually exclusive — the step is taken from the directory name"
|
||||
)
|
||||
if self.dir is not None and not re.fullmatch(r"step_\d+", self.dir.name):
|
||||
raise ValueError(f"resume.dir must point at a checkpoint step directory (`.../step_<N>`), got '{self.dir}'")
|
||||
return self
|
||||
|
||||
@property
|
||||
def dir_step(self) -> int:
|
||||
"""The step encoded in ``dir``'s name (validated to exist)."""
|
||||
assert self.dir is not None
|
||||
return int(self.dir.name.removeprefix("step_"))
|
||||
|
||||
|
||||
class SlurmConfig(BaseConfig):
|
||||
job_name: str = "prime-rl"
|
||||
"""SLURM job name."""
|
||||
@@ -156,78 +192,6 @@ class TrainerLogConfig(LogConfig):
|
||||
"""Trainer ranks to show in console output. Passed to ``torchrun --local-ranks-filter``."""
|
||||
|
||||
|
||||
class LogExtrasConfig(BaseConfig):
|
||||
samples: bool = True
|
||||
"""Log prompt/response samples."""
|
||||
|
||||
distributions: bool = True
|
||||
"""Log distributions (rewards, advantages, etc.)."""
|
||||
|
||||
interval: int = Field(10, ge=1)
|
||||
"""Step interval between extras logs."""
|
||||
|
||||
sample_ratio: float | None = Field(None, ge=0.0, le=1.0)
|
||||
"""Fraction of rollouts to log per step. The effective cap is ``len(rollouts) * sample_ratio``; 1.0 = all, 0.5 = half, 0.0 = none."""
|
||||
|
||||
|
||||
class WandbConfig(BaseConfig):
|
||||
# Shared configs (May be overwritten by WandbConfig from `rl.py`)
|
||||
project: str = "prime-rl"
|
||||
"""W&B project to log to."""
|
||||
|
||||
entity: str | None = None
|
||||
"""W&B entity to log to."""
|
||||
|
||||
name: str | None = None
|
||||
"""W&B run name."""
|
||||
|
||||
group: str | None = None
|
||||
"""W&B group."""
|
||||
|
||||
tags: list[str] | None = None
|
||||
"""W&B tags attached to the run."""
|
||||
|
||||
offline: bool = False
|
||||
"""Run W&B in offline mode."""
|
||||
|
||||
|
||||
class WandbWithExtrasConfig(WandbConfig):
|
||||
log_extras: LogExtrasConfig | None = LogExtrasConfig()
|
||||
"""Extras logging configuration. If None, no extras are logged."""
|
||||
|
||||
|
||||
class FileMonitorConfig(BaseConfig):
|
||||
"""Enable the local JSONL metric sink (``<output_dir>/metrics.jsonl``).
|
||||
|
||||
Present (non-None) enables it, mirroring the ``prime_monitor`` pattern. Metrics
|
||||
are the same scalars sent to W&B; useful for self-hosted dashboards or when W&B
|
||||
is disabled.
|
||||
"""
|
||||
|
||||
filename: str = "metrics.jsonl"
|
||||
"""Name of the JSONL file written under the component's ``output_dir``."""
|
||||
|
||||
|
||||
class PrimeMonitorConfig(BaseConfig):
|
||||
base_url: str = "https://api.primeintellect.ai/api/v1/rft"
|
||||
"""Base URL for the Prime Intellect monitoring API."""
|
||||
|
||||
api_key_var: str = "PRIME_API_KEY"
|
||||
"""Environment variable name containing the Prime Intellect API key, resolved via ``os.getenv``."""
|
||||
|
||||
log_extras: LogExtrasConfig | None = LogExtrasConfig()
|
||||
"""Extras logging configuration. If None, no extras are logged."""
|
||||
|
||||
run_name: str | None = None
|
||||
"""Run name shown on the platform. Defaults to the W&B run name when set, otherwise the platform auto-generates one."""
|
||||
|
||||
team_id: str | None = None
|
||||
"""Team ID to associate the run with."""
|
||||
|
||||
frontend_url: str | None = None
|
||||
"""Frontend base URL used for the dashboard link printed after registration. Defaults to the Prime CLI frontend URL when unset."""
|
||||
|
||||
|
||||
class HeartbeatConfig(BaseConfig):
|
||||
url: str
|
||||
"""URL to send the heartbeat to."""
|
||||
|
||||
@@ -4,15 +4,15 @@ from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
HeartbeatConfig,
|
||||
MetricsServerConfig,
|
||||
ResumeConfig,
|
||||
TrainerLogConfig,
|
||||
TransportConfig,
|
||||
WandbConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
@@ -59,11 +59,6 @@ class CompileConfig(BaseConfig):
|
||||
"""Compile transformer blocks with ``fullgraph=True``."""
|
||||
|
||||
|
||||
class BenchConfig(BaseConfig):
|
||||
output_json: Path | None = None
|
||||
"""Path to write benchmark results as JSON. If unset, results are only printed to the console."""
|
||||
|
||||
|
||||
class IndexCacheConfig(BaseConfig):
|
||||
topk_freq: int = Field(1, ge=1)
|
||||
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
|
||||
@@ -431,9 +426,6 @@ class CheckpointConfig(BaseConfig):
|
||||
weights_only: bool = False
|
||||
"""Save only weight checkpoints (no optimizer/scheduler state). Much faster and smaller than full checkpoints, but cannot resume training."""
|
||||
|
||||
resume_step: int | None = Field(None, ge=-1)
|
||||
"""Step to resume training from. None starts from scratch; ``-1`` restarts from the latest checkpoint available."""
|
||||
|
||||
keep_last: int | None = Field(None, ge=1)
|
||||
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
|
||||
|
||||
@@ -456,10 +448,10 @@ class CheckpointConfig(BaseConfig):
|
||||
class DefaultLossConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
dppo_mask_low: float = Field(0.1, ge=0)
|
||||
dppo_mask_low: float = Field(0.2, ge=0)
|
||||
"""Lower DPPO masking threshold."""
|
||||
|
||||
dppo_mask_high: float = Field(0.1, ge=0)
|
||||
dppo_mask_high: float = Field(0.2, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
@@ -577,6 +569,9 @@ class TrainerConfig(BaseConfig):
|
||||
scheduler: SchedulerConfig = ConstantSchedulerConfig()
|
||||
|
||||
ckpt: CheckpointConfig | None = None
|
||||
|
||||
resume: ResumeConfig | None = None
|
||||
"""Resume training from a checkpoint. None starts from scratch; an empty block resumes from the latest checkpoint, ``resume.step`` from that step, ``resume.dir`` from an external checkpoint step directory. Without ``ckpt`` the run loads but saves no new checkpoints."""
|
||||
"""Full training-state checkpoint configuration (model + optimizer + scheduler). If None, no resume-capable checkpoints are written."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
|
||||
@@ -587,10 +582,8 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
log: TrainerLogConfig = TrainerLogConfig()
|
||||
|
||||
wandb: WandbConfig | None = None
|
||||
|
||||
file_monitor: FileMonitorConfig | None = None
|
||||
"""Local JSONL metric sink. If set, trainer metrics are appended to ``<output_dir>/metrics.jsonl``."""
|
||||
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."""
|
||||
@@ -607,9 +600,6 @@ class TrainerConfig(BaseConfig):
|
||||
memory_profiler_path: Path | None = None
|
||||
"""Path to write the memory profile to."""
|
||||
|
||||
bench: BenchConfig | None = None
|
||||
"""Benchmark-mode configuration. When set, ``max_steps`` is forced to 4 and fake data is used."""
|
||||
|
||||
gc: GCConfig | None = GCConfig()
|
||||
"""Garbage collection config. Disables automatic GC and runs deterministic collections every N steps to avoid stragglers. Set to null to use Python's default GC behavior."""
|
||||
|
||||
@@ -661,16 +651,6 @@ class TrainerConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench is not None:
|
||||
self.max_steps = 4 # 1 Warmup + 3 Benchmark
|
||||
if not self.data.fake:
|
||||
self.data.fake = FakeDataLoaderConfig()
|
||||
if self.ckpt: # Do not checkpoint
|
||||
self.ckpt = None
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def dont_do_massive_traces(self):
|
||||
if self.trace_path:
|
||||
|
||||
@@ -6,38 +6,14 @@ from pydantic_config import BaseConfig as BaseConfig # noqa: F401
|
||||
from pydantic_config import cli # noqa: F401
|
||||
|
||||
|
||||
def to_toml_dict(config: BaseModel, exclude: set[str] | None = None) -> dict:
|
||||
"""Dump a config to a TOML-serializable dict.
|
||||
def dump_resolved_config(config: BaseModel, exclude: set[str] | None = None) -> dict:
|
||||
"""Dump a resolved config for a machine-written JSON artifact.
|
||||
|
||||
TOML cannot represent null, so None fields left at their default are dropped
|
||||
(they re-resolve identically on re-parse) while explicitly-set None fields
|
||||
are encoded as the string ``"None"``, which ``BaseConfig`` converts back to
|
||||
``None``. Dropping those too would silently revert explicit None overrides
|
||||
(e.g. ``--trainer.model.compile None``) to their non-None defaults when the
|
||||
written config is re-parsed.
|
||||
Resolved configs are written as JSON, not TOML: JSON keeps nulls, so explicit None
|
||||
overrides (e.g. ``--trainer.optim.max-norm None``) round-trip exactly on re-parse.
|
||||
Hand-written configs stay TOML (sparse, commented); the format split is the marker.
|
||||
"""
|
||||
return _encode_model(config, config.model_dump(exclude=exclude, mode="json"))
|
||||
|
||||
|
||||
def _encode_model(model: BaseModel, dumped: dict) -> dict:
|
||||
encoded = {}
|
||||
for name, value in dumped.items():
|
||||
if value is None:
|
||||
if name in model.model_fields_set:
|
||||
encoded[name] = "None"
|
||||
continue
|
||||
encoded[name] = _encode_value(getattr(model, name), value)
|
||||
return encoded
|
||||
|
||||
|
||||
def _encode_value(attr: Any, value: Any) -> Any:
|
||||
if isinstance(attr, BaseModel) and isinstance(value, dict):
|
||||
return _encode_model(attr, value)
|
||||
if isinstance(value, list) and isinstance(attr, (list, tuple)):
|
||||
return [_encode_value(a, v) for a, v in zip(attr, value)]
|
||||
if isinstance(value, dict) and isinstance(attr, dict):
|
||||
return {k: _encode_value(a, v) for (k, v), a in zip(value.items(), attr.values())}
|
||||
return "None" if value is None else value
|
||||
return config.model_dump(exclude=exclude, mode="json")
|
||||
|
||||
|
||||
def find_package_resource(subdir: str) -> Path | None:
|
||||
|
||||
@@ -90,23 +90,25 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
# ``orchestrator.ckpt`` has no ``output_dir`` field — trainer-only.
|
||||
propagate("ckpt.output_dir", "trainer.ckpt.output_dir")
|
||||
propagate("ckpt.interval", "trainer.ckpt.interval", "orchestrator.ckpt.interval")
|
||||
propagate("ckpt.resume_step", "trainer.ckpt.resume_step", "orchestrator.ckpt.resume_step")
|
||||
propagate("ckpt.keep_last", "trainer.ckpt.keep_last", "orchestrator.ckpt.keep_last")
|
||||
propagate("ckpt.keep_interval", "trainer.ckpt.keep_interval", "orchestrator.ckpt.keep_interval")
|
||||
|
||||
# [wandb] leaves. (Bare empty ``[wandb]`` block enablement is at the end.)
|
||||
# ``wandb.name`` flows verbatim to both sub-configs — shared W&B mode is
|
||||
# [monitors.wandb] leaves. (Bare empty ``[monitors.wandb]`` block enablement is at the end.)
|
||||
# ``monitors.wandb.name`` flows verbatim to both sub-configs — shared W&B mode is
|
||||
# always on for the rl entrypoint, so the legacy ``-trainer`` /
|
||||
# ``-orchestrator`` suffix split is gone.
|
||||
propagate("wandb.project", "trainer.wandb.project", "orchestrator.wandb.project")
|
||||
propagate("wandb.entity", "trainer.wandb.entity", "orchestrator.wandb.entity")
|
||||
propagate("wandb.name", "trainer.wandb.name", "orchestrator.wandb.name")
|
||||
propagate("wandb.group", "trainer.wandb.group", "orchestrator.wandb.group")
|
||||
propagate("wandb.tags", "trainer.wandb.tags", "orchestrator.wandb.tags")
|
||||
propagate("wandb.offline", "trainer.wandb.offline", "orchestrator.wandb.offline")
|
||||
for leaf in ("project", "entity", "name", "group", "tags", "offline"):
|
||||
propagate(
|
||||
f"monitors.wandb.{leaf}",
|
||||
f"trainer.monitors.wandb.{leaf}",
|
||||
f"orchestrator.monitors.wandb.{leaf}",
|
||||
)
|
||||
|
||||
# [file_monitor] leaf. (Bare empty ``[file_monitor]`` block enablement is at the end.)
|
||||
propagate("file_monitor.filename", "trainer.file_monitor.filename", "orchestrator.file_monitor.filename")
|
||||
# [monitors.file] leaf. (Bare empty ``[monitors.file]`` block enablement is at the end.)
|
||||
propagate("monitors.file.path", "trainer.monitors.file.path", "orchestrator.monitors.file.path")
|
||||
|
||||
# [monitors.prime] leaf → orchestrator only (the trainer has no platform integration).
|
||||
propagate("monitors.prime.name", "orchestrator.monitors.prime.name")
|
||||
|
||||
# [tokenizer]. ``chat_template`` also flows to ``inference.vllm`` (vLLM's
|
||||
# ``--chat-template``); ``name`` and ``trust_remote_code`` can legitimately
|
||||
@@ -138,8 +140,6 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
# pass (the per-rank inference.toml drops slurm, so each rank still runs locally).
|
||||
propagate("slurm", "inference.slurm")
|
||||
|
||||
propagate("output_dir", "trainer.output_dir", "orchestrator.output_dir")
|
||||
|
||||
# Cascade trainer.tokenizer.chat_template → inference.vllm.chat_template
|
||||
# (vLLM ``--chat-template``). Read trainer's value *after* the shared
|
||||
# propagation above so we cover both:
|
||||
@@ -152,21 +152,31 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
if trainer_chat_template is not None:
|
||||
fill("inference.vllm.chat_template", trainer_chat_template)
|
||||
|
||||
# Bare ``[ckpt]`` / ``[wandb]`` block: presence-only signal that enables
|
||||
# the section with defaults on both sub-configs. Necessary because
|
||||
# Bare ``[ckpt]`` / ``[monitors.wandb]`` block: presence-only signal that
|
||||
# enables the section with defaults on both sub-configs. Necessary because
|
||||
# ``trainer.ckpt`` / ``orchestrator.ckpt`` are Optional[None] by default —
|
||||
# without this an empty shared block would be a no-op. Leaf-level
|
||||
# conflicts (e.g. shared ``ckpt.interval`` vs ``trainer.ckpt.interval``)
|
||||
# are already caught above; the bare block is exempt because
|
||||
# ``[ckpt]`` + ``[trainer.ckpt] keep_last = 3`` is a legitimate
|
||||
# "enable + customise per side" pattern. The ``isinstance(dict)`` check
|
||||
# (not ``is not None``) is what makes CLI ``--no-wandb`` / ``--no-ckpt``
|
||||
# work — those land as the *string* ``"None"`` until ``BaseConfig``'s
|
||||
# parent-class validator converts it, which happens after this one.
|
||||
for key in ("ckpt", "wandb", "file_monitor"):
|
||||
if isinstance(get(key), dict):
|
||||
fill(f"trainer.{key}", {})
|
||||
fill(f"orchestrator.{key}", {})
|
||||
# without this an empty shared block would be a no-op. Leaf-level conflicts
|
||||
# (e.g. shared ``ckpt.interval`` vs ``trainer.ckpt.interval``) are already
|
||||
# caught above; the bare block is exempt because ``[ckpt]`` +
|
||||
# ``[trainer.ckpt] keep_last = 3`` is a legitimate "enable + customise per
|
||||
# side" pattern. CLI ``--no-ckpt`` / ``--no-monitors.wandb`` land as the
|
||||
# *string* ``"None"`` until ``BaseConfig``'s parent-class validator converts
|
||||
# it, which happens after this one — the disable must propagate too, since
|
||||
# the monitor sub-configs default to enabled.
|
||||
presence_targets = {
|
||||
"ckpt": ("trainer", "orchestrator"),
|
||||
"monitors.wandb": ("trainer", "orchestrator"),
|
||||
"monitors.file": ("trainer", "orchestrator"),
|
||||
"monitors.prime": ("orchestrator",),
|
||||
}
|
||||
for key, targets in presence_targets.items():
|
||||
value = get(key)
|
||||
if isinstance(value, dict):
|
||||
for target in targets:
|
||||
fill(f"{target}.{key}", {})
|
||||
elif value == "None":
|
||||
for target in targets:
|
||||
fill(f"{target}.{key}", "None")
|
||||
|
||||
if conflicts:
|
||||
lines = [
|
||||
@@ -197,9 +207,9 @@ def validate_shared_ckpt_config(
|
||||
raise ValueError(
|
||||
f"Trainer checkpoint interval ({trainer.ckpt.interval}) and orchestrator checkpoint interval ({orchestrator.ckpt.interval}) are not the same. Please specify the same checkpoint interval for both."
|
||||
)
|
||||
if trainer.ckpt and orchestrator.ckpt and trainer.ckpt.resume_step != orchestrator.ckpt.resume_step:
|
||||
if trainer.resume != orchestrator.resume:
|
||||
raise ValueError(
|
||||
f"Trainer checkpoint resume step ({trainer.ckpt.resume_step}) and orchestrator checkpoint resume step ({orchestrator.ckpt.resume_step}) are not the same. Please specify the same checkpoint resume step for both."
|
||||
f"Trainer resume ({trainer.resume}) and orchestrator resume ({orchestrator.resume}) are not the same. Please specify the same resume config for both."
|
||||
)
|
||||
|
||||
|
||||
@@ -225,37 +235,26 @@ def validate_shared_model_name(
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_output_dir(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.output_dir != orchestrator.output_dir:
|
||||
raise ValueError(
|
||||
f"Trainer outputs directory ({trainer.output_dir}) and orchestrator outputs directory ({orchestrator.output_dir}) are not the same. "
|
||||
"Please specify the same outputs directory for both (the orchestrator no longer nests under a run_default subdirectory)."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_wandb_config(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.wandb and not orchestrator.wandb:
|
||||
if trainer.monitors.wandb and not orchestrator.monitors.wandb:
|
||||
raise ValueError(
|
||||
"Trainer W&B config is specified, but orchestrator W&B config is not. "
|
||||
"This means only trainer metrics will be logged. Please specify [orchestrator.wandb] to log orchestrator metrics as well, "
|
||||
"or use [wandb] to configure both at once."
|
||||
"This means only trainer metrics will be logged. Please specify [orchestrator.monitors.wandb] to log orchestrator metrics as well, "
|
||||
"or use [monitors.wandb] to configure both at once."
|
||||
)
|
||||
if orchestrator.wandb and not trainer.wandb:
|
||||
if orchestrator.monitors.wandb and not trainer.monitors.wandb:
|
||||
raise ValueError(
|
||||
"Orchestrator W&B config is specified, but trainer W&B config is not. "
|
||||
"This means only orchestrator metrics will be logged. Please specify [trainer.wandb] to log trainer metrics as well, "
|
||||
"or use [wandb] to configure both at once."
|
||||
"This means only orchestrator metrics will be logged. Please specify [trainer.monitors.wandb] to log trainer metrics as well, "
|
||||
"or use [monitors.wandb] to configure both at once."
|
||||
)
|
||||
if trainer.wandb and orchestrator.wandb:
|
||||
if trainer.wandb.project != orchestrator.wandb.project:
|
||||
if trainer.monitors.wandb and orchestrator.monitors.wandb:
|
||||
if trainer.monitors.wandb.project != orchestrator.monitors.wandb.project:
|
||||
raise ValueError(
|
||||
f"Trainer W&B project ({trainer.wandb.project}) and orchestrator W&B project ({orchestrator.wandb.project}) are not the same. Please specify the same W&B project for both."
|
||||
f"Trainer W&B project ({trainer.monitors.wandb.project}) and orchestrator W&B project ({orchestrator.monitors.wandb.project}) are not the same. Please specify the same W&B project for both."
|
||||
)
|
||||
|
||||
|
||||
|
||||
+8
-7
@@ -128,14 +128,14 @@ override-dependencies = [
|
||||
"openenv-core",
|
||||
]
|
||||
|
||||
# research-environments packages are auto-discovered as workspace members, so new
|
||||
# prime-envs packages are auto-discovered as workspace members, so new
|
||||
# envs there need no per-package registration. verifiers' example envs are opt-in:
|
||||
# only the ones prime-rl trains or tests on are listed, so an upstream example with
|
||||
# conflicting pins can't break the shared lock. Install them with
|
||||
# `uv sync --all-packages`.
|
||||
[tool.uv.workspace]
|
||||
members = [
|
||||
"deps/research-environments/environments/*/*",
|
||||
"deps/prime-envs/environments/*/*",
|
||||
"deps/verifiers/environments/alphabet_sort",
|
||||
"deps/verifiers/environments/color_codeword",
|
||||
"deps/verifiers/environments/gsm8k",
|
||||
@@ -148,8 +148,8 @@ members = [
|
||||
# tau2-synth and tau3-bench pin `tau2` forks/revs that conflict with the
|
||||
# canonical tau2-bench; a workspace shares one lock, so these can't coexist.
|
||||
exclude = [
|
||||
"deps/research-environments/environments/tool_use/tau2_synth",
|
||||
"deps/research-environments/environments/tool_use/tau3_bench",
|
||||
"deps/prime-envs/environments/tool_use/tau2_synth",
|
||||
"deps/prime-envs/environments/tool_use/tau3_bench",
|
||||
]
|
||||
|
||||
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
|
||||
@@ -196,7 +196,7 @@ torchao = false
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
# prime-rl consumes `verifiers.v1` (incl. the built-in harnesses/tasksets); env tasksets
|
||||
# live under deps/{verifiers,research-environments}/environments.
|
||||
# live under deps/{verifiers,prime-envs}/environments.
|
||||
verifiers = { path = "deps/verifiers", editable = true }
|
||||
renderers = { path = "deps/renderers", editable = true }
|
||||
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
|
||||
@@ -208,8 +208,8 @@ torchao = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/downlo
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
@@ -261,6 +261,7 @@ select = ["F", "I"]
|
||||
# Without this, ruff classifies prime_rl.configs.* as third-party because it
|
||||
# doesn't live under src/.
|
||||
known-first-party = ["prime_rl"]
|
||||
known-third-party = ["verifiers", "renderers", "pydantic_config"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
|
||||
+1
-1
@@ -60,7 +60,7 @@ if [[ ${#POSITIONAL[@]} -ge 2 ]]; then
|
||||
OUTPUT_DIR="${POSITIONAL[1]}"
|
||||
fi
|
||||
|
||||
LOG_DIR="${OUTPUT_DIR}/logs"
|
||||
LOG_DIR="${OUTPUT_DIR}/logs/latest"
|
||||
|
||||
if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
|
||||
echo "Attaching to tmux session: $SESSION_NAME"
|
||||
|
||||
@@ -25,7 +25,7 @@ Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max
|
||||
|
||||
```bash
|
||||
uv run rl --help # all fields and defaults
|
||||
uv run rl @ rl.toml --dry-run --output-dir /tmp/x # write resolved TOML to /tmp/x/configs
|
||||
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved configs (JSON) to /tmp/x/check/configs
|
||||
```
|
||||
|
||||
## Validators
|
||||
@@ -90,7 +90,7 @@ In TOML, an empty section header (`[ckpt]`) does the same.
|
||||
|
||||
## RL trainer token exports
|
||||
|
||||
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `<run_dir>/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
|
||||
```toml
|
||||
enable_token_export = true
|
||||
|
||||
@@ -29,7 +29,7 @@ uv sync --all-extras --all-packages # + all env packages (needed to train
|
||||
uv sync --package prime-rl --package gsm8k # core + just one env
|
||||
```
|
||||
|
||||
Environment packages are uv **workspace members**. Those under `deps/research-environments/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`.
|
||||
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,9 +9,9 @@ description: Monitor an ongoing prime-rl training run — find the output direct
|
||||
|
||||
### On launch
|
||||
|
||||
1. Find the output dir and read the resolved configs at `{output_dir}/configs/` (start with `rl.toml`).
|
||||
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.
|
||||
2. Confirm all processes are alive and the run is making progress.
|
||||
3. Write the initial summary into `{output_dir}/STATUS.md`.
|
||||
3. Write the initial summary into `{run_dir}/STATUS.md`.
|
||||
|
||||
### Recurring check-ins
|
||||
|
||||
@@ -19,7 +19,7 @@ Default cadence: **1 hour** (researcher can override). At each check-in:
|
||||
|
||||
1. Confirm processes are alive.
|
||||
2. Grep logs for errors/warnings; note current step and key metrics.
|
||||
3. **Append** an entry to `{output_dir}/STATUS.md` (never overwrite):
|
||||
3. **Append** an entry to `{run_dir}/STATUS.md` (never overwrite):
|
||||
|
||||
```markdown
|
||||
## YYYY-MM-DD HH:MM UTC
|
||||
@@ -55,15 +55,15 @@ 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 output dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
|
||||
- `{output_dir}/configs/` — resolved TOMLs (`rl.toml` has the full picture).
|
||||
- `{output_dir}/logs/` — see below.
|
||||
- `{output_dir}/rollouts/step_N/{train,eval}/` — saved rollout traces (see Traces below).
|
||||
- `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}/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 rollout traces (see Traces below).
|
||||
|
||||
### Logs
|
||||
|
||||
```
|
||||
{output_dir}/logs/
|
||||
{run_dir}/logs/latest/
|
||||
├── trainer.log # rank 0 stdout
|
||||
├── orchestrator.log # orchestrator stdout
|
||||
├── inference.log # vLLM stdout
|
||||
@@ -81,8 +81,8 @@ Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough
|
||||
Scan for problems:
|
||||
|
||||
```bash
|
||||
grep -E "WARNING|ERROR" {output_dir}/logs/{trainer,orchestrator,inference}.log
|
||||
grep -E "WARNING|ERROR" {output_dir}/logs/envs/{train,eval}/*.log
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,inference}.log
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
|
||||
```
|
||||
|
||||
### Metrics
|
||||
@@ -141,8 +141,8 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
|
||||
### Traces
|
||||
|
||||
```
|
||||
{output_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per rollout as it completes
|
||||
{output_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
{run_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per rollout as it completes
|
||||
{run_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
```
|
||||
|
||||
JSONL files of `vf.Trace` records (training tensors excluded), one line per trace — a
|
||||
@@ -157,12 +157,12 @@ share the step file) — untrainable traces (a frozen judge's) appear only in `a
|
||||
`group_id`, `episode_id`, and `policy_version` under `info`.
|
||||
|
||||
```bash
|
||||
wc -l {output_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
|
||||
jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.ok | not) | {id, env: .info.env_name, runtime}' {output_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
wc -l {run_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
|
||||
jq '.rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.ok | not) | {id, env: .info.env_name, runtime}' {run_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
```
|
||||
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{output_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the trace subtrees.
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the trace subtrees.
|
||||
|
||||
### Common failure modes
|
||||
|
||||
|
||||
@@ -7,6 +7,10 @@ description: How to launch prime-rl training runs — the `rl`, `sft`, and `infe
|
||||
|
||||
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
|
||||
|
||||
## Run directories
|
||||
|
||||
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, weights, 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).
|
||||
|
||||
## Config system at a glance
|
||||
|
||||
[`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config) — Pydantic-based TOML + CLI loader. Highlights (see the `configs` skill for full mechanics):
|
||||
@@ -15,7 +19,7 @@ All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/t
|
||||
- Nested groups via dotted CLI paths — kebab-case on the CLI, snake_case in TOML.
|
||||
- Bool toggles: bare `--flag` enables, `--no-flag` disables (nested too).
|
||||
- Lists: space-separated or JSON literal. Dicts: JSON literal, deep-merged with file values.
|
||||
- Optional sub-configs (`WandbConfig | None`): bare `--wandb` enables defaults; `--wandb @ wandb.toml` enables from a file; `--no-wandb` disables.
|
||||
- Optional sub-configs (`WandbMonitorConfig | None`): bare `--monitors.wandb` enables defaults; `--monitors.wandb @ wandb.toml` enables from a file; `--no-monitors.wandb` disables.
|
||||
- Discriminated unions are switched by the `type` tag (e.g. `--optimizer.type muon`).
|
||||
- Validation aliases let renamed fields keep working; legacy keys can be remapped in a `model_validator(mode="before")`.
|
||||
- Auto-generated `--help` panels from `Field(description=...)` or PEP 224 docstrings.
|
||||
@@ -36,7 +40,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
|
||||
- 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'))"`).
|
||||
If a local env exists under `deps/research-environments/environments/` or
|
||||
If a local env exists under `deps/prime-envs/environments/` or
|
||||
`deps/verifiers/environments/` but does not import, install the env workspace
|
||||
members with `uv sync --all-packages` (all) or `uv sync --package prime-rl
|
||||
--package <env>` (one) — they're auto-discovered, no `pyproject.toml` edit needed.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import os
|
||||
from functools import partial
|
||||
|
||||
from verifiers.v1 import pool_serve_kwargs
|
||||
from verifiers.v1.runtimes import set_base_sandbox_labels
|
||||
from verifiers.v1.serve import env_config_data, serve_env
|
||||
|
||||
from prime_rl.configs.env_server import EnvServerConfig
|
||||
@@ -10,14 +12,21 @@ from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
|
||||
def setup_worker(log_level: str | None, json_logging: bool, sandbox_labels: list[str]) -> None:
|
||||
setup_env_server_logging(log_level, json_logging)
|
||||
set_base_sandbox_labels(sandbox_labels)
|
||||
|
||||
|
||||
@clean_exit
|
||||
def run_server(config: EnvServerConfig):
|
||||
# ``serve.pool`` (static or elastic) sizes the server. serve_env applies the logging
|
||||
run_name = os.environ.get("PRL_RUN_NAME")
|
||||
sandbox_labels = [run_name] if run_name else []
|
||||
# ``serve.pool`` (static or elastic) sizes the server. serve_env applies the worker
|
||||
# setup in this process and in every spawned worker.
|
||||
serve_env(
|
||||
**pool_serve_kwargs(config.serve.pool),
|
||||
address=config.serve.address,
|
||||
log_setup=partial(setup_env_server_logging, config.log.level, config.log.json_logging),
|
||||
log_setup=partial(setup_worker, config.log.level, config.log.json_logging, sandbox_labels),
|
||||
config_data=env_config_data(config.env),
|
||||
max_concurrent=config.serve.max_concurrent,
|
||||
)
|
||||
|
||||
@@ -7,12 +7,10 @@ from pathlib import Path
|
||||
from threading import Event, Thread
|
||||
from typing import Any
|
||||
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli, to_toml_dict
|
||||
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, get_log_dir
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, latest_log_dir
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
@@ -20,7 +18,7 @@ from prime_rl.utils.process import (
|
||||
set_proc_title,
|
||||
)
|
||||
|
||||
INFERENCE_TOML = "inference.toml"
|
||||
INFERENCE_CONFIG = "inference.json"
|
||||
INFERENCE_SBATCH = "inference.sbatch"
|
||||
|
||||
|
||||
@@ -44,12 +42,12 @@ def write_config(
|
||||
engines — the sbatch script starts the single global router.
|
||||
"""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_path = output_dir / INFERENCE_TOML
|
||||
toml_dict = to_toml_dict(config, exclude=exclude)
|
||||
config_path = output_dir / INFERENCE_CONFIG
|
||||
config_dict = dump_resolved_config(config, exclude=exclude)
|
||||
if engine_only:
|
||||
toml_dict["router"] = "None"
|
||||
with open(config_path, "wb") as f:
|
||||
tomli_w.dump(toml_dict, f)
|
||||
config_dict["router"] = None
|
||||
with open(config_path, "w") as f:
|
||||
json.dump(config_dict, f, indent=2)
|
||||
return config_path
|
||||
|
||||
|
||||
@@ -137,7 +135,7 @@ def inference_slurm(config: InferenceConfig):
|
||||
write_slurm_script(config, config_path, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
log_dir = get_log_dir(config.output_dir)
|
||||
log_dir = latest_log_dir(config.output_dir)
|
||||
num_nodes = getattr(config.deployment, "num_nodes", 1)
|
||||
log_message = format_log_message(log_dir=log_dir, inference=True, job_log=True, num_infer_nodes=num_nodes)
|
||||
|
||||
|
||||
@@ -11,22 +11,23 @@ from threading import Event, Thread
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import pynvml
|
||||
import tomli_w
|
||||
|
||||
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.inference import vllm_overrides_fragment
|
||||
from prime_rl.utils.config import cli, to_toml_dict
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_log_dir,
|
||||
format_log_message,
|
||||
get_ckpt_dir,
|
||||
get_log_dir,
|
||||
get_config_dir,
|
||||
latest_log_dir,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_output_dir,
|
||||
validate_run_dir,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -38,12 +39,12 @@ from prime_rl.utils.process import (
|
||||
set_proc_title,
|
||||
)
|
||||
|
||||
RL_TOML = "rl.toml"
|
||||
RL_CONFIG = "rl.json"
|
||||
RL_SBATCH = "rl.sbatch"
|
||||
|
||||
TRAINER_TOML = "trainer.toml"
|
||||
ORCHESTRATOR_TOML = "orchestrator.toml"
|
||||
INFERENCE_TOML = "inference.toml"
|
||||
TRAINER_CONFIG = "trainer.json"
|
||||
ORCHESTRATOR_CONFIG = "orchestrator.json"
|
||||
INFERENCE_CONFIG = "inference.json"
|
||||
|
||||
ENVS_DIR = "envs"
|
||||
|
||||
@@ -79,29 +80,29 @@ def get_physical_gpu_ids() -> list[int]:
|
||||
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
|
||||
"""Write resolved config to disk, excluding launcher-only fields."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
with open(output_dir / RL_TOML, "wb") as f:
|
||||
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
|
||||
with open(output_dir / RL_CONFIG, "w") as f:
|
||||
json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2)
|
||||
|
||||
|
||||
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
"""Write resolved subconfigs to disk as TOML files."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(output_dir / TRAINER_TOML, "wb") as f:
|
||||
tomli_w.dump(to_toml_dict(config.trainer), f)
|
||||
with open(output_dir / TRAINER_CONFIG, "w") as f:
|
||||
json.dump(dump_resolved_config(config.trainer), f, indent=2)
|
||||
|
||||
with open(output_dir / ORCHESTRATOR_TOML, "wb") as f:
|
||||
tomli_w.dump(to_toml_dict(config.orchestrator), f)
|
||||
with open(output_dir / ORCHESTRATOR_CONFIG, "w") as f:
|
||||
json.dump(dump_resolved_config(config.orchestrator), f, indent=2)
|
||||
|
||||
if config.inference is not None:
|
||||
# Exclude launcher-only fields that are not needed by the vLLM server
|
||||
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
|
||||
inference_dict = to_toml_dict(config.inference, exclude=exclude_inference)
|
||||
inference_dict = dump_resolved_config(config.inference, exclude=exclude_inference)
|
||||
if config.deployment.type == "multi_node":
|
||||
# Per-rank processes run bare engines; the sbatch starts the single global router.
|
||||
inference_dict["router"] = "None"
|
||||
with open(output_dir / INFERENCE_TOML, "wb") as f:
|
||||
tomli_w.dump(inference_dict, f)
|
||||
inference_dict["router"] = None
|
||||
with open(output_dir / INFERENCE_CONFIG, "w") as f:
|
||||
json.dump(inference_dict, f, indent=2)
|
||||
|
||||
# One EnvServerConfig TOML per launcher-managed source: `env-server @ <path>` binds
|
||||
# at the source's deterministic address, where the orchestrator connects. The source's
|
||||
@@ -110,14 +111,14 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
for split, source, address in env_servers(config):
|
||||
env_dir = output_dir / ENVS_DIR / split
|
||||
env_dir.mkdir(parents=True, exist_ok=True)
|
||||
source_dict = to_toml_dict(source)
|
||||
source_dict = dump_resolved_config(source)
|
||||
env_server_dict = {
|
||||
"env": source_dict["env"],
|
||||
"serve": {**source_dict.get("serve", {}), "address": address},
|
||||
"log": {"level": config.orchestrator.log.vf_level, "json_logging": config.orchestrator.log.json_logging},
|
||||
}
|
||||
with open(env_dir / f"{source.resolved_name}.toml", "wb") as f:
|
||||
tomli_w.dump(env_server_dict, f)
|
||||
with open(env_dir / f"{source.resolved_name}.json", "w") as f:
|
||||
json.dump(env_server_dict, f, indent=2)
|
||||
|
||||
|
||||
def rl_local(config: RLConfig):
|
||||
@@ -128,7 +129,7 @@ def rl_local(config: RLConfig):
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
|
||||
config_dir = config.output_dir / "configs"
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
@@ -161,11 +162,12 @@ def rl_local(config: RLConfig):
|
||||
logger.debug(f"RL start command: {' '.join(start_command)}")
|
||||
|
||||
# Build shared W&B env vars for subprocesses. Shared mode is always on for
|
||||
# the rl entrypoint — trainer and orchestrator log to a single W&B run.
|
||||
# The monitor short-circuits when WANDB_MODE=disabled/offline is also set.
|
||||
# the rl entrypoint — trainer and orchestrator log to a single W&B run whose
|
||||
# id ($WANDB_RUN_ID) equals $PRL_RUN_ID. The monitor short-circuits when
|
||||
# WANDB_MODE=disabled/offline is also set.
|
||||
wandb_shared_env: dict[str, str] = {
|
||||
"WANDB_SHARED_MODE": "1",
|
||||
"WANDB_SHARED_RUN_ID": os.environ.get("WANDB_SHARED_RUN_ID", uuid.uuid4().hex),
|
||||
"WANDB_RUN_ID": os.environ["PRL_RUN_ID"],
|
||||
}
|
||||
|
||||
# Validate client port matches inference server port
|
||||
@@ -180,9 +182,8 @@ def rl_local(config: RLConfig):
|
||||
f"Update the base_url to use port {expected_port} to match the inference server."
|
||||
)
|
||||
|
||||
# Prepare paths to communicate with the trainer
|
||||
log_dir = get_log_dir(config.output_dir)
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
# Per-attempt log dir: a resume never overwrites an earlier attempt's logs
|
||||
log_dir = create_attempt_log_dir(config.run_dir)
|
||||
|
||||
# Start processes
|
||||
processes: list[Popen] = []
|
||||
@@ -201,7 +202,7 @@ def rl_local(config: RLConfig):
|
||||
try:
|
||||
# Optionally, start inference process
|
||||
if config.inference:
|
||||
inference_cmd = ["inference", "@", (config_dir / INFERENCE_TOML).as_posix()]
|
||||
inference_cmd = ["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()]
|
||||
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
|
||||
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
|
||||
# If we don't log stdout, the server hangs
|
||||
@@ -260,7 +261,7 @@ def rl_local(config: RLConfig):
|
||||
# orchestrator start in parallel.
|
||||
for split, source, address in env_servers(config):
|
||||
name = source.resolved_name
|
||||
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.toml").as_posix()]
|
||||
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
|
||||
logger.info(f"Starting {split} env server {name} at {address}")
|
||||
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
|
||||
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
|
||||
@@ -290,7 +291,7 @@ def rl_local(config: RLConfig):
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_TOML).as_posix()]
|
||||
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()]
|
||||
logger.info("Starting orchestrator process")
|
||||
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
|
||||
with open(log_dir / "orchestrator.log", "w") as log_file:
|
||||
@@ -340,7 +341,7 @@ def rl_local(config: RLConfig):
|
||||
"-m",
|
||||
"prime_rl.trainer.rl.train",
|
||||
"@",
|
||||
(config_dir / TRAINER_TOML).as_posix(),
|
||||
(config_dir / TRAINER_CONFIG).as_posix(),
|
||||
]
|
||||
logger.info(f"Starting trainer on GPU(s) {' '.join(map(str, trainer_gpu_ids))}")
|
||||
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
|
||||
@@ -469,8 +470,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_dir / RL_TOML,
|
||||
output_dir=config.output_dir,
|
||||
config_path=config_dir / RL_CONFIG,
|
||||
output_dir=config.run_dir,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
elif config.inference is not None and config.inference.deployment.type == "disaggregated":
|
||||
@@ -479,8 +480,9 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
is_disaggregated=True,
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir,
|
||||
output_dir=config.output_dir,
|
||||
output_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,
|
||||
@@ -519,8 +521,9 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
is_disaggregated=False,
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir, # TODO: should prob have each subconfig path separately
|
||||
output_dir=config.output_dir,
|
||||
output_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,
|
||||
@@ -563,12 +566,12 @@ def rl_slurm(config: RLConfig):
|
||||
config.log.level or os.environ.get("PRIME_LOG_LEVEL", "info"), json_logging=config.log.json_logging
|
||||
)
|
||||
|
||||
config_dir = config.output_dir / "configs"
|
||||
log_dir = get_log_dir(config.output_dir)
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
log_dir = latest_log_dir(config.run_dir)
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean_output_dir"})
|
||||
logger.info(f"Wrote config to {config_dir / RL_TOML}")
|
||||
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean"})
|
||||
logger.info(f"Wrote config to {config_dir / RL_CONFIG}")
|
||||
|
||||
train_env_names = env_server_names(config, "train")
|
||||
eval_env_names = env_server_names(config, "eval")
|
||||
@@ -600,7 +603,7 @@ def rl_slurm(config: RLConfig):
|
||||
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
|
||||
)
|
||||
|
||||
script_path = config.output_dir / RL_SBATCH
|
||||
script_path = config.run_dir / RL_SBATCH
|
||||
write_slurm_script(config, config_dir, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
@@ -618,36 +621,49 @@ def rl_slurm(config: RLConfig):
|
||||
|
||||
|
||||
def rl(config: RLConfig):
|
||||
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
|
||||
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
|
||||
# The run identity is runtime-only, never sub-config: $PRL_RUN_ID / $PRL_RUN_NAME are
|
||||
# the vehicle for runtime info between processes, and every spawned process inherits
|
||||
# them. Components launched standalone have no run identity. TODO: fetch the id from
|
||||
# the Prime SDK once runs are registered there.
|
||||
os.environ.setdefault("PRL_RUN_ID", uuid.uuid4().hex)
|
||||
assert config.run.name is not None # resolved at construction
|
||||
os.environ["PRL_RUN_NAME"] = config.run.name
|
||||
|
||||
resuming = config.resume is not None
|
||||
clean = config.clean and not os.environ.get("NEVER_CLEAN")
|
||||
ckpt_output_dir = config.ckpt.output_dir if config.ckpt else None
|
||||
validate_output_dir(config.output_dir, resuming=resuming, clean=clean, ckpt_output_dir=ckpt_output_dir)
|
||||
config.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
validate_run_dir(
|
||||
config.run_dir, output_dir=config.output_dir, resuming=resuming, clean=clean, ckpt_output_dir=ckpt_output_dir
|
||||
)
|
||||
config.run_dir.mkdir(parents=True, exist_ok=True)
|
||||
if ckpt_output_dir is not None:
|
||||
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Clean stale rollouts and broadcasts. When resuming, anything past the resume
|
||||
# step is stale. When training from scratch, every existing step directory is
|
||||
# stale — without this, a fresh run in a dirty output_dir would pick up rollouts
|
||||
# stale — without this, a fresh run in a dirty run dir would pick up rollouts
|
||||
# from a previous run and the orchestrator would see a negative async level.
|
||||
resume_step: int | None = None
|
||||
if resuming:
|
||||
resume_step = config.ckpt.resume_step
|
||||
if resume_step == -1:
|
||||
ckpt_base = ckpt_output_dir if ckpt_output_dir is not None else config.output_dir
|
||||
resume_step = resolve_latest_ckpt_step(get_ckpt_dir(ckpt_base))
|
||||
if config.resume.dir is not None:
|
||||
resume_step = config.resume.dir_step
|
||||
else:
|
||||
resume_step = config.resume.step
|
||||
if resume_step is None:
|
||||
ckpt_base = ckpt_output_dir if ckpt_output_dir is not None else config.run_dir
|
||||
resume_step = resolve_latest_ckpt_step(get_ckpt_dir(ckpt_base))
|
||||
|
||||
if resume_step is not None:
|
||||
get_logger().info(f"Resuming from step {resume_step}, cleaning future rollouts and broadcasts")
|
||||
clean_future_steps(config.output_dir, resume_step)
|
||||
clean_future_steps(config.run_dir, resume_step)
|
||||
else:
|
||||
get_logger().info("Training from scratch, cleaning any stale rollouts and broadcasts")
|
||||
clean_future_steps(config.output_dir, -1)
|
||||
clean_future_steps(config.run_dir, -1)
|
||||
|
||||
if not config.dry_run:
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
|
||||
pre_download_model(config.trainer.model.name)
|
||||
pre_download_model(config.trainer.model.name, skip_weights=config.trainer.model.debug.random_init)
|
||||
|
||||
if config.slurm is not None:
|
||||
rl_slurm(config)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -6,12 +7,16 @@ from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.utils.config import cli, to_toml_dict
|
||||
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, get_log_dir, validate_output_dir
|
||||
from prime_rl.utils.pathing import (
|
||||
create_attempt_log_dir,
|
||||
format_log_message,
|
||||
get_config_dir,
|
||||
latest_log_dir,
|
||||
validate_run_dir,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_TRAINER_ENV_VARS,
|
||||
@@ -21,15 +26,15 @@ from prime_rl.utils.process import (
|
||||
set_proc_title,
|
||||
)
|
||||
|
||||
SFT_TOML = "sft.toml"
|
||||
SFT_CONFIG = "sft.json"
|
||||
SFT_SBATCH = "sft.sbatch"
|
||||
|
||||
|
||||
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
|
||||
"""Write resolved config to disk, excluding launcher-only fields."""
|
||||
config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(config_path, "wb") as f:
|
||||
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
|
||||
with open(config_path, "w") as f:
|
||||
json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2)
|
||||
|
||||
|
||||
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path) -> None:
|
||||
@@ -52,14 +57,14 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path)
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.output_dir,
|
||||
output_dir=config.run_dir,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.output_dir,
|
||||
output_dir=config.run_dir,
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
num_nodes=config.deployment.num_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
@@ -76,21 +81,21 @@ def sft_slurm(config: SFTConfig):
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = get_config_dir(config.output_dir)
|
||||
config_path = config_dir / SFT_TOML
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
exclude = (
|
||||
{"deployment", "slurm", "dry_run", "clean_output_dir"}
|
||||
{"deployment", "slurm", "dry_run", "clean"}
|
||||
if config.deployment.type == "multi_node"
|
||||
else {"slurm", "dry_run", "clean_output_dir"}
|
||||
else {"slurm", "dry_run", "clean"}
|
||||
)
|
||||
write_config(config, config_path, exclude=exclude)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
script_path = config.output_dir / SFT_SBATCH
|
||||
script_path = config.run_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
log_dir = get_log_dir(config.output_dir)
|
||||
log_dir = latest_log_dir(config.run_dir)
|
||||
num_nodes = config.deployment.num_nodes if config.deployment.type == "multi_node" else 1
|
||||
log_message = format_log_message(log_dir=log_dir, trainer=True, num_train_nodes=num_nodes)
|
||||
|
||||
@@ -113,8 +118,8 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = get_config_dir(config.output_dir)
|
||||
config_path = config_dir / SFT_TOML
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
write_config(config, config_path)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
@@ -122,8 +127,7 @@ def sft_local(config: SFTConfig):
|
||||
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
log_dir = config.output_dir / "logs"
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
log_dir = create_attempt_log_dir(config.run_dir)
|
||||
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
@@ -132,7 +136,7 @@ def sft_local(config: SFTConfig):
|
||||
"--role=trainer",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
f"--log-dir={config.output_dir / 'logs' / 'trainer' / 'torchrun'}",
|
||||
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
|
||||
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
@@ -140,7 +144,7 @@ def sft_local(config: SFTConfig):
|
||||
"-m",
|
||||
"prime_rl.trainer.sft.train",
|
||||
"@",
|
||||
(config_dir / SFT_TOML).as_posix(),
|
||||
(config_dir / SFT_CONFIG).as_posix(),
|
||||
]
|
||||
|
||||
logger.info(f"Starting SFT trainer with {config.deployment.num_gpus} GPU(s)")
|
||||
@@ -206,15 +210,15 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
|
||||
def sft(config: SFTConfig):
|
||||
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
|
||||
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
|
||||
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
|
||||
config.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
resuming = config.resume is not None
|
||||
clean = config.clean and not os.environ.get("NEVER_CLEAN")
|
||||
validate_run_dir(config.run_dir, output_dir=config.output_dir, resuming=resuming, clean=clean)
|
||||
config.run_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if not config.dry_run:
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
|
||||
pre_download_model(config.model.name)
|
||||
pre_download_model(config.model.name, skip_weights=config.model.debug.random_init)
|
||||
|
||||
if config.slurm is not None:
|
||||
sft_slurm(config)
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Metric monitors.
|
||||
|
||||
Monitors are registered once per process via ``setup`` and used through the
|
||||
module-level functions (``log``, ``finalize``, ...), which fan out to every
|
||||
registered monitor. Fan-out never raises — a monitoring failure must not take
|
||||
down training.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, overload
|
||||
|
||||
from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig, WandbMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.monitors.file import FileMonitor
|
||||
from prime_rl.monitors.prime import PrimeMonitor
|
||||
from prime_rl.monitors.wandb import WandbMonitor
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
__all__ = [
|
||||
"Monitor",
|
||||
"WandbMonitor",
|
||||
"PrimeMonitor",
|
||||
"FileMonitor",
|
||||
"setup",
|
||||
"get",
|
||||
"log",
|
||||
"finalize",
|
||||
]
|
||||
|
||||
# All monitors registered for the current run.
|
||||
MONITORS: list[Monitor] = []
|
||||
|
||||
|
||||
async def setup(
|
||||
wandb: WandbMonitorConfig | None = None,
|
||||
prime: PrimeMonitorConfig | None = None,
|
||||
file: FileMonitorConfig | None = None,
|
||||
*,
|
||||
output_dir: Path,
|
||||
run_config: BaseConfig | None = None,
|
||||
train_env_names: list[str] | None = None,
|
||||
eval_env_names: list[str] | None = None,
|
||||
) -> None:
|
||||
"""Construct, initialize, and register one monitor per non-None config.
|
||||
|
||||
Only rank 0 registers monitors — on other ranks the fan-out functions are
|
||||
no-ops. A monitor whose ``init`` raises crashes the run: a configured
|
||||
monitor must work.
|
||||
"""
|
||||
assert not MONITORS, "Monitors already set up. Call `setup` only once per process."
|
||||
rank = int(os.environ.get("RANK", os.environ.get("DP_RANK", "0")))
|
||||
if rank != 0:
|
||||
return
|
||||
|
||||
monitors: list[tuple[Monitor, dict[str, Any]]] = []
|
||||
if prime is not None:
|
||||
monitors.append((PrimeMonitor(prime), dict(config=run_config)))
|
||||
if wandb is not None:
|
||||
monitors.append(
|
||||
(
|
||||
WandbMonitor(wandb),
|
||||
dict(
|
||||
output_dir=output_dir,
|
||||
config=run_config,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
),
|
||||
)
|
||||
)
|
||||
if file is not None:
|
||||
monitors.append((FileMonitor(file), dict(output_dir=output_dir)))
|
||||
|
||||
for monitor, init_kwargs in monitors:
|
||||
await monitor.init(**init_kwargs)
|
||||
MONITORS.append(monitor)
|
||||
|
||||
|
||||
def get(monitor_cls: type[Monitor]) -> Monitor | None:
|
||||
"""The registered monitor of the given type, None when it isn't running
|
||||
(not configured, or a non-zero rank)."""
|
||||
return next((monitor for monitor in MONITORS if isinstance(monitor, monitor_cls)), None)
|
||||
|
||||
|
||||
@overload
|
||||
async def log(data: dict[str, Any], step: int) -> None: ...
|
||||
|
||||
|
||||
@overload
|
||||
async def log(data: vf.Episode | list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None: ...
|
||||
|
||||
|
||||
async def log(
|
||||
data: dict[str, Any] | vf.Episode | list[vf.Episode],
|
||||
step: int,
|
||||
kind: Kind = "train",
|
||||
subset: Subset = "effective",
|
||||
) -> None:
|
||||
"""Log to all registered monitors: a dict of scalar metrics, or episodes
|
||||
with their cohort coordinates (train/eval x all/effective)."""
|
||||
for monitor in MONITORS:
|
||||
try:
|
||||
await monitor.log(data, step=step, kind=kind, subset=subset)
|
||||
except Exception as e:
|
||||
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
|
||||
|
||||
|
||||
async def finalize() -> None:
|
||||
"""Finalize the run on all registered monitors."""
|
||||
for monitor in MONITORS:
|
||||
try:
|
||||
await monitor.finalize()
|
||||
except Exception as e:
|
||||
get_logger().warning(f"Failed to finalize {monitor.__class__.__name__}: {e}")
|
||||
@@ -0,0 +1,55 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import TYPE_CHECKING, Any, Literal, overload
|
||||
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
Kind = Literal["train", "eval"]
|
||||
Subset = Literal["all", "effective"]
|
||||
|
||||
|
||||
class Monitor(ABC):
|
||||
"""Base class for monitors."""
|
||||
|
||||
def __init__(self, config: BaseConfig):
|
||||
self.config = config
|
||||
self.logger = get_logger()
|
||||
|
||||
async def init(self, **kwargs: Any) -> None:
|
||||
"""Initialize run. Overrides name their own kwargs."""
|
||||
|
||||
@overload
|
||||
async def log(self, data: dict[str, Any], step: int) -> None: ...
|
||||
|
||||
@overload
|
||||
async def log(self, data: vf.Episode | list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None: ...
|
||||
|
||||
async def log(
|
||||
self,
|
||||
data: dict[str, Any] | vf.Episode | list[vf.Episode],
|
||||
step: int,
|
||||
kind: Kind = "train",
|
||||
subset: Subset = "effective",
|
||||
) -> None:
|
||||
"""Log scalar metrics, or episodes."""
|
||||
if isinstance(data, dict):
|
||||
await self.log_metrics(data, step=step)
|
||||
else:
|
||||
episodes = data if isinstance(data, list) else [data]
|
||||
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."""
|
||||
|
||||
@abstractmethod
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
"""Log episodes."""
|
||||
|
||||
async def finalize(self) -> None:
|
||||
"""Finalize run."""
|
||||
@@ -0,0 +1,62 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, TextIO
|
||||
|
||||
import orjson
|
||||
|
||||
from prime_rl.configs.monitors import FileMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.utils.utils import sanitize
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
|
||||
class FileMonitor(Monitor):
|
||||
"""Logs metrics and episodes to local JSONL files."""
|
||||
|
||||
config: FileMonitorConfig
|
||||
file: TextIO
|
||||
|
||||
async def init(self, output_dir: Path) -> None:
|
||||
self.output_dir = output_dir
|
||||
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 to {self.path} and traces to {output_dir / 'rollouts'}")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
sanitized, dropped = sanitize(metrics)
|
||||
if dropped:
|
||||
self.logger.warning(
|
||||
f"Dropping {len(dropped)} non-finite value(s) from {self.config.path}: {', '.join(dropped[:5])}"
|
||||
)
|
||||
|
||||
row = {"step": step, "time": time.time(), **sanitized}
|
||||
self.file.write(json.dumps(row) + "\n")
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
"""Append the cohort's traces to its per-step trace file. ``all`` grows one
|
||||
episode at a time as they complete, ``effective`` one batch at a time on finalize,
|
||||
so an in-progress run's traces can be inspected live."""
|
||||
|
||||
def write() -> None:
|
||||
path = self.output_dir / "rollouts" / f"step_{step}" / kind / subset / "traces.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
|
||||
with open(path, "ab") as f:
|
||||
for episode in episodes:
|
||||
for trace in episode.traces:
|
||||
f.write(orjson.dumps(trace.to_record(), default=str, option=opts))
|
||||
|
||||
# Record serialization is heavy pure-Python work; keep it off the event loop.
|
||||
# Awaited (not fire-and-forget) so appends to one file never interleave.
|
||||
await asyncio.to_thread(write)
|
||||
|
||||
async def finalize(self) -> None:
|
||||
self.logger.info(f"Finalized metrics at {self.path}")
|
||||
@@ -0,0 +1,325 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import atexit
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Coroutine
|
||||
|
||||
import httpx
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import verifiers.v1 as vf
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from verifiers.v1.utils.platform import build_samples
|
||||
|
||||
from prime_rl.configs.monitors import PrimeMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import sanitize
|
||||
|
||||
BASE_URL = "https://api.primeintellect.ai/api/v1/rft"
|
||||
API_KEY_VAR = "PRIME_API_KEY"
|
||||
|
||||
SAMPLE_SCHEMA = pa.schema(
|
||||
[
|
||||
("run_id", pa.string()),
|
||||
("step", pa.int64()),
|
||||
("tag", pa.string()),
|
||||
("problem_id", pa.int64()),
|
||||
("sample_id", pa.int64()),
|
||||
("prompt", pa.string()),
|
||||
("completion", pa.string()),
|
||||
("trajectory", pa.string()),
|
||||
("answer", pa.string()),
|
||||
("env_name", pa.string()),
|
||||
("task", pa.string()),
|
||||
("info", pa.string()),
|
||||
("reward", pa.float64()),
|
||||
("advantage", pa.float64()),
|
||||
("metrics", pa.string()),
|
||||
("timing", pa.string()),
|
||||
("num_input_tokens", pa.int64()),
|
||||
("num_output_tokens", pa.int64()),
|
||||
("created_at", pa.timestamp("us", tz="UTC")),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
class PrimeMonitor(Monitor):
|
||||
"""Logs metrics and episodes to the Prime platform.
|
||||
|
||||
Uploads are fire-and-forget tasks on the caller's event loop — the prime
|
||||
monitor only runs in the orchestrator, whose call sites are all async. The
|
||||
platform calls and the episode serialization run in worker threads via
|
||||
``asyncio.to_thread``, so they never stall the loop.
|
||||
"""
|
||||
|
||||
config: PrimeMonitorConfig
|
||||
|
||||
async def init(self, config: BaseConfig | None = None) -> None:
|
||||
api_key = os.getenv(API_KEY_VAR) or PrimeConfig().api_key
|
||||
if not api_key:
|
||||
raise RuntimeError(f"API key not found - set {API_KEY_VAR} or run `prime login`")
|
||||
self.run = TrainRun(api_key)
|
||||
if run_id := os.getenv("RUN_ID"):
|
||||
# A managed launch pre-created the platform run and injected its id -
|
||||
# attach instead of registering a duplicate. The backend owns the run's
|
||||
# failure marking then; finalize still marks it completed on clean exit.
|
||||
self.run.id = run_id
|
||||
self.logger.info(f"Logging metrics and episodes to platform run {run_id} (attached via $RUN_ID)")
|
||||
return
|
||||
run_fields: dict[str, Any] = {}
|
||||
if config is not None:
|
||||
run_fields = dict(
|
||||
base_model=config.model.name,
|
||||
max_steps=config.max_steps or 0,
|
||||
batch_size=config.batch_size,
|
||||
rollouts_per_example=config.group_size,
|
||||
seq_len=config.seq_len,
|
||||
environments=[env.env_id for env in config.train.source],
|
||||
run_config=config.model_dump(exclude_none=True, mode="json"),
|
||||
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
|
||||
)
|
||||
await self.run.create(name=self.config.name, **run_fields)
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
metrics, dropped = sanitize(metrics)
|
||||
if dropped:
|
||||
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
|
||||
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:
|
||||
"""Upload one platform sample per episode via the presigned-URL Parquet flow.
|
||||
Only the trained cohort ships to the platform."""
|
||||
# Upload every 10th step, unsampled - the pre-refactor cadence - to not
|
||||
# overwhelm the platform's ingestion. TODO: Lift once we integrate the
|
||||
# prime traces SDK.
|
||||
if kind != "train" or subset != "effective" or not episodes or step % 10 != 0:
|
||||
return
|
||||
|
||||
async def upload() -> None:
|
||||
# Serialization dumps every episode's full model - heavy pure-Python work
|
||||
# that would stall the event loop (and with it dispatch) if run inline.
|
||||
parquet_bytes = await asyncio.to_thread(episodes_to_parquet_bytes, episodes, self.run.id, step)
|
||||
if parquet_bytes is not None:
|
||||
await self.run.upload_samples(parquet_bytes, step)
|
||||
|
||||
self.run.submit(f"episodes upload at step {step}", upload())
|
||||
|
||||
async def finalize(self) -> None:
|
||||
await self.run.finalize()
|
||||
|
||||
|
||||
class TrainRun:
|
||||
"""A training run on the Prime platform's RFT API.
|
||||
|
||||
Owns the HTTP client and the run lifecycle (create, log, finalize) — the
|
||||
natural seam to be subsumed by the train SDK, and it mirrors ``wandb.Run``'s
|
||||
exit behavior: a created run that is never finalized is marked failed at
|
||||
process exit via an atexit hook that ``finalize`` disarms. Fully async,
|
||||
except the atexit hook itself — at interpreter shutdown there is no event
|
||||
loop, so it sends one synchronous request.
|
||||
"""
|
||||
|
||||
def __init__(self, api_key: str):
|
||||
self.id: str | None = None
|
||||
self.logger = get_logger()
|
||||
self._tasks: set[asyncio.Task] = set()
|
||||
self.headers = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"x-api-key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
self.client = httpx.AsyncClient(
|
||||
base_url=BASE_URL,
|
||||
headers=self.headers,
|
||||
timeout=30,
|
||||
transport=httpx.AsyncHTTPTransport(retries=3),
|
||||
)
|
||||
|
||||
def submit(self, what: str, request: Coroutine[Any, Any, None]) -> None:
|
||||
"""Run a request as a fire-and-forget task; a failure only warns. The task set
|
||||
keeps strong references - the loop alone won't."""
|
||||
|
||||
async def guarded() -> None:
|
||||
try:
|
||||
await request
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed {what}: {type(e).__name__}: {e}")
|
||||
|
||||
task = asyncio.get_running_loop().create_task(guarded())
|
||||
self._tasks.add(task)
|
||||
task.add_done_callback(self._tasks.discard)
|
||||
|
||||
async def create(
|
||||
self,
|
||||
name: str | None = None,
|
||||
team_id: str | None = None,
|
||||
base_model: str = "unknown",
|
||||
max_steps: int = 0,
|
||||
batch_size: int | None = None,
|
||||
rollouts_per_example: int | None = None,
|
||||
seq_len: int | None = None,
|
||||
environments: list[str] | None = None,
|
||||
run_config: dict[str, Any] | None = None,
|
||||
wandb_project: str | None = None,
|
||||
) -> str:
|
||||
"""Register the run with the platform and return its id."""
|
||||
prime_config = PrimeConfig()
|
||||
team_id = team_id or prime_config.team_id
|
||||
|
||||
payload: dict[str, Any] = {"base_model": base_model, "max_steps": max_steps}
|
||||
if batch_size is not None:
|
||||
payload["batch_size"] = batch_size
|
||||
if rollouts_per_example is not None:
|
||||
payload["rollouts_per_example"] = rollouts_per_example
|
||||
if seq_len is not None:
|
||||
payload["seq_len"] = seq_len
|
||||
if environments is not None:
|
||||
payload["environments"] = [{"id": env_id} for env_id in environments]
|
||||
if run_config is not None:
|
||||
payload["run_config"] = run_config
|
||||
if wandb_project is not None:
|
||||
payload["wandb_project"] = wandb_project
|
||||
if name:
|
||||
payload["name"] = name
|
||||
if team_id:
|
||||
payload["team_id"] = team_id
|
||||
|
||||
response = await self.client.post("/external-runs", json=payload)
|
||||
if response.status_code != 201:
|
||||
raise RuntimeError(f"Failed to create platform run (HTTP {response.status_code}): {response.text}")
|
||||
|
||||
self.id = response.json()["run"]["id"]
|
||||
self._owner_pid = os.getpid()
|
||||
atexit.register(self._mark_failed)
|
||||
if prime_config.frontend_url:
|
||||
self.logger.info(
|
||||
f"Logging metrics and episodes to platform run {self.id} ({prime_config.frontend_url.rstrip('/')}/dashboard/training/{self.id})"
|
||||
)
|
||||
else:
|
||||
self.logger.info(f"Logging metrics and episodes to platform run {self.id}")
|
||||
return self.id
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any]) -> None:
|
||||
(await self.client.post("/metrics", json={"run_id": self.id, "metrics": metrics})).raise_for_status()
|
||||
|
||||
async def upload_samples(self, parquet_bytes: bytes, step: int) -> None:
|
||||
"""Presigned-URL flow: presign -> R2 PUT -> confirm."""
|
||||
presign = await self.client.post("/samples/presign", json={"run_id": self.id, "step": step})
|
||||
presign.raise_for_status()
|
||||
data = presign.json()["data"]
|
||||
# Bare client - the presigned URL rejects the run client's auth headers.
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
put = await client.put(
|
||||
data["presignedUrl"], content=parquet_bytes, headers={"Content-Type": "application/parquet"}
|
||||
)
|
||||
put.raise_for_status()
|
||||
confirm = await self.client.post(
|
||||
"/samples/confirm", json={"run_id": self.id, "step": step, "s3_key": data["s3Key"]}
|
||||
)
|
||||
confirm.raise_for_status()
|
||||
|
||||
async def finalize(self) -> None:
|
||||
"""Finalize the run as completed."""
|
||||
self.logger.info(f"Finalizing platform run {self.id}")
|
||||
# Drain in-flight uploads so the final step's metrics and episodes land
|
||||
# before the run is marked completed.
|
||||
await asyncio.gather(*self._tasks, return_exceptions=True)
|
||||
try:
|
||||
(await self.client.post("/finalize", json={"run_id": self.id, "summary": {}})).raise_for_status()
|
||||
except httpx.HTTPError as e:
|
||||
self.logger.warning(f"Failed to finalize platform run {self.id}: {e}")
|
||||
await self.set_status(success=True)
|
||||
atexit.unregister(self._mark_failed)
|
||||
|
||||
def _mark_failed(self) -> None:
|
||||
# Forked children inherit the atexit table; only the creating process may
|
||||
# flip the run's status. At interpreter shutdown there is no event loop and
|
||||
# no executor for async DNS, so this path must stay synchronous.
|
||||
if os.getpid() != self._owner_pid:
|
||||
return
|
||||
self.logger.info(f"Marking platform run {self.id} as failed")
|
||||
try:
|
||||
httpx.put(
|
||||
f"{BASE_URL}/external-runs/{self.id}/status",
|
||||
headers=self.headers,
|
||||
json={"status": "failed"},
|
||||
timeout=30,
|
||||
).raise_for_status()
|
||||
except httpx.HTTPError as e:
|
||||
self.logger.warning(f"Failed to mark platform run {self.id} as failed: {e}")
|
||||
|
||||
async def set_status(self, success: bool) -> None:
|
||||
"""Mark the run as completed or failed."""
|
||||
status = "completed" if success else "failed"
|
||||
self.logger.info(f"Marking platform run {self.id} as {status}")
|
||||
try:
|
||||
put = await self.client.put(f"/external-runs/{self.id}/status", json={"status": status})
|
||||
put.raise_for_status()
|
||||
except httpx.HTTPError as e:
|
||||
self.logger.warning(f"Failed to mark platform run {self.id} as {status}: {e}")
|
||||
|
||||
|
||||
def episodes_to_parquet_bytes(episodes: list[vf.Episode], run_id: str | None, step: int) -> bytes | None:
|
||||
"""One row per episode. Sample construction is shared with verifiers' eval
|
||||
``--push`` (``build_samples``: complete native episode in ``info.native_wrapper``,
|
||||
flat summary from one trainable trace), so a training episode and an eval sample
|
||||
land on the platform identically; the RFT-only columns (run/step/advantage/
|
||||
problem_id/env_name) are layered on here."""
|
||||
advantages: dict[str, float | None] = {}
|
||||
env_names: dict[str, str] = {}
|
||||
for episode in episodes:
|
||||
summary_trace = next((trace for trace in episode.traces if trace.agent.trainable), episode.traces[0])
|
||||
advantages[episode.id] = summary_trace.scalar_advantage()
|
||||
env_names[episode.id] = episode.env.id
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
rows = []
|
||||
for sample_id, sample in enumerate(build_samples(episodes)):
|
||||
trajectory = sample["trajectory"]
|
||||
if not trajectory: # no branches (e.g. an episode that errored before any message)
|
||||
continue
|
||||
advantage = advantages.get(sample["episode_id"])
|
||||
trajectory = [{**branch, "advantage": advantage} for branch in trajectory]
|
||||
|
||||
try:
|
||||
problem_id = int(sample["example_id"]) if sample["example_id"] is not None else sample_id
|
||||
except (TypeError, ValueError):
|
||||
problem_id = sample_id
|
||||
|
||||
rows.append(
|
||||
{
|
||||
"run_id": run_id,
|
||||
"step": step,
|
||||
"tag": "",
|
||||
"problem_id": problem_id,
|
||||
"sample_id": sample_id,
|
||||
"prompt": "",
|
||||
"completion": json.dumps(sample["completion"]),
|
||||
"trajectory": json.dumps(trajectory),
|
||||
"answer": "",
|
||||
"env_name": env_names.get(sample["episode_id"], ""),
|
||||
"task": json.dumps(sample["task"]),
|
||||
"info": json.dumps(sample["info"]),
|
||||
"reward": sample["reward"],
|
||||
"advantage": advantage,
|
||||
"metrics": json.dumps(sample["metrics"]),
|
||||
"timing": json.dumps(sample["timing"]),
|
||||
"num_input_tokens": trajectory[-1]["num_input_tokens"],
|
||||
"num_output_tokens": trajectory[-1]["num_output_tokens"],
|
||||
"created_at": now,
|
||||
}
|
||||
)
|
||||
|
||||
if not rows:
|
||||
return None
|
||||
|
||||
table = pa.Table.from_pylist(rows, schema=SAMPLE_SCHEMA)
|
||||
buf = io.BytesIO()
|
||||
pq.write_table(table, buf, compression="snappy", use_dictionary=True, write_statistics=True)
|
||||
return buf.getvalue()
|
||||
@@ -0,0 +1,3 @@
|
||||
from prime_rl.monitors.wandb.monitor import WandbMonitor
|
||||
|
||||
__all__ = ["WandbMonitor"]
|
||||
@@ -0,0 +1,138 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import wandb
|
||||
from wandb.errors import CommError
|
||||
from wandb.sdk.mailbox.mailbox_handle import ServerResponseError
|
||||
|
||||
from prime_rl.configs.monitors import WandbMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.monitors.wandb.overview import ensure_overview_view
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
|
||||
class WandbMonitor(Monitor):
|
||||
"""Logs metrics to Weights and Biases."""
|
||||
|
||||
config: WandbMonitorConfig
|
||||
|
||||
async def init(
|
||||
self,
|
||||
output_dir: Path,
|
||||
config: BaseConfig | None = None,
|
||||
train_env_names: list[str] | None = None,
|
||||
eval_env_names: list[str] | None = None,
|
||||
) -> None:
|
||||
# W&B reads the start command off sys.argv; the launcher passes the original
|
||||
# command to subprocesses via $WANDB_ARGS.
|
||||
wandb_args = os.environ.get("WANDB_ARGS")
|
||||
if wandb_args:
|
||||
self.logger.debug(f"Found WANDB_ARGS in environment variables {wandb_args}")
|
||||
sys.argv = json.loads(wandb_args)
|
||||
|
||||
# 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 (
|
||||
"disabled",
|
||||
"offline",
|
||||
)
|
||||
if shared_mode:
|
||||
# W&B's native run-id var, set by the launcher to $PRL_RUN_ID.
|
||||
run_id = os.environ.get("WANDB_RUN_ID")
|
||||
label = os.environ.get("WANDB_SHARED_LABEL")
|
||||
primary = label == "orchestrator"
|
||||
settings = wandb.Settings(
|
||||
mode="shared",
|
||||
x_label=label,
|
||||
x_primary=primary,
|
||||
x_update_finish_state=primary,
|
||||
)
|
||||
self.logger.info(f"Using shared W&B mode ({label=}, {primary=})")
|
||||
is_online = True
|
||||
else:
|
||||
run_id = None
|
||||
primary = False
|
||||
mode = os.environ.get("WANDB_MODE", "offline" if self.config.offline else "online")
|
||||
settings = wandb.Settings(mode=mode)
|
||||
is_online = mode == "online"
|
||||
|
||||
retryable_errors = (CommError, ServerResponseError) if shared_mode else (CommError,)
|
||||
|
||||
def init_wandb(max_retries: int):
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
return wandb.init(
|
||||
id=run_id,
|
||||
resume="allow" if run_id else None,
|
||||
project=self.config.project,
|
||||
entity=self.config.entity,
|
||||
name=self.config.name,
|
||||
group=self.config.group,
|
||||
tags=self.config.tags,
|
||||
dir=output_dir,
|
||||
config=config.model_dump() if config else None,
|
||||
settings=settings,
|
||||
)
|
||||
except retryable_errors as e:
|
||||
if attempt + 1 == max_retries:
|
||||
raise
|
||||
if shared_mode and not primary:
|
||||
msg = (
|
||||
f"Shared W&B run not yet created by primary - retrying in 10s ({attempt + 1}/{max_retries})"
|
||||
)
|
||||
else:
|
||||
msg = f"Transient W&B init error ({e}) - retrying in 10s ({attempt + 1}/{max_retries})"
|
||||
self.logger.info(msg)
|
||||
# A failed wandb.init leaves the run_id registered in the local
|
||||
# wandb-core StreamMux, causing the next attempt to fail with
|
||||
# "run ID ... is in use". Tear down the service so the retry
|
||||
# starts from a clean state.
|
||||
wandb.teardown()
|
||||
time.sleep(10)
|
||||
|
||||
# Non-primary processes in shared mode wait for the primary to create the run.
|
||||
# Everyone else still retries to absorb transient W&B server errors (e.g. 404 on upsertBucket).
|
||||
max_retries = 30 if shared_mode and not primary else 5
|
||||
self.wandb = init_wandb(max_retries)
|
||||
|
||||
wandb.define_metric("*", step_metric="step")
|
||||
|
||||
# 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
|
||||
# take down training.
|
||||
if is_online and (primary if shared_mode else True):
|
||||
try:
|
||||
url = ensure_overview_view(
|
||||
self.wandb.entity,
|
||||
self.wandb.project,
|
||||
train_envs=train_env_names or [],
|
||||
eval_envs=eval_env_names or [],
|
||||
)
|
||||
if url:
|
||||
self.logger.info(f"Created W&B overview view - {url}")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to create W&B overview view - {e}")
|
||||
|
||||
self.logger.info(f"Logging metrics to W&B run {self.wandb.id} ({self.wandb.url})")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
wandb.log({**metrics, "step": step})
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
pass
|
||||
|
||||
async def finalize(self) -> None:
|
||||
self.logger.info(f"Finalizing W&B run {self.wandb.id}")
|
||||
# Explicit finish: in (experimental) shared mode the SDK's atexit finish does
|
||||
# not land the run state - without this, even clean runs decay to "crashed".
|
||||
await asyncio.to_thread(wandb.finish, exit_code=0)
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Curated "overview" W&B saved view.
|
||||
|
||||
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
|
||||
its raw metric name.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Sequence
|
||||
|
||||
import wandb
|
||||
import wandb_workspaces.reports.v2 as wr
|
||||
import wandb_workspaces.workspaces as ws
|
||||
from wandb_gql import gql
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
OVERVIEW_NAME = "overview"
|
||||
|
||||
# Rollout metrics (under "<scope>/") shown for BOTH train and eval. Quality metrics read the
|
||||
# effective subset — the all subset includes errored rollouts, whose zero values skew the
|
||||
# distributions. has_error only exists on all (effective drops errors by construction). The count
|
||||
# metrics are episode-level exact keys; the trace-level metrics (reward, truncation, errors) live
|
||||
# under the per-agent subtree, whose names are data-dependent — matched by regex, one panel per
|
||||
# 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 = [
|
||||
"effective/num_total_tokens/mean",
|
||||
"effective/num_turns/mean",
|
||||
"effective/num_branches/mean",
|
||||
]
|
||||
COMMON_REGEXES = [
|
||||
"all/[^/]+/has_error/mean",
|
||||
"effective/[^/]+/is_truncated/mean",
|
||||
]
|
||||
|
||||
STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"]
|
||||
|
||||
PERFORMANCE_METRICS = [
|
||||
"perf/mfu",
|
||||
"time/step",
|
||||
"time/wait_for_batch",
|
||||
"time/wait_for_policy",
|
||||
]
|
||||
|
||||
# Inference health panels: each pairs the fleet aggregate (mean/sum) with the cross-engine
|
||||
# tail that flags a single sick engine - max for pressure metrics, min for health metrics.
|
||||
# One saturated engine thrashing its KV cache (preempt -> re-prefill -> cache eviction) hides
|
||||
# inside fleet means; the max/min series is what surfaces it.
|
||||
INFERENCE_PANELS = [
|
||||
[
|
||||
"inference/agg/kv_cache_usage_perc/mean",
|
||||
"inference/agg/kv_cache_usage_perc/min",
|
||||
"inference/agg/kv_cache_usage_perc/max",
|
||||
],
|
||||
["inference/agg/num_preemptions_total:rate/sum", "inference/agg/num_preemptions_total:rate/max"],
|
||||
[
|
||||
"inference/agg/num_requests_running/mean",
|
||||
"inference/agg/num_requests_running/min",
|
||||
"inference/agg/num_requests_running/max",
|
||||
],
|
||||
[
|
||||
"inference/agg/num_requests_waiting/mean",
|
||||
"inference/agg/num_requests_waiting/min",
|
||||
"inference/agg/num_requests_waiting/max",
|
||||
],
|
||||
["inference/agg/prefix_cache_hit_rate/pooled", "inference/agg/prefix_cache_hit_rate/min"],
|
||||
["inference/agg/generation_tokens_total:rate/sum", "inference/agg/generation_tokens_total:rate/min"],
|
||||
["inference/agg/prompt_tokens_total:rate/sum", "inference/agg/prompt_tokens_total:rate/max"],
|
||||
]
|
||||
|
||||
# Dense grid: more, smaller panels per row and enough rows that sections don't paginate.
|
||||
COLUMNS = 4
|
||||
ROWS = 6
|
||||
|
||||
|
||||
def line_panels(metrics: Sequence[str], regexes: Sequence[str]) -> list[wr.LinePlot]:
|
||||
# inference/* is logged against time (step_metric="_timestamp"), plotted on "RelativeTime(Wall)"
|
||||
# (== W&B's "_absolute_runtime", seconds since run start) so runs started at different times
|
||||
# overlay; everything else on "step" (prime-rl's logged training step, not internal "Step").
|
||||
# x is set per-panel because LinePlot defaults it to "Step", which overrides the workspace x_axis.
|
||||
return [wr.LinePlot(x="RelativeTime(Wall)" if m.startswith("inference/") else "step", y=[m]) for m in metrics] + [
|
||||
wr.LinePlot(x="step", metric_regex=r) for r in regexes
|
||||
]
|
||||
|
||||
|
||||
def inference_section() -> ws.Section:
|
||||
# Multi-series panels (aggregate + tail), on wall time like all inference/* metrics.
|
||||
return ws.Section(
|
||||
name="inference",
|
||||
is_open=True,
|
||||
panels=[wr.LinePlot(x="RelativeTime(Wall)", y=list(series)) for series in INFERENCE_PANELS],
|
||||
layout_settings=ws.SectionLayoutSettings(columns=COLUMNS, rows=ROWS),
|
||||
)
|
||||
|
||||
|
||||
def section(name: str, metrics: Sequence[str] = (), regexes: Sequence[str] = ()) -> ws.Section:
|
||||
return ws.Section(
|
||||
name=name,
|
||||
is_open=True,
|
||||
panels=line_panels(metrics, regexes),
|
||||
layout_settings=ws.SectionLayoutSettings(columns=COLUMNS, rows=ROWS),
|
||||
)
|
||||
|
||||
|
||||
def train_section(name: str, scope: str) -> ws.Section:
|
||||
# Env names may carry regex metacharacters (e.g. "+"), so the scope is escaped in the
|
||||
# regex-matched per-agent panels.
|
||||
pattern = re.escape(scope)
|
||||
return section(
|
||||
name,
|
||||
metrics=[f"{scope}/{m}" for m in COMMON_METRICS],
|
||||
regexes=[f"{pattern}/all/[^/]+/reward/mean", f"{pattern}/effective/[^/]+/reward/mean"]
|
||||
+ [f"{pattern}/{r}" for r in COMMON_REGEXES],
|
||||
)
|
||||
|
||||
|
||||
def eval_section(name: str, env_pattern: str) -> ws.Section:
|
||||
# Same metrics as train, but eval's reward is the per-agent "avg@k" (dynamic k → regex).
|
||||
# Everything is a regex so one section can also serve any env (env_pattern=".*").
|
||||
return section(
|
||||
name,
|
||||
regexes=[f"eval/{env_pattern}/all/[^/]+/avg@.*", f"eval/{env_pattern}/effective/[^/]+/avg@.*"]
|
||||
+ [f"eval/{env_pattern}/{m}" for m in COMMON_METRICS]
|
||||
+ [f"eval/{env_pattern}/{r}" for r in COMMON_REGEXES],
|
||||
)
|
||||
|
||||
|
||||
def build_sections(train_envs: Sequence[str] = (), eval_envs: Sequence[str] = ()) -> list[ws.Section]:
|
||||
# With one env the aggregate == that env, so show only its section. With several, put the
|
||||
# cross-env aggregate on top followed by a section per env.
|
||||
if len(train_envs) == 1:
|
||||
sections = [train_section(f"train/{train_envs[0]}", f"train/{train_envs[0]}")]
|
||||
elif len(train_envs) > 1:
|
||||
sections = [train_section("train/agg", "train/agg")]
|
||||
sections += [train_section(f"train/{env}", f"train/{env}") for env in train_envs]
|
||||
else:
|
||||
# Env names unknown (e.g. SFT): fall back to the aggregate.
|
||||
sections = [train_section("train", "train/agg")]
|
||||
if eval_envs:
|
||||
sections += [eval_section(f"eval/{env}", re.escape(env)) for env in eval_envs]
|
||||
else:
|
||||
# Env names unknown (e.g. SFT): one regex section matching any eval env.
|
||||
sections.append(eval_section("eval", ".*"))
|
||||
sections.append(section("stability", metrics=STABILITY_METRICS))
|
||||
sections.append(inference_section())
|
||||
sections.append(section("performance", metrics=PERFORMANCE_METRICS))
|
||||
return sections
|
||||
|
||||
|
||||
def list_views(entity: str, project: str) -> list[tuple[str, str]]:
|
||||
"""``(display_name, internal_name)`` for every saved view in the project."""
|
||||
query = gql(
|
||||
"""
|
||||
query Views($entity: String!, $project: String!) {
|
||||
project(name: $project, entityName: $entity) {
|
||||
allViews(viewType: "project-view") { edges { node { name displayName } } }
|
||||
}
|
||||
}
|
||||
"""
|
||||
)
|
||||
res = wandb.Api().client.execute(query, variable_values={"entity": entity, "project": project})
|
||||
edges = ((res.get("project") or {}).get("allViews") or {}).get("edges") or []
|
||||
return [(e["node"]["displayName"], e["node"]["name"]) for e in edges if e.get("node")]
|
||||
|
||||
|
||||
def view_signature(sections: Sequence[ws.Section]) -> tuple:
|
||||
train = sorted(s.name[len("train/") :] for s in sections if s.name.startswith("train/") and s.name != "train/agg")
|
||||
evals = sorted(s.name[len("eval/") :] for s in sections if s.name.startswith("eval/"))
|
||||
panels = {
|
||||
(getattr(p.x, "name", p.x), tuple(getattr(m, "name", m) for m in p.y or ()), p.metric_regex)
|
||||
for s in sections
|
||||
for p in s.panels
|
||||
if isinstance(p, wr.LinePlot)
|
||||
}
|
||||
return (tuple(train), tuple(evals), tuple(sorted(panels, key=str)))
|
||||
|
||||
|
||||
def next_overview_name(base: str, existing: Sequence[str]) -> str:
|
||||
if base not in existing:
|
||||
return base
|
||||
prefix = f"{base}-v"
|
||||
versions = [1] + [int(n[len(prefix) :]) for n in existing if n.startswith(prefix) and n[len(prefix) :].isdigit()]
|
||||
return f"{base}-v{max(versions) + 1}"
|
||||
|
||||
|
||||
def ensure_overview_view(
|
||||
entity: str,
|
||||
project: str,
|
||||
name: str = OVERVIEW_NAME,
|
||||
train_envs: Sequence[str] = (),
|
||||
eval_envs: Sequence[str] = (),
|
||||
) -> str | None:
|
||||
"""Ensure an overview saved view exists for this run's env set. Reuses an existing overview built
|
||||
for the same envs; when the env set is new, creates a fresh versioned view (``overview`` →
|
||||
``overview-v2`` → …). Returns the URL of a newly created view, else None."""
|
||||
sections = build_sections(train_envs, eval_envs)
|
||||
target = view_signature(sections)
|
||||
overviews = [(dn, iname) for dn, iname in list_views(entity, project) if dn == name or dn.startswith(f"{name}-v")]
|
||||
for _, internal_name in overviews:
|
||||
slug = internal_name.removeprefix("nw-").removesuffix("-v")
|
||||
try:
|
||||
existing = ws.Workspace.from_url(f"https://wandb.ai/{entity}/{project}?nw={slug}")
|
||||
matches = view_signature(existing.sections) == target
|
||||
except Exception as e:
|
||||
# A single unreadable view must not abort reuse detection / versioning for the rest.
|
||||
get_logger().warning(f"Could not inspect overview view {internal_name} - {e}")
|
||||
continue
|
||||
if matches:
|
||||
return None
|
||||
workspace = ws.Workspace(
|
||||
entity=entity,
|
||||
project=project,
|
||||
name=next_overview_name(name, [dn for dn, _ in overviews]),
|
||||
sections=sections,
|
||||
auto_generate_panels=False,
|
||||
settings=ws.WorkspaceSettings(x_axis="step"),
|
||||
)
|
||||
workspace.save()
|
||||
return workspace.url
|
||||
@@ -47,8 +47,10 @@ class CheckpointManager:
|
||||
f"Orchestrator checkpoint saved to {ckpt_path} in {format_time(time.perf_counter() - start)}"
|
||||
)
|
||||
|
||||
def load(self, progress: Progress, train_source: TrainSource, step: int) -> None:
|
||||
ckpt_path = self.get_ckpt_path(step)
|
||||
def load(self, progress: Progress, train_source: TrainSource, step: int, path: Path | None = None) -> None:
|
||||
"""``path`` overrides where the checkpoint is read from (an external run's
|
||||
``step_<N>/orchestrator``)."""
|
||||
ckpt_path = path if path is not None else self.get_ckpt_path(step)
|
||||
state_file = ckpt_path / "progress.pt"
|
||||
if not state_file.exists():
|
||||
raise FileNotFoundError(f"Orchestrator checkpoint not found at {state_file}")
|
||||
@@ -76,7 +78,7 @@ class CheckpointManager:
|
||||
get_logger().debug(f"Orchestrator checkpoint loaded in {format_time(time.perf_counter() - start)}")
|
||||
|
||||
|
||||
def setup_ckpt_manager(output_dir: Path, config: CheckpointConfig | None) -> CheckpointManager | None:
|
||||
if config is None:
|
||||
return None
|
||||
return CheckpointManager(output_dir, config)
|
||||
def setup_ckpt_manager(output_dir: Path, config: CheckpointConfig | None) -> CheckpointManager:
|
||||
"""The checkpoint manager always exists: ``resume`` decides whether it loads,
|
||||
``ckpt`` whether it saves (a resume without ``ckpt`` loads but saves nothing)."""
|
||||
return CheckpointManager(output_dir, config or CheckpointConfig())
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import math
|
||||
import time
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
from statistics import mean, median
|
||||
|
||||
import wandb
|
||||
from httpx import AsyncClient
|
||||
@@ -12,105 +13,43 @@ from prometheus_client.parser import text_string_to_metric_families
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
POLL_INTERVAL = 5.0
|
||||
WINDOW_SIZE = 20
|
||||
FETCH_TIMEOUT = 5.0
|
||||
METRIC_PREFIX = "vllm:"
|
||||
PD_ROLES = {"prefill", "decode"}
|
||||
QUANTILES = {"p50": 0.5, "p90": 0.9, "p99": 0.99}
|
||||
AGGREGATIONS = {"min": min, "max": max, "sum": sum, "mean": mean, "median": median}
|
||||
OVERLOAD_WAITING_FRACTION = 0.2
|
||||
OVERLOAD_WARN_INTERVAL = 60.0
|
||||
|
||||
COUNTER_KEYS = {
|
||||
"vllm:prompt_tokens": "prompt_tokens_total",
|
||||
"vllm:prompt_tokens_total": "prompt_tokens_total",
|
||||
"vllm:generation_tokens": "generation_tokens_total",
|
||||
"vllm:generation_tokens_total": "generation_tokens_total",
|
||||
"vllm:request_success": "request_success_total",
|
||||
"vllm:request_success_total": "request_success_total",
|
||||
"vllm:prefix_cache_queries": "prefix_cache_queries",
|
||||
"vllm:prefix_cache_queries_total": "prefix_cache_queries",
|
||||
"vllm:prefix_cache_hits": "prefix_cache_hits",
|
||||
"vllm:prefix_cache_hits_total": "prefix_cache_hits",
|
||||
"vllm:nixl_num_failed_transfers_total": "nixl_failed_transfers_total",
|
||||
"vllm:nixl_num_failed_notifications_total": "nixl_failed_notifications_total",
|
||||
"vllm:nixl_num_kv_expired_reqs_total": "nixl_kv_expired_requests_total",
|
||||
}
|
||||
|
||||
GAUGE_KEYS = {
|
||||
"vllm:num_requests_running": "running_requests",
|
||||
"vllm:num_requests_waiting": "waiting_requests",
|
||||
"vllm:kv_cache_usage_perc": "kv_cache_usage_perc",
|
||||
"vllm:gpu_cache_usage_perc": "kv_cache_usage_perc",
|
||||
"vllm:cpu_cache_usage_perc": "cpu_cache_usage_perc",
|
||||
"vllm:gpu_prefix_cache_hit_rate": "gpu_prefix_cache_hit_rate",
|
||||
"vllm:cpu_prefix_cache_hit_rate": "cpu_prefix_cache_hit_rate",
|
||||
}
|
||||
|
||||
HISTOGRAM_SUM_KEYS = {
|
||||
"vllm:request_prefill_time_seconds_sum": "request_prefill_time_seconds_sum",
|
||||
"vllm:request_decode_time_seconds_sum": "request_decode_time_seconds_sum",
|
||||
"vllm:request_queue_time_seconds_sum": "request_queue_time_seconds_sum",
|
||||
"vllm:time_to_first_token_seconds_sum": "time_to_first_token_seconds_sum",
|
||||
"vllm:inter_token_latency_seconds_sum": "inter_token_latency_seconds_sum",
|
||||
"vllm:e2e_request_latency_seconds_sum": "e2e_request_latency_seconds_sum",
|
||||
"vllm:nixl_xfer_time_seconds_sum": "nixl_xfer_time_seconds_sum",
|
||||
"vllm:nixl_bytes_transferred_sum": "nixl_bytes_transferred_sum",
|
||||
}
|
||||
|
||||
HISTOGRAM_COUNT_KEYS = {
|
||||
"vllm:request_prefill_time_seconds_count": "request_prefill_time_seconds_count",
|
||||
"vllm:request_decode_time_seconds_count": "request_decode_time_seconds_count",
|
||||
"vllm:request_queue_time_seconds_count": "request_queue_time_seconds_count",
|
||||
"vllm:time_to_first_token_seconds_count": "time_to_first_token_seconds_count",
|
||||
"vllm:inter_token_latency_seconds_count": "inter_token_latency_seconds_count",
|
||||
"vllm:e2e_request_latency_seconds_count": "e2e_request_latency_seconds_count",
|
||||
"vllm:nixl_xfer_time_seconds_count": "nixl_xfer_time_seconds_count",
|
||||
"vllm:nixl_bytes_transferred_count": "nixl_bytes_transferred_count",
|
||||
# Scope-level ratios derived from counter deltas; each operand lists legacy and
|
||||
# OpenMetrics sample names, whichever the running vLLM version emits.
|
||||
RATIO_METRICS = {
|
||||
"prefix_cache_hit_rate": (
|
||||
("prefix_cache_hits", "prefix_cache_hits_total"),
|
||||
("prefix_cache_queries", "prefix_cache_queries_total"),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class EngineRollup:
|
||||
running_requests: float = 0.0
|
||||
waiting_requests: float = 0.0
|
||||
kv_cache_usage_perc: float = 0.0
|
||||
cpu_cache_usage_perc: float | None = None
|
||||
gpu_prefix_cache_hit_rate: float | None = None
|
||||
cpu_prefix_cache_hit_rate: float | None = None
|
||||
prompt_tokens_total: float = 0.0
|
||||
generation_tokens_total: float = 0.0
|
||||
request_success_total: float = 0.0
|
||||
prefix_cache_queries: float = 0.0
|
||||
prefix_cache_hits: float = 0.0
|
||||
nixl_failed_transfers_total: float = 0.0
|
||||
nixl_failed_notifications_total: float = 0.0
|
||||
nixl_kv_expired_requests_total: float = 0.0
|
||||
request_prefill_time_seconds_sum: float = 0.0
|
||||
request_prefill_time_seconds_count: float = 0.0
|
||||
request_decode_time_seconds_sum: float = 0.0
|
||||
request_decode_time_seconds_count: float = 0.0
|
||||
request_queue_time_seconds_sum: float = 0.0
|
||||
request_queue_time_seconds_count: float = 0.0
|
||||
time_to_first_token_seconds_sum: float = 0.0
|
||||
time_to_first_token_seconds_count: float = 0.0
|
||||
inter_token_latency_seconds_sum: float = 0.0
|
||||
inter_token_latency_seconds_count: float = 0.0
|
||||
e2e_request_latency_seconds_sum: float = 0.0
|
||||
e2e_request_latency_seconds_count: float = 0.0
|
||||
nixl_xfer_time_seconds_sum: float = 0.0
|
||||
nixl_xfer_time_seconds_count: float = 0.0
|
||||
nixl_bytes_transferred_sum: float = 0.0
|
||||
nixl_bytes_transferred_count: float = 0.0
|
||||
class HistogramSnapshot:
|
||||
sum: float = 0.0
|
||||
count: float = 0.0
|
||||
buckets: dict[float, float] = field(default_factory=dict)
|
||||
"""Upper bound (``le``) -> cumulative count."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class NodeRollup:
|
||||
engines: dict[str, EngineRollup] = field(default_factory=dict)
|
||||
class EngineSnapshot:
|
||||
"""All samples scraped for one engine, keyed by vLLM sample name.
|
||||
|
||||
@property
|
||||
def engine_count(self) -> int:
|
||||
return len(self.engines)
|
||||
Samples that carry extra labels (e.g. ``finished_reason``) are summed over
|
||||
those labels so each name maps to a single value per engine.
|
||||
"""
|
||||
|
||||
def summed(self, attribute: str) -> float:
|
||||
return sum(getattr(engine, attribute) for engine in self.engines.values())
|
||||
|
||||
def values(self, attribute: str) -> list[float]:
|
||||
return [value for engine in self.engines.values() if (value := getattr(engine, attribute)) is not None]
|
||||
gauges: dict[str, float] = field(default_factory=dict)
|
||||
counters: dict[str, float] = field(default_factory=dict)
|
||||
histograms: dict[str, HistogramSnapshot] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -118,284 +57,229 @@ class MetricsEndpoint:
|
||||
client: AsyncClient
|
||||
role: str | None
|
||||
key: str
|
||||
name: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TimedRollup:
|
||||
class TimedSnapshot:
|
||||
timestamp: float
|
||||
rollup: NodeRollup
|
||||
snapshot: EngineSnapshot
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EndpointSample:
|
||||
class EngineSample:
|
||||
endpoint: MetricsEndpoint
|
||||
engine_label: str
|
||||
timestamp: float
|
||||
rollup: NodeRollup
|
||||
snapshot: EngineSnapshot
|
||||
|
||||
@property
|
||||
def engine_id(self) -> str:
|
||||
return f"{self.endpoint.name}.{self.engine_label}"
|
||||
|
||||
@property
|
||||
def key(self) -> tuple[str, str]:
|
||||
return (self.endpoint.key, self.engine_label)
|
||||
|
||||
|
||||
def parse_prometheus_text(text: str) -> NodeRollup:
|
||||
"""Parse vLLM Prometheus metrics into per-engine counters, gauges, and histogram totals."""
|
||||
engines: dict[str, EngineRollup] = {}
|
||||
def parse_prometheus_text(text: str) -> dict[str, EngineSnapshot]:
|
||||
"""Parse a vLLM Prometheus exposition into one snapshot per engine label."""
|
||||
engines: dict[str, EngineSnapshot] = {}
|
||||
for family in text_string_to_metric_families(text):
|
||||
if not family.name.startswith(METRIC_PREFIX) or family.type not in ("counter", "gauge", "histogram"):
|
||||
continue
|
||||
for sample in family.samples:
|
||||
engine_id = sample.labels.get("engine", "aggregate")
|
||||
engine = engines.setdefault(engine_id, EngineRollup())
|
||||
if sample.name in GAUGE_KEYS:
|
||||
setattr(engine, GAUGE_KEYS[sample.name], float(sample.value))
|
||||
elif sample.name in COUNTER_KEYS:
|
||||
attribute = COUNTER_KEYS[sample.name]
|
||||
setattr(engine, attribute, getattr(engine, attribute) + float(sample.value))
|
||||
elif sample.name in HISTOGRAM_SUM_KEYS:
|
||||
setattr(engine, HISTOGRAM_SUM_KEYS[sample.name], float(sample.value))
|
||||
elif sample.name in HISTOGRAM_COUNT_KEYS:
|
||||
setattr(engine, HISTOGRAM_COUNT_KEYS[sample.name], float(sample.value))
|
||||
return NodeRollup(engines=engines)
|
||||
if sample.name.endswith("_created") or not math.isfinite(sample.value):
|
||||
continue
|
||||
engine = engines.setdefault(sample.labels.get("engine", "0"), EngineSnapshot())
|
||||
name = sample.name.removeprefix(METRIC_PREFIX)
|
||||
if family.type == "gauge":
|
||||
engine.gauges[name] = engine.gauges.get(name, 0.0) + sample.value
|
||||
elif family.type == "counter":
|
||||
engine.counters[name] = engine.counters.get(name, 0.0) + sample.value
|
||||
else:
|
||||
histogram = engine.histograms.setdefault(family.name.removeprefix(METRIC_PREFIX), HistogramSnapshot())
|
||||
if sample.name.endswith("_sum"):
|
||||
histogram.sum += sample.value
|
||||
elif sample.name.endswith("_count"):
|
||||
histogram.count += sample.value
|
||||
elif sample.name.endswith("_bucket"):
|
||||
le = float(sample.labels["le"])
|
||||
histogram.buckets[le] = histogram.buckets.get(le, 0.0) + sample.value
|
||||
return engines
|
||||
|
||||
|
||||
def build_metrics_endpoints(
|
||||
admin_clients: list[AsyncClient], roles: list[str | None] | None = None
|
||||
) -> list[MetricsEndpoint]:
|
||||
"""Attach optional P/D roles to admin clients used for metrics polling."""
|
||||
"""Attach optional P/D roles and stable display names to admin clients."""
|
||||
if roles is None:
|
||||
roles = [None] * len(admin_clients)
|
||||
if len(roles) != len(admin_clients):
|
||||
raise ValueError(f"Got {len(roles)} inference metric role(s) for {len(admin_clients)} admin client(s)")
|
||||
|
||||
endpoints: list[MetricsEndpoint] = []
|
||||
counts: dict[str, int] = {}
|
||||
for client, role in zip(admin_clients, roles):
|
||||
normalized_role = role if role in PD_ROLES else None
|
||||
if role is not None and normalized_role is None:
|
||||
if role is not None and role not in PD_ROLES:
|
||||
raise ValueError(f"Unsupported inference metrics role: {role}")
|
||||
endpoints.append(MetricsEndpoint(client=client, role=normalized_role, key=str(client.base_url).rstrip("/")))
|
||||
prefix = role or "server"
|
||||
index = counts.get(prefix, 0)
|
||||
counts[prefix] = index + 1
|
||||
endpoints.append(
|
||||
MetricsEndpoint(
|
||||
client=client,
|
||||
role=role,
|
||||
key=str(client.base_url).rstrip("/"),
|
||||
name=f"{prefix}{index}",
|
||||
)
|
||||
)
|
||||
return endpoints
|
||||
|
||||
|
||||
def max_vio(values: list[float]) -> float:
|
||||
"""Return the max-load violation used for MoE load-balance reporting."""
|
||||
if not values:
|
||||
return 0.0
|
||||
balanced_load = sum(values) / len(values)
|
||||
if balanced_load == 0:
|
||||
return 0.0
|
||||
return (max(values) - balanced_load) / balanced_load
|
||||
|
||||
|
||||
def counter_rate(samples: list[EndpointSample], previous: dict[str, TimedRollup], attribute: str) -> float | None:
|
||||
"""Sum per-endpoint counter rates for a scope."""
|
||||
rates: list[float] = []
|
||||
for sample in samples:
|
||||
previous_sample = previous.get(sample.endpoint.key)
|
||||
if previous_sample is None:
|
||||
continue
|
||||
dt = sample.timestamp - previous_sample.timestamp
|
||||
delta = sample.rollup.summed(attribute) - previous_sample.rollup.summed(attribute)
|
||||
if dt <= 0 or delta < 0:
|
||||
continue
|
||||
rates.append(delta / dt)
|
||||
if not rates:
|
||||
def histogram_quantile(buckets: dict[float, float], quantile: float) -> float | None:
|
||||
"""Estimate a quantile from cumulative bucket deltas, Prometheus-style."""
|
||||
total = max(buckets.values(), default=0.0)
|
||||
if total <= 0:
|
||||
return None
|
||||
return sum(rates)
|
||||
target = quantile * total
|
||||
previous_le, previous_cumulative = 0.0, 0.0
|
||||
for le, cumulative in sorted(buckets.items()):
|
||||
if cumulative >= target:
|
||||
if math.isinf(le) or cumulative == previous_cumulative:
|
||||
return previous_le
|
||||
return previous_le + (le - previous_le) * (target - previous_cumulative) / (
|
||||
cumulative - previous_cumulative
|
||||
)
|
||||
previous_le, previous_cumulative = le, cumulative
|
||||
return None
|
||||
|
||||
|
||||
def counter_ratio(
|
||||
samples: list[EndpointSample],
|
||||
previous: dict[str, TimedRollup],
|
||||
numerator_attribute: str,
|
||||
denominator_attribute: str,
|
||||
) -> float | None:
|
||||
"""Compute a scope-level ratio from counter deltas."""
|
||||
numerator_delta = 0.0
|
||||
denominator_delta = 0.0
|
||||
for sample in samples:
|
||||
previous_sample = previous.get(sample.endpoint.key)
|
||||
if previous_sample is None:
|
||||
continue
|
||||
endpoint_numerator_delta = sample.rollup.summed(numerator_attribute) - previous_sample.rollup.summed(
|
||||
numerator_attribute
|
||||
def engine_values(sample: EngineSample, previous: TimedSnapshot | None) -> dict[str, float]:
|
||||
"""Pass-through values plus interval-derived rates and means for one engine.
|
||||
|
||||
Counter rates use ``:rate`` (per second), histogram interval means use
|
||||
``:mean``, and histogram completion rates use ``:rate``, mirroring how one
|
||||
would express them as PromQL over the poll interval.
|
||||
"""
|
||||
values: dict[str, float] = dict(sample.snapshot.gauges)
|
||||
values.update(sample.snapshot.counters)
|
||||
for name, histogram in sample.snapshot.histograms.items():
|
||||
values[f"{name}_sum"] = histogram.sum
|
||||
values[f"{name}_count"] = histogram.count
|
||||
|
||||
if previous is None:
|
||||
return values
|
||||
dt = sample.timestamp - previous.timestamp
|
||||
if dt <= 0:
|
||||
return values
|
||||
|
||||
for name, value in sample.snapshot.counters.items():
|
||||
delta = value - previous.snapshot.counters.get(name, 0.0)
|
||||
if delta >= 0:
|
||||
values[f"{name}:rate"] = delta / dt
|
||||
for name, histogram in sample.snapshot.histograms.items():
|
||||
previous_histogram = previous.snapshot.histograms.get(name, HistogramSnapshot())
|
||||
sum_delta = histogram.sum - previous_histogram.sum
|
||||
count_delta = histogram.count - previous_histogram.count
|
||||
if count_delta >= 0:
|
||||
values[f"{name}:rate"] = count_delta / dt
|
||||
if count_delta > 0 and sum_delta >= 0:
|
||||
values[f"{name}:mean"] = sum_delta / count_delta
|
||||
# Per-engine ratios so the scope aggregations include min/max — the pooled
|
||||
# scope-level ratio alone hides a single engine's collapse (e.g. one engine
|
||||
# thrashing at a 5% prefix hit rate inside a healthy fleet average).
|
||||
for name, (numerator_names, denominator_names) in RATIO_METRICS.items():
|
||||
numerator = sum(
|
||||
sample.snapshot.counters.get(c, 0.0) - previous.snapshot.counters.get(c, 0.0) for c in numerator_names
|
||||
)
|
||||
endpoint_denominator_delta = sample.rollup.summed(denominator_attribute) - previous_sample.rollup.summed(
|
||||
denominator_attribute
|
||||
denominator = sum(
|
||||
sample.snapshot.counters.get(c, 0.0) - previous.snapshot.counters.get(c, 0.0) for c in denominator_names
|
||||
)
|
||||
if endpoint_numerator_delta < 0 or endpoint_denominator_delta < 0:
|
||||
continue
|
||||
numerator_delta += endpoint_numerator_delta
|
||||
denominator_delta += endpoint_denominator_delta
|
||||
if denominator_delta <= 0:
|
||||
return None
|
||||
return numerator_delta / denominator_delta
|
||||
if numerator >= 0 and denominator > 0:
|
||||
values[name] = numerator / denominator
|
||||
return values
|
||||
|
||||
|
||||
def histogram_average(
|
||||
samples: list[EndpointSample],
|
||||
previous: dict[str, TimedRollup],
|
||||
sum_attribute: str,
|
||||
count_attribute: str,
|
||||
) -> float | None:
|
||||
"""Compute a scope-level histogram average from sum/count deltas."""
|
||||
sum_delta = 0.0
|
||||
count_delta = 0.0
|
||||
for sample in samples:
|
||||
previous_sample = previous.get(sample.endpoint.key)
|
||||
if previous_sample is None:
|
||||
continue
|
||||
endpoint_sum_delta = sample.rollup.summed(sum_attribute) - previous_sample.rollup.summed(sum_attribute)
|
||||
endpoint_count_delta = sample.rollup.summed(count_attribute) - previous_sample.rollup.summed(count_attribute)
|
||||
if endpoint_sum_delta < 0 or endpoint_count_delta < 0:
|
||||
continue
|
||||
sum_delta += endpoint_sum_delta
|
||||
count_delta += endpoint_count_delta
|
||||
if count_delta <= 0:
|
||||
return None
|
||||
return sum_delta / count_delta
|
||||
|
||||
|
||||
def mean(values: list[float]) -> float | None:
|
||||
"""Return the arithmetic mean for non-empty metric value lists."""
|
||||
if not values:
|
||||
return None
|
||||
return sum(values) / len(values)
|
||||
def bucket_deltas(sample: EngineSample, previous: TimedSnapshot | None) -> dict[str, dict[float, float]]:
|
||||
"""Per-histogram cumulative bucket deltas since the previous scrape."""
|
||||
if previous is None:
|
||||
return {}
|
||||
deltas: dict[str, dict[float, float]] = {}
|
||||
for name, histogram in sample.snapshot.histograms.items():
|
||||
previous_buckets = previous.snapshot.histograms.get(name, HistogramSnapshot()).buckets
|
||||
delta = {le: count - previous_buckets.get(le, 0.0) for le, count in histogram.buckets.items()}
|
||||
if delta and all(count >= 0 for count in delta.values()):
|
||||
deltas[name] = delta
|
||||
return deltas
|
||||
|
||||
|
||||
def build_scope_metrics(
|
||||
scope: str,
|
||||
samples: list[EndpointSample],
|
||||
previous: dict[str, TimedRollup],
|
||||
values_per_engine: list[dict[str, float]],
|
||||
bucket_deltas_per_engine: list[dict[str, dict[float, float]]],
|
||||
counter_deltas: dict[str, float],
|
||||
) -> dict[str, float]:
|
||||
"""Build W&B metric values for one inference scope."""
|
||||
running_values = [value for sample in samples for value in sample.rollup.values("running_requests")]
|
||||
waiting_values = [value for sample in samples for value in sample.rollup.values("waiting_requests")]
|
||||
kv_values = [value for sample in samples for value in sample.rollup.values("kv_cache_usage_perc")]
|
||||
cpu_kv_values = [value for sample in samples for value in sample.rollup.values("cpu_cache_usage_perc")]
|
||||
prefix_gauge_values = [value for sample in samples for value in sample.rollup.values("gpu_prefix_cache_hit_rate")]
|
||||
cpu_prefix_values = [value for sample in samples for value in sample.rollup.values("cpu_prefix_cache_hit_rate")]
|
||||
|
||||
"""Aggregate per-engine values into ``inference/{scope}/{metric}/{agg}`` series."""
|
||||
prefix = f"inference/{scope}"
|
||||
metrics: dict[str, float] = {
|
||||
f"{prefix}/running_requests": sum(running_values),
|
||||
f"{prefix}/waiting_requests": sum(waiting_values),
|
||||
f"{prefix}/running_imbalance": max_vio(running_values),
|
||||
f"{prefix}/waiting_imbalance": max_vio(waiting_values),
|
||||
f"{prefix}/nixl_failed_transfers_total": sum(
|
||||
sample.rollup.summed("nixl_failed_transfers_total") for sample in samples
|
||||
),
|
||||
f"{prefix}/nixl_failed_notifications_total": sum(
|
||||
sample.rollup.summed("nixl_failed_notifications_total") for sample in samples
|
||||
),
|
||||
f"{prefix}/nixl_kv_expired_requests_total": sum(
|
||||
sample.rollup.summed("nixl_kv_expired_requests_total") for sample in samples
|
||||
),
|
||||
}
|
||||
metrics: dict[str, float] = {}
|
||||
|
||||
if kv_values:
|
||||
metrics[f"{prefix}/kv_cache_usage_mean"] = sum(kv_values) / len(kv_values)
|
||||
metrics[f"{prefix}/kv_cache_usage_max"] = max(kv_values)
|
||||
if cpu_kv_values:
|
||||
metrics[f"{prefix}/cpu_kv_cache_usage_mean"] = sum(cpu_kv_values) / len(cpu_kv_values)
|
||||
metrics[f"{prefix}/cpu_kv_cache_usage_max"] = max(cpu_kv_values)
|
||||
names = {name for values in values_per_engine for name in values}
|
||||
for name in sorted(names):
|
||||
engine_values_for_name = [values[name] for values in values_per_engine if name in values]
|
||||
for aggregation, fn in AGGREGATIONS.items():
|
||||
metrics[f"{prefix}/{name}/{aggregation}"] = fn(engine_values_for_name)
|
||||
|
||||
prefix_cache_hit_rate = counter_ratio(samples, previous, "prefix_cache_hits", "prefix_cache_queries")
|
||||
if prefix_cache_hit_rate is None:
|
||||
prefix_cache_hit_rate = mean(prefix_gauge_values)
|
||||
if prefix_cache_hit_rate is not None:
|
||||
metrics[f"{prefix}/prefix_cache_hit_rate"] = prefix_cache_hit_rate
|
||||
cpu_prefix_cache_hit_rate = mean(cpu_prefix_values)
|
||||
if cpu_prefix_cache_hit_rate is not None:
|
||||
metrics[f"{prefix}/cpu_prefix_cache_hit_rate"] = cpu_prefix_cache_hit_rate
|
||||
histogram_names = {name for deltas in bucket_deltas_per_engine for name in deltas}
|
||||
for name in sorted(histogram_names):
|
||||
pooled: dict[float, float] = {}
|
||||
for deltas in bucket_deltas_per_engine:
|
||||
for le, count in deltas.get(name, {}).items():
|
||||
pooled[le] = pooled.get(le, 0.0) + count
|
||||
for label, quantile in QUANTILES.items():
|
||||
value = histogram_quantile(pooled, quantile)
|
||||
if value is not None:
|
||||
metrics[f"{prefix}/{name}/{label}"] = value
|
||||
|
||||
prompt_token_rate = counter_rate(samples, previous, "prompt_tokens_total")
|
||||
generation_token_rate = counter_rate(samples, previous, "generation_tokens_total")
|
||||
if scope == "prefill":
|
||||
if prompt_token_rate is not None:
|
||||
metrics[f"{prefix}/throughput"] = prompt_token_rate
|
||||
elif scope == "decode":
|
||||
if generation_token_rate is not None:
|
||||
metrics[f"{prefix}/throughput"] = generation_token_rate
|
||||
else:
|
||||
token_rates = [rate for rate in (prompt_token_rate, generation_token_rate) if rate is not None]
|
||||
if token_rates:
|
||||
metrics[f"{prefix}/throughput"] = sum(token_rates)
|
||||
|
||||
counter_metrics = {
|
||||
"completed_requests": "request_success_total",
|
||||
"nixl_transfers_per_second": "nixl_xfer_time_seconds_count",
|
||||
"nixl_bytes_per_second": "nixl_bytes_transferred_sum",
|
||||
}
|
||||
for metric_name, attribute in counter_metrics.items():
|
||||
rate = counter_rate(samples, previous, attribute)
|
||||
if rate is not None:
|
||||
metrics[f"{prefix}/{metric_name}"] = rate
|
||||
|
||||
histogram_metrics = {
|
||||
"avg_queue_time_seconds": (
|
||||
"request_queue_time_seconds_sum",
|
||||
"request_queue_time_seconds_count",
|
||||
),
|
||||
"avg_ttft_seconds": (
|
||||
"time_to_first_token_seconds_sum",
|
||||
"time_to_first_token_seconds_count",
|
||||
),
|
||||
"avg_tpot_seconds": (
|
||||
"inter_token_latency_seconds_sum",
|
||||
"inter_token_latency_seconds_count",
|
||||
),
|
||||
"avg_e2e_latency_seconds": (
|
||||
"e2e_request_latency_seconds_sum",
|
||||
"e2e_request_latency_seconds_count",
|
||||
),
|
||||
"nixl_transfer_time_seconds": (
|
||||
"nixl_xfer_time_seconds_sum",
|
||||
"nixl_xfer_time_seconds_count",
|
||||
),
|
||||
"nixl_avg_bytes_per_transfer": (
|
||||
"nixl_bytes_transferred_sum",
|
||||
"nixl_bytes_transferred_count",
|
||||
),
|
||||
}
|
||||
for metric_name, (sum_attribute, count_attribute) in histogram_metrics.items():
|
||||
value = histogram_average(samples, previous, sum_attribute, count_attribute)
|
||||
if value is not None:
|
||||
metrics[f"{prefix}/{metric_name}"] = value
|
||||
|
||||
prefill_time = histogram_average(
|
||||
samples,
|
||||
previous,
|
||||
"request_prefill_time_seconds_sum",
|
||||
"request_prefill_time_seconds_count",
|
||||
)
|
||||
decode_time = histogram_average(
|
||||
samples,
|
||||
previous,
|
||||
"request_decode_time_seconds_sum",
|
||||
"request_decode_time_seconds_count",
|
||||
)
|
||||
if scope == "prefill":
|
||||
if prefill_time is not None:
|
||||
metrics[f"{prefix}/avg_time_seconds"] = prefill_time
|
||||
elif scope == "decode":
|
||||
if decode_time is not None:
|
||||
metrics[f"{prefix}/avg_time_seconds"] = decode_time
|
||||
else:
|
||||
time_values = [value for value in (prefill_time, decode_time) if value is not None]
|
||||
if time_values:
|
||||
metrics[f"{prefix}/avg_time_seconds"] = sum(time_values) / len(time_values)
|
||||
for name, (numerator_names, denominator_names) in RATIO_METRICS.items():
|
||||
numerator = sum(counter_deltas.get(candidate, 0.0) for candidate in numerator_names)
|
||||
denominator = sum(counter_deltas.get(candidate, 0.0) for candidate in denominator_names)
|
||||
if denominator > 0:
|
||||
metrics[f"{prefix}/{name}/pooled"] = numerator / denominator
|
||||
|
||||
return metrics
|
||||
|
||||
|
||||
class InferenceMetricsCollector:
|
||||
"""Polls vLLM Prometheus /metrics and logs smoothed role-aware values to W&B.
|
||||
"""Polls vLLM Prometheus /metrics and mirrors every engine metric to W&B.
|
||||
|
||||
The ``agg`` scope is always logged. The ``prefill`` and ``decode`` scopes are
|
||||
logged only when endpoints are explicitly or implicitly identified as a
|
||||
disaggregated P/D deployment.
|
||||
All ``vllm:*`` families are passed through dynamically (the ``vllm:``
|
||||
prefix is stripped): gauges and counters verbatim, histograms as
|
||||
``_sum``/``_count`` plus derived ``:rate``/``:mean`` and scope-level
|
||||
quantiles. Keys are ``inference/{scope}/{metric}/{stat}``: per-engine
|
||||
series under ``inference/{engine_id}/{metric}`` and cross-engine
|
||||
aggregations under ``inference/agg/{metric}/{stat}`` (plus
|
||||
``inference/prefill|decode/...`` for disaggregated deployments). Engine
|
||||
ids (``server0.0``, ``prefill0.1``, ...) never collide with the scope
|
||||
names.
|
||||
"""
|
||||
|
||||
def __init__(self, admin_clients: list[AsyncClient], roles: list[str | None] | None = None):
|
||||
def __init__(
|
||||
self,
|
||||
admin_clients: list[AsyncClient],
|
||||
roles: list[str | None] | None = None,
|
||||
max_inflight_episodes: int | None = None,
|
||||
):
|
||||
self.endpoints = build_metrics_endpoints(admin_clients, roles=roles)
|
||||
self.metric_history: dict[str, deque[float]] = {}
|
||||
self.previous: dict[str, TimedRollup] = {}
|
||||
self.previous: dict[tuple[str, str], TimedSnapshot] = {}
|
||||
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.max_inflight_episodes = max_inflight_episodes
|
||||
self.last_overload_warning = float("-inf")
|
||||
get_logger().info(
|
||||
"Collecting inference metrics from "
|
||||
+ ", ".join(f"{endpoint.name}={endpoint.key}" for endpoint in self.endpoints)
|
||||
)
|
||||
|
||||
async def start(self):
|
||||
wandb.define_metric("inference/*", step_metric="_timestamp")
|
||||
@@ -415,7 +299,7 @@ class InferenceMetricsCollector:
|
||||
|
||||
async def fetch(endpoint: MetricsEndpoint) -> str | None:
|
||||
try:
|
||||
response = await endpoint.client.get("/metrics", timeout=5.0)
|
||||
response = await endpoint.client.get("/metrics", timeout=FETCH_TIMEOUT)
|
||||
response.raise_for_status()
|
||||
return response.text
|
||||
except Exception as e:
|
||||
@@ -424,33 +308,71 @@ class InferenceMetricsCollector:
|
||||
|
||||
results = await asyncio.gather(*[fetch(endpoint) for endpoint in self.endpoints])
|
||||
samples = [
|
||||
EndpointSample(endpoint=endpoint, timestamp=now, rollup=parse_prometheus_text(text))
|
||||
EngineSample(endpoint=endpoint, engine_label=engine_label, timestamp=now, snapshot=snapshot)
|
||||
for endpoint, text in zip(self.endpoints, results)
|
||||
if text is not None
|
||||
for engine_label, snapshot in sorted(parse_prometheus_text(text).items())
|
||||
]
|
||||
if not samples:
|
||||
return
|
||||
|
||||
metrics = build_scope_metrics("agg", samples, self.previous)
|
||||
metrics = self.build_metrics(samples)
|
||||
for sample in samples:
|
||||
self.previous[sample.key] = TimedSnapshot(timestamp=sample.timestamp, snapshot=sample.snapshot)
|
||||
|
||||
waiting_requests = metrics.get("inference/agg/num_requests_waiting/sum", 0.0)
|
||||
if (
|
||||
self.max_inflight_episodes is not None
|
||||
and waiting_requests > OVERLOAD_WAITING_FRACTION * self.max_inflight_episodes
|
||||
and now - self.last_overload_warning >= OVERLOAD_WARN_INTERVAL
|
||||
):
|
||||
self.last_overload_warning = now
|
||||
get_logger().warning(
|
||||
f"Inference is overloaded: {waiting_requests:.0f} waiting request(s), more than "
|
||||
f"{OVERLOAD_WAITING_FRACTION:.0%} of max_inflight_episodes={self.max_inflight_episodes} - "
|
||||
"training is slowed by queued requests. If intermittent, wait it out - if persistent, "
|
||||
"lower concurrency by decreasing max_inflight_episodes"
|
||||
)
|
||||
|
||||
if metrics:
|
||||
metrics["_timestamp"] = time.time()
|
||||
wandb.log(metrics)
|
||||
|
||||
def build_metrics(self, samples: list[EngineSample]) -> dict[str, float]:
|
||||
values_per_engine = [engine_values(sample, self.previous.get(sample.key)) for sample in samples]
|
||||
bucket_deltas_per_engine = [bucket_deltas(sample, self.previous.get(sample.key)) for sample in samples]
|
||||
|
||||
metrics: dict[str, float] = {}
|
||||
for sample, values in zip(samples, values_per_engine):
|
||||
for name, value in values.items():
|
||||
metrics[f"inference/{sample.engine_id}/{name}"] = value
|
||||
|
||||
scopes: list[tuple[str, list[int]]] = [("agg", list(range(len(samples))))]
|
||||
if self.has_pd_roles:
|
||||
for role in sorted(PD_ROLES):
|
||||
role_samples = [sample for sample in samples if sample.endpoint.role == role]
|
||||
if role_samples:
|
||||
metrics.update(build_scope_metrics(role, role_samples, self.previous))
|
||||
indices = [i for i, sample in enumerate(samples) if sample.endpoint.role == role]
|
||||
if indices:
|
||||
scopes.append((role, indices))
|
||||
|
||||
for sample in samples:
|
||||
self.previous[sample.endpoint.key] = TimedRollup(timestamp=sample.timestamp, rollup=sample.rollup)
|
||||
|
||||
smoothed_metrics = self.smooth_metrics(metrics)
|
||||
if smoothed_metrics:
|
||||
smoothed_metrics["_timestamp"] = time.time()
|
||||
wandb.log(smoothed_metrics)
|
||||
|
||||
def smooth_metrics(self, metrics: dict[str, float]) -> dict[str, float]:
|
||||
"""Add current values to the smoothing window and return W&B-ready metrics."""
|
||||
for key, value in metrics.items():
|
||||
self.metric_history.setdefault(key, deque(maxlen=WINDOW_SIZE)).append(value)
|
||||
return {key: sum(values) / len(values) for key, values in self.metric_history.items() if values}
|
||||
for scope, indices in scopes:
|
||||
counter_deltas: dict[str, float] = {}
|
||||
for i in indices:
|
||||
previous = self.previous.get(samples[i].key)
|
||||
if previous is None:
|
||||
continue
|
||||
for name, value in samples[i].snapshot.counters.items():
|
||||
delta = value - previous.snapshot.counters.get(name, 0.0)
|
||||
if delta >= 0:
|
||||
counter_deltas[name] = counter_deltas.get(name, 0.0) + delta
|
||||
metrics.update(
|
||||
build_scope_metrics(
|
||||
scope,
|
||||
[values_per_engine[i] for i in indices],
|
||||
[bucket_deltas_per_engine[i] for i in indices],
|
||||
counter_deltas,
|
||||
)
|
||||
)
|
||||
return metrics
|
||||
|
||||
async def stop(self):
|
||||
if self.task is not None:
|
||||
|
||||
@@ -27,10 +27,10 @@ import time
|
||||
import uuid
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import tomli_w
|
||||
import verifiers.v1 as vf
|
||||
from modelexpress import p2p_pb2
|
||||
from modelexpress.client import MxClient
|
||||
from verifiers.v1.runtimes import set_base_sandbox_labels
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from renderers.base import Renderer
|
||||
@@ -39,8 +39,8 @@ if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.ckpt import CheckpointManager
|
||||
from prime_rl.transport.base import MicroBatchSender
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.monitor.base import Monitor
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
|
||||
from prime_rl.orchestrator.dispatcher import DispatcherMetrics, DispatcherMode, RolloutDispatcher
|
||||
@@ -66,8 +66,8 @@ from prime_rl.orchestrator.types import (
|
||||
)
|
||||
from prime_rl.orchestrator.utils import (
|
||||
get_weight_dir,
|
||||
group_episodes,
|
||||
intercept_vf_logging,
|
||||
save_rollouts,
|
||||
set_default_executor,
|
||||
setup_policy_inference_pool,
|
||||
trim_process_memory,
|
||||
@@ -78,12 +78,8 @@ from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.transport import setup_micro_batch_sender
|
||||
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
|
||||
from prime_rl.utils.client import init_nccl_broadcast, init_nixl_broadcast
|
||||
from prime_rl.utils.config import to_toml_dict
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
from prime_rl.utils.pathing import get_trace_path
|
||||
from prime_rl.utils.usage_reporter import UsageReporter
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
resolve_latest_ckpt_step,
|
||||
@@ -123,13 +119,12 @@ class Orchestrator:
|
||||
last_batch_at: float | None
|
||||
consecutive_empty_batches: int
|
||||
eval_triggered_at: dict[tuple[str, int], float]
|
||||
ckpt_manager: CheckpointManager | None
|
||||
ckpt_manager: CheckpointManager
|
||||
component_tasks: list[asyncio.Task]
|
||||
|
||||
# Always set by ``setup()``
|
||||
tokenizer: PreTrainedTokenizer
|
||||
policy_inference: InferencePool
|
||||
monitor: Monitor
|
||||
sender: MicroBatchSender | None
|
||||
packer: BatchPacker
|
||||
train_envs: TrainEnvs
|
||||
@@ -144,7 +139,6 @@ class Orchestrator:
|
||||
renderer: Renderer | None
|
||||
mm_token_type_ids_mapping: dict[int, int] | None
|
||||
heart: Heartbeat | None
|
||||
usage_reporter: UsageReporter | None
|
||||
inference_metrics: InferenceMetricsCollector | None
|
||||
eval_envs: EvalEnvs | None
|
||||
eval_sink: EvalSink | None
|
||||
@@ -162,9 +156,6 @@ class Orchestrator:
|
||||
algorithms = sorted({env.algo.type for env in config.train.source if env.algo is not None})
|
||||
get_logger().info(f"Starting orchestrator (algorithm: {', '.join(algorithms)})")
|
||||
|
||||
if config.bench:
|
||||
get_logger().warning(f"Running in benchmark mode (max_steps={config.max_steps})")
|
||||
|
||||
self.progress = Progress()
|
||||
self.ckpt_manager = setup_ckpt_manager(config.output_dir, config.ckpt)
|
||||
self.policy = Policy(version=0, model_name="")
|
||||
@@ -189,7 +180,6 @@ class Orchestrator:
|
||||
self.renderer = None
|
||||
self.mm_token_type_ids_mapping = None
|
||||
self.heart = None
|
||||
self.usage_reporter = None
|
||||
self.inference_metrics = None
|
||||
self.eval_envs = None
|
||||
self.eval_sink = None
|
||||
@@ -207,12 +197,6 @@ class Orchestrator:
|
||||
config = self.config
|
||||
set_default_executor()
|
||||
|
||||
# Persist the resolved config alongside the run
|
||||
config_dir = config.output_dir / "control"
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
with open(config_dir / "orch.toml", "wb") as f:
|
||||
tomli_w.dump(to_toml_dict(config), f)
|
||||
|
||||
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
self.tokenizer = setup_tokenizer(config.tokenizer)
|
||||
|
||||
@@ -231,30 +215,27 @@ class Orchestrator:
|
||||
if self.mm_token_type_ids_mapping == {}:
|
||||
self.mm_token_type_ids_mapping = None
|
||||
|
||||
get_logger().info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
|
||||
self.monitor = setup_monitor(
|
||||
wandb_config=config.wandb,
|
||||
prime_config=config.prime_monitor,
|
||||
file_config=config.file_monitor,
|
||||
get_logger().info(f"Initializing monitors ({config.monitors})")
|
||||
await monitors.setup(
|
||||
wandb=config.monitors.wandb,
|
||||
prime=config.monitors.prime,
|
||||
file=config.monitors.file,
|
||||
output_dir=config.output_dir,
|
||||
tokenizer=self.tokenizer,
|
||||
run_config=config,
|
||||
keep_full_history=config.bench,
|
||||
train_env_names=[env.resolved_name for env in config.train.source],
|
||||
eval_env_names=[source.resolved_name for source in config.eval.source] if config.eval is not None else [],
|
||||
)
|
||||
# ``RunInfo.id`` is required on the trace: fall back to a run-local uuid
|
||||
# when no external monitor identity (W&B) exists.
|
||||
self.run_id = self.monitor.run_id or uuid.uuid4().hex
|
||||
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
|
||||
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
|
||||
# Base labels for sandboxes created in this process; env-server processes read
|
||||
# the same launcher-set env var themselves.
|
||||
self.run_name = os.environ.get("PRL_RUN_NAME")
|
||||
if self.run_name:
|
||||
set_base_sandbox_labels([self.run_name])
|
||||
|
||||
if config.heartbeat is not None:
|
||||
self.heart = Heartbeat(config.heartbeat.url)
|
||||
|
||||
usage_base_url = os.environ.get("PI_USAGE_BASE_URL")
|
||||
usage_api_key = os.environ.get("PI_USAGE_API_KEY")
|
||||
if usage_base_url and usage_api_key:
|
||||
self.usage_reporter = UsageReporter()
|
||||
|
||||
# Filters apply to train rollouts only
|
||||
pre_filters = setup_filters(config.pre_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="pre-batch")
|
||||
post_filters = setup_filters(config.post_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="post-batch")
|
||||
@@ -279,11 +260,13 @@ class Orchestrator:
|
||||
await self.eval_envs.start()
|
||||
get_logger().success("Eval environment(s) ready")
|
||||
|
||||
if config.ckpt is not None and config.ckpt.resume_step is not None and self.ckpt_manager is not None:
|
||||
if config.ckpt.resume_step == -1:
|
||||
self.resume_step = resolve_latest_ckpt_step(self.ckpt_manager.ckpt_dir)
|
||||
if config.resume is not None:
|
||||
if config.resume.dir is not None:
|
||||
self.resume_step = config.resume.dir_step
|
||||
else:
|
||||
self.resume_step = config.ckpt.resume_step
|
||||
self.resume_step = config.resume.step
|
||||
if self.resume_step is None:
|
||||
self.resume_step = resolve_latest_ckpt_step(self.ckpt_manager.ckpt_dir)
|
||||
|
||||
# Resume below may bump ``policy.version`` and the LoRA model name
|
||||
self.policy.model_name = self.policy_inference.model_name
|
||||
@@ -298,10 +281,13 @@ class Orchestrator:
|
||||
*(env.algorithm.setup() for env in self.train_envs),
|
||||
)
|
||||
|
||||
if config.wandb is not None and config.collect_inference_metrics:
|
||||
# Gate on the registered monitor, not the config - the collector logs to the global
|
||||
# W&B session, which only exists when the monitor's init succeeded.
|
||||
if monitors.get(monitors.WandbMonitor) is not None and config.collect_inference_metrics:
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.policy_inference.admin_clients,
|
||||
roles=config.inference_metrics_roles,
|
||||
max_inflight_episodes=config.max_inflight_episodes,
|
||||
)
|
||||
await self.inference_metrics.start()
|
||||
|
||||
@@ -338,8 +324,10 @@ class Orchestrator:
|
||||
|
||||
self.train_source = TrainSource(self.train_envs)
|
||||
|
||||
if self.resume_step is not None and self.ckpt_manager is not None:
|
||||
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step)
|
||||
if self.resume_step is not None:
|
||||
resume = self.config.resume
|
||||
resume_path = resume.dir / "orchestrator" if resume is not None and resume.dir is not None else None
|
||||
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step, path=resume_path)
|
||||
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
|
||||
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
|
||||
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
|
||||
@@ -349,50 +337,44 @@ class Orchestrator:
|
||||
get_logger().info("Training from scratch")
|
||||
|
||||
self.packer = BatchPacker(config)
|
||||
if config.bench:
|
||||
# Bench runs have no trainer: nothing consumes shipped batches, and the
|
||||
# ZMQ sender's READY barrier would block forever.
|
||||
self.sender = None
|
||||
else:
|
||||
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
|
||||
self.sender = setup_micro_batch_sender(
|
||||
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
|
||||
)
|
||||
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
|
||||
self.sender = setup_micro_batch_sender(
|
||||
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
|
||||
)
|
||||
|
||||
# Sync inference to the incoming policy before the first step, rendezvousing
|
||||
# with the trainer's startup broadcast (v{resume_step} on resume, v0 from
|
||||
# scratch). Bench runs have no trainer, so there is no broadcast to wait for.
|
||||
if not config.bench:
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
if config.weight_broadcast.type == "nixl":
|
||||
weights_path = None
|
||||
else:
|
||||
check_exists = config.weight_broadcast.type == "filesystem"
|
||||
# The trainer's startup broadcast is always coming, so wait for it
|
||||
# rather than failing immediately when the directory is not there yet.
|
||||
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
)
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
# Complete the startup rendezvous before the watcher begins its next cycle.
|
||||
await asyncio.to_thread(
|
||||
self.model_express.wait_for,
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=config.weight_broadcast.timeout,
|
||||
)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = sync_version
|
||||
# scratch).
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
if config.weight_broadcast.type == "nixl":
|
||||
weights_path = None
|
||||
else:
|
||||
check_exists = config.weight_broadcast.type == "filesystem"
|
||||
# The trainer's startup broadcast is always coming, so wait for it
|
||||
# rather than failing immediately when the directory is not there yet.
|
||||
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
)
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
# Complete the startup rendezvous before the watcher begins its next cycle.
|
||||
await asyncio.to_thread(
|
||||
self.model_express.wait_for,
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=config.weight_broadcast.timeout,
|
||||
)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = sync_version
|
||||
|
||||
self.eval_source: EvalSource | None = (
|
||||
EvalSource(
|
||||
@@ -406,7 +388,7 @@ class Orchestrator:
|
||||
|
||||
assert config.max_inflight_episodes is not None, "max_inflight_episodes must be resolved before dispatcher init"
|
||||
log_interval = config.log.interval
|
||||
wandb_enabled = config.wandb is not None
|
||||
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
|
||||
self.dispatcher = RolloutDispatcher(
|
||||
train_envs=self.train_envs,
|
||||
eval_envs=self.eval_envs,
|
||||
@@ -504,13 +486,15 @@ class Orchestrator:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
if clean_exit:
|
||||
get_logger().success(f"Orchestrator step loop done in {elapsed}")
|
||||
# Finalize only on a clean exit — a crashed run must not be marked
|
||||
# completed; the platform run's atexit hook marks it failed instead.
|
||||
await monitors.finalize()
|
||||
else:
|
||||
get_logger().warning(f"Orchestrator interrupted after {elapsed} — forcing cleanup (not a clean exit)")
|
||||
self.monitor.save_final_summary()
|
||||
# ``progress.step`` points at the next (unshipped) step; the last finished step is
|
||||
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
|
||||
# first ship).
|
||||
if self.ckpt_manager is not None and self.progress.step > 1:
|
||||
if self.config.ckpt is not None and self.progress.step > 1:
|
||||
self.progress.step -= 1
|
||||
get_logger().info("Writing final checkpoint")
|
||||
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
|
||||
@@ -544,9 +528,9 @@ class Orchestrator:
|
||||
step = episode[0].eval_step if kind == "eval" else self.progress.step
|
||||
assert step is not None
|
||||
run: vf.RunInfo = (
|
||||
vf.EvalRunInfo(id=self.run_id, step=step)
|
||||
vf.EvalRunInfo(id=self.run_id, name=self.run_name, step=step)
|
||||
if kind == "eval"
|
||||
else vf.TrainRunInfo(id=self.run_id, step=step)
|
||||
else vf.TrainRunInfo(id=self.run_id, name=self.run_name, step=step)
|
||||
)
|
||||
for rollout in episode:
|
||||
rollout.record_run(
|
||||
@@ -556,11 +540,7 @@ class Orchestrator:
|
||||
episode_id=rollout.episode_id,
|
||||
policy_version=rollout.policy_version,
|
||||
)
|
||||
await asyncio.to_thread(
|
||||
save_rollouts,
|
||||
[rollout.to_record() for rollout in episode],
|
||||
get_trace_path(self.config.output_dir, step, kind, "all"),
|
||||
)
|
||||
await monitors.log(group_episodes(episode), step, kind, "all")
|
||||
|
||||
if kind == "eval":
|
||||
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
|
||||
@@ -577,7 +557,7 @@ class Orchestrator:
|
||||
|
||||
async def finalize_train_batch(self, batch: TrainBatch) -> None:
|
||||
"""Ship one ``TrainBatch`` out to the trainer and handle the I/O
|
||||
side-effects (ckpt, save_rollouts, reference scoring, sender.send,
|
||||
side-effects (ckpt, monitors.log, reference scoring, sender.send,
|
||||
metrics, heartbeat, progress, eval trigger). The sink has already
|
||||
done all data-transformation work."""
|
||||
config = self.config
|
||||
@@ -627,9 +607,9 @@ class Orchestrator:
|
||||
# orchestrator finishes early, and its teardown strands the trainer inside
|
||||
# an in-memory broadcast handshake that needs the live weight watcher.
|
||||
# Always satisfiable: the trainer skips only the final TARGET_LAG+1
|
||||
# in-memory broadcasts. Bench runs have no trainer, so they ship freely.
|
||||
# in-memory broadcasts.
|
||||
required_version = step - 1 - TARGET_LAG
|
||||
if not config.bench and self.policy.version < required_version:
|
||||
if self.policy.version < required_version:
|
||||
get_logger().info(
|
||||
f"Holding batch {step} until the trainer publishes policy v{required_version} "
|
||||
f"(currently v{self.policy.version})"
|
||||
@@ -651,18 +631,14 @@ class Orchestrator:
|
||||
if self.train_envs.get(r.env_name).sampler.samples_from_live_policy:
|
||||
r.off_policy_steps = (step - 1) - r.policy_version
|
||||
|
||||
# The effective (clean, trained-on) subset lands in the per-step ``effective`` trace file
|
||||
# at ship time; the full arrival window already streamed into ``all`` on arrival.
|
||||
# to_record drops the per-node training tensors — they're for training, not the rollout
|
||||
# record, and can't round-trip json (raw numpy bytes).
|
||||
records = [r.to_record() for r in effective]
|
||||
await asyncio.to_thread(save_rollouts, records, get_trace_path(config.output_dir, step, "train", "effective"))
|
||||
# The effective (clean, trained-on) subset is logged at ship time; the full arrival
|
||||
# window already streamed into the ``all`` cohort on arrival.
|
||||
await monitors.log(group_episodes(effective.rollouts), step, "train", "effective")
|
||||
|
||||
pack_start_time = time.perf_counter()
|
||||
micro_batch_grid = await asyncio.to_thread(self.packer.pack, batch.samples)
|
||||
pack_time = time.perf_counter() - pack_start_time
|
||||
if self.sender is not None:
|
||||
await self.sender.send(micro_batch_grid)
|
||||
await self.sender.send(micro_batch_grid)
|
||||
self.progress.step += 1
|
||||
self.update_dispatch_gate()
|
||||
# Checkpoint the step we just shipped (resume point: continue at step + 1).
|
||||
@@ -709,25 +685,9 @@ class Orchestrator:
|
||||
)
|
||||
for name, count in self.train_sink.pre_filter_dropped_by_name.items():
|
||||
metrics[f"pre_filters/all/{name}/rate"] = count / self.train_sink.pre_filter_seen
|
||||
self.monitor.log(metrics, step=step)
|
||||
await monitors.log(metrics, step=step)
|
||||
self.wait_for_policy_time = 0.0
|
||||
self.monitor.log_samples(effective.rollouts, step=step)
|
||||
self.monitor.log_distributions(
|
||||
distributions={
|
||||
"rewards": [r.reward for r in effective],
|
||||
"advantages": [a for r in effective if (a := r.scalar_advantage()) is not None],
|
||||
},
|
||||
step=step,
|
||||
)
|
||||
|
||||
if self.usage_reporter is not None:
|
||||
run_id = os.getenv("RUN_ID", "")
|
||||
if run_id:
|
||||
self.usage_reporter.report_training_usage(
|
||||
run_id=run_id,
|
||||
step=step,
|
||||
tokens=num_input + num_output,
|
||||
)
|
||||
if self.heart is not None:
|
||||
self.heart.beat()
|
||||
|
||||
@@ -865,21 +825,15 @@ class Orchestrator:
|
||||
get_logger().success("\n\t\t ".join(lines))
|
||||
|
||||
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
|
||||
"""Persist + log one completed eval epoch (save_rollouts,
|
||||
monitor.log_eval_samples, monitor.log)."""
|
||||
"""Persist + log one completed eval epoch through the monitors."""
|
||||
if not batch.rollouts:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
|
||||
return
|
||||
|
||||
# The non-errored subset lands in the per-step ``effective`` trace file on epoch
|
||||
# completion (multiple eval envs share the step file — each epoch appends its cohort
|
||||
# once, and every record carries ``env_name``); the full returned cohort already
|
||||
# streamed into ``all`` on arrival.
|
||||
records = [r.to_record() for r in batch.rollouts.effective]
|
||||
await asyncio.to_thread(
|
||||
save_rollouts, records, get_trace_path(self.config.output_dir, batch.step, "eval", "effective")
|
||||
)
|
||||
self.monitor.log_eval_samples(batch.rollouts, env_name=batch.env_name, step=batch.step)
|
||||
# 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(group_episodes(batch.rollouts.effective.rollouts), batch.step, "eval", "effective")
|
||||
policy_versions = {r.policy_version for r in batch.rollouts}
|
||||
policy_version = min(policy_versions)
|
||||
if len(policy_versions) > 1:
|
||||
@@ -895,7 +849,7 @@ class Orchestrator:
|
||||
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(policy_version)
|
||||
metrics["step"] = float(batch.step)
|
||||
self.monitor.log(metrics, step=batch.step)
|
||||
await monitors.log(metrics, step=batch.step)
|
||||
|
||||
# Success line — quality metrics over the effective set, error rate over the full returned
|
||||
# cohort. ``Stat.mean()`` is 0.0 for an empty set.
|
||||
@@ -912,7 +866,7 @@ class Orchestrator:
|
||||
async def maybe_save_ckpt(self, step: int) -> float:
|
||||
"""Checkpoint the step just shipped if it's an interval boundary. Returns
|
||||
elapsed time (0.0 when no save happened)."""
|
||||
if self.ckpt_manager is None or self.config.ckpt is None or not self.config.ckpt.interval:
|
||||
if self.config.ckpt is None or not self.config.ckpt.interval:
|
||||
return 0.0
|
||||
# The final step's checkpoint is written once in ``start()``'s teardown; skip it here so
|
||||
# we don't double-save. This mirrors the trainer (its is_last_step skips the in-loop save).
|
||||
@@ -979,8 +933,7 @@ class Orchestrator:
|
||||
training artifacts are already persisted before this is reached."""
|
||||
|
||||
async def teardown() -> None:
|
||||
if self.sender is not None:
|
||||
self.sender.close()
|
||||
self.sender.close()
|
||||
if self.dispatcher is not None:
|
||||
await self.dispatcher.stop()
|
||||
if self.watcher is not None:
|
||||
@@ -1001,8 +954,6 @@ class Orchestrator:
|
||||
for env in self.train_envs:
|
||||
for pool in (*env.sampler.connected_pools, *env.algorithm.connected_pools):
|
||||
await pool.stop()
|
||||
if self.usage_reporter is not None:
|
||||
self.usage_reporter.close()
|
||||
|
||||
task = asyncio.create_task(teardown())
|
||||
_, pending = await asyncio.wait({task}, timeout=SHUTDOWN_TIMEOUT_S)
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
``add()`` takes one episode (``list[Rollout]``) and returns
|
||||
``TrainBatch | None``; group accounting counts episodes, never loose traces.
|
||||
I/O concerns (ship to trainer, save_rollouts, monitor.log) live on the
|
||||
I/O concerns (ship to trainer, monitors.log) live on the
|
||||
orchestrator.
|
||||
"""
|
||||
|
||||
|
||||
@@ -6,8 +6,10 @@ import math
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import orjson
|
||||
import verifiers.v1 as vf
|
||||
from verifiers.v1.episode import EnvInfo
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.utils.client import InferencePool
|
||||
@@ -18,6 +20,9 @@ from prime_rl.utils.utils import (
|
||||
get_step_path,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
|
||||
"""Build the live policy inference pool + matching renderer. Returns
|
||||
@@ -49,15 +54,22 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
|
||||
return renderer, inference_pool
|
||||
|
||||
|
||||
def save_rollouts(rollouts: list[dict], path: Path) -> None:
|
||||
"""Append rollouts (Trace record dicts, already JSON-serializable) to a JSONL file.
|
||||
The trace streams are append-only: ``all`` grows one rollout at a time as they
|
||||
complete, ``effective`` one batch at a time on finalize."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
|
||||
with open(path, "ab") as f:
|
||||
for rollout in rollouts:
|
||||
f.write(orjson.dumps(rollout, default=str, option=opts))
|
||||
def group_episodes(rollouts: "list[Rollout]") -> list[vf.Episode]:
|
||||
"""Regroup rollouts into their episodes. The dispatcher unwraps every
|
||||
``vf.Episode`` into its traces on arrival; ``episode_id`` links them back
|
||||
together (a rollout without one forms a single-trace episode)."""
|
||||
groups: dict[str, list] = {}
|
||||
for rollout in rollouts:
|
||||
groups.setdefault(rollout.episode_id or rollout.id, []).append(rollout)
|
||||
return [
|
||||
vf.Episode(
|
||||
id=episode_id,
|
||||
env=EnvInfo(id=group[0].env_name),
|
||||
traces=group,
|
||||
ok=all(trace.ok for trace in group),
|
||||
)
|
||||
for episode_id, group in groups.items()
|
||||
]
|
||||
|
||||
|
||||
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
# ranks 1+ get their own node_<rank>_rank<k>.log.
|
||||
rank_log() {
|
||||
if [ "$2" -eq 0 ]; then
|
||||
echo "$OUTPUT_DIR/logs/inference/node_$1.log"
|
||||
echo "$LOG_DIR/inference/node_$1.log"
|
||||
else
|
||||
echo "$OUTPUT_DIR/logs/inference/node_$1_rank$2.log"
|
||||
echo "$LOG_DIR/inference/node_$1_rank$2.log"
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ launch_router() {
|
||||
{%- if router.type == "llm-d" %}
|
||||
echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port" | tee "$log"
|
||||
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
|
||||
local LLMD_DIR="$OUTPUT_DIR/logs/inference/llmd"
|
||||
local LLMD_DIR="$LOG_DIR/inference/llmd"
|
||||
mkdir -p "$LLMD_DIR"
|
||||
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
|
||||
{%- if is_disaggregated %}
|
||||
|
||||
@@ -53,9 +53,13 @@ export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_PATH={{ config_path }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
mkdir -p $OUTPUT_DIR/logs/inference
|
||||
rm -f $OUTPUT_DIR/logs/inference/*.log
|
||||
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
# Per-attempt log dir: a relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
|
||||
mkdir -p $LOG_DIR/inference
|
||||
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
@@ -271,11 +275,11 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
fi
|
||||
|
||||
echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT LOCAL_IP=$LOCAL_IP" \
|
||||
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
| tee $LOG_DIR/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
# Start the single global router on node 0 (external LB across all per-rank endpoints)
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
launch_router pd "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
|
||||
launch_router pd "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$LOG_DIR/inference/router.log"
|
||||
fi
|
||||
{%- if router.type == "llm-d" %}
|
||||
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
|
||||
@@ -283,7 +287,7 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
# Every decode node fronts its own local ranks, so launch on each (not just the
|
||||
# replica head), or decode nodes beyond the head get advertised but unserved endpoints.
|
||||
if [ "$ROLE" = "decode" ]; then
|
||||
SIDECAR_LOG="$OUTPUT_DIR/logs/inference/sidecar_${INFER_NODE_RANK}.log"
|
||||
SIDECAR_LOG="$LOG_DIR/inference/sidecar_${INFER_NODE_RANK}.log"
|
||||
echo "Starting pd-sidecar on $LOCAL_IP:$DECODE_SIDECAR_PORT(+rank) -> vLLM $DECODE_PORT(+rank)" | tee $SIDECAR_LOG
|
||||
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
|
||||
pd-sidecar \
|
||||
@@ -311,7 +315,7 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
done
|
||||
{%- elif num_nodes > 1 %}
|
||||
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
|
||||
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
| tee $LOG_DIR/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
DP_PER_NODE={{ dp_per_node }}
|
||||
TP=$((GPUS_PER_NODE / DP_PER_NODE))
|
||||
@@ -319,7 +323,7 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
|
||||
# Start the single global router on node 0 (balances across per-rank endpoints — no intra-node DP header)
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$LOG_DIR/inference/router.log"
|
||||
fi
|
||||
|
||||
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
|
||||
@@ -340,11 +344,11 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
fi
|
||||
done
|
||||
{%- else %}
|
||||
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" | tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" | tee $LOG_DIR/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
uv run inference \
|
||||
@ $CONFIG_PATH \
|
||||
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
|
||||
2>&1 | tee -a $LOG_DIR/inference/node_${INFER_NODE_RANK}.log &
|
||||
{%- endif %}
|
||||
|
||||
# Wait for the first background job to exit and propagate its exit code. This
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user