Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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:
|
||||
|
||||
+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),
|
||||
"--file-monitor.filename",
|
||||
"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:
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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)
|
||||
|
||||
+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
+1
-1
@@ -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. |
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -260,14 +260,15 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
|
||||
--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.
|
||||
|
||||
+30
-22
@@ -77,10 +77,11 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
|
||||
| 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
|
||||
|
||||
@@ -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,12 +298,12 @@ 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
|
||||
|
||||
@@ -341,5 +349,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.
|
||||
|
||||
@@ -32,7 +32,8 @@ timeout = 3600
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[resume]
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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,9 +109,6 @@ 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]
|
||||
@@ -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]
|
||||
|
||||
@@ -33,7 +33,8 @@ timeout = 3600
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[resume]
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
@@ -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,7 +1,10 @@
|
||||
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"
|
||||
@@ -137,7 +140,6 @@ id = "r2e-gym"
|
||||
id = "rlm"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["glm5-llmd"]
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -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]]
|
||||
|
||||
@@ -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]]
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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,9 +93,6 @@ 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]
|
||||
@@ -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]
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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:**
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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).
|
||||
|
||||
+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
|
||||
|
||||
@@ -17,6 +17,7 @@ from prime_rl.configs.shared import (
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
PrimeMonitorConfig,
|
||||
ResumeConfig,
|
||||
TransportConfig,
|
||||
WandbWithExtrasConfig,
|
||||
ZMQTransportConfig,
|
||||
@@ -286,11 +287,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."""
|
||||
@@ -453,6 +451,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 +501,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."""
|
||||
|
||||
@@ -638,20 +636,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
|
||||
@@ -21,16 +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,
|
||||
@@ -100,9 +100,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 +224,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,6 +256,9 @@ class RLConfig(BaseConfig):
|
||||
ckpt: SharedCheckpointConfig | None = None
|
||||
"""Shared checkpoint config. If None, falls back to the sub-config checkpoint 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."""
|
||||
|
||||
wandb: SharedWandbConfig | None = None
|
||||
"""Shared W&B config. If None, falls back to the sub-config W&B settings."""
|
||||
|
||||
@@ -263,9 +281,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 +331,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 +375,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_run_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.wandb, self.trainer.wandb, self.orchestrator.wandb):
|
||||
if wandb is not None and wandb.name is None:
|
||||
wandb.name = self.run.name
|
||||
prime_monitor = self.orchestrator.prime_monitor
|
||||
if prime_monitor is not None and prime_monitor.run_name is None:
|
||||
prime_monitor.run_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 +524,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
|
||||
@@ -10,13 +11,14 @@ 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,6 +190,9 @@ 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
|
||||
@@ -195,11 +200,34 @@ class SFTConfig(BaseConfig):
|
||||
file_monitor: FileMonitorConfig | None = None
|
||||
"""Local JSONL metric sink. If set, metrics are appended to ``<output_dir>/metrics.jsonl``."""
|
||||
|
||||
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."""
|
||||
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 (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space."""
|
||||
|
||||
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.wandb is not None and self.wandb.name is None:
|
||||
self.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 +238,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 +390,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."""
|
||||
|
||||
@@ -10,6 +10,7 @@ from prime_rl.configs.shared import (
|
||||
FileMonitorConfig,
|
||||
HeartbeatConfig,
|
||||
MetricsServerConfig,
|
||||
ResumeConfig,
|
||||
TrainerLogConfig,
|
||||
TransportConfig,
|
||||
WandbConfig,
|
||||
@@ -59,11 +60,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 +427,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 +449,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 +570,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()
|
||||
@@ -607,9 +603,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 +654,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,7 +90,6 @@ 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")
|
||||
|
||||
@@ -138,8 +137,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:
|
||||
@@ -197,9 +194,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,17 +222,6 @@ 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,
|
||||
|
||||
+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):
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
@@ -78,7 +78,6 @@ 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
|
||||
@@ -123,7 +122,7 @@ 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()``
|
||||
@@ -162,9 +161,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="")
|
||||
@@ -207,12 +203,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)
|
||||
|
||||
@@ -239,13 +229,17 @@ class Orchestrator:
|
||||
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
|
||||
# Prefer the monitor identity (platform run id, else W&B id) so traces link
|
||||
# back to it, then the launcher-set $PRL_RUN_ID; standalone runs mint a local one.
|
||||
self.run_id = self.monitor.run_id or 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)
|
||||
@@ -279,11 +273,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
|
||||
@@ -302,6 +298,7 @@ class Orchestrator:
|
||||
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 +335,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 +348,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(
|
||||
@@ -510,7 +503,7 @@ class Orchestrator:
|
||||
# ``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 +537,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(
|
||||
@@ -627,9 +620,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})"
|
||||
@@ -661,8 +654,7 @@ class Orchestrator:
|
||||
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).
|
||||
@@ -912,7 +904,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 +971,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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -58,13 +58,19 @@ export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parall
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
mkdir -p $OUTPUT_DIR/logs/trainer $OUTPUT_DIR/logs/inference
|
||||
rm -f $OUTPUT_DIR/logs/inference/*.log
|
||||
ln -sfn trainer/node_0.log $OUTPUT_DIR/logs/trainer.log
|
||||
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
|
||||
mkdir -p $LOG_DIR/trainer $LOG_DIR/inference
|
||||
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
|
||||
export PRL_RUN_ID=${PRL_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")}
|
||||
export PRL_RUN_NAME={{ run_name }}
|
||||
export WANDB_RUN_ID=$PRL_RUN_ID
|
||||
export WANDB_SHARED_MODE=1
|
||||
export WANDB_SHARED_RUN_ID=${WANDB_SHARED_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")}
|
||||
|
||||
# Networking
|
||||
HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
@@ -240,9 +246,9 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
RANK_IN_REPLICA=$((INFER_NODE_RANK % NODES_PER_INFER_REPLICA))
|
||||
|
||||
echo "INFER_NODE_RANK=$INFER_NODE_RANK REPLICA=$REPLICA_IDX RANK_IN_REPLICA=$RANK_IN_REPLICA LOCAL_IP=$LOCAL_IP" \
|
||||
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
| tee $LOG_DIR/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
CONFIG_PATH="$CONFIG_DIR/inference.toml"
|
||||
CONFIG_PATH="$CONFIG_DIR/inference.json"
|
||||
{% include '_launch_rank.sh.j2' %}
|
||||
{% include '_launch_router.sh.j2' %}
|
||||
|
||||
@@ -310,11 +316,11 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
fi
|
||||
|
||||
echo "ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT" \
|
||||
| tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
| tee -a $LOG_DIR/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
# Start the single global router on inference node 0 (PD mode, 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
|
||||
@@ -322,7 +328,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
# 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 \
|
||||
@@ -351,7 +357,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
{%- else -%}
|
||||
# Start the single global router on inference node 0 (external LB across all per-rank endpoints)
|
||||
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 + d),
|
||||
@@ -392,7 +398,7 @@ else
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
|
||||
echo $HOSTNAMES_STR | tee $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
echo $HOSTNAMES_STR | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
|
||||
WANDB_SHARED_LABEL=trainer uv run torchrun \
|
||||
--role=trainer \
|
||||
@@ -401,21 +407,21 @@ else
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$OUTPUT_DIR/logs/trainer/torchrun \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.toml \
|
||||
@ $CONFIG_DIR/trainer.json \
|
||||
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log &
|
||||
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log &
|
||||
{% if num_infer_nodes > 0 %} fi{% endif %}
|
||||
{% if num_infer_nodes > 0 %}
|
||||
# Launch the orchestrator on the node ORCH_ADDR points at (see the ORCH_PROCID
|
||||
# computation above). Top-level (after the role if/else) so the wait -n teardown
|
||||
# covers it.
|
||||
if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
|
||||
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.json"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --model.client.base-url $INFER_URLS"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --model.client.admin-base-url $ADMIN_URLS"
|
||||
{%- if orchestrator_env_vars %}
|
||||
@@ -433,21 +439,21 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
# single-quoted bash -c string, so a stray quote closes it early and the rest of
|
||||
# the script fails to parse.
|
||||
{%- for name in train_env_names %}
|
||||
mkdir -p $OUTPUT_DIR/logs/envs/train
|
||||
uv run env-server @ $CONFIG_DIR/envs/train/{{ name }}.toml \
|
||||
> $OUTPUT_DIR/logs/envs/train/{{ name }}.log 2>&1 &
|
||||
mkdir -p $LOG_DIR/envs/train
|
||||
uv run env-server @ $CONFIG_DIR/envs/train/{{ name }}.json \
|
||||
> $LOG_DIR/envs/train/{{ name }}.log 2>&1 &
|
||||
{%- endfor %}
|
||||
{%- for name in eval_env_names %}
|
||||
mkdir -p $OUTPUT_DIR/logs/envs/eval
|
||||
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.toml \
|
||||
> $OUTPUT_DIR/logs/envs/eval/{{ name }}.log 2>&1 &
|
||||
mkdir -p $LOG_DIR/envs/eval
|
||||
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.json \
|
||||
> $LOG_DIR/envs/eval/{{ name }}.log 2>&1 &
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
|
||||
2>&1 | tee $LOG_DIR/orchestrator.log &
|
||||
fi
|
||||
{% endif %}
|
||||
|
||||
|
||||
@@ -33,8 +33,13 @@ export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_PATH={{ config_path }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
mkdir -p $OUTPUT_DIR/logs/trainer
|
||||
ln -sfn trainer/node_0.log $OUTPUT_DIR/logs/trainer.log
|
||||
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
|
||||
mkdir -p $LOG_DIR/trainer
|
||||
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
|
||||
|
||||
# Networking
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
@@ -123,7 +128,7 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
|
||||
echo $HOSTNAMES | tee $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
echo $HOSTNAMES | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_NODES \
|
||||
@@ -131,11 +136,11 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$OUTPUT_DIR/logs/trainer/torchrun \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.sft.train \
|
||||
@ $CONFIG_PATH \
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
LAUNCH_SH
|
||||
|
||||
@@ -37,4 +37,5 @@ uv sync --all-extras --all-packages
|
||||
# Pre-run command
|
||||
{{ pre_run_command }}
|
||||
{% endif %}
|
||||
export PRL_RUN_ID=${PRL_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")}
|
||||
uv run rl @ {{ config_path }}
|
||||
|
||||
@@ -21,6 +21,7 @@ from torchdata.stateful_dataloader import StatefulDataLoader
|
||||
from transformers.processing_utils import ProcessorMixin
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.configs.shared import ResumeConfig
|
||||
from prime_rl.configs.trainer import CheckpointConfig, LoRAConfig, WeightCheckpointConfig
|
||||
from prime_rl.trainer.lora import get_lora_state, has_lora_layers, save_lora_config
|
||||
from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
@@ -166,7 +167,7 @@ class AppState(Stateful):
|
||||
class CheckpointManager:
|
||||
"""Utility class to save and load trainer checkpoints to resume SFT and RL training."""
|
||||
|
||||
def __init__(self, output_dir: Path, config: CheckpointConfig):
|
||||
def __init__(self, output_dir: Path, config: CheckpointConfig, resume: ResumeConfig | None = None):
|
||||
self.config = config
|
||||
self.skip_optimizer = config.skip_optimizer
|
||||
self.ckpt_dir = get_ckpt_dir(output_dir)
|
||||
@@ -174,8 +175,8 @@ class CheckpointManager:
|
||||
self.world = get_world()
|
||||
|
||||
all_steps = get_all_ckpt_steps(self.ckpt_dir)
|
||||
if config.resume_step is not None and config.resume_step >= 0:
|
||||
self.ckpt_steps = [s for s in all_steps if s <= config.resume_step]
|
||||
if resume is not None and resume.step is not None:
|
||||
self.ckpt_steps = [s for s in all_steps if s <= resume.step]
|
||||
else:
|
||||
self.ckpt_steps = all_steps
|
||||
|
||||
@@ -263,9 +264,11 @@ class CheckpointManager:
|
||||
scheduler: LRScheduler | None,
|
||||
progress: Progress | None,
|
||||
dataloader: StatefulDataLoader | None = None,
|
||||
path: Path | None = None,
|
||||
) -> None:
|
||||
"""Load the trainer checkpoint for a given step (in-place)."""
|
||||
ckpt_path = self.get_ckpt_path(step)
|
||||
"""Load the trainer checkpoint for a given step (in-place). ``path`` overrides
|
||||
where the checkpoint is read from (an external run's ``step_<N>/trainer``)."""
|
||||
ckpt_path = path if path is not None else self.get_ckpt_path(step)
|
||||
if not ckpt_path.exists():
|
||||
raise FileNotFoundError(f"Checkpoint not found at {ckpt_path}")
|
||||
self.load_from_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
|
||||
@@ -336,7 +339,7 @@ class WeightCheckpointManager:
|
||||
save_async: bool = False,
|
||||
keep_last: int | None = None,
|
||||
keep_interval: int | None = None,
|
||||
resume_step: int | None = None,
|
||||
resume: ResumeConfig | None = None,
|
||||
):
|
||||
self.weights_dir = get_weights_dir(output_dir)
|
||||
self.config = config
|
||||
@@ -345,8 +348,8 @@ class WeightCheckpointManager:
|
||||
self.world = get_world()
|
||||
if self.world.is_master:
|
||||
all_steps = get_all_ckpt_steps(self.weights_dir)
|
||||
if resume_step is not None and resume_step >= 0:
|
||||
self.ckpt_steps = [s for s in all_steps if s <= resume_step]
|
||||
if resume is not None and resume.step is not None:
|
||||
self.ckpt_steps = [s for s in all_steps if s <= resume.step]
|
||||
else:
|
||||
self.ckpt_steps = all_steps
|
||||
else:
|
||||
@@ -523,20 +526,23 @@ class WeightCheckpointManager:
|
||||
|
||||
|
||||
def setup_ckpt_managers(
|
||||
output_dir: Path, ckpt_config: CheckpointConfig | None, lora_config: LoRAConfig | None = None
|
||||
) -> tuple[CheckpointManager | None, WeightCheckpointManager | None]:
|
||||
if ckpt_config is None:
|
||||
return None, None
|
||||
ckpt_output_dir = ckpt_config.output_dir or output_dir
|
||||
ckpt_manager = CheckpointManager(ckpt_output_dir, ckpt_config)
|
||||
if ckpt_config.weights and not ckpt_config.skip_gather_master_weights:
|
||||
output_dir: Path,
|
||||
ckpt_config: CheckpointConfig | None,
|
||||
lora_config: LoRAConfig | None = None,
|
||||
resume: ResumeConfig | None = None,
|
||||
) -> tuple[CheckpointManager, WeightCheckpointManager | None]:
|
||||
"""The checkpoint manager always exists: ``resume`` decides whether it loads,
|
||||
``ckpt`` whether it saves (a resume without ``ckpt`` loads but saves nothing)."""
|
||||
ckpt_output_dir = (ckpt_config.output_dir if ckpt_config else None) or output_dir
|
||||
ckpt_manager = CheckpointManager(ckpt_output_dir, ckpt_config or CheckpointConfig(), resume)
|
||||
if ckpt_config and ckpt_config.weights and not ckpt_config.skip_gather_master_weights:
|
||||
weight_ckpt_manager = WeightCheckpointManager(
|
||||
ckpt_output_dir,
|
||||
ckpt_config.weights,
|
||||
lora_config=lora_config,
|
||||
keep_last=ckpt_config.keep_last,
|
||||
keep_interval=ckpt_config.keep_interval,
|
||||
resume_step=ckpt_config.resume_step,
|
||||
resume=resume,
|
||||
)
|
||||
else:
|
||||
weight_ckpt_manager = None
|
||||
|
||||
@@ -68,14 +68,23 @@ from prime_rl.utils.utils import format_time
|
||||
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
|
||||
|
||||
|
||||
def pre_download_model(model_name: str) -> None:
|
||||
"""Pre-download model from HuggingFace Hub so all nodes have cached weights before training."""
|
||||
def pre_download_model(model_name: str, *, skip_weights: bool = False) -> None:
|
||||
"""Pre-download model from HuggingFace Hub so all nodes have cached weights before training.
|
||||
|
||||
With ``skip_weights`` (random-init debug runs), only config and tokenizer files are fetched.
|
||||
"""
|
||||
if Path(model_name).exists():
|
||||
get_logger().info(f"Model {model_name} found at local path, skipping download")
|
||||
return
|
||||
get_logger().info(f"Pre-downloading model {model_name}")
|
||||
t0 = time.perf_counter()
|
||||
path = snapshot_download(repo_id=model_name, repo_type="model")
|
||||
if skip_weights:
|
||||
get_logger().info(f"Pre-downloading config and tokenizer for {model_name} (random init, skipping weights)")
|
||||
path = snapshot_download(
|
||||
repo_id=model_name, repo_type="model", allow_patterns=["*.json", "*.txt", "tokenizer*", "*.jinja"]
|
||||
)
|
||||
else:
|
||||
get_logger().info(f"Pre-downloading model {model_name}")
|
||||
path = snapshot_download(repo_id=model_name, repo_type="model")
|
||||
get_logger().debug(
|
||||
f"Finished pre-downloading model {model_name} to {path} in {format_time(time.perf_counter() - t0)}"
|
||||
)
|
||||
|
||||
@@ -48,12 +48,9 @@ from prime_rl.trainer.utils import (
|
||||
GarbageCollection,
|
||||
MemoryProfiler,
|
||||
Tensors,
|
||||
export_benchmark_json,
|
||||
filter_rl_trainer_tensor_stats_for_wandb,
|
||||
get_zero_gradient_ratio,
|
||||
get_ckpt_disk_metrics,
|
||||
setup_torch_distributed,
|
||||
print_benchmark,
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.trainer.lora import get_lora_state
|
||||
@@ -63,7 +60,7 @@ from prime_rl.utils.metrics_server import HealthServer, MetricsServer
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step, to_col_format
|
||||
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
|
||||
from ring_flash_attn import substitute_hf_flash_attn
|
||||
from torchtitan.distributed.utils import clip_grad_norm_
|
||||
|
||||
@@ -78,10 +75,6 @@ def train(config: TrainerConfig):
|
||||
)
|
||||
logger.info(f"Starting RL trainer in {world} in {config.output_dir}")
|
||||
|
||||
# Print warning if running in benchmark mode
|
||||
if config.bench is not None:
|
||||
logger.warning(f"Running in benchmark mode (max_steps={config.max_steps})")
|
||||
|
||||
# Setup the monitor
|
||||
logger.info(f"Initializing monitor ({config.wandb})")
|
||||
monitor = setup_monitor(
|
||||
@@ -125,17 +118,21 @@ def train(config: TrainerConfig):
|
||||
# Check for checkpoint to resume from
|
||||
checkpoint_step = None
|
||||
logger.info(f"Initializing checkpoint managers ({config.ckpt})")
|
||||
ckpt_manager, weight_ckpt_manager = setup_ckpt_managers(config.output_dir, config.ckpt, config.model.lora)
|
||||
ckpt_manager, weight_ckpt_manager = setup_ckpt_managers(
|
||||
config.output_dir, config.ckpt, config.model.lora, resume=config.resume
|
||||
)
|
||||
|
||||
if config.ckpt and config.ckpt.resume_step is not None and ckpt_manager is not None:
|
||||
if config.ckpt.resume_step == -1:
|
||||
checkpoint_step = resolve_latest_ckpt_step(ckpt_manager.ckpt_dir)
|
||||
if config.resume is not None:
|
||||
if config.resume.dir is not None:
|
||||
checkpoint_step = config.resume.dir_step
|
||||
else:
|
||||
checkpoint_step = config.ckpt.resume_step
|
||||
checkpoint_step = config.resume.step
|
||||
if checkpoint_step is None:
|
||||
checkpoint_step = resolve_latest_ckpt_step(ckpt_manager.ckpt_dir)
|
||||
|
||||
# Initialize the model and tokenizer
|
||||
logger.info(f"Initializing model ({config.model})")
|
||||
loading_from_ckpt_later = config.ckpt and checkpoint_step is not None
|
||||
loading_from_ckpt_later = checkpoint_step is not None
|
||||
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
|
||||
|
||||
logger.info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
@@ -210,7 +207,15 @@ def train(config: TrainerConfig):
|
||||
# Optionally, resume training from a checkpoint
|
||||
progress = Progress()
|
||||
if checkpoint_step is not None:
|
||||
ckpt_manager.load(checkpoint_step, model, [optimizer], scheduler, progress)
|
||||
resume_dir = config.resume.dir if config.resume else None
|
||||
ckpt_manager.load(
|
||||
checkpoint_step,
|
||||
model,
|
||||
[optimizer],
|
||||
scheduler,
|
||||
progress,
|
||||
path=resume_dir / "trainer" if resume_dir is not None else None,
|
||||
)
|
||||
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
|
||||
progress.step += 1
|
||||
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
|
||||
@@ -242,6 +247,7 @@ def train(config: TrainerConfig):
|
||||
prof = profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True).__enter__()
|
||||
maybe_record_function = record_function
|
||||
start_step = progress.step
|
||||
max_peak_memory = 0.0
|
||||
while True:
|
||||
# Reset peak memory stats
|
||||
torch.cuda.reset_peak_memory_stats()
|
||||
@@ -544,8 +550,6 @@ def train(config: TrainerConfig):
|
||||
if grad_norm.device.type == "cpu":
|
||||
grad_norm = grad_norm.to(torch.device("cuda"))
|
||||
|
||||
zero_grad_ratio = get_zero_gradient_ratio(model.parameters(), parallel_dims.dp_replicate)
|
||||
|
||||
# Update the model parameters
|
||||
optimizer.step()
|
||||
optimizer.zero_grad()
|
||||
@@ -580,8 +584,7 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Checkpoint the step we just finished (model = policy v{progress.step}).
|
||||
if (
|
||||
ckpt_manager is not None
|
||||
and (config.ckpt and config.ckpt.interval)
|
||||
(config.ckpt and config.ckpt.interval)
|
||||
# the last step is written once after the loop (final ckpt), so skip it here
|
||||
and not is_last_step
|
||||
and progress.step % config.ckpt.interval == 0
|
||||
@@ -622,6 +625,7 @@ def train(config: TrainerConfig):
|
||||
throughput = perf_counter.get_step_tokens_per_second(num_tokens, forward_backward_time)
|
||||
mfu = perf_counter.get_step_mfu(num_tokens, forward_backward_time)
|
||||
peak_memory = torch.cuda.max_memory_reserved() / 1024**3 # GiB
|
||||
max_peak_memory = max(max_peak_memory, peak_memory)
|
||||
|
||||
# Log step metrics
|
||||
step_time = time.perf_counter() - step_start_time
|
||||
@@ -650,7 +654,6 @@ def train(config: TrainerConfig):
|
||||
# Log optimizer metrics
|
||||
optim_metrics = {
|
||||
"optim/lr": current_lr,
|
||||
"optim/zero_grad_ratio": zero_grad_ratio,
|
||||
"step": progress.step,
|
||||
}
|
||||
if grad_norm is not None:
|
||||
@@ -695,7 +698,6 @@ def train(config: TrainerConfig):
|
||||
mfu=mfu,
|
||||
entropy=tensor_stats.get("entropy/all/mean", 0.0),
|
||||
mismatch_kl=tensor_stats.get("mismatch_kl/all/mean", 0.0),
|
||||
zero_grad_ratio=zero_grad_ratio,
|
||||
)
|
||||
|
||||
# Send heartbeat if configured
|
||||
@@ -717,8 +719,8 @@ def train(config: TrainerConfig):
|
||||
token_exporter.close()
|
||||
|
||||
# Write final checkpoint
|
||||
if ckpt_manager is not None:
|
||||
if not (config.ckpt and config.ckpt.weights_only):
|
||||
if config.ckpt is not None:
|
||||
if not config.ckpt.weights_only:
|
||||
logger.info("Writing final checkpoint")
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
ckpt_manager.maybe_clean()
|
||||
@@ -728,7 +730,7 @@ def train(config: TrainerConfig):
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
|
||||
logger.info(f"Peak memory: {max(to_col_format(monitor.history)['perf/peak_memory']):.1f} GiB")
|
||||
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
|
||||
logger.success("RL trainer finished!")
|
||||
|
||||
# Stop metrics/health server if configured
|
||||
@@ -737,14 +739,6 @@ def train(config: TrainerConfig):
|
||||
if health_server is not None:
|
||||
health_server.stop()
|
||||
|
||||
# Optionally, print benchmark table and export JSON
|
||||
if config.bench is not None and world.is_master:
|
||||
history = to_col_format(monitor.history)
|
||||
print_benchmark(history)
|
||||
if config.bench.output_json:
|
||||
export_benchmark_json(history, config.bench.output_json)
|
||||
logger.info(f"Benchmark results written to {config.bench.output_json}")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry-point for RL trainer. Run using `uv run trainer`"""
|
||||
|
||||
@@ -18,6 +18,7 @@ from torch.profiler import profile, ProfilerActivity, record_function
|
||||
from prime_rl.trainer.ckpt import Progress, setup_ckpt_managers
|
||||
from prime_rl.utils.pathing import resolve_latest_ckpt_step
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.trainer import CheckpointConfig
|
||||
from prime_rl.utils.cp import setup_cp_params, shard_for_cp
|
||||
from prime_rl.trainer.lora import get_lora_state
|
||||
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
|
||||
@@ -39,19 +40,16 @@ from prime_rl.trainer.sft.data import load_sft_dataset, setup_dataloader, setup_
|
||||
from prime_rl.trainer.utils import (
|
||||
GarbageCollection,
|
||||
MemoryProfiler,
|
||||
export_benchmark_json,
|
||||
get_zero_gradient_ratio,
|
||||
get_ckpt_disk_metrics,
|
||||
print_sample,
|
||||
setup_torch_distributed,
|
||||
print_benchmark,
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.utils import clean_exit, to_col_format
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
import torch.distributed as dist
|
||||
|
||||
from torchtitan.distributed.utils import clip_grad_norm_
|
||||
@@ -67,15 +65,9 @@ def train(config: SFTConfig):
|
||||
)
|
||||
logger.info(f"Starting SFT trainer in {world}")
|
||||
|
||||
# Print warning if running in benchmark mode
|
||||
if config.bench is not None:
|
||||
logger.warning(f"Running in benchmark mode (max_steps={config.max_steps})")
|
||||
|
||||
# Setup the monitor
|
||||
logger.info(f"Initializing monitor ({config.wandb})")
|
||||
monitor = setup_monitor(
|
||||
config.wandb, file_config=config.file_monitor, output_dir=config.output_dir, run_config=config
|
||||
)
|
||||
monitor = setup_monitor(config.wandb, file_config=config.file_monitor, output_dir=config.run_dir, run_config=config)
|
||||
|
||||
# Setup heartbeat (only on rank 0)
|
||||
heart = None
|
||||
@@ -128,18 +120,22 @@ def train(config: SFTConfig):
|
||||
|
||||
# Set up checkpoint manager
|
||||
logger.info(f"Initializing checkpoint managers ({config.ckpt})")
|
||||
ckpt_manager, weight_ckpt_manager = setup_ckpt_managers(config.output_dir, config.ckpt, config.model.lora)
|
||||
ckpt_manager, weight_ckpt_manager = setup_ckpt_managers(
|
||||
config.run_dir, config.ckpt, config.model.lora, resume=config.resume
|
||||
)
|
||||
|
||||
checkpoint_step = None
|
||||
if config.ckpt and config.ckpt.resume_step is not None and ckpt_manager is not None:
|
||||
if config.ckpt.resume_step == -1:
|
||||
checkpoint_step = resolve_latest_ckpt_step(ckpt_manager.ckpt_dir)
|
||||
if config.resume is not None:
|
||||
if config.resume.dir is not None:
|
||||
checkpoint_step = config.resume.dir_step
|
||||
else:
|
||||
checkpoint_step = config.ckpt.resume_step
|
||||
checkpoint_step = config.resume.step
|
||||
if checkpoint_step is None:
|
||||
checkpoint_step = resolve_latest_ckpt_step(ckpt_manager.ckpt_dir)
|
||||
|
||||
# Initialize the model and tokenizer
|
||||
logger.info(f"Initializing model ({config.model})")
|
||||
loading_from_ckpt_later = config.ckpt and checkpoint_step is not None
|
||||
loading_from_ckpt_later = checkpoint_step is not None
|
||||
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
|
||||
|
||||
if parallel_dims.cp_enabled:
|
||||
@@ -179,10 +175,11 @@ def train(config: SFTConfig):
|
||||
)
|
||||
|
||||
# Set up the learning rate scheduler
|
||||
# skip_scheduler rebuilds a fresh schedule over the remaining steps: size it from the
|
||||
# resolved checkpoint step (bare --resume and --resume.dir carry no explicit step).
|
||||
scheduler_steps = (
|
||||
config.max_steps - config.ckpt.resume_step
|
||||
if config.max_steps is not None
|
||||
and (config.ckpt and config.ckpt.skip_scheduler and config.ckpt.resume_step is not None)
|
||||
config.max_steps - checkpoint_step
|
||||
if config.max_steps is not None and (config.ckpt and config.ckpt.skip_scheduler and checkpoint_step is not None)
|
||||
else config.max_steps
|
||||
)
|
||||
logger.info(f"Setting up {config.scheduler.type} scheduler with {scheduler_steps} steps ({config.scheduler})")
|
||||
@@ -204,20 +201,23 @@ def train(config: SFTConfig):
|
||||
progress = Progress()
|
||||
|
||||
if checkpoint_step is not None:
|
||||
resume_dir = config.resume.dir if config.resume else None
|
||||
skip = config.ckpt or CheckpointConfig()
|
||||
ckpt_manager.load(
|
||||
checkpoint_step,
|
||||
model,
|
||||
[optimizer],
|
||||
scheduler if not config.ckpt.skip_scheduler else None,
|
||||
progress if not config.ckpt.skip_progress else None,
|
||||
dataloader=dataloader if not config.ckpt.skip_dataloader else None,
|
||||
scheduler if not skip.skip_scheduler else None,
|
||||
progress if not skip.skip_progress else None,
|
||||
dataloader=dataloader if not skip.skip_dataloader else None,
|
||||
path=resume_dir / "trainer" if resume_dir is not None else None,
|
||||
)
|
||||
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
|
||||
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
|
||||
if not config.ckpt.skip_progress:
|
||||
if not skip.skip_progress:
|
||||
progress.step += 1
|
||||
# This redundant setup is necessary because loading the optimizer's state has side effects on the scheduler state dict
|
||||
if config.ckpt.skip_scheduler:
|
||||
if skip.skip_scheduler:
|
||||
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
|
||||
logger.info(
|
||||
f"Starting from step {progress.step} (total_tokens={progress.total_tokens}, total_samples={progress.total_samples}, dataset_state={dataloader.state_dict()['dataset_state']})"
|
||||
@@ -369,6 +369,7 @@ def train(config: SFTConfig):
|
||||
logger.info(f"Tracing to {config.trace_path}")
|
||||
prof = profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True).__enter__()
|
||||
maybe_record_function = record_function # noqa: F841 – captured by run_forward_loop closure
|
||||
max_peak_memory = 0.0
|
||||
while True:
|
||||
# Reset peak memory stats
|
||||
torch.cuda.reset_peak_memory_stats()
|
||||
@@ -470,8 +471,6 @@ def train(config: SFTConfig):
|
||||
)
|
||||
if grad_norm.device.type == "cpu":
|
||||
grad_norm = grad_norm.to(torch.device("cuda"))
|
||||
zero_grad_ratio = get_zero_gradient_ratio(model.parameters(), parallel_dims.dp_replicate)
|
||||
|
||||
logger.debug("Optimizer step")
|
||||
optimizer.step()
|
||||
optimizer.zero_grad()
|
||||
@@ -482,12 +481,7 @@ def train(config: SFTConfig):
|
||||
|
||||
# Checkpoint the step we just finished. The last step's checkpoint is written once after
|
||||
# the loop, so skip it here to avoid a double-save.
|
||||
if (
|
||||
ckpt_manager is not None
|
||||
and (config.ckpt and config.ckpt.interval)
|
||||
and not is_last_step
|
||||
and progress.step % config.ckpt.interval == 0
|
||||
):
|
||||
if (config.ckpt and config.ckpt.interval) and not is_last_step and progress.step % config.ckpt.interval == 0:
|
||||
save_ckpt_time = 0
|
||||
|
||||
if not config.ckpt.weights_only:
|
||||
@@ -528,6 +522,7 @@ def train(config: SFTConfig):
|
||||
throughput = perf_counter.get_tokens_per_second() or 0
|
||||
mfu = perf_counter.get_mfu() or 0
|
||||
peak_memory = torch.cuda.max_memory_reserved() / 1024**3 # GiB
|
||||
max_peak_memory = max(max_peak_memory, peak_memory)
|
||||
|
||||
# Log step metrics
|
||||
step_time = time.perf_counter() - step_start_time
|
||||
@@ -578,7 +573,6 @@ def train(config: SFTConfig):
|
||||
# Log optimizer metrics
|
||||
optim_metrics = {
|
||||
"optim/lr": current_lr,
|
||||
"optim/zero_grad_ratio": zero_grad_ratio,
|
||||
"step": progress.step,
|
||||
}
|
||||
if grad_norm is not None:
|
||||
@@ -603,7 +597,7 @@ def train(config: SFTConfig):
|
||||
monitor.log(time_metrics, step=progress.step)
|
||||
|
||||
# Log disk metrics
|
||||
disk_metrics = get_ckpt_disk_metrics(config.output_dir)
|
||||
disk_metrics = get_ckpt_disk_metrics(config.run_dir)
|
||||
disk_metrics["step"] = progress.step
|
||||
monitor.log(disk_metrics, step=progress.step)
|
||||
|
||||
@@ -630,8 +624,8 @@ def train(config: SFTConfig):
|
||||
logger.info(f"Saved trace to {trace_file}")
|
||||
|
||||
# Write final checkpoint
|
||||
if ckpt_manager is not None:
|
||||
if not (config.ckpt and config.ckpt.weights_only):
|
||||
if config.ckpt is not None:
|
||||
if not config.ckpt.weights_only:
|
||||
logger.info("Writing final checkpoint")
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
ckpt_manager.maybe_clean()
|
||||
@@ -642,17 +636,9 @@ def train(config: SFTConfig):
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer, processor)
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
|
||||
logger.info(f"Peak memory: {max(to_col_format(monitor.history)['perf/peak_memory']):.1f} GiB")
|
||||
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
|
||||
logger.success("SFT trainer finished!")
|
||||
|
||||
# Optionally, print benchmark table and export JSON
|
||||
if config.bench is not None and world.is_master:
|
||||
history = to_col_format(monitor.history)
|
||||
print_benchmark(history)
|
||||
if config.bench.output_json:
|
||||
export_benchmark_json(history, config.bench.output_json)
|
||||
logger.info(f"Benchmark results written to {config.bench.output_json}")
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("SFTTrainer")
|
||||
|
||||
@@ -1,29 +1,22 @@
|
||||
import gc
|
||||
import json
|
||||
import pickle
|
||||
import shutil
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from rich import print as rich_print
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from rich.text import Text
|
||||
from torch import Tensor, nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
from torch import Tensor
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.pathing import get_ckpt_dir
|
||||
from prime_rl.utils.utils import format_num, format_time, get_step_path
|
||||
from prime_rl.utils.utils import get_step_path
|
||||
|
||||
DEFAULT_TIMEOUT = timedelta(seconds=600)
|
||||
|
||||
@@ -55,62 +48,6 @@ class GarbageCollection:
|
||||
get_logger().info(f"[GC] collection took {time.monotonic() - begin:.2f}s")
|
||||
|
||||
|
||||
def _to_local_tensor(tensor: Tensor | DTensor) -> Tensor:
|
||||
if isinstance(tensor, DTensor):
|
||||
return tensor.to_local()
|
||||
return tensor
|
||||
|
||||
|
||||
def count_zero_gradient_elements(parameters: Iterable[nn.Parameter]) -> tuple[Tensor, Tensor]:
|
||||
"""Count zero-gradient parameter elements on the local distributed shards.
|
||||
|
||||
Parameters that require gradients but did not receive one in the current step
|
||||
are counted as fully zero. This makes inactive MoE experts visible in the
|
||||
metric instead of silently dropping them from the count.
|
||||
"""
|
||||
|
||||
device = torch.device("cuda", torch.cuda.current_device()) if torch.cuda.is_available() else torch.device("cpu")
|
||||
num_zeros = torch.zeros((), dtype=torch.long, device=device)
|
||||
num_tracked = torch.zeros((), dtype=torch.long, device=device)
|
||||
|
||||
for param in parameters:
|
||||
if not param.requires_grad:
|
||||
continue
|
||||
|
||||
local_param = _to_local_tensor(param.detach())
|
||||
if local_param.numel() == 0:
|
||||
continue
|
||||
|
||||
if local_param.device != num_zeros.device:
|
||||
num_zeros = num_zeros.to(local_param.device)
|
||||
num_tracked = num_tracked.to(local_param.device)
|
||||
|
||||
local_numel = torch.tensor(local_param.numel(), dtype=torch.long, device=local_param.device)
|
||||
num_tracked += local_numel
|
||||
|
||||
if param.grad is None:
|
||||
num_zeros += local_numel
|
||||
continue
|
||||
|
||||
local_grad = _to_local_tensor(param.grad.detach())
|
||||
if local_grad.numel() != local_param.numel():
|
||||
raise ValueError("Local gradient shape does not match the local parameter shape")
|
||||
|
||||
num_zeros += local_numel - torch.count_nonzero(local_grad)
|
||||
|
||||
return num_zeros, num_tracked
|
||||
|
||||
|
||||
def get_zero_gradient_ratio(parameters: Iterable[nn.Parameter], dp_replicate: int = 1) -> float:
|
||||
num_zero_grad, num_grad_elements = count_zero_gradient_elements(parameters)
|
||||
dist.all_reduce(num_zero_grad, op=dist.ReduceOp.SUM)
|
||||
dist.all_reduce(num_grad_elements, op=dist.ReduceOp.SUM)
|
||||
if dp_replicate > 1:
|
||||
num_zero_grad = torch.div(num_zero_grad, dp_replicate, rounding_mode="floor")
|
||||
num_grad_elements = torch.div(num_grad_elements, dp_replicate, rounding_mode="floor")
|
||||
return (num_zero_grad.float() / num_grad_elements.clamp_min(1).float()).item()
|
||||
|
||||
|
||||
def get_ckpt_disk_metrics(output_dir: Path) -> dict[str, float]:
|
||||
"""
|
||||
Disk usage metrics for the checkpoint directory (<output_dir>/checkpoints).
|
||||
@@ -154,125 +91,6 @@ def print_sample(input_ids: list[int], loss_mask: list[bool], tokenizer: PreTrai
|
||||
rich_print(text)
|
||||
|
||||
|
||||
def print_benchmark(history: dict[str, list[Any]]) -> None:
|
||||
"""
|
||||
Print benchmark results as rich table. Shows formatted values for the
|
||||
training throughput and overall step time. First first N rows show the
|
||||
per-step values, and the last row shows the mean, std, min, and max values.
|
||||
"""
|
||||
history.pop("step")
|
||||
assert all(len(v) for v in history.values()), "All metrics must have logged the same number of steps"
|
||||
|
||||
# Turn metric history into pd.DataFrame
|
||||
df = pd.DataFrame(dict(history.items()))
|
||||
columns = {
|
||||
"perf/mfu": "MFU",
|
||||
"perf/throughput": "Throughput",
|
||||
"time/step": "Step Time",
|
||||
"perf/peak_memory": "Peak Memory",
|
||||
}
|
||||
df = df[columns.keys()].rename(columns=columns)
|
||||
df = df.iloc[1:] # Exclude first row
|
||||
|
||||
# Setup console
|
||||
console = Console()
|
||||
table = Table(title="Benchmark")
|
||||
|
||||
# Add columns
|
||||
table.add_column("Step", justify="right")
|
||||
for col in df.columns:
|
||||
table.add_column(col, justify="center", style="magenta")
|
||||
|
||||
# Add formatted rows
|
||||
formatted_df = pd.DataFrame(columns=df.columns)
|
||||
formatted_df["MFU"] = df["MFU"].apply(lambda x: f"{format_num(x, precision=2)}%")
|
||||
formatted_df["Throughput"] = df["Throughput"].apply(lambda x: format_num(x, precision=2))
|
||||
formatted_df["Step Time"] = df["Step Time"].apply(format_time)
|
||||
formatted_df["Peak Memory"] = df["Peak Memory"].apply(lambda x: f"{format_num(x, precision=1)} GiB")
|
||||
for step, row in formatted_df.iterrows():
|
||||
table.add_row(*([str(step)] + [str(x) for x in row]))
|
||||
|
||||
# Separator
|
||||
table.add_row(*([""] * len(formatted_df.columns)))
|
||||
|
||||
# Add row for formatted, aggregated statistics
|
||||
mean_df = df.describe().loc[["mean", "std", "min", "max"], :]
|
||||
formatted_mean_df = pd.DataFrame()
|
||||
formatted_mean_df["MFU"] = mean_df["MFU"].apply(lambda x: f"{format_num(x, precision=2)}%")
|
||||
formatted_mean_df["Throughput"] = mean_df["Throughput"].apply(format_num, precision=2)
|
||||
formatted_mean_df["Step Time"] = mean_df["Step Time"].apply(format_time)
|
||||
mean_row = (
|
||||
["Overall"]
|
||||
+ formatted_mean_df.T.apply(
|
||||
lambda row: f"{row['mean']} ± {row['std']} [{row['min']}, {row['max']}]", axis=1
|
||||
).tolist()
|
||||
+ [
|
||||
f"{format_num(mean_df['Peak Memory']['mean'], precision=1)} GiB ({mean_df['Peak Memory']['mean'] / (torch.cuda.mem_get_info()[1] / 1024**3) * 100:.1f}%)"
|
||||
]
|
||||
)
|
||||
table.add_row(*mean_row)
|
||||
|
||||
# Display table
|
||||
console.print(table)
|
||||
|
||||
|
||||
def export_benchmark_json(history: dict[str, list[Any]], output_path: Path) -> None:
|
||||
"""
|
||||
Export benchmark results to a JSON file.
|
||||
|
||||
The JSON contains aggregated statistics (mean, std, min, max) for each metric.
|
||||
"""
|
||||
history = history.copy()
|
||||
history.pop("step", None)
|
||||
|
||||
# Turn metric history into pd.DataFrame
|
||||
df = pd.DataFrame(dict(history.items()))
|
||||
columns = {
|
||||
"perf/mfu": "mfu",
|
||||
"perf/throughput": "throughput",
|
||||
"time/step": "step_time",
|
||||
"perf/peak_memory": "peak_memory",
|
||||
}
|
||||
df = df[columns.keys()].rename(columns=columns)
|
||||
df = df.iloc[1:] # Exclude first warmup row
|
||||
|
||||
# Calculate statistics
|
||||
stats = df.describe().loc[["mean", "std", "min", "max"], :]
|
||||
|
||||
# Get peak memory percentage
|
||||
total_memory_gib = torch.cuda.mem_get_info()[1] / 1024**3
|
||||
peak_memory_pct = stats["peak_memory"]["mean"] / total_memory_gib * 100
|
||||
|
||||
result = {
|
||||
"mfu": {
|
||||
"mean": float(stats["mfu"]["mean"]),
|
||||
"std": float(stats["mfu"]["std"]),
|
||||
"min": float(stats["mfu"]["min"]),
|
||||
"max": float(stats["mfu"]["max"]),
|
||||
},
|
||||
"throughput": {
|
||||
"mean": float(stats["throughput"]["mean"]),
|
||||
"std": float(stats["throughput"]["std"]),
|
||||
"min": float(stats["throughput"]["min"]),
|
||||
"max": float(stats["throughput"]["max"]),
|
||||
},
|
||||
"step_time": {
|
||||
"mean": float(stats["step_time"]["mean"]),
|
||||
"std": float(stats["step_time"]["std"]),
|
||||
"min": float(stats["step_time"]["min"]),
|
||||
"max": float(stats["step_time"]["max"]),
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": float(stats["peak_memory"]["mean"]),
|
||||
"pct": float(peak_memory_pct),
|
||||
},
|
||||
}
|
||||
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(output_path, "w") as f:
|
||||
json.dump(result, f, indent=2)
|
||||
|
||||
|
||||
def flexible_all_gather(tensor: Tensor) -> Tensor:
|
||||
"""
|
||||
All-gather a 1D tensor between all ranks, with potentially different numbr of element per rank.
|
||||
|
||||
@@ -103,11 +103,6 @@ class MetricsServer(HealthServer):
|
||||
"trainer_mismatch_kl", "KL divergence between trainer and inference model", registry=self._registry
|
||||
)
|
||||
self._kl_ent_ratio = Gauge("trainer_kl_ent_ratio", "Ratio of mismatch KL to entropy", registry=self._registry)
|
||||
self._zero_grad_ratio = Gauge(
|
||||
"trainer_zero_grad_ratio",
|
||||
"Fraction of tracked parameter elements with zero gradient",
|
||||
registry=self._registry,
|
||||
)
|
||||
|
||||
def _make_handler(self) -> type[BaseHTTPRequestHandler]:
|
||||
"""Create handler with /metrics and /health endpoints."""
|
||||
@@ -164,7 +159,6 @@ class MetricsServer(HealthServer):
|
||||
mfu: float = 0.0,
|
||||
entropy: float = 0.0,
|
||||
mismatch_kl: float = 0.0,
|
||||
zero_grad_ratio: float = 0.0,
|
||||
) -> None:
|
||||
"""Update metrics after a training step."""
|
||||
self._step.set(step)
|
||||
@@ -177,7 +171,6 @@ class MetricsServer(HealthServer):
|
||||
self._mfu.set(mfu)
|
||||
self._entropy.set(entropy)
|
||||
self._mismatch_kl.set(mismatch_kl)
|
||||
self._zero_grad_ratio.set(zero_grad_ratio)
|
||||
if entropy > 0:
|
||||
self._kl_ent_ratio.set(mismatch_kl / entropy)
|
||||
self._last_step_ts.set(time.time())
|
||||
|
||||
@@ -40,19 +40,12 @@ def setup_monitor(
|
||||
*,
|
||||
prime_config: PrimeMonitorConfig | None = None,
|
||||
file_config: FileMonitorConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
train_env_names: list[str] = [],
|
||||
eval_env_names: list[str] = [],
|
||||
# Backward compatibility: support old 'config' keyword argument
|
||||
config: WandbWithExtrasConfig | None = None,
|
||||
) -> Monitor:
|
||||
"""
|
||||
Sets up monitors to log metrics.
|
||||
|
||||
`keep_full_history`: when False, monitors retain only the most recent
|
||||
metrics dict. The orchestrator passes False outside `--bench` mode to
|
||||
avoid an unbounded list growing for the lifetime of the run.
|
||||
"""
|
||||
"""Sets up monitors to log metrics."""
|
||||
global _MONITOR
|
||||
if _MONITOR is not None:
|
||||
raise RuntimeError("Monitor already initialized. Please call `setup_monitor` only once.")
|
||||
@@ -69,7 +62,6 @@ def setup_monitor(
|
||||
output_dir=output_dir,
|
||||
tokenizer=tokenizer,
|
||||
run_config=run_config,
|
||||
keep_full_history=keep_full_history,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
)
|
||||
@@ -82,7 +74,6 @@ def setup_monitor(
|
||||
output_dir=output_dir,
|
||||
tokenizer=tokenizer,
|
||||
run_config=run_config,
|
||||
keep_full_history=keep_full_history,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -92,12 +83,11 @@ def setup_monitor(
|
||||
config=file_config,
|
||||
output_dir=output_dir,
|
||||
run_config=run_config,
|
||||
keep_full_history=keep_full_history,
|
||||
)
|
||||
)
|
||||
|
||||
if len(monitors) == 0:
|
||||
_MONITOR = NoOpMonitor(keep_full_history=keep_full_history)
|
||||
_MONITOR = NoOpMonitor()
|
||||
elif len(monitors) == 1:
|
||||
_MONITOR = monitors[0]
|
||||
else:
|
||||
|
||||
@@ -71,11 +71,7 @@ def sample_items_for_logging(items: list[Any], sample_ratio: float | None) -> li
|
||||
|
||||
|
||||
class Monitor(ABC):
|
||||
"""Base class for all monitoring implementations.
|
||||
|
||||
Subclasses should initialize a `history` attribute as a list of dictionaries
|
||||
to store logged metrics.
|
||||
"""
|
||||
"""Base class for all monitoring implementations."""
|
||||
|
||||
run_id: str | None = None
|
||||
"""External identifier of the run this monitor reports to (platform / W&B), when it has one."""
|
||||
@@ -108,15 +104,8 @@ class Monitor(ABC):
|
||||
class NoOpMonitor(Monitor):
|
||||
"""Monitor that does nothing. Used when no monitors are configured."""
|
||||
|
||||
def __init__(self, keep_full_history: bool = True):
|
||||
self.history: list[dict[str, Any]] = []
|
||||
self._keep_full_history = keep_full_history
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
if self._keep_full_history:
|
||||
self.history.append(metrics)
|
||||
else:
|
||||
self.history = [metrics]
|
||||
pass
|
||||
|
||||
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
|
||||
pass
|
||||
|
||||
@@ -30,12 +30,10 @@ class FileMonitor(Monitor):
|
||||
config: FileMonitorConfig | None,
|
||||
output_dir: Path | None = None,
|
||||
run_config: BaseConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
):
|
||||
self.config = config
|
||||
self.logger = get_logger()
|
||||
self.history: list[dict[str, Any]] = []
|
||||
self._keep_full_history = keep_full_history
|
||||
self._last_metrics: dict[str, Any] = {}
|
||||
self.output_dir = output_dir
|
||||
self._file = None
|
||||
|
||||
@@ -59,10 +57,7 @@ class FileMonitor(Monitor):
|
||||
self.logger.info(f"Logging metrics to {self._path}")
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
if self._keep_full_history:
|
||||
self.history.append(metrics)
|
||||
else:
|
||||
self.history = [metrics]
|
||||
self._last_metrics = metrics
|
||||
if not self.is_master or not self.enabled or self._file is None:
|
||||
return
|
||||
|
||||
@@ -91,7 +86,7 @@ class FileMonitor(Monitor):
|
||||
def save_final_summary(self, filename: str = "final_summary.json") -> None:
|
||||
if not self.is_master or not self.enabled or self.output_dir is None:
|
||||
return
|
||||
summary = self.history[-1] if self.history else {}
|
||||
summary = self._last_metrics
|
||||
dropped_paths: list[str] = []
|
||||
sanitized = drop_non_finite_json_values(summary, dropped_paths)
|
||||
with open(self.output_dir / filename, "w") as f:
|
||||
|
||||
@@ -20,12 +20,6 @@ class MultiMonitor(Monitor):
|
||||
prime = next((m for m in monitors if isinstance(m, PrimeMonitor)), None)
|
||||
self.run_id = (prime.run_id if prime else None) or next((m.run_id for m in monitors if m.run_id), None)
|
||||
|
||||
@property
|
||||
def history(self) -> list[dict[str, Any]]:
|
||||
if not self.monitors:
|
||||
return []
|
||||
return self.monitors[0].history
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
for monitor in self.monitors:
|
||||
try:
|
||||
|
||||
@@ -75,12 +75,10 @@ class PrimeMonitor(Monitor):
|
||||
output_dir: Path | None = None,
|
||||
tokenizer: PreTrainedTokenizer | None = None,
|
||||
run_config: OrchestratorConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
):
|
||||
self.config = config
|
||||
self.logger = get_logger()
|
||||
self.history: list[dict[str, Any]] = []
|
||||
self._keep_full_history = keep_full_history
|
||||
self._last_metrics: dict[str, Any] = {}
|
||||
self.output_dir = output_dir
|
||||
self._registered = False
|
||||
self._finalized = False
|
||||
@@ -232,10 +230,7 @@ class PrimeMonitor(Monitor):
|
||||
self.logger.info(f"Platform run {self.run_id} marked as {status_label}")
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
if self._keep_full_history:
|
||||
self.history.append(metrics)
|
||||
else:
|
||||
self.history = [metrics]
|
||||
self._last_metrics = metrics
|
||||
if not self.is_master:
|
||||
return
|
||||
if not self.enabled:
|
||||
@@ -518,7 +513,7 @@ class PrimeMonitor(Monitor):
|
||||
return
|
||||
|
||||
self.logger.info("Saving final summary to Prime Intellect API")
|
||||
summary = self.history[-1] if self.history else {}
|
||||
summary = self._last_metrics
|
||||
finalized_via_summary = self._submit_final_summary(summary)
|
||||
|
||||
if os.getpid() != self._owner_pid:
|
||||
|
||||
@@ -52,14 +52,11 @@ class WandbMonitor(Monitor):
|
||||
output_dir: Path | None = None,
|
||||
tokenizer: PreTrainedTokenizer | None = None,
|
||||
run_config: BaseConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
train_env_names: list[str] = [],
|
||||
eval_env_names: list[str] = [],
|
||||
):
|
||||
self.config = config
|
||||
self.logger = get_logger()
|
||||
self.history: list[dict[str, Any]] = []
|
||||
self._keep_full_history = keep_full_history
|
||||
self.output_dir = output_dir
|
||||
|
||||
rank = int(os.environ.get("RANK", os.environ.get("DP_RANK", "0")))
|
||||
@@ -79,7 +76,8 @@ class WandbMonitor(Monitor):
|
||||
_wandb_mode = os.environ.get("WANDB_MODE")
|
||||
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1" and _wandb_mode not in ("disabled", "offline")
|
||||
if shared_mode:
|
||||
run_id = os.environ.get("WANDB_SHARED_RUN_ID")
|
||||
# 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(
|
||||
@@ -179,10 +177,6 @@ class WandbMonitor(Monitor):
|
||||
sys.argv = json.loads(wandb_args)
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
if self._keep_full_history:
|
||||
self.history.append(metrics)
|
||||
else:
|
||||
self.history = [metrics]
|
||||
if not self.is_master:
|
||||
return
|
||||
if not self.enabled:
|
||||
@@ -322,11 +316,32 @@ PERFORMANCE_METRICS = [
|
||||
"time/step",
|
||||
"time/wait_for_batch",
|
||||
"time/wait_for_policy",
|
||||
"inference/agg/throughput",
|
||||
"inference/agg/running_requests",
|
||||
"inference/agg/waiting_requests",
|
||||
"inference/agg/kv_cache_usage_mean",
|
||||
"inference/agg/prefix_cache_hit_rate",
|
||||
]
|
||||
|
||||
# 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.
|
||||
@@ -344,6 +359,16 @@ def line_panels(metrics: Sequence[str], regexes: Sequence[str]) -> list[wr.LineP
|
||||
]
|
||||
|
||||
|
||||
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,
|
||||
@@ -393,6 +418,7 @@ def build_sections(train_envs: Sequence[str] = (), eval_envs: Sequence[str] = ()
|
||||
# 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
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
@@ -10,6 +11,34 @@ def get_log_dir(output_dir: Path) -> Path:
|
||||
return output_dir / "logs"
|
||||
|
||||
|
||||
def create_attempt_log_dir(run_dir: Path) -> Path:
|
||||
"""Create ``logs/attempt_<n>`` for this launch attempt and repoint ``logs/latest`` to it.
|
||||
|
||||
Every launch — fresh or resumed — gets its own numbered log directory, so a resume
|
||||
never overwrites an earlier attempt's logs. Returns the attempt directory."""
|
||||
logs_dir = get_log_dir(run_dir)
|
||||
logs_dir.mkdir(parents=True, exist_ok=True)
|
||||
attempts = (
|
||||
int(p.name.removeprefix("attempt_"))
|
||||
for p in logs_dir.glob("attempt_*")
|
||||
if p.name.removeprefix("attempt_").isdigit()
|
||||
)
|
||||
attempt_dir = logs_dir / f"attempt_{1 + max(attempts, default=0)}"
|
||||
attempt_dir.mkdir()
|
||||
# Atomically repoint the relative ``latest`` symlink: create a temp link, then rename.
|
||||
tmp_link = logs_dir / f".{attempt_dir.name}"
|
||||
if tmp_link.is_symlink() or tmp_link.exists():
|
||||
tmp_link.unlink()
|
||||
os.symlink(attempt_dir.name, tmp_link)
|
||||
os.replace(tmp_link, logs_dir / "latest")
|
||||
return attempt_dir
|
||||
|
||||
|
||||
def latest_log_dir(run_dir: Path) -> Path:
|
||||
"""The current attempt's log directory, via the ``logs/latest`` symlink."""
|
||||
return get_log_dir(run_dir) / "latest"
|
||||
|
||||
|
||||
def format_log_message(
|
||||
log_dir: Path,
|
||||
trainer: bool = False,
|
||||
@@ -30,7 +59,7 @@ def format_log_message(
|
||||
|
||||
log_lines: list[str] = []
|
||||
if job_log:
|
||||
log_lines.append(f"{i1}{'Job:':<{col}}tail -F {log_dir.parent}/job_*.log")
|
||||
log_lines.append(f"{i1}{'Job:':<{col}}tail -F {log_dir.parent.parent}/job_*.log")
|
||||
if trainer:
|
||||
log_lines.append(f"{i1}{'Trainer:':<{col}}tail -F {log_dir}/trainer.log")
|
||||
if num_train_nodes > 1:
|
||||
@@ -117,37 +146,58 @@ def has_checkpoints(output_dir: Path) -> bool:
|
||||
return ckpt_dir.exists() and any(ckpt_dir.iterdir())
|
||||
|
||||
|
||||
def validate_output_dir(output_dir: Path, *, resuming: bool, clean: bool, ckpt_output_dir: Path | None = None) -> None:
|
||||
"""Validate the output directory before training starts.
|
||||
# Launcher artifacts that may exist in a run directory before training starts: resolved
|
||||
# configs and the SLURM script/job log (a submitted job re-invokes the entrypoint inside
|
||||
# the run directory). Everything else is treated as artifacts of a previous run.
|
||||
LAUNCHER_ARTIFACTS = ("configs", "rl.sbatch", "sft.sbatch", "job_*.log")
|
||||
|
||||
Raises if the directory contains checkpoints from a previous run, unless
|
||||
explicitly resuming or opting into cleaning. Other artifacts (logs,
|
||||
rollouts, configs) are fine and don't trigger the error.
|
||||
|
||||
def has_run_artifacts(run_dir: Path) -> bool:
|
||||
"""Check if the run directory contains artifacts beyond what the launcher pre-writes."""
|
||||
if not run_dir.exists():
|
||||
return False
|
||||
launcher_entries = {entry for pattern in LAUNCHER_ARTIFACTS for entry in run_dir.glob(pattern)}
|
||||
return any(entry not in launcher_entries for entry in run_dir.iterdir())
|
||||
|
||||
|
||||
def validate_run_dir(
|
||||
run_dir: Path, *, output_dir: Path, resuming: bool, clean: bool, ckpt_output_dir: Path | None = None
|
||||
) -> None:
|
||||
"""Validate the run directory before training starts.
|
||||
|
||||
Raises if the run directory was already used by a previous run, unless explicitly
|
||||
resuming or opting into cleaning — a second run writing into the same run directory
|
||||
would overwrite or interleave with the first run's artifacts.
|
||||
|
||||
When ckpt_output_dir is set, checkpoints live there instead of under
|
||||
output_dir, so the guard and clean logic check both locations.
|
||||
run_dir, so the guard and clean logic check both locations.
|
||||
"""
|
||||
dirs_to_check = [output_dir]
|
||||
if ckpt_output_dir is not None and ckpt_output_dir != output_dir:
|
||||
dirs_to_check.append(ckpt_output_dir)
|
||||
|
||||
if resuming:
|
||||
return
|
||||
if clean:
|
||||
if not run_dir.resolve().is_relative_to(output_dir.resolve()):
|
||||
raise ValueError(f"clean requires the run directory ({run_dir}) to remain under output_dir ({output_dir})")
|
||||
logger = get_logger()
|
||||
for d in dirs_to_check:
|
||||
dirs_to_clean = [run_dir]
|
||||
if ckpt_output_dir is not None and ckpt_output_dir != run_dir:
|
||||
dirs_to_clean.append(ckpt_output_dir)
|
||||
for d in dirs_to_clean:
|
||||
if d.exists():
|
||||
logger.warning(f"Cleaning existing directory: {d}")
|
||||
shutil.rmtree(d)
|
||||
return
|
||||
for d in dirs_to_check:
|
||||
if has_checkpoints(d):
|
||||
raise FileExistsError(
|
||||
f"Directory '{d}' already contains checkpoints from a previous run. "
|
||||
f"To resume the latest step of the previous run, set ckpt.resume_step=-1 or --ckpt.resume-step -1 via CLI. "
|
||||
f"To delete the existing directory and start fresh, set clean_output_dir=true or --clean-output-dir via CLI. "
|
||||
f"Otherwise use a unique output_dir for this experiment."
|
||||
)
|
||||
blocked = None
|
||||
if has_run_artifacts(run_dir):
|
||||
blocked = f"Run directory '{run_dir}' already contains artifacts from a previous run."
|
||||
elif ckpt_output_dir is not None and ckpt_output_dir != run_dir and has_checkpoints(ckpt_output_dir):
|
||||
blocked = f"Checkpoint directory '{ckpt_output_dir}' already contains checkpoints from a previous run."
|
||||
if blocked:
|
||||
raise FileExistsError(
|
||||
f"{blocked} "
|
||||
f"To resume the latest step of the previous run, pass --resume (or --resume.step N). "
|
||||
f"To delete the existing directory and start fresh, set clean=true or --clean via CLI. "
|
||||
f"Otherwise use a unique run name (run.name or --run.name via CLI) or output_dir for this run."
|
||||
)
|
||||
|
||||
|
||||
def clean_future_steps(output_dir: Path, resume_step: int) -> None:
|
||||
|
||||
@@ -83,30 +83,6 @@ def clean_exit(func: Callable) -> Callable:
|
||||
return sync_wrapper
|
||||
|
||||
|
||||
def to_col_format(list_of_dicts: list[dict[str, Any]]) -> dict[str, list[Any]]:
|
||||
"""
|
||||
Turns a list of dicts to a dict of lists.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
list_of_dicts = [{"a": 1, "b": 2}, {"a": 3, "b": 4}] # Row format
|
||||
to_col_format(list_of_dicts)
|
||||
```
|
||||
|
||||
Returns:
|
||||
|
||||
```python
|
||||
{"a": [1, 3], "b": [2, 4]} # Column format
|
||||
```
|
||||
"""
|
||||
dict_of_lists = defaultdict(list)
|
||||
for row in list_of_dicts:
|
||||
for key, value in row.items():
|
||||
dict_of_lists[key].append(value)
|
||||
return dict(dict_of_lists)
|
||||
|
||||
|
||||
def format_time(time_s: float) -> str:
|
||||
"""
|
||||
Format a time in seconds to a human-readable format:
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ def branch_name() -> str:
|
||||
@pytest.fixture(scope="session")
|
||||
def output_dir(tmp_path_factory: pytest.TempPathFactory) -> Generator[Path, None, None]:
|
||||
"""Fixture for the tests' output directory. Never deleted — CI uploads run logs
|
||||
from it on failure; runs start with ``--clean-output-dir`` for a fresh workspace."""
|
||||
from it on failure; runs start with ``--clean`` for a fresh workspace."""
|
||||
output_dir = Path(os.environ.get("PYTEST_OUTPUT_DIR", tmp_path_factory.mktemp("outputs")))
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
yield output_dir
|
||||
|
||||
@@ -14,6 +14,13 @@ from tests.utils import (
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
RUN_NAME = "alphabet-sort"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
TIMEOUT = 1200 # 20 minutes (was 900s — alphabet-sort steps can take 2+ min
|
||||
# each on contended CI GPU runners, and vLLM warm-up eats ~2 min)
|
||||
@@ -38,39 +45,41 @@ def rl_process(
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/alphabet_sort.toml",
|
||||
"--clean-output-dir",
|
||||
"--clean",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
def test_no_error(rl_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
check_no_error(rl_process, run_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process."""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
|
||||
def test_reward_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_in_range(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the reward is in range in the RL process."""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.10)
|
||||
|
||||
|
||||
def test_mismatch_kl_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_mismatch_kl_in_range(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the average mismatch KL is below 0.15 across the last 5 steps."""
|
||||
with open(output_dir / "logs" / "trainer.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "trainer.log", "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_avg_mismatch_kl_in_range(trainer_stdout, last_n_steps=5, max_threshold=0.15)
|
||||
|
||||
@@ -14,6 +14,13 @@ from tests.utils import (
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
RUN_NAME = "reverse-text"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
TIMEOUT = 900 # 15 minutes (was 600s — can be tight on contended CI runners
|
||||
# after verifiers per-call tracing overhead was added)
|
||||
@@ -38,13 +45,15 @@ def rl_process(
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/reverse-text/start.toml",
|
||||
"--clean-output-dir",
|
||||
"--clean",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
@@ -72,46 +81,48 @@ def rl_resume_process(
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
def test_no_error(rl_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
check_no_error(rl_process, run_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
|
||||
def test_reward_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_in_range(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the reward is in range in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.6)
|
||||
|
||||
|
||||
def test_mismatch_kl_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_mismatch_kl_in_range(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the average mismatch KL is below 0.01 across all steps"""
|
||||
with open(output_dir / "logs" / "trainer.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "trainer.log", "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_avg_mismatch_kl_in_range(trainer_stdout, last_n_steps=3, max_threshold=0.01)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error_resume(rl_resume_process: ProcessResult, output_dir: Path):
|
||||
def test_no_error_resume(rl_resume_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the RL resume process does not fail."""
|
||||
check_no_error(rl_resume_process, output_dir)
|
||||
check_no_error(rl_resume_process, run_dir)
|
||||
|
||||
|
||||
def test_reward_in_range_resume(rl_resume_process: ProcessResult, test_no_error_resume, output_dir: Path):
|
||||
def test_reward_in_range_resume(rl_resume_process: ProcessResult, test_no_error_resume, run_dir: Path):
|
||||
"""Tests that the reward is in range in the RL resume process"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.6)
|
||||
|
||||
@@ -8,6 +8,13 @@ from tests.utils import check_no_error, check_reward_goes_up, check_reward_in_ra
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
RUN_NAME = "reverse-text-lora"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
TIMEOUT = 600 # 10 minutes
|
||||
|
||||
@@ -31,13 +38,15 @@ def rl_process(
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/reverse-text-lora/start.toml",
|
||||
"--clean-output-dir",
|
||||
"--clean",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
return run_process(cmd, env={"VLLM_ALLOW_RUNTIME_LORA_UPDATING": "True"}, timeout=TIMEOUT)
|
||||
|
||||
@@ -65,39 +74,41 @@ def rl_resume_process(
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
|
||||
return run_process(cmd, env={"VLLM_ALLOW_RUNTIME_LORA_UPDATING": "True"}, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
def test_no_error(rl_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
check_no_error(rl_process, run_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
|
||||
def test_reward_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_in_range(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the reward is in range in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.65)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error_resume(rl_resume_process: ProcessResult, output_dir: Path):
|
||||
def test_no_error_resume(rl_resume_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the RL resume process does not fail."""
|
||||
check_no_error(rl_resume_process, output_dir)
|
||||
check_no_error(rl_resume_process, run_dir)
|
||||
|
||||
|
||||
def test_reward_in_range_resume(rl_resume_process: ProcessResult, test_no_error_resume, output_dir: Path):
|
||||
def test_reward_in_range_resume(rl_resume_process: ProcessResult, test_no_error_resume, run_dir: Path):
|
||||
"""Tests that the reward is in range in the RL resume process"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.65)
|
||||
|
||||
@@ -8,6 +8,14 @@ from tests.utils import check_no_error
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
RUN_NAME = "reverse-text-moe"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
TIMEOUT = 900 # 15 minutes
|
||||
|
||||
|
||||
@@ -29,7 +37,7 @@ def rl_process(
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/reverse-text-moe/start.toml",
|
||||
"--clean-output-dir",
|
||||
"--clean",
|
||||
"--trainer.model.impl",
|
||||
"custom",
|
||||
"--wandb.project",
|
||||
@@ -38,13 +46,15 @@ def rl_process(
|
||||
f"{wandb_name}-custom",
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
check_no_error(rl_process, output_dir)
|
||||
def test_no_error(rl_process: ProcessResult, run_dir: Path):
|
||||
check_no_error(rl_process, run_dir)
|
||||
|
||||
|
||||
def test_moe_runs(rl_process: ProcessResult, test_no_error):
|
||||
|
||||
@@ -14,6 +14,14 @@ from tests.utils import check_final_eval_reward_above, check_no_error, strip_esc
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
RUN_NAME = "reverse-text-rl-opd"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
TIMEOUT = 900 # 15 minutes (was 600s — the OPD orchestrator finishes in ~8m but
|
||||
# the rl entrypoint cleanup phase can push total wall-clock past the old limit)
|
||||
REF_PORT = 8001
|
||||
@@ -40,7 +48,7 @@ def ref_inference(output_dir: Path) -> Generator[subprocess.Popen, None, None]:
|
||||
"""Spawn a `uv run inference` frozen reference server on GPU 0 (shared with the rl-launched
|
||||
policy) at 40% gpu_memory_utilization. Tears down at module scope.
|
||||
"""
|
||||
# The rl entrypoint's --clean-output-dir wipes the rl output_dir on start,
|
||||
# The rl entrypoint's --clean wipes the rl output_dir on start,
|
||||
# so park the reference-server log next to it instead of inside it.
|
||||
ref_log_dir = output_dir.parent / f"{output_dir.name}_ref"
|
||||
ref_log_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -92,23 +100,25 @@ def rl_opd_process(
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/reverse-text-rl-opd/start.toml",
|
||||
"--clean-output-dir",
|
||||
"--clean",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_opd_process: ProcessResult, output_dir: Path):
|
||||
check_no_error(rl_opd_process, output_dir)
|
||||
def test_no_error(rl_opd_process: ProcessResult, run_dir: Path):
|
||||
check_no_error(rl_opd_process, run_dir)
|
||||
|
||||
|
||||
def test_eval_reward_converges(rl_opd_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
def test_eval_reward_converges(rl_opd_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_final_eval_reward_above(orchestrator_stdout, env_name="reverse-text", min_threshold=0.5)
|
||||
|
||||
@@ -14,6 +14,14 @@ from tests.utils import check_final_eval_reward_above, check_no_error, strip_esc
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
RUN_NAME = "reverse-text-rl-sft"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
TIMEOUT = 900 # 15 minutes (was 600s — same overhead as reverse_text)
|
||||
REF_PORT = 8001
|
||||
REF_READY_TIMEOUT_S = 300
|
||||
@@ -39,7 +47,7 @@ def ref_inference(output_dir: Path) -> Generator[subprocess.Popen, None, None]:
|
||||
"""Spawn a `uv run inference` frozen reference server on GPU 0 (shared with the rl-launched
|
||||
policy) at 40% gpu_memory_utilization. Tears down at module scope.
|
||||
"""
|
||||
# The rl entrypoint's --clean-output-dir wipes the rl output_dir on start,
|
||||
# The rl entrypoint's --clean wipes the rl output_dir on start,
|
||||
# so park the reference-server log next to it instead of inside it.
|
||||
ref_log_dir = output_dir.parent / f"{output_dir.name}_ref"
|
||||
ref_log_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -91,23 +99,25 @@ def rl_sft_process(
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/reverse-text-rl-sft/start.toml",
|
||||
"--clean-output-dir",
|
||||
"--clean",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_sft_process: ProcessResult, output_dir: Path):
|
||||
check_no_error(rl_sft_process, output_dir)
|
||||
def test_no_error(rl_sft_process: ProcessResult, run_dir: Path):
|
||||
check_no_error(rl_sft_process, run_dir)
|
||||
|
||||
|
||||
def test_eval_reward_converges(rl_sft_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
def test_eval_reward_converges(rl_sft_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_final_eval_reward_above(orchestrator_stdout, env_name="reverse-text", min_threshold=0.5)
|
||||
|
||||
@@ -8,6 +8,14 @@ from tests.utils import check_loss_goes_down, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
|
||||
|
||||
RUN_NAME = "reverse-text-sft"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
TIMEOUT = 300 # 5 minutes
|
||||
|
||||
|
||||
@@ -33,13 +41,15 @@ def sft_process(
|
||||
"configs/ci/integration/reverse-text-sft/start.toml",
|
||||
"--deployment.num-gpus",
|
||||
"2",
|
||||
"--clean-output-dir",
|
||||
"--clean",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
@@ -69,6 +79,8 @@ def sft_resume_process(
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
@@ -79,9 +91,9 @@ def test_no_error(sft_process: ProcessResult):
|
||||
assert sft_process.returncode == 0, f"Process has non-zero return code ({sft_process})"
|
||||
|
||||
|
||||
def test_loss_goes_down(sft_process: ProcessResult, output_dir: Path):
|
||||
def test_loss_goes_down(sft_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the loss goes down in the SFT process"""
|
||||
trainer_log_path = output_dir / "logs" / "trainer.log"
|
||||
trainer_log_path = run_dir / "logs" / "latest" / "trainer.log"
|
||||
print(f"Checking trainer path in {trainer_log_path}")
|
||||
with open(trainer_log_path, "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
@@ -93,9 +105,9 @@ def test_no_error_resume(sft_resume_process: ProcessResult):
|
||||
assert sft_resume_process.returncode == 0, f"Process has non-zero return code ({sft_resume_process})"
|
||||
|
||||
|
||||
def test_loss_goes_down_resume(sft_resume_process: ProcessResult, output_dir: Path):
|
||||
def test_loss_goes_down_resume(sft_resume_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the loss goes down in the SFT resume process"""
|
||||
trainer_log_path = output_dir / "logs" / "trainer.log"
|
||||
trainer_log_path = run_dir / "logs" / "latest" / "trainer.log"
|
||||
print(f"Checking trainer path in {trainer_log_path}")
|
||||
with open(trainer_log_path, "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
|
||||
@@ -9,6 +9,14 @@ from tests.utils import check_loss_goes_down, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
|
||||
|
||||
RUN_NAME = "reverse-text-sft-lora"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
TIMEOUT = 300 # 5 minutes
|
||||
|
||||
|
||||
@@ -43,13 +51,15 @@ def sft_lora_process(
|
||||
"configs/ci/integration/reverse-text-sft-lora/start.toml",
|
||||
"--deployment.num-gpus",
|
||||
"2",
|
||||
"--clean-output-dir",
|
||||
"--clean",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
@@ -79,6 +89,8 @@ def sft_lora_resume_process(
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
@@ -89,18 +101,18 @@ def test_no_error(sft_lora_process: ProcessResult):
|
||||
assert sft_lora_process.returncode == 0, f"Process has non-zero return code ({sft_lora_process})"
|
||||
|
||||
|
||||
def test_loss_goes_down(sft_lora_process: ProcessResult, output_dir: Path):
|
||||
def test_loss_goes_down(sft_lora_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the loss goes down in the SFT LoRA process"""
|
||||
trainer_log_path = output_dir / "logs" / "trainer.log"
|
||||
trainer_log_path = run_dir / "logs" / "latest" / "trainer.log"
|
||||
print(f"Checking trainer path in {trainer_log_path}")
|
||||
with open(trainer_log_path, "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_loss_goes_down(trainer_stdout)
|
||||
|
||||
|
||||
def test_adapter_checkpoint_written(sft_lora_process: ProcessResult, output_dir: Path):
|
||||
def test_adapter_checkpoint_written(sft_lora_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the adapter checkpoint is written with valid PEFT-compatible keys."""
|
||||
adapter_dir = output_dir / "weights" / "step_5" / "lora_adapters"
|
||||
adapter_dir = run_dir / "weights" / "step_5" / "lora_adapters"
|
||||
assert_adapter_checkpoint(adapter_dir)
|
||||
|
||||
|
||||
@@ -109,16 +121,16 @@ def test_no_error_resume(sft_lora_resume_process: ProcessResult):
|
||||
assert sft_lora_resume_process.returncode == 0, f"Process has non-zero return code ({sft_lora_resume_process})"
|
||||
|
||||
|
||||
def test_loss_goes_down_resume(sft_lora_resume_process: ProcessResult, output_dir: Path):
|
||||
def test_loss_goes_down_resume(sft_lora_resume_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the loss goes down in the SFT LoRA resume process"""
|
||||
trainer_log_path = output_dir / "logs" / "trainer.log"
|
||||
trainer_log_path = run_dir / "logs" / "latest" / "trainer.log"
|
||||
print(f"Checking trainer path in {trainer_log_path}")
|
||||
with open(trainer_log_path, "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_loss_goes_down(trainer_stdout)
|
||||
|
||||
|
||||
def test_adapter_checkpoint_written_resume(sft_lora_resume_process: ProcessResult, output_dir: Path):
|
||||
def test_adapter_checkpoint_written_resume(sft_lora_resume_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the adapter checkpoint is written after resuming with valid PEFT-compatible keys."""
|
||||
adapter_dir = output_dir / "weights" / "step_10" / "lora_adapters"
|
||||
adapter_dir = run_dir / "weights" / "step_10" / "lora_adapters"
|
||||
assert_adapter_checkpoint(adapter_dir)
|
||||
|
||||
@@ -8,6 +8,13 @@ from tests.utils import check_no_error, check_reward_goes_up, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
RUN_NAME = "alphabet-sort"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
@@ -34,18 +41,20 @@ def rl_process(
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
return run_process(cmd)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
def test_no_error(rl_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
check_no_error(rl_process, run_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
@@ -14,6 +14,13 @@ from tests.utils import (
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
RUN_NAME = "hendrycks-sanity"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
@@ -40,6 +47,8 @@ def rl_process(
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
"--max-steps",
|
||||
"1000", # do less steps to finish in time
|
||||
]
|
||||
@@ -52,27 +61,27 @@ MISMATCH_KL_MAX = 0.0005
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
def test_no_error(rl_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
check_no_error(rl_process, run_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the train reward goes up during training"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
|
||||
def test_reward_reaches_threshold(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_reaches_threshold(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the train reward reaches a minimum threshold"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=MIN_TRAIN_REWARD)
|
||||
|
||||
|
||||
def test_mismatch_kl_in_band(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_mismatch_kl_in_band(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that mismatch KL stays within the expected band."""
|
||||
with open(output_dir / "logs" / "trainer.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "trainer.log", "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_mismatch_kl_in_range(trainer_stdout, min_threshold=MISMATCH_KL_MIN, max_threshold=MISMATCH_KL_MAX)
|
||||
|
||||
@@ -8,6 +8,14 @@ from tests.utils import check_avg_reward_in_range, check_no_error, check_reward_
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
RUN_NAME = "multimodal-color-codeword"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
REWARD_MIN_THRESHOLD = 0.85
|
||||
REWARD_AVG_LAST_N_STEPS = 7
|
||||
|
||||
@@ -37,26 +45,28 @@ def rl_process(
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
return run_process(cmd)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
def test_no_error(rl_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
check_no_error(rl_process, run_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
|
||||
def test_reward_reaches_threshold(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_reaches_threshold(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the average reward over the last steps exceeds the threshold"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_avg_reward_in_range(
|
||||
orchestrator_stdout, last_n_steps=REWARD_AVG_LAST_N_STEPS, min_threshold=REWARD_MIN_THRESHOLD
|
||||
|
||||
@@ -8,6 +8,13 @@ from tests.utils import check_no_error, check_reward_goes_up, check_reward_in_ra
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
RUN_NAME = "reverse-text"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
@@ -34,25 +41,27 @@ def rl_process(
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
return run_process(cmd)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
def test_no_error(rl_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
check_no_error(rl_process, run_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
|
||||
def test_reward_reaches_threshold(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_reaches_threshold(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.65)
|
||||
|
||||
@@ -8,6 +8,13 @@ from tests.utils import check_no_error, check_reward_goes_up, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
RUN_NAME = "wiki-search"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
@@ -34,18 +41,20 @@ def rl_process(
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
return run_process(cmd)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
def test_no_error(rl_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
check_no_error(rl_process, run_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
@@ -8,6 +8,13 @@ from tests.utils import check_no_error, check_reward_goes_up, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
RUN_NAME = "wordle"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def run_dir(output_dir: Path) -> Path:
|
||||
return output_dir / RUN_NAME
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
@@ -34,18 +41,20 @@ def rl_process(
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--run.name",
|
||||
RUN_NAME,
|
||||
]
|
||||
return run_process(cmd)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
def test_no_error(rl_process: ProcessResult, run_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
check_no_error(rl_process, run_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, run_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
+20
-13
@@ -13,7 +13,7 @@ from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.trainer import ModelConfig as TrainerModelConfig
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
from prime_rl.utils.config import BaseConfig, cli, to_toml_dict
|
||||
from prime_rl.utils.config import BaseConfig, cli, dump_resolved_config
|
||||
|
||||
# All config config classes
|
||||
CONFIG_CLASSES = [
|
||||
@@ -161,21 +161,22 @@ def test_removed_fused_lm_head_chunk_size_field_is_rejected():
|
||||
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
|
||||
|
||||
|
||||
def test_to_toml_dict_roundtrips_explicit_none(tmp_path):
|
||||
"""An explicit None override survives the write/re-parse round-trip used by SLURM launches."""
|
||||
def test_resolved_json_roundtrips_explicit_none(tmp_path):
|
||||
"""An explicit None override survives the write/re-parse round-trip used by launches:
|
||||
resolved configs are JSON, which keeps nulls (TOML cannot)."""
|
||||
import json
|
||||
|
||||
config = cli(TrainerConfig, args=["--model.compile", "None", "--optim.max_norm", "None"])
|
||||
assert config.model.compile is None
|
||||
assert config.optim.max_norm is None
|
||||
|
||||
write_toml(tmp_path / "cfg.toml", to_toml_dict(config))
|
||||
reloaded = cli(TrainerConfig, args=["@", str(tmp_path / "cfg.toml")])
|
||||
path = tmp_path / "cfg.json"
|
||||
path.write_text(json.dumps(dump_resolved_config(config)))
|
||||
reloaded = cli(TrainerConfig, args=["@", str(path)])
|
||||
assert reloaded.model.compile is None
|
||||
assert reloaded.optim.max_norm is None
|
||||
assert reloaded == config
|
||||
|
||||
# Unset None fields stay dropped, so defaults still resolve on re-parse
|
||||
assert "max_steps" not in to_toml_dict(cli(TrainerConfig, args=[]))
|
||||
|
||||
|
||||
def test_env_algo_overrides_top_level():
|
||||
config = OrchestratorConfig.model_validate(
|
||||
@@ -547,8 +548,8 @@ def test_shared_and_subconfig_disjoint_fields_coexist():
|
||||
assert config.trainer.model.impl == "custom"
|
||||
|
||||
|
||||
def test_shared_output_dir_propagates_through_cli(tmp_path):
|
||||
"""Shared output_dir from CLI reaches sub-configs even when tyro constructs sub-configs before the before-validator."""
|
||||
def test_run_dir_propagates_through_cli(tmp_path):
|
||||
"""Sub-configs receive the run directory (output_dir / run.name) resolved from the CLI."""
|
||||
toml_path = tmp_path / "cfg.toml"
|
||||
write_toml(
|
||||
toml_path,
|
||||
@@ -556,15 +557,21 @@ def test_shared_output_dir_propagates_through_cli(tmp_path):
|
||||
"max_steps": 1,
|
||||
"seq_len": 128,
|
||||
"model": {"name": "Qwen/Qwen3-0.6B"},
|
||||
"wandb": {},
|
||||
"trainer": {},
|
||||
"orchestrator": {"batch_size": 16, "group_size": 1},
|
||||
"inference": {},
|
||||
},
|
||||
)
|
||||
shared_out = tmp_path / "shared"
|
||||
config = cli(RLConfig, args=["@", str(toml_path), "--output-dir", str(shared_out)])
|
||||
assert config.trainer.output_dir == shared_out
|
||||
assert config.orchestrator.output_dir == shared_out
|
||||
config = cli(RLConfig, args=["@", str(toml_path), "--output-dir", str(shared_out), "--run.name", "my-exp"])
|
||||
assert config.run_dir == shared_out / "my-exp"
|
||||
assert config.trainer.output_dir == shared_out / "my-exp"
|
||||
assert config.orchestrator.output_dir == shared_out / "my-exp"
|
||||
# Unset monitor names inherit run.name
|
||||
assert config.wandb is not None and config.wandb.name == "my-exp"
|
||||
assert config.trainer.wandb is not None and config.trainer.wandb.name == "my-exp"
|
||||
assert config.orchestrator.wandb is not None and config.orchestrator.wandb.name == "my-exp"
|
||||
|
||||
|
||||
def test_orchestrator_renderer_auto_rejects_unmapped_model():
|
||||
|
||||
@@ -1,57 +1,86 @@
|
||||
import pytest
|
||||
|
||||
from prime_rl.utils.pathing import validate_output_dir
|
||||
from prime_rl.utils.pathing import validate_run_dir
|
||||
|
||||
|
||||
def test_nonexistent_dir_passes(tmp_path):
|
||||
output_dir = tmp_path / "does_not_exist"
|
||||
validate_output_dir(output_dir, resuming=False, clean=False)
|
||||
run_dir = tmp_path / "does_not_exist"
|
||||
validate_run_dir(run_dir, output_dir=tmp_path, resuming=False, clean=False)
|
||||
|
||||
|
||||
def test_empty_dir_passes(tmp_path):
|
||||
output_dir = tmp_path / "empty"
|
||||
output_dir.mkdir()
|
||||
validate_output_dir(output_dir, resuming=False, clean=False)
|
||||
run_dir = tmp_path / "empty"
|
||||
run_dir.mkdir()
|
||||
validate_run_dir(run_dir, output_dir=tmp_path, resuming=False, clean=False)
|
||||
|
||||
|
||||
def test_dir_with_only_logs_passes(tmp_path):
|
||||
output_dir = tmp_path / "has_logs"
|
||||
output_dir.mkdir()
|
||||
(output_dir / "logs").mkdir()
|
||||
(output_dir / "logs" / "trainer.log").touch()
|
||||
validate_output_dir(output_dir, resuming=False, clean=False)
|
||||
def test_dir_with_launcher_artifacts_passes(tmp_path):
|
||||
run_dir = tmp_path / "submitted"
|
||||
run_dir.mkdir()
|
||||
(run_dir / "configs").mkdir()
|
||||
(run_dir / "configs" / "trainer.toml").touch()
|
||||
(run_dir / "rl.sbatch").touch()
|
||||
(run_dir / "job_1234.log").touch()
|
||||
validate_run_dir(run_dir, output_dir=tmp_path, resuming=False, clean=False)
|
||||
|
||||
|
||||
def test_dir_with_logs_raises(tmp_path):
|
||||
run_dir = tmp_path / "has_logs"
|
||||
run_dir.mkdir()
|
||||
(run_dir / "logs").mkdir()
|
||||
(run_dir / "logs" / "trainer.log").touch()
|
||||
with pytest.raises(FileExistsError, match="already contains artifacts"):
|
||||
validate_run_dir(run_dir, output_dir=tmp_path, resuming=False, clean=False)
|
||||
|
||||
|
||||
def test_dir_with_checkpoints_raises(tmp_path):
|
||||
output_dir = tmp_path / "has_ckpt"
|
||||
output_dir.mkdir()
|
||||
(output_dir / "checkpoints").mkdir()
|
||||
(output_dir / "checkpoints" / "step_0").mkdir()
|
||||
with pytest.raises(FileExistsError, match="already contains checkpoints"):
|
||||
validate_output_dir(output_dir, resuming=False, clean=False)
|
||||
run_dir = tmp_path / "has_ckpt"
|
||||
run_dir.mkdir()
|
||||
(run_dir / "checkpoints").mkdir()
|
||||
(run_dir / "checkpoints" / "step_0").mkdir()
|
||||
with pytest.raises(FileExistsError, match="already contains artifacts"):
|
||||
validate_run_dir(run_dir, output_dir=tmp_path, resuming=False, clean=False)
|
||||
|
||||
|
||||
def test_dir_with_checkpoints_passes_when_resuming(tmp_path):
|
||||
output_dir = tmp_path / "has_ckpt"
|
||||
output_dir.mkdir()
|
||||
(output_dir / "checkpoints").mkdir()
|
||||
(output_dir / "checkpoints" / "step_0").mkdir()
|
||||
validate_output_dir(output_dir, resuming=True, clean=False)
|
||||
run_dir = tmp_path / "has_ckpt"
|
||||
run_dir.mkdir()
|
||||
(run_dir / "checkpoints").mkdir()
|
||||
(run_dir / "checkpoints" / "step_0").mkdir()
|
||||
validate_run_dir(run_dir, output_dir=tmp_path, resuming=True, clean=False)
|
||||
|
||||
|
||||
def test_dir_with_checkpoints_cleaned_when_flag_set(tmp_path):
|
||||
output_dir = tmp_path / "has_ckpt"
|
||||
output_dir.mkdir()
|
||||
(output_dir / "checkpoints").mkdir()
|
||||
(output_dir / "checkpoints" / "step_0").mkdir()
|
||||
(output_dir / "logs").mkdir()
|
||||
run_dir = tmp_path / "has_ckpt"
|
||||
run_dir.mkdir()
|
||||
(run_dir / "checkpoints").mkdir()
|
||||
(run_dir / "checkpoints" / "step_0").mkdir()
|
||||
(run_dir / "logs").mkdir()
|
||||
|
||||
validate_output_dir(output_dir, resuming=False, clean=True)
|
||||
validate_run_dir(run_dir, output_dir=tmp_path, resuming=False, clean=True)
|
||||
|
||||
assert not output_dir.exists()
|
||||
assert not run_dir.exists()
|
||||
|
||||
|
||||
def test_clean_on_nonexistent_dir_is_noop(tmp_path):
|
||||
output_dir = tmp_path / "does_not_exist"
|
||||
validate_output_dir(output_dir, resuming=False, clean=True)
|
||||
assert not output_dir.exists()
|
||||
run_dir = tmp_path / "does_not_exist"
|
||||
validate_run_dir(run_dir, output_dir=tmp_path, resuming=False, clean=True)
|
||||
assert not run_dir.exists()
|
||||
|
||||
|
||||
def test_ckpt_output_dir_with_checkpoints_raises(tmp_path):
|
||||
run_dir = tmp_path / "fresh"
|
||||
ckpt_output_dir = tmp_path / "ckpts"
|
||||
ckpt_output_dir.mkdir()
|
||||
(ckpt_output_dir / "checkpoints").mkdir()
|
||||
(ckpt_output_dir / "checkpoints" / "step_0").mkdir()
|
||||
with pytest.raises(FileExistsError, match="already contains checkpoints"):
|
||||
validate_run_dir(run_dir, output_dir=tmp_path, resuming=False, clean=False, ckpt_output_dir=ckpt_output_dir)
|
||||
|
||||
|
||||
def test_clean_outside_output_dir_raises(tmp_path):
|
||||
escaped = tmp_path / "elsewhere"
|
||||
escaped.mkdir()
|
||||
with pytest.raises(ValueError, match="remain under output_dir"):
|
||||
validate_run_dir(escaped, output_dir=tmp_path / "outputs", resuming=False, clean=True)
|
||||
assert escaped.exists()
|
||||
|
||||
+3
-3
@@ -9,14 +9,14 @@ def strip_escape_codes(text: str) -> str:
|
||||
return re.sub(r"\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])", "", text)
|
||||
|
||||
|
||||
def check_no_error(process: ProcessResult, output_dir: Path) -> None:
|
||||
def check_no_error(process: ProcessResult, run_dir: Path) -> None:
|
||||
"""Helper to assert that a process did not error"""
|
||||
if process.returncode != 0:
|
||||
print("=== Inference Outputs ===")
|
||||
with open(output_dir / "logs" / "inference.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "inference.log", "r") as f:
|
||||
print(*f.readlines()[-100:], sep="")
|
||||
print("=== Orchestrator Outputs ===")
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
|
||||
print(*f.readlines()[-1000:], sep="")
|
||||
assert process.returncode == 0, f"Process has non-zero return code ({process})"
|
||||
|
||||
|
||||
@@ -164,7 +164,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "aime24"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/math/aime24" }
|
||||
source = { editable = "deps/prime-envs/environments/math/aime24" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -179,7 +179,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "aime25"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/math/aime25" }
|
||||
source = { editable = "deps/prime-envs/environments/math/aime25" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -194,7 +194,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "aime26"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/math/aime26" }
|
||||
source = { editable = "deps/prime-envs/environments/math/aime26" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -359,7 +359,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "apex-shortlist"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/math/apex_shortlist" }
|
||||
source = { editable = "deps/prime-envs/environments/math/apex_shortlist" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -392,7 +392,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "arxivmath"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/math/arxivmath" }
|
||||
source = { editable = "deps/prime-envs/environments/math/arxivmath" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -447,7 +447,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "automationbench-env"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/tool_use/automationbench_env" }
|
||||
source = { editable = "deps/prime-envs/environments/tool_use/automationbench_env" }
|
||||
dependencies = [
|
||||
{ name = "automation-bench" },
|
||||
{ name = "datasets" },
|
||||
@@ -575,7 +575,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "bfcl-v3"
|
||||
version = "0.3.0"
|
||||
source = { editable = "deps/research-environments/environments/tool_use/bfcl_v3" }
|
||||
source = { editable = "deps/prime-envs/environments/tool_use/bfcl_v3" }
|
||||
dependencies = [
|
||||
{ name = "bfcl-eval" },
|
||||
{ name = "soundfile" },
|
||||
@@ -677,7 +677,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "browsecomp"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/search/browsecomp" }
|
||||
source = { editable = "deps/prime-envs/environments/search/browsecomp" }
|
||||
dependencies = [
|
||||
{ name = "httpx" },
|
||||
{ name = "openai" },
|
||||
@@ -694,7 +694,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "browsecomp-plus"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/search/browsecomp_plus" }
|
||||
source = { editable = "deps/prime-envs/environments/search/browsecomp_plus" }
|
||||
dependencies = [
|
||||
{ name = "bm25s" },
|
||||
{ name = "datasets" },
|
||||
@@ -831,7 +831,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "charxiv"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/multimodal/charxiv" }
|
||||
source = { editable = "deps/prime-envs/environments/multimodal/charxiv" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "pillow" },
|
||||
@@ -893,7 +893,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "clbench"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/research-environments/environments/long_context/clbench" }
|
||||
source = { editable = "deps/prime-envs/environments/long_context/clbench" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
@@ -1319,7 +1319,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "deepdive"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/search/deepdive" }
|
||||
source = { editable = "deps/prime-envs/environments/search/deepdive" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
@@ -1336,7 +1336,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "deepseek-prover"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/lean/deepseek_prover" }
|
||||
source = { editable = "deps/prime-envs/environments/lean/deepseek_prover" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -1476,7 +1476,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "drug-discovery-bench"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/science/drug_discovery_bench" }
|
||||
source = { editable = "deps/prime-envs/environments/science/drug_discovery_bench" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub" },
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
@@ -1531,7 +1531,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "enterprise-ops-gym"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/tool_use/enterprise_ops_gym" }
|
||||
source = { editable = "deps/prime-envs/environments/tool_use/enterprise_ops_gym" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -1859,7 +1859,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "forth-lang"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/research-environments/environments/code/forth_lang" }
|
||||
source = { editable = "deps/prime-envs/environments/code/forth_lang" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -1874,7 +1874,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "frontierscience"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/science/frontierscience" }
|
||||
source = { editable = "deps/prime-envs/environments/science/frontierscience" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
@@ -1932,7 +1932,7 @@ http = [
|
||||
[[package]]
|
||||
name = "general-agent"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/tool_use/general_agent" }
|
||||
source = { editable = "deps/prime-envs/environments/tool_use/general_agent" }
|
||||
dependencies = [
|
||||
{ name = "pydantic" },
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
@@ -2007,7 +2007,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "goedel-pset"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/lean/goedel_pset" }
|
||||
source = { editable = "deps/prime-envs/environments/lean/goedel_pset" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -2082,7 +2082,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "gpqa"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/science/gpqa" }
|
||||
source = { editable = "deps/prime-envs/environments/science/gpqa" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
@@ -2099,7 +2099,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "graphwalks"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/long_context/graphwalks" }
|
||||
source = { editable = "deps/prime-envs/environments/long_context/graphwalks" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -2243,7 +2243,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "hle"
|
||||
version = "0.3.0"
|
||||
source = { editable = "deps/research-environments/environments/knowledge/hle" }
|
||||
source = { editable = "deps/prime-envs/environments/knowledge/hle" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
@@ -2354,7 +2354,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "humaneval"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/code/humaneval" }
|
||||
source = { editable = "deps/prime-envs/environments/code/humaneval" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -2407,7 +2407,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "i3-code"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/code/i3_code" }
|
||||
source = { editable = "deps/prime-envs/environments/code/i3_code" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "orjson" },
|
||||
@@ -2424,7 +2424,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "i3-logic"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/research-environments/environments/reasoning/i3_logic" }
|
||||
source = { editable = "deps/prime-envs/environments/reasoning/i3_logic" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "markdown" },
|
||||
@@ -2445,7 +2445,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "i3-math"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/math/i3_math" }
|
||||
source = { editable = "deps/prime-envs/environments/math/i3_math" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -2460,7 +2460,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "i3-science"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/science/i3_science" }
|
||||
source = { editable = "deps/prime-envs/environments/science/i3_science" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -2493,7 +2493,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "ifbench"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/if/ifbench" }
|
||||
source = { editable = "deps/prime-envs/environments/if/ifbench" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "emoji" },
|
||||
@@ -2524,7 +2524,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "ifeval"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/if/ifeval" }
|
||||
source = { editable = "deps/prime-envs/environments/if/ifeval" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "immutabledict" },
|
||||
@@ -2899,7 +2899,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "kimina"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/lean/kimina" }
|
||||
source = { editable = "deps/prime-envs/environments/lean/kimina" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -2959,7 +2959,7 @@ requires-dist = [{ name = "verifiers" }]
|
||||
[[package]]
|
||||
name = "lab"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/tool_use/lab" }
|
||||
source = { editable = "deps/prime-envs/environments/tool_use/lab" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
@@ -3055,7 +3055,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "livecodebench"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/code/livecodebench" }
|
||||
source = { editable = "deps/prime-envs/environments/code/livecodebench" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "huggingface-hub" },
|
||||
@@ -3116,7 +3116,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "longbenchpro"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/research-environments/environments/long_context/longbenchpro" }
|
||||
source = { editable = "deps/prime-envs/environments/long_context/longbenchpro" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
@@ -3149,7 +3149,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "longcot-env"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/long_context/longcot_env" }
|
||||
source = { editable = "deps/prime-envs/environments/long_context/longcot_env" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "longcot" },
|
||||
@@ -3166,7 +3166,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "longcot-mini"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/long_context/longcot_mini" }
|
||||
source = { editable = "deps/prime-envs/environments/long_context/longcot_mini" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "longcot" },
|
||||
@@ -3183,7 +3183,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "longpdfs"
|
||||
version = "0.0.1"
|
||||
source = { editable = "deps/research-environments/environments/long_context/longpdfs" }
|
||||
source = { editable = "deps/prime-envs/environments/long_context/longpdfs" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -3263,7 +3263,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "math-env"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/math/math_env" }
|
||||
source = { editable = "deps/prime-envs/environments/math/math_env" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -3290,7 +3290,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "math500"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/math/math500" }
|
||||
source = { editable = "deps/prime-envs/environments/math/math500" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -3363,7 +3363,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "mcp-atlas"
|
||||
version = "0.3.0"
|
||||
source = { editable = "deps/research-environments/environments/tool_use/mcp_atlas" }
|
||||
source = { editable = "deps/prime-envs/environments/tool_use/mcp_atlas" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "httpx" },
|
||||
@@ -3403,7 +3403,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "minif2f"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/lean/minif2f" }
|
||||
source = { editable = "deps/prime-envs/environments/lean/minif2f" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -3488,7 +3488,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "mmk12"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/multimodal/mmk12" }
|
||||
source = { editable = "deps/prime-envs/environments/multimodal/mmk12" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "math-verify" },
|
||||
@@ -3507,7 +3507,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "mmlu-pro"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/knowledge/mmlu_pro" }
|
||||
source = { editable = "deps/prime-envs/environments/knowledge/mmlu_pro" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -3522,7 +3522,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "mmmu"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/knowledge/mmmu" }
|
||||
source = { editable = "deps/prime-envs/environments/knowledge/mmmu" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "pillow" },
|
||||
@@ -3539,7 +3539,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "mmmu-pro"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/multimodal/mmmu_pro" }
|
||||
source = { editable = "deps/prime-envs/environments/multimodal/mmmu_pro" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "pillow" },
|
||||
@@ -3646,7 +3646,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "mrcr-v2"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/long_context/mrcr_v2" }
|
||||
source = { editable = "deps/prime-envs/environments/long_context/mrcr_v2" }
|
||||
dependencies = [
|
||||
{ name = "filelock" },
|
||||
{ name = "httpx" },
|
||||
@@ -3736,7 +3736,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "multiswe"
|
||||
version = "0.1.2"
|
||||
source = { editable = "deps/research-environments/environments/swe/multiswe" }
|
||||
source = { editable = "deps/prime-envs/environments/swe/multiswe" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "multi-swe-bench" },
|
||||
@@ -3867,7 +3867,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "nl2repobench"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/research-environments/environments/code/nl2repobench" }
|
||||
source = { editable = "deps/prime-envs/environments/code/nl2repobench" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "prime-sandboxes" },
|
||||
@@ -3922,7 +3922,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "numina"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/lean/numina" }
|
||||
source = { editable = "deps/prime-envs/environments/lean/numina" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -4193,7 +4193,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "oolong-pairs"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/long_context/oolong_pairs" }
|
||||
source = { editable = "deps/prime-envs/environments/long_context/oolong_pairs" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "huggingface-hub" },
|
||||
@@ -4210,7 +4210,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "oolong-real"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/long_context/oolong_real" }
|
||||
source = { editable = "deps/prime-envs/environments/long_context/oolong_real" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
@@ -4227,7 +4227,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "oolong-synth"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/long_context/oolong_synth" }
|
||||
source = { editable = "deps/prime-envs/environments/long_context/oolong_synth" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
@@ -4313,7 +4313,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "openseeker"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/search/openseeker" }
|
||||
source = { editable = "deps/prime-envs/environments/search/openseeker" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -4328,7 +4328,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "openswe"
|
||||
version = "0.1.3"
|
||||
source = { editable = "deps/research-environments/environments/swe/openswe" }
|
||||
source = { editable = "deps/prime-envs/environments/swe/openswe" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "huggingface-hub" },
|
||||
@@ -4470,7 +4470,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "openthoughts-tblite"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/research-environments/environments/terminal/openthoughts_tblite" }
|
||||
source = { editable = "deps/prime-envs/environments/terminal/openthoughts_tblite" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
@@ -4546,7 +4546,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "papersearchqa"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/search/papersearchqa" }
|
||||
source = { editable = "deps/prime-envs/environments/search/papersearchqa" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
@@ -4590,7 +4590,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "patterned-needle-in-haystack"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/long_context/patterned_needle_in_haystack" }
|
||||
source = { editable = "deps/prime-envs/environments/long_context/patterned_needle_in_haystack" }
|
||||
dependencies = [
|
||||
{ name = "nltk" },
|
||||
{ name = "verifiers" },
|
||||
@@ -4631,7 +4631,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "pinchbench"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/research-environments/environments/tool_use/pinchbench" }
|
||||
source = { editable = "deps/prime-envs/environments/tool_use/pinchbench" }
|
||||
dependencies = [
|
||||
{ name = "openai" },
|
||||
{ name = "prime-sandboxes" },
|
||||
@@ -4866,8 +4866,8 @@ all = [
|
||||
{ name = "nixl" },
|
||||
{ name = "nixl-cu12", version = "0.10.1", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
|
||||
{ name = "quack-kernels" },
|
||||
{ name = "vllm-router", version = "0.1.26", source = { 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 != 'x86_64'" },
|
||||
{ name = "vllm-router", version = "0.1.26", source = { 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'" },
|
||||
{ name = "vllm-router", version = "0.2.0", source = { 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 != 'x86_64'" },
|
||||
{ name = "vllm-router", version = "0.2.0", source = { 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'" },
|
||||
]
|
||||
disagg = [
|
||||
{ name = "deep-ep", version = "1.1.0+1fd57b0", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
|
||||
@@ -4876,8 +4876,8 @@ disagg = [
|
||||
{ name = "deep-gemm", version = "2.5.0+891d57b", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
|
||||
{ name = "nixl" },
|
||||
{ name = "nixl-cu12", version = "0.10.1", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
|
||||
{ name = "vllm-router", version = "0.1.26", source = { 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 != 'x86_64'" },
|
||||
{ name = "vllm-router", version = "0.1.26", source = { 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'" },
|
||||
{ name = "vllm-router", version = "0.2.0", source = { 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 != 'x86_64'" },
|
||||
{ name = "vllm-router", version = "0.2.0", source = { 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'" },
|
||||
]
|
||||
flash-attn = [
|
||||
{ name = "flash-attn", version = "2.8.3+cu128torch2.11", source = { url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.22/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
|
||||
@@ -4970,9 +4970,9 @@ requires-dist = [
|
||||
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64'", specifier = ">=0.26.0" },
|
||||
{ name = "vllm", marker = "platform_machine == 'aarch64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine == 'x86_64'", 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" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'aarch64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'aarch64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'disagg'" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and extra == 'disagg'", 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" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and extra == 'disagg'", 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" },
|
||||
{ name = "wandb", specifier = ">=0.26.1" },
|
||||
{ name = "wandb-workspaces", specifier = ">=0.4.3" },
|
||||
]
|
||||
@@ -5014,19 +5014,21 @@ requires-dist = [
|
||||
|
||||
[[package]]
|
||||
name = "prime-sandboxes"
|
||||
version = "0.2.35"
|
||||
version = "0.2.36"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "aiofiles" },
|
||||
{ name = "certifi" },
|
||||
{ name = "connect-python" },
|
||||
{ name = "httpx" },
|
||||
{ name = "protobuf" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "pyqwest" },
|
||||
{ name = "tenacity" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/57/cc/287c0db192ddbe003bd5882d1aab5461cdb3912d0c92db7b39734a9e828e/prime_sandboxes-0.2.35.tar.gz", hash = "sha256:e716bfccdcb51aefd5e2d48fdfc3a79bea8c6825bce1871f49f095ced03efc94", size = 86226, upload-time = "2026-08-05T14:29:53.33Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d5/c8/ca5261ff5d5c2e944e198866ead91b09bc88eb0390a905925bb6d7f9cd28/prime_sandboxes-0.2.36.tar.gz", hash = "sha256:3a5c8a7912b1ea0fb775674650835f7f86aac1a05aa8566c2db129b9a622fe55", size = 88415, upload-time = "2026-08-12T23:30:15.214Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/25/07/c186395925f780b1a18b350f562ebc4e8a64a182c37bd1e3db3948f297e2/prime_sandboxes-0.2.35-py3-none-any.whl", hash = "sha256:29d7057532b21545be5938d3aee822ae3a54085a45934d5c3ac55190e06c5bbb", size = 47189, upload-time = "2026-08-05T14:29:52.142Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0b/26/081296fc8e6d8ce962f2aee0e47ac843982094dedb34a1fad22d10086f37/prime_sandboxes-0.2.36-py3-none-any.whl", hash = "sha256:a5db92d927cf4a3dd37ce230027a9d83dbf21804d4f6ed2255d276c1962fa8f2", size = 49316, upload-time = "2026-08-12T23:30:14.047Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5065,7 +5067,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "programbench-env"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/research-environments/environments/code/programbench_env" }
|
||||
source = { editable = "deps/prime-envs/environments/code/programbench_env" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "huggingface-hub" },
|
||||
@@ -5086,7 +5088,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "prolog"
|
||||
version = "0.5.0"
|
||||
source = { editable = "deps/research-environments/environments/reasoning/prolog" }
|
||||
source = { editable = "deps/prime-envs/environments/reasoning/prolog" }
|
||||
dependencies = [
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
@@ -5166,7 +5168,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "proverbench"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/lean/proverbench" }
|
||||
source = { editable = "deps/prime-envs/environments/lean/proverbench" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -5672,7 +5674,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "r2e-gym"
|
||||
version = "0.1.2"
|
||||
source = { editable = "deps/research-environments/environments/swe/r2e_gym" }
|
||||
source = { editable = "deps/prime-envs/environments/swe/r2e_gym" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -5735,7 +5737,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "redsearcher"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/search/redsearcher" }
|
||||
source = { editable = "deps/prime-envs/environments/search/redsearcher" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -5923,7 +5925,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "s1-deepresearch"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/search/s1_deepresearch" }
|
||||
source = { editable = "deps/prime-envs/environments/search/s1_deepresearch" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub" },
|
||||
{ name = "verifiers" },
|
||||
@@ -5962,7 +5964,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "scaleswe"
|
||||
version = "0.1.2"
|
||||
source = { editable = "deps/research-environments/environments/swe/scaleswe" }
|
||||
source = { editable = "deps/prime-envs/environments/swe/scaleswe" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -5990,7 +5992,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "scicode"
|
||||
version = "0.3.0"
|
||||
source = { editable = "deps/research-environments/environments/code/scicode" }
|
||||
source = { editable = "deps/prime-envs/environments/code/scicode" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -6051,7 +6053,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "senior-swe-bench"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/research-environments/environments/swe/senior_swe_bench" }
|
||||
source = { editable = "deps/prime-envs/environments/swe/senior_swe_bench" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
@@ -6143,7 +6145,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "simpleqa"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/research-environments/environments/knowledge/simpleqa" }
|
||||
source = { editable = "deps/prime-envs/environments/knowledge/simpleqa" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
@@ -6160,7 +6162,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "simpleqa-verified"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/research-environments/environments/knowledge/simpleqa_verified" }
|
||||
source = { editable = "deps/prime-envs/environments/knowledge/simpleqa_verified" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
@@ -6469,7 +6471,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "swebench-multilingual"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/swe/swebench_multilingual" }
|
||||
source = { editable = "deps/prime-envs/environments/swe/swebench_multilingual" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
@@ -6480,7 +6482,7 @@ requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.2.2
|
||||
[[package]]
|
||||
name = "swebench-pro"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/swe/swebench_pro" }
|
||||
source = { editable = "deps/prime-envs/environments/swe/swebench_pro" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
@@ -6491,7 +6493,7 @@ requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.2.2
|
||||
[[package]]
|
||||
name = "swebench-verified"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/swe/swebench_verified" }
|
||||
source = { editable = "deps/prime-envs/environments/swe/swebench_verified" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
@@ -6502,7 +6504,7 @@ requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.2.2
|
||||
[[package]]
|
||||
name = "swelego"
|
||||
version = "0.1.2"
|
||||
source = { editable = "deps/research-environments/environments/swe/swelego" }
|
||||
source = { editable = "deps/prime-envs/environments/swe/swelego" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -6517,7 +6519,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "swerebench-v2"
|
||||
version = "0.1.2"
|
||||
source = { editable = "deps/research-environments/environments/swe/swerebench_v2" }
|
||||
source = { editable = "deps/prime-envs/environments/swe/swerebench_v2" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -6537,7 +6539,7 @@ source = { git = "https://github.com/SWE-bench/SWE-smith.git?rev=9b74ac0#9b74ac0
|
||||
[[package]]
|
||||
name = "swesmith-env"
|
||||
version = "0.1.2"
|
||||
source = { editable = "deps/research-environments/environments/swe/swesmith_env" }
|
||||
source = { editable = "deps/prime-envs/environments/swe/swesmith_env" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "swebench" },
|
||||
@@ -6631,7 +6633,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "tau2-bench"
|
||||
version = "0.3.0"
|
||||
source = { editable = "deps/research-environments/environments/tool_use/tau2_bench" }
|
||||
source = { editable = "deps/prime-envs/environments/tool_use/tau2_bench" }
|
||||
dependencies = [
|
||||
{ name = "tau2" },
|
||||
{ name = "verifiers" },
|
||||
@@ -6685,7 +6687,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "terminal-bench-2"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/terminal/terminal_bench_2" }
|
||||
source = { editable = "deps/prime-envs/environments/terminal/terminal_bench_2" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
@@ -6696,7 +6698,7 @@ requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.2.1
|
||||
[[package]]
|
||||
name = "terminal-lego"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/research-environments/environments/terminal/terminal_lego" }
|
||||
source = { editable = "deps/prime-envs/environments/terminal/terminal_lego" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub" },
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
@@ -6846,7 +6848,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "tmax"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/terminal/tmax" }
|
||||
source = { editable = "deps/prime-envs/environments/terminal/tmax" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
@@ -7178,7 +7180,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "triviaqa"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/knowledge/triviaqa" }
|
||||
source = { editable = "deps/prime-envs/environments/knowledge/triviaqa" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -7316,7 +7318,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "unscramble"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/reasoning/unscramble" }
|
||||
source = { editable = "deps/prime-envs/environments/reasoning/unscramble" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "verifiers" },
|
||||
@@ -7340,7 +7342,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "uuid-ctf"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/reasoning/uuid_ctf" }
|
||||
source = { editable = "deps/prime-envs/environments/reasoning/uuid_ctf" }
|
||||
dependencies = [
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
@@ -7386,7 +7388,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "verbatim-copy"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/long_context/verbatim_copy" }
|
||||
source = { editable = "deps/prime-envs/environments/long_context/verbatim_copy" }
|
||||
dependencies = [
|
||||
{ name = "faker" },
|
||||
{ name = "verifiers" },
|
||||
@@ -7461,7 +7463,7 @@ requires-dist = [
|
||||
{ name = "openai-agents", specifier = ">=0.8.2" },
|
||||
{ name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" },
|
||||
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.2" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.35" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.36" },
|
||||
{ name = "prime-tunnel", specifier = ">=0.1.8" },
|
||||
{ name = "pydantic", specifier = ">=2.12.3" },
|
||||
{ name = "python-dotenv", marker = "extra == 'browser'", specifier = ">=1.0.0" },
|
||||
@@ -7498,17 +7500,21 @@ dev = [
|
||||
]
|
||||
examples = [
|
||||
{ name = "alphabet-sort", editable = "deps/verifiers/environments/alphabet_sort" },
|
||||
{ name = "bash-interception", editable = "deps/verifiers/environments/bash_interception" },
|
||||
{ name = "code-golf", editable = "deps/verifiers/environments/code_golf" },
|
||||
{ name = "color-codeword", editable = "deps/verifiers/environments/color_codeword" },
|
||||
{ name = "compact", editable = "deps/verifiers/environments/compact" },
|
||||
{ name = "deepwiki", editable = "deps/verifiers/environments/deepwiki" },
|
||||
{ name = "glossary", editable = "deps/verifiers/environments/glossary" },
|
||||
{ name = "grayscale-interception", editable = "deps/verifiers/environments/grayscale_interception" },
|
||||
{ name = "gsm8k", editable = "deps/verifiers/environments/gsm8k" },
|
||||
{ name = "interception", editable = "deps/verifiers/environments/interception" },
|
||||
{ name = "kuhn-poker", editable = "deps/verifiers/environments/kuhn_poker" },
|
||||
{ name = "openenv-wordle", editable = "deps/verifiers/environments/openenv_wordle" },
|
||||
{ name = "proposer-solver", editable = "deps/verifiers/environments/proposer_solver" },
|
||||
{ name = "reverse-text", editable = "deps/verifiers/environments/reverse_text" },
|
||||
{ name = "scratchpad", editable = "deps/verifiers/environments/scratchpad" },
|
||||
{ name = "web-search-interception", editable = "deps/verifiers/environments/web_search_interception" },
|
||||
{ name = "wiki-search", editable = "deps/verifiers/environments/wiki_search" },
|
||||
{ name = "wordle", editable = "deps/verifiers/environments/wordle" },
|
||||
]
|
||||
@@ -7516,7 +7522,7 @@ examples = [
|
||||
[[package]]
|
||||
name = "virl39k"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/multimodal/virl39k" }
|
||||
source = { editable = "deps/prime-envs/environments/multimodal/virl39k" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "huggingface-hub" },
|
||||
@@ -7925,8 +7931,8 @@ provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttens
|
||||
|
||||
[[package]]
|
||||
name = "vllm-router"
|
||||
version = "0.1.26"
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl" }
|
||||
version = "0.2.0"
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'aarch64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -7939,7 +7945,7 @@ dependencies = [
|
||||
{ name = "uvicorn" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:ab8d0da61faa588fd5a7ed947bd58ddb31f5836cf55518bdd0122cfbc83989f4" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:07b4b18155231c926334a497db504767930fb81758049cbd9113c1e9f9c2ba69" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -7958,8 +7964,8 @@ provides-extras = ["dev"]
|
||||
|
||||
[[package]]
|
||||
name = "vllm-router"
|
||||
version = "0.1.26"
|
||||
source = { 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" }
|
||||
version = "0.2.0"
|
||||
source = { 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" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'x86_64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -7972,7 +7978,7 @@ dependencies = [
|
||||
{ name = "uvicorn" },
|
||||
]
|
||||
wheels = [
|
||||
{ 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", hash = "sha256:db0c9410a4c130da8ffeea22f569faca7c85c58c5e183be1ebf758076361a6ec" },
|
||||
{ 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", hash = "sha256:bac193bedf10f9a0265fe4fdaae0f0418574cd1f15c45f27da1b4a2bae8c10b8" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -8135,7 +8141,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "wideseek"
|
||||
version = "0.2.0"
|
||||
source = { editable = "deps/research-environments/environments/search/wideseek" }
|
||||
source = { editable = "deps/prime-envs/environments/search/wideseek" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
{ name = "openai" },
|
||||
@@ -8178,7 +8184,7 @@ requires-dist = [
|
||||
[[package]]
|
||||
name = "wikispeedia"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/reasoning/wikispeedia" }
|
||||
source = { editable = "deps/prime-envs/environments/reasoning/wikispeedia" }
|
||||
dependencies = [
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user