Compare commits

...
Author SHA1 Message Date
Mika SenghaasandGitHub 7da7c4d108 fix: unify multi-node SFT launch logging (#3401)
## Summary

- run multi-node SFT training and online evals in one SLURM job
- reserve `num_train_nodes + num_infer_nodes` and assign inference nodes
first
- keep every node in the shared step until trainer and eval completion
sentinels exist
- keep trainer, inference, router, evals, and env logs in one
`logs/attempt_<n>` directory
- give standalone `evals` launches an attempt directory and update
`logs/latest`
- update configuration help, training docs, and run skills for the new
topology

## Breaking

- Multi-node SFT online evals now require one combined SLURM allocation.
The scheduler must allocate all trainer and inference nodes together.
Trainer nodes remain allocated until the final eval finishes.
- The launcher no longer writes `launcher/eval.sbatch`. Custom
multi-node SFT templates must launch inference and eval roles from the
main SFT template.
- The bundled `multi_node_sft_eval.sbatch.j2` template is removed. Use
`multi_node_sft.sbatch.j2` as the template source.

## Verification

Before this change, a multi-node SFT dry run generated two batch
scripts. The eval script wrote inference, evals, and env logs directly
under `$OUTPUT_DIR/logs`.

After this change, the same dry run generates only
`launcher/sft.sbatch`. A `2 trainer + 1 inference` configuration renders
`#SBATCH --nodes=3`. The script contains one attempt allocator and no
`TRAIN_JOB_ID`, log-path marker, or NCCL-host marker. It backgrounds
trainer and evals roles. Every node waits for the job-specific trainer
and eval completion sentinels. Online-eval and trainer-only renders both
pass `bash -n` and sentinel checks.

Local two-GPU end-to-end smokes passed:

- SFT completed one training step with NCCL broadcasts and evals at
steps 0 and 1.
- RL completed one training step and evals at policy versions 0 and 1.
- Standalone inference served a standalone two-example eval run.

The filesystem audit found relative `latest -> attempt_1` links for all
three runs. Every component log was nonempty UTF-8 text. No component
log existed outside its attempt directory.

Targeted config, CLI parser, and pathing tests passed: 282 tests. Ruff
checks and formatting checks passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking change for multi-node SFT online evals: cluster scheduling
and custom SLURM templates must launch inference and trainer in one job;
misconfiguration could strand nodes or break NCCL broadcast wiring.
> 
> **Overview**
> **Multi-node SFT with online evals** no longer submits separate
trainer and eval SLURM jobs. One allocation reserves `num_train_nodes +
num_infer_nodes`; the first `num_infer_nodes` run the inference pool,
router, env servers, and `evals`, and the rest run the trainer. NCCL
weight broadcast uses the trainer rank-0 hostname directly—no cross-job
`TRAIN_JOB_ID` or shared run-dir host marker.
> 
> The launcher only writes `launcher/sft.sbatch` (
**`multi_node_sft_eval.sbatch.j2` is removed** ). The unified template
backgrounds trainer and eval roles, waits on job-specific completion
sentinels so the job can drain the final eval after a clean trainer
exit, and uses one attempt-scoped log tree under `logs/attempt_<n>/`
(including `evals.log` and env logs). Standalone/local SFT sets
`PRL_LOG_DIR` for evals; the dashboard still lists legacy `logs/envs/`
files for older runs.
> 
> Docs, `SFTConfig` field descriptions, and training skills are updated
for the single-job topology and log paths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
997c8c1457c1ba95a013eb353abdcb754bc1a648. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-25 23:58:02 -07:00
parkerpettitandGitHub 9e3be00b39 feat(dashboard): add trace timeline viewer (#3390)
## Summary

- add a Prime-styled synchronized timeline for agent lifecycle phases
and model-call activity
- render VF-native root-to-leaf `Branch` paths instead of inferring
harness-specific subagent identities or hierarchy
- keep each environment agent as the main lane and show one flat row per
native zero-based branch index, ordered by its first unique activity
- retain shared-prefix calls on every branch path and mute them visually
to distinguish reuse from branch-unique execution
- show the trace reward on every branch training sample
- preserve exact call identity, including repeated calls, node-less
calls, and explicitly unknown timing
- show input, cached input, total input, output, reasoning, maximum
context length, total tokens, and cost in timeline tooltips and Overview
when reported
- keep large multi-agent tab strips horizontally scrollable and
integrate with Messages and Rendered transcript modes
- reject stale timeline responses after episode selection changes and
preserve unknown completed-phase end timing
- retain report navigation, transcript highlighting, rendered-token
mode, and dashboard view-command support

## Screenshot of multiagent episode (with subagent calls)
Codex harness
<img width="2400" height="2490" alt="image"
src="https://github.com/user-attachments/assets/1fe4a274-5cf2-49de-adf8-f328086d9f4a"
/>

RLM harness
<img width="2400" height="3260" alt="image"
src="https://github.com/user-attachments/assets/1ea0d693-a72e-495d-8133-c5b82770f2a0"
/>

## Validation

- `uv run --frozen ruff check .`
- `uv run --frozen ruff format --check .`
- `node --check src/prime_rl/dashboard/static/app.js`
- real interactive Codex multi-agent episode projects 29 native branches
across four environment-agent traces, with every branch containing
exactly its root-to-leaf model calls and all 46 actual calls covered
- real interactive RLM multi-agent episode projects 40 native branches
across four environment-agent traces, with every branch containing
exactly its root-to-leaf model calls and all 125 actual calls covered
- captured full-episode Playwright screenshots of both branch timelines
2026-08-25 17:53:01 -07:00
ef66401434 feat: traces -> hf dataset converter (#3382)
## Summary

- Replace `scripts/export_sft.py` with
`tools/convert_traces_to_hf_dataset.py`.
- Convert each branch of each agent trace into one dataset row.
- Export trainable and non-trainable agents without selection or
filtering.
- Add top-level outcome fields for downstream filters, including
`reward`, `stop_condition`, `has_error`, and `is_truncated`.
- Preserve task, run, agent, error, timing, usage, call, reward, metric,
and trace metadata.
- Push to a private Hugging Face Hub dataset by default, with `--public`
as an explicit opt-out.
- Use `--local` to write Parquet files with Hugging Face dataset-card
metadata.
- Preserve existing dataset-card content when local metadata is updated.

## Verification

### Eval → dataset → SFT

1. Generated eight GSM8K episodes without uploading the eval:

```bash
uv run --project /home/ubuntu/prime-rl eval gsm8k -n 8 -r 1 -c 8 \
    --no-push -o /tmp/trace-converter-e2e-20260825 \
    --run.name trace-converter-gsm8k --run.dir eval
```

All eight episodes succeeded. Mean reward was 1.0 and the error rate was
0.0.

2. Converted the trace file into a local Hugging Face dataset:

```bash
uv run --project /home/ubuntu/prime-rl python \
    tools/convert_traces_to_hf_dataset.py \
    /tmp/trace-converter-e2e-20260825/eval/traces.jsonl \
    --name /tmp/trace-converter-e2e-20260825/dataset --local
```

The converter wrote eight branch rows. The dataset loaded through
`load_dataset`.

3. Trained Qwen3-0.6B on the converted dataset:

```bash
uv run --project /home/ubuntu/prime-rl sft \
    --output-dir /tmp/trace-converter-e2e-20260825 --run.name sft \
    --max-steps 5 --model.name Qwen/Qwen3-0.6B \
    --data.type sft --data.name /tmp/trace-converter-e2e-20260825/dataset \
    --data.subsets '["default"]' --data.splits '["train"]' \
    --data.seq-len 2048 --data.batch-size 4 --data.micro-batch-size 1 \
    --deployment.gpus-per-node 2 --deployment.num-train-gpus 1
```

The run completed all five steps. Final loss was 0.7764, the NaN count
was zero, and peak GPU memory was 10.7 GiB. No Hub or Prime platform
uploads occurred.

### Additional checks

- Ran the Ruff check and format pre-commit hooks.
- Converted a separate saved file with 132 episodes and loaded all 132
branch rows with `load_dataset`.
- Verified that a non-trainable errored trace still emits its branch row
and top-level error fields.
- Verified that local updates preserve plain, valid-frontmatter, and
unclosed-frontmatter README content.
- Verified that default uploads pass `private=True`, while `--public`
passes `private=False`.

## Breaking

- `scripts/export_sft.py` is removed. Use `uv run python
tools/convert_traces_to_hf_dataset.py <traces.jsonl> --name
<dir-or-repo-id>`.
- The converter no longer accepts `--min-reward` or `--drop-truncated`.
Apply filters in a separate script.
- The converter pushes to the Hub by default. Use `--local` to write a
local dataset.
- New Hub datasets are private by default. Use `--public` to create a
public dataset.
- The `--push` flag is removed because Hub upload is now the default.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are limited to offline export tooling and CLI workflows; no
in-repo training or runtime code is modified in this diff.
> 
> **Overview**
> **Removes** `scripts/export_sft.py` and **adds**
`tools/convert_traces_to_hf_dataset.py` as the path from eval/train
`traces.jsonl` to Hugging Face datasets.
> 
> The new converter reads **one episode per line** (`WireEpisode`)
instead of per-trace wire rows, emits **one row per branch** for every
agent trace (no `--min-reward`, `--drop-truncated`, or empty-branch
skipping), and keeps **`messages`** plus JSON **`tools`** for SFT while
adding top-level filter fields (`reward`, `stop_condition`, `has_error`,
`is_truncated`, etc.) and JSON metadata for task, run, agent, errors,
timing, and usage.
> 
> **Output behavior changes:** Hub upload is the default via required
`--name`; use **`--local`** to write `<name>/<subset>/<split>.parquet`
and update **`README.md`** dataset-card configs for `load_dataset`.
**`--public`** controls visibility on new Hub repos; **`--push`** is
gone.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8834b7aea61f2e6e9ba467758b593cf6ffb7a29b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 16:14:03 -07:00
eligottsandGitHub be5855cfe3 Harden dashboard cited-report guidance (#3393) 2026-08-25 15:35:55 -07:00
Mika SenghaasandGitHub 43365ec52f feat: model converter scripts (#3348)
## Summary

- Add `tools/convert_dcp_to_bf16.py`: convert a DCP trainer checkpoint
to HF sharded safetensors offline. Recovers the converter deferred out
of #3316 and adapts it: required positional `ckpt_dir` (accepts
`<run>/checkpoints/step_{n}` or `.../step_{n}/trainer`), output defaults
to `<ckpt_dir>/weights` (or a second positional arg), model/tokenizer
configs read from the run's resolved `configs/trainer.json` / `sft.json`
(the single source of truth — the checkpoint must live in its run
directory), single-process (`uv run python`) and multi-rank (`torchrun`)
invocations. Local `trust_remote_code` models get their custom code
files copied next to the weights. Full fine-tunes only — LoRA
checkpoints are rejected up front. Export replaces training-only
attention, fused-MoE, and DeepEP settings with portable
model-construction values.
- Add `tools/convert_bf16_to_fp8.py`: quantize an HF safetensors dir to
blockwise FP8 (DeepSeek/GLM format: e4m3 weights + `weight_scale_inv`
per-128×128-block scales, `quantization_config` block vLLM loads
natively). Streams shard-by-shard; norms, embeddings, lm_head, router
gates, GatedDeltaNet low-rank projections, MTP projection, and vision
towers stay bf16. Reuses `quantize_to_fp8_blockwise` from
`prime_rl.trainer.models.fp8`. Inspired by slime/miles
`tools/convert_hf_to_fp8.py`.
- Add `tools/convert_dcp_to_fp8.py`: DCP straight to fp8 — same gather
as `dcp_to_bf16`, but each rank quantizes its slice on GPU and only fp8
shards are written to `<ckpt_dir>/weights-FP8` (no intermediate bf16
export on disk).
- Add `tools/convert_fp8_to_bf16.py`: the inverse (dequantize
blockwise-fp8 releases like GLM-5-FP8 to bf16 for training). Inspired by
slime/miles `tools/fp8_cast_bf16.py`.
- Fold converter e2e checks into the existing reverse-text CI runs (no
new CI matrix entries): both the SFT and RL integration tests convert
their final DCP checkpoint to bf16 and fp8 and assert the exports reload
in HF with a clean loading report; the RL test additionally asserts
direct `dcp_to_fp8` output is byte-identical to chained `bf16_to_fp8` on
a real trainer checkpoint. Shared helpers
`convert_checkpoint`/`check_hf_load` in `tests/utils.py`. (A standalone
per-arch byte-exactness matrix over the mini_moe archs — glm4_moe,
laguna, minimax_m2, qwen3.5-MoE VLM; bf16 exports byte-identical to
their random-init sources, both fp8 paths byte-identical — was validated
during development and dropped from CI in favor of these hooks.) Also
fixes the mini_moe VLM preset `mrope_section` for its shrunken head_dim.
- Read the run config from the `configs/resolved/` layout via
`get_config_dir` (adapted after merging main).
- Document the export flow in `docs/training.md` and
`skills/training/start-run/SKILL.md`, and note the CLI convention in
`AGENTS.md`: `tools/` scripts use plain argparse, `[project.scripts]`
entrypoints use pydantic-config.

## Verification

All run on 2× RTX PRO 6000 Blackwell (SM120), vLLM 0.26.

**dcp→hf, real RL run (qwen3 dense)** — 20-step reverse-text RL run with
`--ckpt.interval 10 --weight-broadcast.type filesystem`:
- step 10 converted single-process, step 20 with `torchrun
--nproc-per-node 2`.
- Both exports are **bit-identical** (all 310 tensors) to the trainer's
own filesystem-broadcast weights at the same step; tied `lm_head.weight`
is dropped per HF convention and verified equal to `embed_tokens`.
- `uv run inference --vllm.model .../step_10/weights` serves the export;
reverse-text eval (`uv run eval`, n=64 r=4) scores **0.754** vs 0.744
training reward at step 10. Step 20 export scores **0.801** vs ~0.80 at
end of training.

**dcp→hf, architecture matrix** — per arch: tiny random model
(`scripts/mini_moe.py`) → 3-step fake-data SFT → convert (exercises
`configs/sft.json` auto-detection) → verify:

| arch | strict HF load | prime reload + forward | notes |
|---|---|---|---|
| glm4_moe (MoE) | ✓ | ✓ | plus direct HF→DCP→HF round trip: 889/889
tensors bit-exact (expert stack/unstack) |
| laguna | ✓ (`trust_remote_code=True`) | ✓ | HF→DCP→HF round trip
433/433 tensors bit-exact modulo the conversion chain's canonical
per-expert layout (the same layout the live broadcast path emits;
poolside's HF class stores fused `experts.gate_up_proj` and re-inits
experts it doesn't recognize — see `converting_laguna.py` docstring) |
| minimax_m2 (MoE) | ✓ | ✓ | mini built via prime impl (MiniMax remote
code incompatible with transformers v5) |
| qwen3_5_moe VLM | ✓ (`Qwen3_5MoeForConditionalGeneration`) | key-set
identity vs source | vision tower + linear attention round-trip |


**bf16→fp8 + fp8→bf16** — on the real step-20 Qwen3-0.6B export and all
four minis: dequant error bounded (worst median relative error ~2.2%,
e4m3-consistent), skip-list modules bit-identical,
index/`quantization_config` consistent; fp8→bf16 round trip drops all
`*_scale_inv` keys and `quantization_config`. Structure matches the
official `Qwen/Qwen3-0.6B-FP8` release (same scale shapes/names).
Serving the fp8→bf16 round-tripped weights scores **0.798** (vs 0.801
bf16 baseline), confirming the stored values.

**fp8 serving on SM120 (vLLM kernel bug, not the script)**: serving the
fp8 checkpoint scores **0.31** with vLLM's default
`CutlassFp8BlockScaledMMKernel` on this box, but **0.790** with the same
checkpoint after forcing the Triton kernel
(`VLLM_DISABLED_KERNELS=...CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel`
→ `TritonFp8BlockScaledMMKernel`), and vLLM's *online* fp8 of the same
weights scores 0.79. vLLM's CUTLASS blockwise-fp8 GEMM silently degrades
on SM120 (RTX PRO 6000); upstream already tracks other SM120
blockwise-fp8 breakage (vllm-project/vllm#47990, #47436). Noted the
workaround in `skills/training/start-run/SKILL.md`; H100/H200/B200
(SM90/SM100) use different kernels.

## Not ported from slime/miles

Megatron converters (`convert_torch_dist_to_hf*`,
`convert_hf_to_torch_dist`) — prime-rl is FSDP/DCP; int4 converters
(Kimi-K2-specific); mxfp8/nvfp4 (no checkpoint-level use case yet);
`param_name_remap.py` (covered by prime conversion chains); profiling
tools (prime-rl has its own monitors).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Converters touch distributed gather, HF weight layout, and
quantization paths that must match live training/broadcast behavior;
mistakes could ship broken checkpoints, though integration tests and
LoRA rejection reduce exposure.
> 
> **Overview**
> Adds offline **checkpoint export and FP8 conversion** tooling under
`tools/convert_*.py`, plus docs/skills updates and integration-test
coverage.
> 
> **DCP → Hugging Face:** `convert_dcp_to_bf16.py` loads FSDP DCP
trainer checkpoints using the run’s resolved
`configs/resolved/trainer.json` or `sft.json`, gathers weights in
parallel (single GPU or `torchrun`), writes sharded bf16 safetensors and
tokenizer/config assets to `<ckpt_dir>/weights`, and **rejects LoRA**
checkpoints.
> 
> **FP8 round-trip:** `convert_bf16_to_fp8.py` blockwise-quantizes HF
safetensors (e4m3 + `weight_scale_inv`, vLLM-native
`quantization_config`); `convert_dcp_to_fp8.py` quantizes each rank’s
gathered slice straight to `<ckpt_dir>/weights-FP8` without a bf16
export on disk; `convert_fp8_to_bf16.py` dequantizes fp8-only releases
for training.
> 
> **CI:** Reverse-text RL and SFT integration tests convert the final
checkpoint, assert clean `AutoModelForCausalLM` loads, and (RL)
byte-identity between direct `dcp_to_fp8` and chained `bf16_to_fp8`.
Shared helpers `convert_checkpoint` / `check_hf_load` live in
`tests/utils.py`. `scripts/mini_moe.py` fixes `mrope_section` for the
shrunk VLM preset.
> 
> **Docs:** `docs/training.md` and training skills document the export
flow; `AGENTS.md` notes `tools/` scripts use plain argparse vs
pydantic-config entrypoints. Run artifact paths use `step_{n}`
consistently.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fe1241dec3e1369cc930ffa6b736fe6baf4e5200. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-25 14:30:07 -07:00
Mika SenghaasandGitHub ab5de8fff4 chore: release v0.9.0 (#3379)
Tag and Release / kernels-from-auto-tag (push) Canceled after 0s
Tag and Release / auto-tag-on-main (push) Canceled after 0s
Tag and Release / release-from-auto-tag (push) Canceled after 0s
Tag and Release / resolve-release (push) Canceled after 0s
Tag and Release / kernels-from-tag (push) Canceled after 0s
Tag and Release / publish-release (push) Canceled after 0s
## Summary

- bump the prime-rl project version from 0.8.0 to 0.9.0
- update the matching prime-rl entry in uv.lock
- prepare the [draft v0.9.0 GitHub
release](https://github.com/PrimeIntellect-ai/prime-rl/releases/tag/untagged-6fdfe34d2c7a47da166a)
with notes for 105 commits since v0.8.0
- include the latest dashboard, SLURM teardown, weight synchronization,
and eval policy fixes in the release notes

## Verification

- uv lock --check
- git diff --check origin/main...HEAD
2026-08-25 13:11:39 -07:00
97d32d947f fix(orchestrator): pre-seed datasets' tqdm lock to avoid concurrent-load crash (#3391)
## Problem

`Envs.start()` starts every source concurrently
(`asyncio.gather(env.start() for env in self)`), and each `env.start()`
materializes its taskset via `load_dataset()` in a worker thread
(`asyncio.to_thread(lambda: list(taskset))`). HuggingFace `datasets`
reads cached arrow shards through
`tqdm.contrib.concurrent.thread_map(tqdm_class=hf_tqdm)`, whose
`ensure_lock()` is:

```python
old_lock = getattr(tqdm_class, "_lock", None)
lock = old_lock or tqdm_class.get_lock()
...
yield lock                       # the (slow) arrow read happens here
if old_lock is None:
    del tqdm_class._lock         # <-- racing line
else:
    tqdm_class.set_lock(old_lock)
```

When two of these run concurrently with the class lock unset, both
observe `old_lock is None`, both reach `del tqdm_class._lock` on exit,
and the second raises:

```
AttributeError: type object 'tqdm' has no attribute '_lock'
```

That kills the orchestrator during `setup()` ("Fatal error in
run_orchestrator"), and the trainer then hangs waiting for rollouts that
never come.

**When it triggers:** ≥2 sources load datasets concurrently at startup
(e.g. multiple train sources over the same taskset). The race window is
the arrow read, so more sources / colder caches make it more likely — 3
concurrent loads hit it essentially every run, 2 intermittently, 1
never. It is **not** caught by `--dry-run`, which never calls
`load_dataset()`.

Root cause is a tqdm thread-safety gap (`ensure_lock` isn't safe for
concurrent use on a single class), exposed by `datasets`' `thread_map`
plus concurrent taskset loading here.

## Fix

Pre-seed the `datasets` tqdm class lock once, before the concurrent
gather, so `old_lock` is never `None` and every `ensure_lock` takes the
non-deleting `else` branch — the same state tqdm is in whenever a
progress bar is active:

```python
from datasets.utils import tqdm as _hf_tqdm
_hf_tqdm.set_lock(_hf_tqdm.get_lock())
```

This targets the exact class `datasets` passes to `thread_map`
(`datasets.utils.tqdm.tqdm`, the same object `arrow_reader` imports). It
only stops the lock object from being created-and-deleted per call; no
change to progress-bar display, dataset contents, or ordering.

## Reproduction

Hammering the failing primitive directly (16 threads, window widened to
mimic the slow arrow read):

- **without** the fix: consistent `AttributeError: type object 'tqdm'
has no attribute '_lock'`
- **with** the fix: clean, 0 failures

Also observed live: a 3-train-source run crashed here every time; after
the fix all three arms load cleanly.

## Alternative considered

Loading sources sequentially in `Envs.start()` also avoids the race, at
the cost of startup parallelism. The pre-seed keeps the parallel load.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single-line lock initialization before existing parallel env startup;
no auth, data, or algorithm changes.
> 
> **Overview**
> **Fixes a startup crash** when multiple train/eval sources load
HuggingFace datasets in parallel during `Envs.start()`.
> 
> Concurrent `load_dataset()` paths use `datasets`' `thread_map` with
tqdm's `ensure_lock()`, which can race on `del tqdm_class._lock` and
raise `AttributeError`—fatal during orchestrator `setup()` and leaving
the trainer waiting on rollouts.
> 
> Before `asyncio.gather` on `env.start()`, the change **pre-seeds** the
lock on `datasets.utils.tqdm` via `set_lock(get_lock())` so concurrent
readers never hit the delete branch. Parallel startup is preserved; no
change to dataset contents or progress display.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a1007d2d9cc0b8e15a2df959cec54cf3b366fce3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-25 13:09:20 -07:00
Mika SenghaasandGitHub 6b3364d1a8 fix: align evals with applied policies (#3385)
## Summary

- Route startup and later policy loads through one `WeightWatcher`
update path. Advance `policy.version` and trigger evals only after
inference applies the weights.
- Key fresh startup evals to policy v0. On resume, evaluate the loaded
checkpoint only when `retrigger_on_resume=true`.
- Pause rollout scheduling across each weight apply so rollout
provenance matches the policy served at dispatch.
- Remove the resume-step broadcast directory before the trainer rebuilds
its startup handshake.
- Always broadcast and consume the final RL policy. Remove the
conditional final-broadcast config and helper path.
- Remove the mixed-policy eval warning. Keep the minimum policy version
in metrics and success logs.
- Remove the parenthesized step from eval success logs.

## Verification

Before the fix, a 20-step reverse-text run with eval interval 1
reproduced the bug:

- Eval step 20 used policy v18.
- The final policy broadcast triggered eval step 21 with policy v20.
- The run wrote step-21 eval artifacts.

After the fix, this requested interval-10 run completed all 20 steps:

```bash
uv run rl @ examples/basic/reverse-text/rl.toml \
  --orchestrator.eval.interval 10 \
  --orchestrator.eval.num-examples 1 \
  --orchestrator.eval.group-size 1 \
  --orchestrator.eval.source '[{"name":"reverse-text-eval","env":{"taskset":{"id":"reverse-text"},"agent":{"harness":{"id":"null"},"runtime":{"type":"subprocess"}}}}]' \
  --no-monitors.wandb --no-dashboard
```

- Eval step 10 used policy v10.
- Final eval step 20 used policy v20.
- No step-21 eval artifacts were written.

A two-step run without evals applied final policy v2 and exited cleanly.
This verifies unconditional final broadcast and consumption.

Fresh and resumed two-step smokes verified the startup matrix:

- A fresh interval-1 run evaluated policies v0, v1, and v2.
- Resume from v2 with `retrigger_on_resume=false` skipped v2, then
evaluated v3 and v4.
- Resume from v2 with `retrigger_on_resume=true` evaluated v2, v3, and
v4.
- Resume from v2 with interval 3 skipped v2 and evaluated v3 only.
- Every resumed startup rebuilt its v2 broadcast handshake and exited
cleanly.

After the final review fixes, a fresh interval-1 run evaluated v0, v1,
and v2. A resume from v2 with `retrigger_on_resume=false` skipped only
v2, then evaluated v3 and v4.

```bash
uv run pytest \
  tests/unit/test_configs.py \
  tests/unit/orchestrator/test_batch.py \
  tests/unit/utils/test_pathing.py -q
# 156 passed

uv run ruff check \
  src/prime_rl/orchestrator/orchestrator.py \
  src/prime_rl/orchestrator/watcher.py \
  src/prime_rl/orchestrator/dispatcher.py \
  src/prime_rl/orchestrator/eval_source.py \
  src/prime_rl/utils/pathing.py \
  src/prime_rl/trainer/rl/train.py \
  src/prime_rl/utils/utils.py \
  packages/prime-rl-configs/src/prime_rl/configs/rl.py \
  packages/prime-rl-configs/src/prime_rl/configs/shared.py \
  tests/unit/utils/test_pathing.py \
  tests/utils.py
# All checks passed!
```

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes core RL orchestration around weight updates, rollout
scheduling barriers, and eval timing—incorrect ordering could cause
wrong-policy evals or inference crashes during weight swaps.
> 
> **Overview**
> Fixes evals running against stale or wrong policy versions by tying
**eval triggers and `policy.version` to inference actually applying
weights**, not merely publishing them.
> 
> **Policy lifecycle:** `WeightWatcher` now advances `policy.version`
only after `receive()` completes, routes startup sync through
`sync_startup` + shared `on_update` hooks, and registers orchestrator
hooks for eval and dispatch-gate refresh. Batch shipping and shutdown
waits refer to **inference-applied** versions.
> 
> **Eval scheduling:** Eval fires from `trigger_eval` after each applied
policy (including startup v0 on fresh runs). Resume skips re-eval at the
checkpoint step unless `retrigger_on_resume=true`; final eval uses
`force` at `max_steps` without a spurious step-21 epoch. The dispatcher
blocks new scheduling across weight swaps via `policy_update_pending`
and a scheduling lock.
> 
> **Broadcast config:** Removes `broadcast_final` and
`final_broadcast_version`; the trainer **always** broadcasts every step
including the final policy, and resume cleanup deletes broadcast dirs
from the resume step onward so the startup handshake is rebuilt.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5fa6b01df79f028ad974509ff78e9e51188cf1f0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-25 12:32:45 -07:00
eligottsandGitHub 544bd6205a feat(dashboard): agent view commands + report tab with verified citations (#3387) 2026-08-25 12:24:51 -07:00
rasdaniandGitHub 3460245d63 feat(dashboard): expose tool context and rendered tokens (#3377)
## Summary

- show `trace.tools` as a distinct, collapsible model-context block in
the Messages view, with tool counts/names, full descriptions, formatted
parameter schemas, and per-item/schema/all copy actions
- add a separate `Rendered` view that decodes recorded post-renderer
`token_ids` for the selected trace and branch as a full sequence,
retaining special tokens and offering decoded-text and authoritative-ID
copy actions
- compose both `Messages` and `Rendered` with the `Text`, `Advantage`,
`Logprob`, `Mask`, and `Content` signal dropdown, with explicit
unavailable states for missing IDs, missing model metadata, tokenizer
load failures, and decode failures

## Details

The Messages view continues to render literal `message.content`. Tool
definitions are shown immediately after the first system message in a
purple-accented context card, so they are not presented as
system-message text; traces without a system message keep the card at
the top. The collapsed row shows the count and normalized names;
expanding it exposes each full description and scrollable JSON schema.
Direct tool objects, OpenAI-style `function` wrappers, multiple
definitions, missing fields, and malformed values degrade to readable
fallback labels.

Rendered does not rerun or infer a chat template. The server uses
`client.renderer_model_name` with the existing run-model fallback,
concatenates the recorded node spans in the selected root-to-leaf order,
and calls the tokenizer once for the full sequence with special-token
skipping disabled. The selected branch controls which decoded sequence
is shown; the all-branches option uses recorded node write order. With
`Text` selected, Rendered shows that exact full-sequence decode. With
another signal selected, it shows the same recorded sequence as token
spans with the existing color scale and token hover metadata.

Compatibility is intentionally additive: the default endpoint response
and default Messages/Text display stay unchanged, token strings are
still fetched lazily for overlays, and full rendered text is only added
when `rendered=true` is requested. The mode buttons and signal dropdown
are independent, and a one-time preference migration recovers sessions
that briefly saved `Rendered` in the signal field.

Episode navigation and token/render enrichment use separate request
lifecycles. Opening or closing an episode invalidates prior enrichment,
while changing controls during an in-flight open no longer discards the
episode response; the newly opened episode then picks up any enrichment
required by the latest controls. Decode failures remain branch-local in
the viewer: valid text for the selected branch is shown even if another
branch fails to decode.

## Verification

- `uv run --no-sync ruff format --check
src/prime_rl/dashboard/server.py`
- `uv run --no-sync ruff check src/prime_rl/dashboard/server.py`
- `uv run ruff check src/prime_rl/dashboard`
- `node --check src/prime_rl/dashboard/static/app.js`
- `git diff origin/main...HEAD --check`
- exercised a generic synthetic two-branch trace through the live
dashboard API with three tool-definition shapes; verified renderer-model
selection, retained `<|im_start|>` / `<|im_end|>` markers, separate
branch text, all-node ordering, and existing per-token pieces

## Visual description

A compact `Tool definitions · 3 tools · lookup, calculate, tool 3` row
appears directly after the system message. It expands into nested tool
cards with full prose and scrollable monospace schemas. `Messages` /
`Rendered` buttons sit beside a signal dropdown containing `Text`,
`Advantage`, `Logprob`, `Mask`, and `Content`. Either mode can use any
signal; Rendered/Text shows the exact decoded transcript, while Rendered
with an overlay shows colored token spans. A hover tooltip describes the
signal choices. A screenshot is not included because a browser runtime
was unavailable in the checkout used for verification.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Additive dashboard and optional episode API fields; no changes to
training, auth, or data persistence beyond larger lazy-loaded episode
payloads.
> 
> **Overview**
> The trace viewer adds **Messages** vs **Rendered** modes and surfaces
**`trace.tools`** as model context separate from message text.
> 
> In **Messages**, tool definitions appear in a collapsible context
block (after the first system message when present), with descriptions,
parameter schemas, and copy actions; message bodies still show literal
**`message.content`**. **Rendered** decodes recorded post-renderer
**`token_ids`** per branch (or all nodes) via **`renderer_model_name`**
with run-model fallback—no chat-template reconstruction—and reports
missing IDs, model, tokenizer, or decode failures.
> 
> The episode API accepts optional **`tokens`** and **`rendered`** query
params; **`rendered_token_text`** on the server concatenates branch
paths and decodes full sequences with special tokens retained. The UI
lazily fetches enrichment, versions open/enrichment requests to avoid
stale responses, and shares the Text / Advantage / Logprob / Mask /
Content signal dropdown across both modes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
596f7d3fe9746c9283d8a872b1d506c26a525e1a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-25 11:40:30 -07:00
3758321f08 fix: preserve final eval during teardown (#3324)
## Summary

- Use successful trainer and orchestrator exits as the shared completion
condition in local and multi-node SLURM launchers.
- Let each SLURM component publish `.trainer.done` or
`.orchestrator.done`, then stop inference after both markers exist.
- Make trainer-only fake-data SLURM runs stop after `.trainer.done`; no
orchestrator exists in that mode.
- Store all generated SLURM scripts and coordination files under
`<run_dir>/launcher/`.
- Store SLURM stdout and stderr under `<run_dir>/launcher/logs/`.
- Apply the launcher layout to RL, SFT, decoupled SFT eval, and
standalone inference entrypoints.
- Keep local launchers unchanged on disk. They do not create `launcher/`
because they persist no launcher files.
- Preserve failure propagation through `srun --kill-on-bad-exit=1`.

At `max_steps`, the trainer can exit while the orchestrator still drains
the final eval. The template previously tore down the node after the
first background process exited. This killed the final eval. A clean
exit also did not trigger `--kill-on-bad-exit`, so inference nodes could
hold the allocation until wall time.

## Breaking

- Generated SLURM scripts move from `<run_dir>/*.sbatch` to
`<run_dir>/launcher/*.sbatch`. Update manual submission commands and
tooling to use the new paths.
- SLURM job logs move from `<run_dir>/*job_*.log` to
`<run_dir>/launcher/logs/*job_*.log`. Update log collection and
monitoring paths.

## Verification

Before this change, a 1000-step GLM-4.5-Air run lost its final eval at
450 of 500 tasks. The six-node allocation then remained active for
another 23 hours.

After this change, a 10-step reverse-text run evaluated at its final
step and exited successfully:

- The final eval completed all 64 rollouts with no rollout errors.
- The trainer finished at 01:39:08 UTC.
- The orchestrator drained its pipeline and finished at 01:39:14 UTC.
- Inference stopped after both terminal components finished.
- The launcher exited with code 0 and released both GPUs.

A two-node trainer-only fake-data dry run rendered a one-marker watcher
with no `ORCHESTRATOR_DONE` reference. The normal inference path still
rendered the two-marker watcher. Both scripts passed `bash -n`.

All RL, SFT, decoupled SFT eval, and inference SLURM variants rendered
successfully. Every rendered script passed `bash -n`. Local RL, SFT, and
inference dry runs did not create `launcher/`.

An additional two-node SLURM run used the regular reverse-text
configuration with 100 eval rollouts per evaluation:

- The trainer completed all 20 steps and wrote `launcher/.trainer.done`.
- The orchestrator continued to drain queued evaluations after trainer
completion.
- The orchestrator then wrote `launcher/.orchestrator.done`.
- Both nodes logged teardown with exit code 0, and the job released its
allocation.

Ruff passed. The pathing unit tests passed with 10 tests.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes multi-node SLURM lifecycle and coordination (eval completion
vs allocation hold time) and breaks paths for manual `sbatch` and log
monitoring; incorrect completion logic could still strand nodes or kill
in-flight evals.
> 
> **Overview**
> Fixes premature SLURM teardown at `max_steps` when the trainer exits
while the orchestrator is still draining the **final eval**. Multi-node
RL jobs no longer stop on the first background process exit; trainer
rank 0 and the orchestrator publish **`launcher/.trainer.done`** and
**`launcher/.orchestrator.done`** on success, and every node waits for
the appropriate pair (trainer-only vs trainer+orchestrator) before
killing inference and releasing the allocation. Failures still propagate
via **`srun --kill-on-bad-exit=1`**.
> 
> **Breaking layout change:** generated `*.sbatch` scripts, coordination
sentinels, and SLURM `job_*.log` output move from the run directory root
to **`&lt;run_dir&gt;/launcher/`** and **`launcher/logs/`** for RL, SFT,
decoupled SFT eval, and standalone inference. Entrypoints and Jinja
templates pass `launcher_dir` / `launcher_log_dir`; local launches stay
unchanged on disk (no `launcher/`). Docs and training skills note the
new paths; `format_log_message` and `LAUNCHER_ARTIFACTS` validation
follow the same layout.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
02f3807d4a4f9cd53830b9b90e4035c386d01bdc. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 21:58:23 -07:00
Mika SenghaasandGitHub 01dc127b1a fix: synchronize before the pre-broadcast empty_cache (#3383)
## Summary
- One-line fix for the deterministic `CUDA error: an illegal memory
access` that killed every SignSGD run without full optimizer offload
since #3234.
- `torch.cuda.empty_cache()` returns cached blocks to the driver; a
kernel still in flight that references a cached block faults once its
block is freed under it. The pre-broadcast `empty_cache` (added in #3234
for FP8 gather headroom) runs immediately after `optimizer.step()` —
SignSGD's per-param loop leaves thousands of tiny kernels still running
at that point, while AdamW's compact foreach step happens to finish in
time, which is why only SignSGD crashed. Draining pending work with
`torch.cuda.synchronize()` before releasing blocks closes the race for
every optimizer, at ~ms cost once per step.

## Verification

All on the same GLM-4.5-Air scaleswe config (2 trainer + 2 inference
nodes, `sign_sgd` + `optim_cpu_offload`, no full offload):

| state | outcome |
|---|---|
| main | illegal memory access right after step 1, 2/2 slurm attempts |
| main + `CUDA_LAUNCH_BLOCKING=1` | no crash — ordering, not indexing |
| **main + this one line** | [runs
clean](https://wandb.ai/primeintellect/swe-ablations?nw=nwuser&search=sgd-nooffload):
11+ steps and counting, healthy grad norms, no restarts |

Supersedes #3373 — its foreach SignSGD rewrite turned out to be
unnecessary for correctness (verified by running the untouched optimizer
with only this line).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the per-step RL training hot path and GPU memory lifecycle
before weight broadcast; the change is narrow and matches existing
synchronize-before-empty_cache patterns elsewhere, but any extra sync
can affect step timing.
> 
> **Overview**
> Fixes a **CUDA illegal memory access** that could occur right after
`optimizer.step()` when the trainer frees GPU cache before broadcasting
weights.
> 
> The pre-broadcast `torch.cuda.empty_cache()` (for FP8 gather headroom)
can return cached blocks to the driver while **optimizer kernels are
still in flight**—especially with SignSGD’s many small per-parameter
updates. The change **drains pending GPU work** via
`torch.cuda.synchronize()` immediately before `empty_cache()`, with
expanded comments explaining the race.
> 
> This is a one-line behavioral fix in the RL training loop’s
weight-broadcast path; it does not change broadcast semantics, only
ordering so memory is not reclaimed under active kernels.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8947aa400631ca5a2dab829642f7755fab7dafd0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 18:33:04 -07:00
Konstantin DunasandGitHub 663b53bbc2 fix: silence W&B Weave advertisement on wandb.init (#3380) 2026-08-25 01:51:29 +02:00
f96a46f090 feat(configs): add PRL_OUTPUT_DIR env var for default output_dir (#3375)
Lets a user set a persistent default output location for all runs
without repeating --output-dir on every launch. Precedence stays class
default ("outputs") < PRL_OUTPUT_DIR < TOML < CLI, since the new
default_factory only fires when output_dir is untouched by TOML/CLI
merge.

Also respected by the dashboard UI.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 19:15:19 -04:00
01994b8168 fix: misc dashboard improvs (#3374)
## Summary

- refresh live metrics and trace rows on the same five-second cadence
- better `no data yet` for unavailable overview data
- show episode and trace errors at the bottom of the trace viewer
- add the task key as `task ID` to the identity section of the trace
overview pane
- use `n/a` for missing value uniformly; some spots showed an en dash.
- allow filter from trace viewer

## Verification

### Overview empty state

<img width="1608" height="1045" alt="Screenshot 2026-08-24 at 3 54 20
PM"
src="https://github.com/user-attachments/assets/02e06087-5286-435e-9776-52ec9502f7f5"
/>

### Errors

<img width="1608" height="1045" alt="Screenshot 2026-08-24 at 3 52 29
PM"
src="https://github.com/user-attachments/assets/b39a28cc-c50d-467c-b7f7-39c354a5e008"
/>

### Task ID

<img width="318" height="151" alt="Screenshot 2026-08-24 at 3 52 42 PM"
src="https://github.com/user-attachments/assets/f12f50b5-685d-4ca5-8b80-5c89877cab43"
/>

### Checks

- `node --check src/prime_rl/dashboard/static/app.js`
- `git diff --check`
- dashboard browser smoke against `outputs/reverse-text-rl`
- live append browser repro for metrics, trace rows, and new trace steps
- fake inference URL eval and browser layout check with a full traceback
- headless browser render of a synthetic `ProviderError` episode:
collapsed and expanded traceback, `task ID` row, consistent `n/a`
placeholders, red-marked error rows in the sidebar

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Frontend-only dashboard static assets; no API or training-path
changes. Risk is limited to UI regressions in metrics/traces polling and
the trace modal.
> 
> **Overview**
> This PR tightens **live updates** and **trace UX** in the static
dashboard (`app.js`, `index.html`, `style.css`).
> 
> **Polling & loading:** Poll interval moves to **5s**; metrics and
traces refresh when switching tabs with live on, on tab visibility, and
when re-enabling live. Metrics streaming stops retrying the same offset
when a partial JSONL line sits at EOF; `fetching` guards avoid
overlapping metrics/trace loads.
> 
> **Traces:** Step selection **follows the latest preferred step** while
you’re on the tail (historical picks and an open modal stay put). Empty
trace/metrics states use shorter labels and the episode table keeps its
chrome with an in-table empty row to avoid layout shift. Overview panels
show **“no data yet”** for configured eval sections before data lands.
> 
> **Trace viewer:** Episode/trace **errors render as banners** at the
bottom of the message column (with expandable tracebacks); **task ID**
appears in the identity pane. The modal gets the same
**filter/sort/env/errors** controls as the traces tab, synced through
shared state. Error episodes are highlighted in the sidebar list.
> 
> **Polish:** Missing numeric/overview fields use **`n/a`** instead of
en dashes (empty eval env list still shows **–**). Run overview merges
the full run record from the runs list on refresh.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
239dc7797d996fb0b17badb9dd60b640474b431d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 16:11:11 -07:00
e6b5e4de5d feat: auto-started dashboard daemon (#3371)
## Summary

- Launchers (`rl`, `sft`) register their output dir in
`~/.cache/prime-rl/dashboard/dirs.json` and make sure one dashboard
serves it (`ensure_dashboard` in the new `entrypoints/dashboard.py`,
kept free of `dashboard`-extra imports). Every dashboard instance serves
its CLI dirs **plus** the registry, re-read live — a run in a new output
dir appears on the one live URL without a restart: one dashboard per
host per user.
- Discovery goes through `daemon.json` (pid + **actual** url), so it
survives port spillover — nothing ever probes port 7788. A live daemon's
URL is logged (`Dashboard running at <url>`); interactive sessions spawn
a detached daemon (own session — killing a run never takes it down) when
none is live (`Dashboard started at <url>`); non-tty launches (CI,
nohup) only register. A stale claim from a dead process is taken over on
the next start.
- `--isolated` is the escape hatch: serve only the given dirs, no
registry read/write, no discovery claim (launchers ignore the instance).
`dashboard: bool = True` on RL/SFT opts a run out via `--no-dashboard`.
- The daemon carries the process title `PRL::Dashboard` via the shared
`set_proc_title`. `psutil` is promoted from transitive to a core
dependency so `prime_rl.utils.process` imports in the slim GPU-free env.
- Launcher startup now ends with a `Dashboard · <url>` banner (blank
lines around, green url) as the last log, after `Launcher complete` (was
`Startup complete. Showing ... logs`). The launcher no longer tails
orchestrator/trainer logs into its terminal - the dashboard is the
monitoring surface.
- New `skills/dashboard/SKILL.md` teaches agents discovery, liveness
checks, and kill/restart commands; `monitor-run` and `start-run` skills
point at it.

Supersedes #3368, rebuilt on the (now merged) stack #3369 (PRL prefix) →
#3370 (GPU extra; the server is a normal package member, so no
setproctitle fallback and no duplicated cache-dir logic); targets
`main`.

## Verification

E2E on this box: daemon claims `daemon.json` with pid + url and shows
`PRL::Dashboard` in `ps`; `ensure_dashboard` from a second process
registers a fresh output dir and the live dashboard absorbs it (run
count grows without restart); a second instance spills to port 7789 and
does **not** steal the claim; `--isolated` serves only its dirs and
leaves the registry untouched; a pty-spawned launcher starts a detached
daemon that survives the launcher's exit; slim `uv sync --extra
dashboard` env (no torch/vllm) imports `entrypoints.dashboard`,
`dashboard.server`, and `set_proc_title`, and `dashboard --help` works;
`tests/unit/test_configs.py` passes (122).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are local dev/monitoring UX and read-only dashboard serving;
training paths are unchanged aside from optional subprocess spawn and
registry file writes.
> 
> **Overview**
> **RL and SFT launchers** now register each run’s `output_dir` in a
per-user registry and ensure a single local dashboard serves it. New
`dashboard: bool = True` (disable with `--no-dashboard`) drives
`ensure_dashboard` in `entrypoints/dashboard.py`, which reuses a live
daemon via `~/.cache/prime-rl/dashboard/daemon.json` or spawns a
detached process in interactive TTY sessions only.
> 
> The **dashboard server** merges CLI dirs with `dirs.json` (live
re-read), claims/releases daemon discovery, adds **`--isolated`** to opt
out of the registry, and moves sidecar cache under the shared dashboard
state dir. The **`dashboard` console script** now enters through
`entrypoints.dashboard.main`.
> 
> **Launcher UX** drops `tail -F` on orchestrator/trainer logs; startup
ends with **Launcher complete** and a **Dashboard · url** banner.
**`psutil`** is a direct dependency so process titles work without the
GPU stack. Agent skills/docs describe discovery, liveness, and
kill/restart.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
035e7ec4c1a2671db778a85a42147d332a8a73ed. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 15:12:09 -07:00
a5853ce9ab feat: slim uv sync (#3370)
## Summary

- The CUDA/linux-only stack (torch+cu128 index, vllm, torchtitan,
mooncake-transfer-engine, ring-flash-attn, dion, tilelang,
flash-linear-attention, torchao, nvidia-ml-py, modelexpress) moves from
core dependencies into a **`gpu` extra** (linux-marked), and
`darwin/arm64` joins `tool.uv.environments` — a bare `uv sync` now
resolves and installs on a MacBook (slim: configs, monitors, dashboard,
CLI tooling). `uv sync --all-extras` — already the recommended install
on GPU machines — pulls everything exactly as before (`all` aggregates
`gpu` too).
- Every other GPU extra (`flash-attn-3`, `flash-attn-cute`, `disagg`,
`gpt-oss`, `quack`, `kernels`, the `mamba-ssm` group) gets linux markers
so the darwin lock split resolves; the torch cu128 index sources are
linux-scoped.
- CI (`cpu_tests`, benchmarks) and the docker entrypoint's
`PRIME_RL_REF` override sync move to `--all-extras`; `Dockerfile.cuda`
adds `--extra gpu`; the install skill documents the split.
- The dashboard's standalone PEP 723 `--script` form is removed: `uv
sync --extra dashboard && uv run dashboard` is now the dependency-free
path everywhere, and `server.py` becomes a normal package member — it
imports the new `CACHE_DIR` from `utils/pathing` instead of duplicating
the cache-dir logic.

## Breaking

- `uv sync` without extras no longer installs the training/inference
stack; use `uv sync --all-extras` (recommended) or `--extra gpu`.
Anything invoking `uv sync --extra flash-attn` alone must add `--extra
gpu`.
- `uv run --script src/prime_rl/dashboard/server.py` no longer works
(header removed); use `uv sync --extra dashboard && uv run dashboard`.

## Verification

On linux: bare `uv sync --extra dashboard` produces an env with no
torch/vllm from which `uv run dashboard` serves real runs end to end;
`uv sync --all-extras --all-packages` restores the full env (torch
2.11+cu128, vllm import, `entrypoints.rl` import OK);
`tests/unit/test_configs.py` (122 passed) and the dashboard browser
smoke pass. `uv lock` resolves all three environments including the new
darwin split.

#3369 (PRL prefix) is merged and this now targets `main`; the
dashboard-daemon PR (#3371) lands on top.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes the default dependency contract and Docker runtime `uv sync`
behavior; anyone on bare `uv sync` or old dashboard script paths will
miss GPU deps, and PRIME_RL_REF overrides now pull all extras (including
heavy disagg/quack) at pod startup.
> 
> **Overview**
> **Slim default install:** Core dependencies no longer pull the Linux
CUDA training stack (torch/cu128, vllm, torchtitan, mooncake,
ring-flash-attn, dion, tilelang, flash-linear-attention, torchao,
modelexpress, nvidia-ml-py). Those move behind a new **`gpu` optional
extra** (linux-marked). Other GPU extras (`flash-attn-3`, `disagg`,
`quack`, `kernels`, `mamba-ssm`, etc.) get linux markers;
**`darwin/arm64`** is added to `tool.uv.environments` so a bare `uv
sync` resolves on macOS. The **`all`** extra now includes
`prime-rl[gpu]`.
> 
> **Install paths updated:** CI (`cpu_tests`, benchmarks) and
**`Dockerfile.cuda`** sync with **`--all-extras`** / explicit **`--extra
gpu`** so Linux GPU images still get the full stack.
**`scripts/docker-entrypoint.sh`** on `PRIME_RL_REF` overrides switches
from a hand-picked extra list to **`uv sync --inexact --all-extras`**
(plus `mamba-ssm` group)—so override checkouts may install disagg/quack
at startup, not only flash-attn/gpt-oss.
> 
> **Dashboard:** The PEP 723 **`uv run --script`** standalone form is
removed from `server.py`; docs/skills point to **`uv sync --extra
dashboard && uv run dashboard`**. Dashboard sidecar cache uses shared
**`CACHE_DIR`** from `utils/pathing` (`home_dir()` fallback to temp).
> 
> **Breaking:** `uv sync` alone no longer installs training/inference
deps—use **`uv sync --all-extras`** (recommended on GPU Linux) or
**`--extra gpu`** (and add flash-attn etc. as before). **`uv run
--script src/prime_rl/dashboard/server.py`** no longer works.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
64562e87834dc6ef1eba7ab372b50f102088cb5f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 14:43:45 -07:00
Mika SenghaasandGitHub 38582b2bf1 chore: bump verifiers to 0.3.1 (#3372)
## Summary

- require the stable `verifiers[harbor]>=0.3.1` release instead of a
development build
- point the Verifiers submodule at the published `v0.3.1` tag

## Verification

- `uv lock --check`
- built `verifiers-0.3.1-py3-none-any.whl` and `verifiers-0.3.1.tar.gz`
from `deps/verifiers`
- verified the submodule commit has the exact `v0.3.1` tag

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dependency constraint only—switches from a dev pre-release to the
stable 0.3.1 minimum with no application code changes in this diff.
> 
> **Overview**
> Pins **`verifiers[harbor]`** to the stable **`>=0.3.1`** release
instead of the prior **`>=0.3.1.dev59`** development build in
`pyproject.toml`.
> 
> This moves dependency resolution off a pre-release dev tag onto the
published 0.3.1 line while keeping the same optional **`harbor`** extra
and existing editable **`deps/verifiers`** source configuration.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f399e80c03ad6e26533aa770df28e90c69517891. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 14:24:46 -07:00
a266325605 feat: rename proc-title prefix to PRL (#3369)
## Summary

- `PRIME_RL_PROC_PREFIX` becomes `PRL`, so every component's process
title reads `PRL::Trainer`, `PRL::Orchestrator`, `PRL::Inference`,
`PRL::EnvServer`, `PRL::Launcher`, ... — shorter to type and grep. The
`monitor-run` skill's process tree is updated.

## Breaking

- Process titles change from `PRIME-RL::<Name>` to `PRL::<Name>`;
anything matching the old prefix (`pgrep -f PRIME-RL`, dashboards, ops
scripts) must switch.

First PR of a 3-stack: PRL prefix → CPU-only `uv sync` (GPU deps behind
an extra) → dashboard daemon.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 14:17:03 -07:00
Konstantin DunasandGitHub b9de4a0f7a fix(orchestrator): make dispatch failures explicit (#3364) 2026-08-24 22:23:30 +02:00
75663f0d4c feat: add local run dashboard (#3351)
## Summary

Adds a local run dashboard for SFT / RL / Eval runs. Start with

```bash
# default (all runs in outputs/, port 7788)
uv run dashboard 
```

For example, populate with

```
# rl run
uv run rl @ examples/basic/reverse-text/rl.toml --run.name reverse-text-rl

# sft run
uv run sft @ examples/basic/reverse-text/sft.toml --max-steps 10 --run.name reverse-text-sft

# eval run (multi-agent, multi-branch)
uv run eval \
  --env.id agentic-judge \
  --env.taskset.id terminal-bench-2 \
  --env.taskset.tasks '["fix-git"]' \
  --env.solver.harness.id rlm \
  --env.solver.harness.summarize-at-tokens 4000 \
  --env.judge.harness.id bash \
  --run.name tb2-agentic-judge
```

Combines the best things from W&B + PI platform. Fully isolated
agent-maintained logic in `prime_rl.dashboard`. Fully supersedes the
previously advertised tmux viewer. Should basically be always on when
working with prl locally.

## Gallery

**Configs**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 01 35
PM"
src="https://github.com/user-attachments/assets/a6dec2e2-26d0-49a9-a220-f1baa8c7b1ea"
/>

**Metrics**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 01 55
PM"
src="https://github.com/user-attachments/assets/c38cbac5-177e-4850-a3fc-d09e10da6185"
/>

**Trace Overview**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 02 08
PM"
src="https://github.com/user-attachments/assets/27f4d197-3969-4334-a629-161ac5df434d"
/>

**Trace Viewer**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 02 47
PM"
src="https://github.com/user-attachments/assets/2b9c4aed-20bb-4623-a272-93b5603a79d3"
/>

**Logs**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 03 08
PM"
src="https://github.com/user-attachments/assets/91aa3334-8f97-409a-9f8a-d9e19bff1892"
/>

## Breaking

- `scripts/tmux.sh` is removed — the dashboard replaces the tmux
log-pane workflow (docs, example walkthroughs, and the monitor-run skill
updated).

- Resolved per-component configs move from `{run_dir}/configs/*.json` to
`{run_dir}/configs/resolved/*.json`; `configs/` now holds the launch
TOML (`rl.toml`/`sft.toml`). Anything reading the old paths must switch
(the dashboard reads both layouts).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are additive for training (new CLI and docs) plus removal of
the tmux helper; the config path split may break external tooling that
still reads `{run_dir}/configs/*.json` directly.
> 
> **Overview**
> This PR adds **`uv run dashboard`** — a local web UI (default
**http://localhost:7788**) for watching SFT/RL/eval runs from output
directories only: **metrics** (W&B-style overview from `metrics.jsonl`),
**configs** (launch TOML vs merged resolved JSON), **rollout traces**
with per-token advantage/logprob views, and **merged component logs**.
It ships as a **`dashboard` optional extra** (FastAPI/uvicorn) or as
**`uv run --script src/prime_rl/dashboard/server.py`** on machines
without full GPU deps.
> 
> **`scripts/tmux.sh` is removed**; docs, basic examples, and the
**monitor-run** skill now recommend two terminals plus the dashboard
instead of tmux panes. Side-by-side ablations on one node can use **`uv
run dashboard outputs`** to track multiple experiments.
> 
> **Resolved configs** from dry-run and launches are documented at
**`{run_dir}/configs/resolved/*.json`**, with the launch TOML at
**`configs/*.toml`**; the dashboard server still reads the old flat
`configs/*.json` layout for older runs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
99d9a8f34e9c53b7de1f6a74f82c4053285ba506. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 12:59:39 -07:00
Mika SenghaasandGitHub a975cab86d chore: bump renderers to 0.1.10 (#3367)
## Summary

- Require renderers 0.1.10 in Prime RL and prime-rl-configs.
- Update the renderers submodule to the 0.1.10 release.
- Update the verifiers submodule to the latest main commit.
- Refresh lock metadata for both dependency constraints.

## Verification

- uv lock --check
- uv run --no-project --with pre-commit pre-commit run --files
pyproject.toml packages/prime-rl-configs/pyproject.toml uv.lock

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> <sup>[Cursor Bugbot](https://cursor.com/bugbot) is generating a
summary for commit 95ca34dcca9b2737cf2ebb431a47391ed874052a. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 11:33:20 -07:00
Garrett GoonandGitHub 9aa5f1f2c8 docs(install): document pre-commit hook install step (#3366)
`uv sync --group dev` only installs the pre-commit package; the git hook
stays inert until `uv run pre-commit install` runs, which the install
skill omitted (README's Development section already covers it).
2026-08-24 14:25:05 -04:00
Matej SirovatkaandGitHub c09bb0b30c fix(nccl): avoid cloning received weight tensors (#3365)
## Summary

- yield tensor views into the contiguous NCCL receive buffer instead of
cloning every reconstructed tensor
- avoid duplicating checkpoint payloads while vLLM performs layerwise
weight loading

The change intentionally keeps the existing flat receive stream and vLLM
reload lifecycle. Trainer state-dict boundaries are transport framing,
not loader semantics: vLLM tracks layer completion from the weights
loaded for each module.

## Safety

Each yielded tensor is a disjoint view of the receive buffer. A view
retains its underlying storage, so the buffer cannot be released while
the loader still references one of its tensors. The existing consumers
either copy tensors directly into model parameters or synchronously
process the ordered checkpoint stream.

## H200 reproduction

The reported Laguna-S-2.1 failure was reproduced with one EP8 trainer
node, one TP8 inference node, BF16 checkpoint transfer, and
`gpu_memory_utilization = 0.94`. The receiver code at the tested
baseline (`f53e4d9c`) is unchanged on current `main`.

| Receiver | Startup v0 | Post-training v1 |
|---|---:|---:|
| `main` | OOM on a 20 MiB clone in state dict 3/49; HTTP 500; retry
decoded `54639` state dicts | — |
| this change | 49/49 on all 8 ranks; HTTP 200 | 49/49 on all 8 ranks;
HTTP 200 |

Both successful transfers took approximately 12 seconds by broadcast
markers; the trainer reported `time/broadcast_weights = 13.2418s` for
v1. The inference server subsequently completed two rollout batches, and
the trainer completed its first optimization step.

At `gpu_memory_utilization = 0.97`, the baseline failed earlier while
allocating the 4.64 GiB receive buffer itself, so `0.94` was used to
isolate the additional clone allocation.

## Validation

- `uv run --no-sync pytest -q tests/unit/inference
tests/unit/transports/test_nccl_broadcast.py` — 14 passed, 1 existing
skip
- `uv run --no-sync ruff check
src/prime_rl/inference/vllm/worker/nccl.py`
- `uv run --no-sync python -m py_compile
src/prime_rl/inference/vllm/worker/nccl.py`
- `git diff --check`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches distributed weight-transfer memory semantics on the inference
path; incorrect view lifetime could corrupt loads, but consumers copy
into model parameters synchronously.
> 
> **Overview**
> Fixes GPU OOM during NCCL weight broadcast by **not cloning** each
tensor when splitting the per-dtype receive buffer in
`receive_state_dict`.
> 
> Reconstructed weights are now **views** into the contiguous
`concatenated` buffer (`view(shape)` only), so checkpoint payloads are
not duplicated while vLLM runs layerwise loading via
`load_weights_checkpoint_layerwise` / `load_weights_kernel`. The flat
NCCL stream and per-state-dict receive lifecycle stay the same; disjoint
views keep the buffer alive until consumers finish using yielded
tensors.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d7bd908099d5cffb6792b9b40bdbd322851bc19a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 11:12:34 -07:00
3e93371dad chore: bump verifiers and prime-envs to latest main (#3363)
## Summary
- Bump the `deps/verifiers` submodule from `d4f3d5a8c` to `807aaf389`
(latest `main`).
  - Pulls in:
- [vf#2425](https://github.com/PrimeIntellect-ai/verifiers/pull/2425):
forward sampling parameters across dialects.
- [vf#2428](https://github.com/PrimeIntellect-ai/verifiers/pull/2428):
centralize v1 egress policy decisions.
- [vf#2427](https://github.com/PrimeIntellect-ai/verifiers/pull/2427):
simplify v1 CLI plumbing.
- Bump the `deps/prime-envs` submodule from `b30aad36` to `26dafdc9`
(latest `main`).
  - Pulls in:
-
[prime-envs#761](https://github.com/PrimeIntellect-ai/prime-envs/pull/761):
environment-design rules in AGENTS.md.
-
[prime-envs#762](https://github.com/PrimeIntellect-ai/prime-envs/pull/762):
CI fix for swebench 5 + prime-sandboxes 0.2.37.
-
[prime-envs#684](https://github.com/PrimeIntellect-ai/prime-envs/pull/684):
deshuffle-papers environment.
-
[prime-envs#675](https://github.com/PrimeIntellect-ai/prime-envs/pull/675):
DeepSWE environment.
- Relock `uv.lock`: new workspace members `deep-swe` and
`deshuffle-papers`; `mcp-atlas` 0.3.0 → 0.3.1, `swesmith-env` 0.1.2 →
0.1.3.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Dependency/submodule bump that pulls new training environments and
tighter swebench/prime-sandboxes pins; not auth-critical, but can change
eval/training behavior.
> 
> **Overview**
> Bumps `deps/verifiers` and `deps/prime-envs` to latest `main` and
relocks `uv.lock`.
> 
> **verifiers** picks up sampling-parameter forwarding across dialects,
centralized v1 egress policy, and simpler v1 CLI plumbing.
> 
> **prime-envs** adds the `deep-swe` and `deshuffle-papers` workspace
environments, plus env-design AGENTS.md rules. `mcp-atlas` goes 0.3.0 →
0.3.1 (`prime-sandboxes>=0.2.37`); `swesmith-env` goes 0.1.2 → 0.1.3
(`swebench>=4.1.0,<5`).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b5b07f4795eb911daf72d30203dbd617dec63b37. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-23 18:11:10 -07:00
f53e4d9c63 fix: health-check only the router when admin clients bypass it (#3359)
## Summary

- `AdminClients.wait_for_ready` still health-checks every engine and the
router, but when admin URLs bypass a router, the per-engine waiting
lines log at debug. Startup then logs one info waiting line instead of
one per engine plus the router:

```
03:18:09    INFO Waiting for inference server at http://localhost:8000 to start up (30s elapsed)
03:18:09    INFO Waiting for inference server at http://localhost:8100 to start up (30s elapsed)
```

- `check_health` grows a `quiet` flag that demotes its periodic waiting
lines to debug.
- Deployments without a router (no `client.admin_base_url`) keep logging
at info, as before.

Waiting only on the router is not enough: the llm-d router (Envoy) only
routes `/v1/` and `/inference/v1/`, so `/health` 404s and `check_health`
treats that as "no health route" and skips. The engines therefore stay
part of the readiness wait for correctness; the router just owns the
info-level log. Caveat: on llm-d deployments the info-level waiting line
disappears once Envoy binds its port (the engine waits continue at
debug).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Readiness polling and log-level only; no change to auth, weights, or
request serving. Timeout behavior is the same, just split across two
concurrent health waits.
> 
> **Overview**
> Fixes readiness for llm-d/Envoy routers: `/health` on the router 404s
and was treated as “no health route,” so waiting on the router alone was
not a real ready signal.
> 
> `AdminClients.wait_for_ready` now health-checks engines and router in
parallel. Engine waits use a new `quiet` flag so periodic “waiting”
lines log at debug when a router is present; the router still logs at
info. Deployments without `admin_base_url` are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5167b63bac1ed60edf3f79a99ed470d25a6a026e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 22:03:11 -07:00
Mika SenghaasandGitHub cabbd132eb feat: unified weight transport protocol (#3357)
## Summary

The weight-broadcast core: one protocol for every transport instead of
three private ones.

- **One handshake per version, on every transport**:
`WeightSender.broadcast` is a template method - the trainer resets the
step dir and offers (`.sender_ready`), blocks until the consumer
acknowledges (`.receiver_ready`), transfers (`.started`), commits
(`.finished`), and cleans old dirs. Filesystem does the full handshake:
no consumer run-ahead while the trainer writes, no version skipping ("fs
== nccl behavior").
- **`WeightReceiver`**: consumer-side counterpart, colocated with its
sender per transport file
(`transports/weights/{base,filesystem,nccl,nixl}`). The weight watcher,
the orchestrator startup rendezvous, and the evals process drive the
same object; discovery is uniform on `.sender_ready`. Every offered
version must be received - a failed receive fails the run. This deletes
the NIXL version-cap/cycle-counting hack (markers are versioned on every
transport). The engine-side byte receiver stays in
`inference/vllm/worker`.
- **Consumption-driven sequencing**: broadcast `v{N}` iff something
consumes it. `broadcast_final` lives once on the shared
`BaseWeightBroadcastConfig`, launcher-stamped, never user-set (RL:
`orchestrator.eval is not None`; SFT: `True`). With evals, the final
eval measures `v{max_steps}` on every transport.
- **Bounded handshake**: the trainer's wait for the receiver raises
`TimeoutError` after `weight_broadcast.timeout` (now on the shared
config base, so filesystem has it too), with progress warnings every
60s.
- **Unified cleaning**: keep exactly `{step, step-1}` - broadcasts are
purely transitive, `checkpoints/` owns persistence. Fixes NCCL/NIXL dirs
leaking forever.
- **Fail-fast startup**: RL and SFT both broadcast the incoming policy
before the first step; resume hygiene (`prune_broadcasts_beyond`) lives
at the trainer call sites and prunes stale future dirs.

## Breaking

- On-disk sentinels replaced: `STARTED`/`STABLE`/`NCCL_READY` →
`.sender_ready`/`.receiver_ready`/`.started`/`.finished`, one uniform
handshake per version. Trainer and orchestrator must ship together. A
resume over old broadcast dirs re-broadcasts the startup version.
- Filesystem runs in lockstep with its consumer: the trainer blocks
until each version is acknowledged (bounded by
`weight_broadcast.timeout`), no longer writes versions nobody consumes,
and the consumer no longer skips to the newest version.
- RL with evals broadcasts `v{max_steps}` and the final eval measures it
(metric shift). Without evals, `v{max_steps}` is skipped on every
transport.
- Broadcast-dir retention: exactly the last 2 dirs on every transport
(NCCL/NIXL dirs were previously leaked; SFT kept newest-only).

## Verification

Stack 6/6 of the #3335 breakup; the composed stack is tree-identical to
the e2e-verified #3335 branch (FFT NCCL 10→20 with resume, FFT
filesystem 10→20 with resume, LoRA filesystem 15→20 with resume,
LoRA+NCCL config rejection - all green; per-leg details in #3335).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Rewrites the trainer–inference weight-sync protocol (handshake,
version sequencing, eval/startup rendezvous) across all transports. A
mismatch or timeout now blocks or fails the run rather than skipping a
version.
> 
> **Overview**
> Unifies filesystem, NCCL, and NIXL weight updates onto one lockstep
handshake so every offered policy version is acknowledged before
transfer.
> 
> Trainer `WeightSender.broadcast` now always offers `.sender_ready`,
waits for `.receiver_ready` (bounded by `weight_broadcast.timeout`),
then marks `.started` / `.finished`. Orchestrator, evals, and the weight
watcher all drive a shared `WeightReceiver` instead of per-transport
polling (`STABLE` / `NCCL_READY` / ModelExpress cycle counting). Failed
receives fail the run; filesystem no longer lets the consumer skip ahead
while the trainer writes.
> 
> Broadcasts are consumption-driven: `v{max_steps}` is sent only when a
final eval will measure it (`broadcast_final`, launcher-stamped). Both
RL and SFT fail-fast with a startup broadcast, prune stale future dirs
on resume, and keep only `{step, step-1}` on disk. Trainer and consumer
must ship together — on-disk sentinels are a breaking change.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
53da37d3028a5755afc3615581c9664bfc47bf85. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-22 20:04:36 -07:00
Mika SenghaasandGitHub 947a02aafc feat: serve the LoRA adapter under the base model name (#3358)
## Summary

- Register the single training adapter under `config.model.name`: the
adapter shadows the base model (vLLM resolves `lora_requests` before the
base-model match; verified on the pinned vLLM 0.26), so requests keep
addressing one stable name and nothing switches model names mid-run.
- `update_weights` becomes artifact-driven: a weight dir holding
`adapter_config.json` is hot-swapped as an adapter (a vLLM-native
in-place reload, no engine pause); anything else is a full checkpoint
load.
- Deletes the adapter-naming machinery: the per-version model-name
rewrite in watcher/orchestrator/evals, evals' fixed `eval-adapter` name
and disk-sniff dance, `update_model_name`, and the dead
`unload_lora_adapter`.
- Guardrails: `modules_to_save` is rejected when the weight broadcast is
live (only adapter tensors ship - fully-trained modules would silently
diverge from inference); the LoRA/in-memory rejection states the real
reason (vLLM loads adapters only from a PEFT-shaped directory on disk).
The fallback, if a future vLLM rejects registering an adapter under a
served model name, is documented in the `/load_lora_adapter` wrapper: a
distinct constant name set once at startup.

## Breaking

- `orchestrator.model.lora.name` config field removed (with its
`r{rank}-a{alpha}` auto-derivation). External clients that addressed the
adapter name must use the base model name.
- Inference `max_loras` default 8 → 1 (in-place reload reuses one slot);
the `max_cpu_loras = 100` unload-era override is removed.

Part of the #3335 breakup (stack 5/6); re-lands #3356, whose
squash-merge landed on the stacked base branch instead of main. Verified
e2e as part of #3335 (LoRA reverse-text 15→20 with resume, reward
climbing under the base name).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the LoRA inference serving path and is a breaking config
change (`orchestrator.model.lora.name` removed, `max_loras` default
8→1). Wrong adapter naming or slot count would mis-serve or fail weight
updates.
> 
> **Overview**
> Registers the single training LoRA under `config.model.name` so the
adapter shadows the base model in vLLM. Requests keep using one stable
name; each policy version is an in-place reload (no engine pause, no
mid-run `model_name` rewrite).
> 
> `update_weights` is now artifact-driven: a dir with
`adapter_config.json` loads as LoRA; anything else is a full checkpoint.
Adapter-naming machinery is gone (`orchestrator.model.lora.name`, evals'
`eval-adapter`, `update_model_name`, `unload_lora_adapter`). `max_loras`
defaults to 1 and `max_cpu_loras` is dropped.
> 
> Rejects `modules_to_save` on live broadcasts (only adapter tensors
ship) and documents why LoRA needs filesystem broadcast. Clients that
used a custom adapter name must now hit the base model name.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7e4ba4ce153ee54b87816b573701cf9f95bda928. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-22 19:58:13 -07:00
Mika SenghaasandGitHub f615de9383 refactor: split InferencePool into InferenceClient and AdminClients (#3355)
## Summary

- Split `InferencePool` into two explicit classes under
`prime_rl.orchestrator.clients` (moved out of `utils.client`):
`InferenceClient` (data plane: train/eval client configs, model name,
prefill scoring - single-valued, one router endpoint) and `AdminClients`
(admin plane: one httpx client per engine process, in GPU-rank order -
the `rank_offset` math in the broadcast init depends on it; readiness
checks).
- Data-plane variables are named `clients` across the codebase
(`policy_pool`/`pool`/`policy_inference` renamed; the dispatcher uses
`policy_clients` to distinguish from frozen-source clients).
- Fixes the httpx-client leak: `InferencePool.stop()` closed only the
prefill scorer, leaking N+1 admin/router clients per pool; `aclose()`
now closes all of them.
- Deletes the dispatcher's `pinned_client` - a no-op since the
single-URL router (the client for a group never changes).

Behavior-preserving otherwise: the LoRA-name plumbing and the NCCL_READY
marker semantics are untouched (they change in the stacked follow-ups).

Part of the #3335 breakup (stack 4/6).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches orchestrator inference wiring, weight updates, and shutdown,
but is a behavior-preserving split plus a resource-leak fix. NCCL
world-size is now required rather than defaulted.
> 
> **Overview**
> Splits the combined `InferencePool` into a **data plane**
(`InferenceClient`: train/eval clients, model name, prefill scoring) and
an **admin plane** (`AdminClients`: per-engine httpx clients in GPU-rank
order, readiness). Client helpers now live under
`prime_rl.orchestrator.clients`.
> 
> Call sites (orchestrator, evals, dispatcher, algorithms, generation
sources, watcher) take `clients` / `admin_clients` instead of a pool.
Frozen endpoints use a one-shot `check_inference_ready` instead of a
persistent admin plane.
> 
> Also **closes the httpx leak** (`aclose()` now shuts down admin/router
clients, not just the scorer), drops the unused dispatcher
`pinned_client`, and requires `inference_world_size` for NCCL init.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
19092eeb66bd30ff0fe34e5e64eb9a3276fa9c0f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-22 19:54:55 -07:00
Mika SenghaasandGitHub 1093f9b914 refactor: rename transports.rollouts to transports.batch (#3354)
## Summary

- Rename `transports.rollouts` → `transports.batch`: the module ships
packed training batches, not rollouts.
`MicroBatchSender`/`MicroBatchReceiver` (and the ZMQ/FileSystem
variants) become `BatchSender`/`BatchReceiver`;
`setup_micro_batch_{sender,receiver}` become
`setup_batch_{sender,receiver}`.
- The `MicroBatch` payload type, every `list[MicroBatch]` signature, and
the `rollout_transport` config field are unchanged.

Part of the #3335 breakup (stack 3/6).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-08-22 19:34:34 -07:00
Mika SenghaasandGitHub 67ab1d6667 chore: remove dead extra_headers_from_state config (#3353)
## Summary

- Remove the `client.extra_headers_from_state` config field and the
`auto_setup_session_headers` validator that populated it. The field has
no readers: v1 clients send the `X-Session-ID` sticky-routing header
themselves, from the rollout's trace id (`SESSION_ID_HEADER` in
`verifiers/v1/clients`, attached per request in `train.py` and
`eval.py`). Verified at the wire: requests through the real vf client
arrive at the router with the header and route sticky per session.

## Breaking

- `client.extra_headers_from_state` config field removed (dead - nothing
read it).

Part of the #3335 breakup (stack 2/6, on #3352).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-08-22 19:33:01 -07:00
134 changed files with 10538 additions and 2114 deletions
+1 -1
View File
@@ -170,7 +170,7 @@ jobs:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync
run: uv sync --all-extras
- name: Download all benchmark artifacts
uses: actions/download-artifact@v8
with:
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --extra flash-attn --all-packages --locked
run: uv sync --all-extras --all-packages --locked
- name: Run tests
env:
USERNAME_CI: CI_RUNNER
+1
View File
@@ -31,6 +31,7 @@ Namespaces are one honking great idea -- let's do more of those!
## Running code
- **Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
- **Tools vs entrypoints**: standalone scripts in `tools/` use plain argparse with positional args; `[project.scripts]` entrypoints use pydantic-config (`@ file.toml` + dotted CLI overrides).
- **Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
+2 -2
View File
@@ -96,7 +96,7 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# mount here: .git would bust the cache every commit.
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
@@ -132,7 +132,7 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
@@ -23,7 +23,6 @@ group_size = 16
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -20,7 +20,6 @@ group_size = 16
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
+1 -1
+1 -1
+1 -1
View File
@@ -159,7 +159,7 @@ Algorithms operate on native verifier artifacts and annotate their message graph
The pipeline drives these through `finalize_episode` and `finalize_group`. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy pool (`self.policy_pool`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
## Async / Off-Policy Training
+2 -2
View File
@@ -247,8 +247,8 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
Then inspect the resolved config:
```bash
ls /tmp/reverse-dry/check/configs/
ls /tmp/reverse-dry/check/configs/resolved/
# rl.json trainer.json orchestrator.json inference.json
```
Each per-process TOML reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/check/configs/trainer.json`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
Each per-process JSON reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/check/configs/resolved/trainer.json`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
+1 -9
View File
@@ -191,15 +191,7 @@ Both backends support the 2 most important things:
### Routing policies
The 2 policies you might want to configure are:
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - this works by hashing a request header to determine where to route the request to. You can configure what to hash by setting
`orchestrator.model.client.extra_headers_from_state` to the header the `router` expects to be set.
We set it to a sensible default, that works with all verifiers environments.
```toml
[orchestrator.model.client.extra_headers_from_state]
X-Session-ID = "trajectory_id" # this is the default - each rollout has a unique trajectory_id and router expects X-Session-ID
```
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - it hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica.
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
+11 -7
View File
@@ -43,19 +43,20 @@ uv run rl @ rl.toml \
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
For quick A/B ablations on the same node, run two RL instances side-by-side in separate tmux sessions, each pinned to half the GPUs and a separate inference port:
For quick A/B ablations on the same node, run two RL instances side-by-side in separate shells, each pinned to half the GPUs and a separate inference port, and track both in one dashboard:
```bash
# session 1, GPUs 0–1, default port 8000
bash scripts/tmux.sh -s exp1 -o outputs/exp1
# shell 1, GPUs 0–1, default port 8000
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --run.name exp1
# session 2, GPUs 2–3, port 8001
bash scripts/tmux.sh -s exp2 -o outputs/exp2
# shell 2, GPUs 2–3, port 8001
CUDA_VISIBLE_DEVICES=2,3 uv run rl @ rl.toml \
--inference.server.port 8001 \
--orchestrator.model.client.base-url http://localhost:8001/v1 \
--run.name exp2
# watch both side by side
uv run dashboard outputs
```
#### SFT and Torchrun
@@ -193,9 +194,11 @@ Launch:
```bash
uv run rl @ base_rl.toml @ my_slurm.toml # submits via sbatch
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script + resolved config, exits
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes launcher/rl.sbatch + resolved config, exits
```
Every SLURM entrypoint stores its generated scripts and coordination files under `<run_dir>/launcher/`. SLURM stdout and stderr go to `launcher/logs/`. Local launches do not create `launcher/`.
### `[deployment]` Block
`[deployment]` is a discriminated union picked by `type` — `single_node` or `multi_node` for RL/SFT, with an extra disaggregated variant for inference. RL multi-node:
@@ -214,7 +217,8 @@ SFT multi-node:
```toml
[deployment]
type = "multi_node"
num_nodes = 2
num_train_nodes = 2
num_infer_nodes = 1 # required only for online evals
gpus_per_node = 8
```
+30 -21
View File
@@ -77,11 +77,11 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| Knob | What it does |
|---|---|
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). |
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). Defaults to `$PRL_OUTPUT_DIR` if set, else `outputs`. |
| `--run.name <name>` | Run name, also the run directory name under `<output_dir>` (override the directory separately via `--run.dir`). Auto-generated as `<envs>--<model>--<short-id>` when unset, so every launch gets a fresh, readable run directory. Set an explicit name for a predictable path — required to resume the run later. |
| `--clean` | Wipe the run directory before starting. Useful when re-running a named run during iteration. |
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
| `--dry-run` | Resolve + validate the full config, write per-process TOMLs to `<run_dir>/configs/`, and exit without launching. The fastest way to debug a misbehaving config. |
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
### Algorithms
@@ -198,17 +198,17 @@ num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at every step an eval env is due, and the evals process watches `broadcasts/step_{n}` for synchronization markers before it drives the NCCL receive. It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
#### Multi-Node (Decoupled Trainer and Inference Pool)
#### Multi-Node Trainer and Inference Pool
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two separate SLURM jobs**. `deployment.num_train_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and evals process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2 # trainer job
num_infer_nodes = 1 # eval job (inference pool + evals)
num_train_nodes = 2 # trainer nodes
num_infer_nodes = 1 # inference pool + evals
[inference.vllm]
tensor_parallel_size = 8
@@ -217,7 +217,7 @@ tensor_parallel_size = 8
job_name = "my-run"
```
The launcher submits the eval job after the trainer allocation starts. The trainer publishes its rank-0 hostname in the shared run directory, and the eval job uses it to join the NCCL weight-broadcast group. Each weight transfer is synchronous, but eval rollout execution overlaps with later training steps. After the final transfer, the trainer job releases its nodes while the eval job finishes the final epoch and exits. Without `max_steps`, the eval job never sees a final broadcast and holds its allocation until walltime. Trainer and evals log to one shared W&B run — the trainer creates it, and the evals process finalizes it. Any trainer-to-inference node layout works because `num_train_nodes` and `num_infer_nodes` are independent.
The shared script passes the trainer rank-0 hostname directly to the evals process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, evals never sees a final broadcast, so the job remains active until walltime. Trainer and evals log to one shared W&B run. The trainer creates it, and evals finalizes it.
### SFT-Specific Knobs
@@ -263,8 +263,8 @@ Checkpointing is split across processes because the orchestrator and trainer can
| Process | What's saved | Where |
|---|---|---|
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_N/trainer/` |
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_N/orchestrator/` |
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_{n}/trainer/` |
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_{n}/orchestrator/` |
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
### Enabling Checkpoints
@@ -297,6 +297,20 @@ uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
--resume.dir outputs/my-run/checkpoints/step_10
```
### Exporting Checkpoints
Trainer checkpoints are DCP-sharded; export them to HF-format safetensors with `tools/convert_dcp_to_bf16.py`. The script reads the model config from the run's resolved config and writes sharded safetensors plus config/tokenizer assets to `<ckpt_dir>/weights` (or a second positional arg). It exports full fine-tunes only — LoRA checkpoints are rejected.
```bash
# single process (1 GPU)
uv run python tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
# multi-rank for faster gathers and models that don't fit one GPU
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
```
The exported directory loads directly into `uv run inference --vllm.model <dir>` or any HF consumer. Quantize it to blockwise FP8 (DeepSeek/GLM format, loads natively in vLLM) with `tools/convert_bf16_to_fp8.py <dir>`, or go straight from the checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (each rank quantizes its gathered slice, writes only `<ckpt_dir>/weights-FP8` — no intermediate bf16 export); dequantize an fp8-only release (e.g. GLM-5-FP8) for training with `tools/convert_fp8_to_bf16.py <dir>`.
## Observability
### Log Files
@@ -307,6 +321,7 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
├── orchestrator.log # single instance, single file
├── evals.log # SFT online-eval process
├── inference.log # symlink → inference/node_0.log on multi-node
├── trainer/
│ ├── node_*.log # per-node trainer stdout (multi-node only)
@@ -317,27 +332,21 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
```
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/latest/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
```bash
tail -F <run_dir>/logs/latest/{trainer,orchestrator,inference}.log
tail -F <run_dir>/logs/latest/{trainer,orchestrator,evals,inference}.log
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
```
### Console Output
### Dashboard
`scripts/tmux.sh` opens a 4-pane tmux session that follows `trainer.log`, `orchestrator.log`, `inference.log`, and the union of env worker logs. Start it before launching:
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved configs, a rollout trace viewer with a per-token advantage/logprob view, merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
```bash
bash scripts/tmux.sh -o outputs/my-run
# then in the Launcher window:
uv run rl @ ... --run.name my-run
```
Pass `-s <session>` and `-o <run_dir>` (the run directory, `<output_dir>/<run_name>`) to run multiple parallel experiments side-by-side in different sessions. The helper also works on a SLURM head node — `bash scripts/tmux.sh my-rl-job /shared/outputs/my-rl-job`.
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
### Weights & Biases
+8 -7
View File
@@ -12,9 +12,10 @@ The taskset is included through the Verifiers workspace. After syncing the repos
uv run python -c "import alphabet_sort"
```
Start the tmux session:
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
```bash
bash scripts/tmux.sh
uv run dashboard
```
## Task
@@ -31,13 +32,13 @@ We use non-default settings to balance the difficulty: 3 fixed turns (instead of
Start the inference server:
```bash
# In the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507
```
Evaluate the base model:
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run eval alphabet-sort --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
@@ -91,7 +92,7 @@ We train with LoRA (rank 32, alpha 64) for 100 steps.
*Check out the logs on [W&B](https://wandb.ai/primeintellect/alphabet-sort-4b-lora/workspace?nw=nwuserandrewpi).*
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run rl @ examples/basic/alphabet-sort/rl.toml \
--run.name rl \
--monitors.wandb.project ... \
@@ -106,12 +107,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetS
Let's see how our final RL checkpoint performs on the eval set.
```bash
# In the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
```
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run eval alphabet-sort --harness.id null \
-m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL \
--client.base-url http://localhost:8000/v1 \
+9 -9
View File
@@ -12,21 +12,21 @@ The `reverse-text` taskset is included through the Verifiers workspace. After sy
uv run python -c "import reverse_text"
```
First, let's start a `tmux` session which we will use throughout the experiment.
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
```bash
bash scripts/tmux.sh
uv run dashboard
```
Let's check how well `Qwen3-0.6B` does out-of-the-box on the `reverse-text` environment.
```bash
# Run this in the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.model Qwen/Qwen3-0.6B
```
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run eval reverse-text --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
@@ -41,7 +41,7 @@ We will fine-tune `PrimeIntellect/Qwen3-0.6B` ([HF](https://huggingface.co/Prime
To train on a single GPU, run
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run sft @ examples/basic/reverse-text/sft.toml \
--run.name sft \
--monitors.wandb.project ... \
@@ -51,7 +51,7 @@ uv run sft @ examples/basic/reverse-text/sft.toml \
To train on multiple GPUs, run
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run torchrun \
--local-ranks-filter 0 \
--nproc-per-node ... \
@@ -71,7 +71,7 @@ For the RL we will only do 20 steps at 8x16 rollouts, for a total batch size of
*Check out the logs of the RL run on [W&B](https://wandb.ai/primeintellect/examples?nw=yxjwjc556do).*
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run rl @ examples/basic/reverse-text/rl.toml \
--model.name ... \
--run.name rl \
@@ -88,12 +88,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL`
Let's see how our final RL checkpoints perform on the `reverse-text` environment.
```bash
# Run this in the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
```
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run eval reverse-text --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
+7 -7
View File
@@ -25,10 +25,10 @@ Set up the credentials for the configured reference judge:
export OPENAI_API_KEY=your_api_key_here
```
Start the tmux session:
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
```bash
bash scripts/tmux.sh
uv run dashboard
```
## Task
@@ -69,14 +69,14 @@ Key configuration highlights:
Start the inference server:
```bash
# In the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507 --vllm.tool-call-parser hermes
```
Evaluate the base model:
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run eval wiki-search --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
@@ -91,7 +91,7 @@ uv run eval wiki-search --harness.id null \
Train with the unified config file:
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run rl @ examples/basic/wiki-search/rl.toml \
--run.name rl \
--monitors.wandb.project your-project-name \
@@ -110,12 +110,12 @@ This will write DCP checkpoints in `outputs/rl/checkpoints/step_*`.
Evaluate your trained model:
```bash
# In the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSearch-RL --vllm.tool-call-parser hermes
```
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run eval wiki-search --harness.id null \
-m <user>/Qwen3-4B-Instruct-WikiSearch-RL \
--client.base-url http://localhost:8000/v1 \
-1
View File
@@ -37,7 +37,6 @@ group_size = 16
initial_inflight = 1024
[orchestrator.model.lora]
name = "qwen3-4b-wiki-search"
[orchestrator.train.sampling]
max_completion_tokens = 512
+9 -9
View File
@@ -12,23 +12,23 @@ The taskset is included through the Verifiers workspace. After syncing the repos
uv run python -c "import wordle"
```
Start the pre-layouted `tmux` session which we will use to run all experiments and view logs conveniently
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
```bash
bash scripts/tmux.sh
uv run dashboard
```
Before training, we want to get a baseline score and test how well `Qwen3-1.7B` does out-of-the-box in the `wordle` environment so that we quantify our training effect. To do so, first start a local inference server to serve `Qwen3-1.7B`.
```bash
# Run this in the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.model Qwen/Qwen3-1.7B
```
Then, use the `eval` entrypoint to evaluate the model in the `wordle` environment. We evaluate on the 20 evaluation examples which are distinct words not appearing in the training set of the environment. We constrain the response length to 1024 tokens as this should be more than enough to play a full game.
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run eval wordle --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
@@ -43,7 +43,7 @@ We will fine-tune `PrimeIntellect/Qwen3-1.7B` ([HF](https://huggingface.co/Prime
To train on a single GPU, run
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run sft @ examples/basic/wordle/sft.toml \
--run.name sft \
--monitors.wandb.project ... \
@@ -53,7 +53,7 @@ uv run sft @ examples/basic/wordle/sft.toml \
To train on multiple GPUs, run
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run torchrun \
--local-ranks-filter 0 \
--nproc-per-node ... \
@@ -74,7 +74,7 @@ Finally, we will do multi-turn RL against the `wordle` environment using the mod
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run rl @ examples/basic/wordle/rl.toml \
--model.name ... \
--run.name rl \
@@ -91,12 +91,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](http
Let's see how our final RL checkpoint performs on the eval set.
```bash
# Run this in the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.model PrimeIntellect/Qwen3-1.7B-Wordle-RL
```
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run eval wordle --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
+1 -1
View File
@@ -7,7 +7,7 @@ requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.4.3",
"renderers>=0.1.9",
"renderers>=0.1.10",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.3.0",
@@ -1,10 +1,10 @@
from pathlib import Path
import verifiers.v1 as vf
from pydantic import SerializeAsAny, model_validator
from pydantic import Field, SerializeAsAny, model_validator
from prime_rl.configs.shared import LogConfig
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.config import BaseConfig, default_output_dir
class EnvServerConfig(BaseConfig):
@@ -20,8 +20,8 @@ class EnvServerConfig(BaseConfig):
log: LogConfig = LogConfig()
output_dir: Path = Path("outputs")
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
@model_validator(mode="before")
@classmethod
@@ -6,7 +6,7 @@ from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.config import BaseConfig, default_output_dir
class EvalsEvalConfig(EvalConfig):
@@ -86,9 +86,9 @@ class EvalsConfig(BaseConfig):
"""Weight transport for online evals. The ``sft`` launcher fills this from its
resolved trainer transport. None uses filesystem reloads."""
output_dir: Path = Path("outputs")
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer for online evals."""
subdirectories. Shared with the trainer for online evals. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
log: LogConfig = LogConfig()
@@ -7,7 +7,7 @@ from pydantic import ConfigDict, Field, model_validator
from pydantic_config import BaseConfig
from prime_rl.configs.shared import EnvVars, LogConfig, SlurmConfig
from prime_rl.utils.config import find_package_resource
from prime_rl.utils.config import default_output_dir, find_package_resource
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
# TODO: Set thinking/ solution budget
@@ -111,14 +111,9 @@ class VllmConfig(BaseConfig):
enable_lora: bool = False
"""Enable LoRA."""
max_loras: int = 8
"""Maximum number of LoRAs."""
# TODO: The default value is very high because our areal impl for lora isn't ideal
# We add a lora with the same name instead of changing weights inplace
# Because we dont cancel requests that are past max_async, these requests could be using a LoRA that gets unloaded which will crash the inference server
max_cpu_loras: int = 100
"""Maximum number of LoRAs on CPU."""
max_loras: int = 1
"""Maximum number of concurrently served LoRAs. prime-rl serves one adapter and reloads
it in place every policy version (same name, same lora_int_id), so one slot suffices."""
max_lora_rank: int | None = None
"""Maximum LoRA rank. Rounded up to the nearest value vLLM accepts."""
@@ -476,8 +471,8 @@ class InferenceConfig(BaseConfig):
slurm: SlurmConfig | None = None
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
output_dir: Path = Path("outputs")
"""Directory for SLURM logs and generated scripts."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory for SLURM logs and generated scripts. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
@@ -12,6 +12,7 @@ from prime_rl.configs.algorithm import (
from prime_rl.configs.monitors import OrchestratorMonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
BaseWeightBroadcastConfig,
ClientConfig,
EnvVars,
HeartbeatConfig,
@@ -21,13 +22,10 @@ from prime_rl.configs.shared import (
ZMQTransportConfig,
)
from prime_rl.configs.trainer import TokenizerConfig
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.config import BaseConfig, default_output_dir
class LoRAConfig(BaseConfig):
name: str | None = None
"""LoRA adapter name. If None, auto-generated from rank and alpha."""
rank: int | None = Field(None, ge=1)
"""LoRA rank for this run. Must be ≤ trainer's max rank. If None, uses the trainer's rank."""
@@ -376,20 +374,17 @@ class CheckpointConfig(BaseConfig):
"""Skip loading the progress from checkpoint."""
class FileSystemWeightBroadcastConfig(BaseConfig):
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["filesystem"] = "filesystem"
class InMemoryWeightBroadcastConfig(BaseConfig):
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
host: str = "localhost"
"""Weight transfer host."""
port: int
"""Weight transfer port."""
timeout: int = 1200
"""Weight transfer timeout in seconds."""
inference_world_size: int = Field(1, ge=1)
"""Total inference workers across all servers."""
@@ -496,8 +491,8 @@ class OrchestratorConfig(BaseConfig):
rollout_transport: TransportConfig = ZMQTransportConfig()
"""Transport used to ship rollouts from orchestrator to trainer."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
@@ -543,12 +538,6 @@ class OrchestratorConfig(BaseConfig):
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def auto_setup_session_headers(self):
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
self.model.client.extra_headers_from_state.setdefault("X-Session-ID", "trajectory_id")
return self
@model_validator(mode="after")
def auto_setup_prime_monitor_name(self):
"""Default ``monitors.prime.name`` to the W&B run name when monitoring
@@ -41,7 +41,7 @@ from prime_rl.configs.trainer import (
TokenizerConfig,
TrainerConfig,
)
from prime_rl.utils.config import BaseConfig, find_package_resource
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
from prime_rl.utils.validation import (
propagate_shared_fields,
validate_shared_ckpt_config,
@@ -136,7 +136,7 @@ class SharedInMemoryWeightBroadcastConfig(BaseConfig):
"""Weight transfer port."""
timeout: int = 1200
"""Timeout in seconds for in-memory weight transfer."""
"""Timeout in seconds for the broadcast handshake and transfer."""
class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
@@ -162,6 +162,9 @@ class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
class SharedFileSystemWeightBroadcastConfig(BaseConfig):
type: Literal["filesystem"] = "filesystem"
timeout: int = 1200
"""Timeout in seconds for the broadcast handshake and transfer."""
SharedWeightBroadcastConfig: TypeAlias = Annotated[
SharedFileSystemWeightBroadcastConfig | SharedNCCLWeightBroadcastConfig | SharedNIXLWeightBroadcastConfig,
@@ -240,8 +243,8 @@ class RLConfig(BaseConfig):
run: RunConfig = Field(default_factory=RunConfig)
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
output_dir: Path = Path("outputs")
"""Directory that groups related runs. Each run writes its artifacts to ``output_dir / run.name``."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory that groups related runs. Each run writes its artifacts to ``output_dir / run.name``. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
clean: bool = False
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
@@ -296,6 +299,10 @@ class RLConfig(BaseConfig):
slurm: SlurmConfig | None = None
"""SLURM configuration. If None, runs locally."""
dashboard: bool = True
"""Make sure a local dashboard daemon serves this run's output dir (started on
demand in interactive sessions; an already-running daemon's URL is logged)."""
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
@@ -460,8 +467,9 @@ class RLConfig(BaseConfig):
self.weight_broadcast = SharedNCCLWeightBroadcastConfig()
if self.weight_broadcast.type != "filesystem" and self.trainer.model.lora is not None:
raise ValueError(
"LoRA training is not yet supported with in-memory weight broadcast. "
"Set weight_broadcast.type = 'filesystem'."
"LoRA requires weight_broadcast.type = 'filesystem': vLLM loads adapters only from a "
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
"have no disk artifact to load from."
)
if self.weight_broadcast.type in ("nccl", "nixl"):
inference_world_size = (
@@ -488,8 +496,12 @@ class RLConfig(BaseConfig):
self.trainer.weight_broadcast = trainer_config_type(**common_config, **transport_config)
self.orchestrator.weight_broadcast = orchestrator_config_type(**common_config, **transport_config)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig(
timeout=self.weight_broadcast.timeout
)
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig(
timeout=self.weight_broadcast.timeout
)
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
@@ -568,11 +580,6 @@ class RLConfig(BaseConfig):
if self.orchestrator.model.lora.alpha is None:
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
if self.orchestrator.model.lora.name is None:
self.orchestrator.model.lora.name = (
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
)
if self.inference is not None:
self.inference.vllm.enable_lora = True
self.inference.vllm.max_lora_rank = self.trainer.model.lora.rank
@@ -33,7 +33,7 @@ from prime_rl.configs.trainer import (
WeightBroadcastConfig,
validate_scheduler,
)
from prime_rl.utils.config import BaseConfig, find_package_resource
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
class BaseDataConfig(BaseConfig):
@@ -175,9 +175,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
"""Training nodes."""
num_infer_nodes: int = Field(0, ge=0, validation_alias=AliasChoices("num_infer_nodes", "num_eval_nodes"))
"""Inference nodes for online evals (alias: ``num_eval_nodes``). Submitted as a separate SLURM job, decoupled
from the trainer job. The eval job can outlive the trainer job while it evaluates
the final weight broadcast."""
"""Inference nodes for online evals (alias: ``num_eval_nodes``). These nodes share
one SLURM allocation with the trainer nodes."""
nodes_per_fsdp_group: int | None = None
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
@@ -233,8 +232,8 @@ class SFTConfig(BaseConfig):
run: RunConfig = Field(default_factory=RunConfig)
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
output_dir: Path = Path("outputs")
"""Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
clean: bool = False
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
@@ -285,6 +284,10 @@ class SFTConfig(BaseConfig):
slurm: SlurmConfig | None = None
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
dashboard: bool = True
"""Make sure a local dashboard daemon serves this run's output dir (started on
demand in interactive sessions; an already-running daemon's URL is logged)."""
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
@@ -390,18 +393,18 @@ class SFTConfig(BaseConfig):
raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
if self.deployment.type == "multi_node":
# Decoupled deployment: the launcher submits a dedicated SLURM job running the
# inference pool (one engine per DP rank behind a router) plus the evals process.
# Dedicated nodes in the SFT allocation run the inference pool, router,
# env servers, and evals process.
if self.inference is None:
raise ValueError(
"Multi-node online evals require an [inference] block - the launcher submits "
"a dedicated SLURM job running the inference pool and the evals process."
"Multi-node online evals require an [inference] block - dedicated nodes in the "
"SFT allocation run the inference pool and evals process."
)
if self.deployment.num_infer_nodes < 1:
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
if self.inference.router is None:
raise ValueError(
"Multi-node online evals require an inference router - the eval job starts one "
"Multi-node online evals require an inference router - the launcher starts one "
"router in front of the per-rank engines. Remove inference.router = 'None'."
)
if self.inference.vllm.model != self.model.name:
@@ -422,10 +425,10 @@ class SFTConfig(BaseConfig):
if self.max_steps is None:
warnings.warn(
"Online evals without max_steps: the evals process never sees a final checkpoint, "
"so the eval SLURM job holds its allocation until its walltime.",
"so the SFT SLURM job holds its allocation until its walltime.",
stacklevel=2,
)
# The client is wired at runtime by the eval sbatch script (the router and
# The client is wired at runtime by the SFT sbatch script (the router and
# per-rank admin URLs are only known once SLURM assigns hosts).
return self
@@ -37,6 +37,12 @@ EnvVars: TypeAlias = Annotated[dict[str, str], AfterValidator(reject_protected_e
"""A per-component `env_vars` mapping, validated to not clobber `PROTECTED_ENV_VARS`."""
class BaseWeightBroadcastConfig(BaseConfig):
timeout: int = 1200
"""Timeout in seconds for the broadcast handshake and transfer. The trainer
fails the run when no consumer acknowledges an offered version in time."""
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."""
@@ -169,9 +175,6 @@ class ClientConfig(BaseConfig):
headers_from_env: dict[str, str] = {}
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
extra_headers_from_state: dict[str, str] = {}
"""Maps HTTP header names to rollout-state field names. The header value is read from the rollout state dict on every request. e.g. ``{"X-Session-ID": "trajectory_id"}`` enables sticky routing at the inference router."""
skip_model_check: bool = False
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
@@ -7,6 +7,7 @@ from pydantic import BeforeValidator, Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
BaseWeightBroadcastConfig,
EnvVars,
HeartbeatConfig,
MetricsServerConfig,
@@ -15,7 +16,7 @@ from prime_rl.configs.shared import (
TransportConfig,
ZMQTransportConfig,
)
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.config import BaseConfig, default_output_dir
# -- Shared trainer configs (used by both SFT and RL trainers) --
@@ -545,10 +546,6 @@ class DataLoaderConfig(BaseConfig):
"""Use a fake data loader sampling random micro-batches (for debugging)."""
class BaseWeightBroadcastConfig(BaseConfig):
pass
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["filesystem"] = "filesystem"
@@ -560,9 +557,6 @@ class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
port: int
"""Weight transfer port."""
timeout: int = 1200
"""Weight transfer timeout in seconds."""
# TODO: Should not be configurable, but auto-inferred
inference_world_size: int = 1
"""Number of inference workers."""
@@ -625,8 +619,8 @@ class TrainerConfig(BaseConfig):
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
matmul_precision: Literal["highest", "high", "medium"] = "high"
"""Precision for float32 matrix multiplications. ``highest`` is full FP32 (required on ROCm/AMD GPUs to avoid catastrophic precision loss in softmax over large vocabularies). ``high`` enables TF32 on NVIDIA GPUs for a speedup with minor precision tradeoff. See ``torch.set_float32_matmul_precision``."""
@@ -733,7 +727,15 @@ class TrainerConfig(BaseConfig):
@model_validator(mode="after")
def validate_lora_broadcast(self):
if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "nixl"):
raise ValueError("In-memory weight broadcast does not support LoRA yet.")
raise ValueError(
"LoRA requires weight_broadcast.type = 'filesystem': vLLM loads adapters only from a "
"PEFT-shaped directory on disk - in-memory transports have no disk artifact to load from."
)
if self.model.lora is not None and self.model.lora.modules_to_save and self.data.fake is None:
raise ValueError(
"model.lora.modules_to_save cannot be served: the weight broadcast ships only the "
"adapter tensors, so fully-trained modules would silently diverge from inference."
)
return self
@model_validator(mode="after")
@@ -1,3 +1,4 @@
import os
from pathlib import Path
from typing import Any
@@ -6,6 +7,11 @@ from pydantic_config import BaseConfig as BaseConfig # noqa: F401
from pydantic_config import cli # noqa: F401
def default_output_dir() -> Path:
"""Default output directory: ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
return Path(os.environ.get("PRL_OUTPUT_DIR", "outputs"))
def dump_resolved_config(config: BaseModel, exclude: set[str] | None = None) -> dict:
"""Dump a resolved config for a machine-written JSON artifact.
+42 -31
View File
@@ -1,6 +1,6 @@
[project]
name = "prime-rl"
version = "0.8.0"
version = "0.9.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
@@ -13,38 +13,25 @@ dependencies = [
"loguru>=0.7.3",
"pyarrow>=21.0.0",
"numpy>=2.2.6",
"torch>=2.9.0",
"torchvision",
"torchaudio",
"torchdata>=0.11.0",
"transformers==5.6.2",
"vllm>=0.26.0",
"mooncake-transfer-engine>=0.3.10.post2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
"ring-flash-attn>=0.1.8",
"prime>=0.6.19",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
"openai>=1.106.1",
"orjson>=3.11.0",
"psutil>=7.0.0",
"rich>=14.0.0",
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.3.1.dev59",
"renderers",
"dion",
"tilelang>=0.1.8",
"flash-linear-attention",
"nvidia-ml-py>=12.575.51",
"verifiers[harbor]>=0.3.1",
"renderers>=0.1.10",
"pybase64>=1.4.2",
"orjson>=3.10",
"pandas>=2.0",
"msgspec>=0.18",
"torchao>=0.17.0",
"modelexpress==0.3.0",
]
[project.scripts]
@@ -55,11 +42,32 @@ trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
evals = "prime_rl.entrypoints.evals:main"
env-server = "prime_rl.entrypoints.env_server:main"
dashboard = "prime_rl.entrypoints.dashboard:main"
[project.entry-points."vllm.general_plugins"]
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
[project.optional-dependencies]
gpu = [
"torch>=2.9.0 ; sys_platform == 'linux'",
"torchvision ; sys_platform == 'linux'",
"torchaudio ; sys_platform == 'linux'",
"torchdata>=0.11.0 ; sys_platform == 'linux'",
"vllm>=0.26.0 ; sys_platform == 'linux'",
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
"torchtitan ; sys_platform == 'linux'",
"dion ; sys_platform == 'linux'",
"tilelang>=0.1.8 ; sys_platform == 'linux'",
"flash-linear-attention ; sys_platform == 'linux'",
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
"torchao>=0.17.0 ; sys_platform == 'linux'",
"modelexpress==0.3.0 ; sys_platform == 'linux'",
]
dashboard = [
"fastapi>=0.115",
"uvicorn>=0.30",
]
# Both wheels are the same flash-attn 2.8.3 / cu128 / torch 2.11 / cp312 build and carry
# sm_80 / sm_90 / sm_100 / sm_120 cubins. `attn="auto"` picks FA4 on sm_100 and FA3 on
# sm_90, so FA2 is the resolved backend on sm_120 (see `_resolve_attn_impl` in
@@ -68,30 +76,31 @@ flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.22/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
]
flash-attn-3 = ["flash_attn_3"]
flash-attn-3 = ["flash_attn_3 ; sys_platform == 'linux'"]
flash-attn-cute = [
"flash-attn-4",
"flash-attn-4 ; sys_platform == 'linux'",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64' or platform_machine == 'aarch64'",
"deep-gemm",
"nixl",
"nixl-cu12 ; platform_machine == 'x86_64'",
"vllm-router",
"deep-ep ; sys_platform == 'linux'",
"deep-gemm ; sys_platform == 'linux'",
"nixl ; sys_platform == 'linux'",
"nixl-cu12 ; sys_platform == 'linux' and platform_machine == 'x86_64'",
"vllm-router ; sys_platform == 'linux'",
]
gpt-oss = [
"kernels",
"kernels ; sys_platform == 'linux'",
]
quack = [
"quack-kernels>=0.4.1",
"quack-kernels>=0.4.1 ; sys_platform == 'linux'",
]
# Prebuilt `prime-kernels` wheels from a release (see the `kernels` skill). Compiled for
# sm_100a; on other GPUs the package installs fine and reports its kernels unavailable.
kernels = [
"prime-kernels",
"prime-kernels ; sys_platform == 'linux'",
]
all = [
"prime-rl[gpu]",
"prime-rl[flash-attn]",
"prime-rl[disagg]",
"prime-rl[quack]",
@@ -101,12 +110,13 @@ all = [
[dependency-groups]
mamba-ssm = [
"mamba-ssm>=2.3.0",
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
]
dev = [
"ipykernel>=6.29.5",
"ipywidgets>=8.1.7",
"pre-commit>=4.2.0",
"playwright>=1.49",
"pytest>=8.4.1",
"pytest-asyncio>=0.23",
"ruff>=0.12.1",
@@ -123,6 +133,7 @@ no-build-isolation-package = ["flash-attn"]
environments = [
"sys_platform == 'linux' and platform_machine == 'x86_64'",
"sys_platform == 'linux' and platform_machine == 'aarch64'",
"sys_platform == 'darwin' and platform_machine == 'arm64'",
]
# Override torch's pinned cuDNN to fix Conv3d performance regression (torch 2.9 + cuDNN 9.8-9.14)
# See: https://github.com/pytorch/pytorch/issues/166122
@@ -210,9 +221,9 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
torch = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
torchvision = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
torchaudio = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
torchao = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
+4 -10
View File
@@ -53,16 +53,10 @@ if [ -n "$PRIME_RL_REF" ]; then
cp -a /app/.venv "$DEST/.venv"
fi
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
# Mirror the image's uv sync extras — explicit instead
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
# startup. --inexact keeps the seeded venv's pre-built wheels
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
# override's lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev --all-packages \
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
--extra gpt-oss \
--group mamba-ssm )
# --inexact keeps the seeded venv's pre-built wheels (flash-attn-3,
# deep-ep, mamba-ssm) in place; uv only rebuilds them if the override's
# lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev --all-packages --all-extras --group mamba-ssm )
export VIRTUAL_ENV="$DEST/.venv"
export PATH="$DEST/.venv/bin:$PATH"
cd "$DEST"
-94
View File
@@ -1,94 +0,0 @@
"""Export a verifiers v1 eval run (traces.jsonl) as an SFT dataset for `uv run sft`.
Reads a finished run's saved traces and reshapes them into the dataset shape the SFT trainer
consumes directly (see `prime_rl.trainer.sft.data`): a `messages` column (OpenAI chat wire
shape) plus a `tools` column (the tools the model was shown, from `Trace.tools`,
JSON-encoded — heterogeneous JSON-schema dicts don't fit a fixed Arrow schema). One row per
branch: a linear rollout contributes one sample, a compacted/subagent rollout one per branch
(one training sample is built per branch).
Selection: generation-errored traces (`stop_condition == "error"`) always drop — a broken
transcript is not a sample. A scoring-only error keeps the generation outcome as its stop
condition and a complete conversation, so it stays; its reward may be partial/zero, which
`--min-reward` handles.
Usage (from the prime-rl repo):
uv run python scripts/export_sft.py <run-dir> [--min-reward 1.0] [--drop-truncated]
[-o OUT_DIR] [--push HF_REPO_ID]
Writes `<run-dir>/sft/train.parquet` by default — point the trainer at it with
`--data.name <run-dir>/sft`. Requires a verifiers release carrying `Trace.tools`
(PrimeIntellect-ai/verifiers#1963).
"""
import argparse
import json
from pathlib import Path
from datasets import Dataset
from verifiers.v1 import Trace, WireTrace
from verifiers.v1.dialects.chat import message_to_wire
def sft_rows(trace: Trace) -> list[dict]:
"""A trace's SFT rows — one per branch: the branch's conversation as OpenAI chat wire
dicts plus the trace's advertised tools, JSON-encoded."""
tools = json.dumps([t.model_dump(mode="json", exclude_none=True) for t in trace.tools or []])
return [
{
"messages": [message_to_wire(m) for m in branch.messages],
"tools": tools,
}
for branch in trace.branches
if branch.messages
]
def keep(trace: Trace, min_reward: float | None, drop_truncated: bool) -> bool:
"""Whether a trace is worth training on (see module docstring for the error semantics)."""
if trace.stop_condition == "error":
return False
if drop_truncated and trace.is_truncated:
return False
return min_reward is None or trace.reward >= min_reward
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("run_dir", type=Path, help="the eval run dir (holds traces.jsonl)")
parser.add_argument("--min-reward", type=float, default=None, help="keep traces with reward >= this")
parser.add_argument("--drop-truncated", action="store_true", help="drop budget-cut traces")
parser.add_argument("-o", "--output-dir", type=Path, default=None, help="default: <run-dir>/sft")
parser.add_argument("--push", default=None, help="HF repo id to push to instead of writing parquet")
args = parser.parse_args()
traces_path = args.run_dir / "traces.jsonl"
if not traces_path.exists():
raise SystemExit(f"no traces.jsonl in {args.run_dir}")
total, rows = 0, []
with traces_path.open(encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
total += 1
trace = WireTrace.model_validate(json.loads(line))
if keep(trace, args.min_reward, args.drop_truncated):
rows.extend(sft_rows(trace))
print(f"export-sft: {total} trace(s) -> {len(rows)} row(s)")
if not rows:
raise SystemExit("export-sft: no rows to export after selection")
dataset = Dataset.from_list(rows)
if args.push:
dataset.push_to_hub(args.push)
print(f"export-sft: pushed to {args.push}")
return
out = args.output_dir or args.run_dir / "sft"
out.mkdir(parents=True, exist_ok=True)
dataset.to_parquet(str(out / "train.parquet"))
print(f"export-sft: wrote {out / 'train.parquet'} -> train with --data.name {out}")
if __name__ == "__main__":
main()
+2
View File
@@ -47,6 +47,8 @@ def _qwen3_5_moe_vlm_config():
tc.num_attention_heads = 4
tc.num_key_value_heads = 2
tc.head_dim = 64
# mrope_section must sum to rotary_dim // 2 for the shrunken head_dim
tc.rope_parameters["mrope_section"] = [3, 3, 2]
tc.moe_intermediate_size = 128
tc.shared_expert_intermediate_size = 128
tc.num_experts = 4
-148
View File
@@ -1,148 +0,0 @@
#!/bin/bash
SESSION_NAME="prime-rl"
OUTPUT_DIR="outputs"
AGENT="claude"
# Optional CLI parsing
# Supports:
# -s|--session-name NAME
# -o|--output-dir DIR
# -a|--agent AGENT (claude|codex, default: claude)
# Positional: [SESSION_NAME [OUTPUT_DIR]]
POSITIONAL=()
while [[ $# -gt 0 ]]; do
case "$1" in
-s|--session-name)
if [[ -z "$2" ]]; then
echo "Error: --session-name requires a value" >&2
exit 1
fi
SESSION_NAME="$2"
shift 2
;;
-o|--output-dir)
if [[ -z "$2" ]]; then
echo "Error: --output-dir requires a value" >&2
exit 1
fi
OUTPUT_DIR="$2"
shift 2
;;
-a|--agent)
if [[ -z "$2" ]]; then
echo "Error: --agent requires a value (claude|codex)" >&2
exit 1
fi
AGENT="$2"
shift 2
;;
-h|--help)
echo "Usage: $0 [-s SESSION_NAME] [-o OUTPUT_DIR] [-a AGENT] [SESSION_NAME [OUTPUT_DIR]]" >&2
echo " -a, --agent claude|codex (default: claude)" >&2
exit 0
;;
--)
shift
break
;;
*)
POSITIONAL+=("$1")
shift
;;
esac
done
if [[ ${#POSITIONAL[@]} -ge 1 ]]; then
SESSION_NAME="${POSITIONAL[0]}"
fi
if [[ ${#POSITIONAL[@]} -ge 2 ]]; then
OUTPUT_DIR="${POSITIONAL[1]}"
fi
LOG_DIR="${OUTPUT_DIR}/logs/latest"
if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
echo "Attaching to tmux session: $SESSION_NAME"
exec tmux attach-session -t "$SESSION_NAME"
fi
echo "Creating new tmux session: $SESSION_NAME"
# Window 0: Launcher - empty shell
tmux new-session -d -s "$SESSION_NAME" -n "Launcher"
# Window 1: Logs - 4 vertical panes
tmux new-window -t "$SESSION_NAME" -n "Logs"
tmux split-window -v -t "$SESSION_NAME:Logs.0"
tmux split-window -v -t "$SESSION_NAME:Logs.1"
tmux split-window -v -t "$SESSION_NAME:Logs.2"
tmux select-layout -t "$SESSION_NAME:Logs" even-vertical
tmux select-pane -t "$SESSION_NAME:Logs.0" -T "Trainer"
tmux select-pane -t "$SESSION_NAME:Logs.1" -T "Orchestrator"
tmux select-pane -t "$SESSION_NAME:Logs.2" -T "Envs"
tmux select-pane -t "$SESSION_NAME:Logs.3" -T "Inference"
tmux send-keys -t "$SESSION_NAME:Logs.0" \
"tail -F ${LOG_DIR}/trainer.log 2>/dev/null" C-m
tmux send-keys -t "$SESSION_NAME:Logs.1" \
"tail -F ${LOG_DIR}/orchestrator.log 2>/dev/null" C-m
tmux send-keys -t "$SESSION_NAME:Logs.2" \
"tail -F ${LOG_DIR}/envs/*/*.log 2>/dev/null" C-m
tmux send-keys -t "$SESSION_NAME:Logs.3" \
"tail -F ${LOG_DIR}/inference.log 2>/dev/null" C-m
# Window 2: SUCCESS - grep SUCCESS on orch and trainer logs (two stacked panes)
tmux new-window -t "$SESSION_NAME" -n "SUCCESS"
tmux split-window -v -t "$SESSION_NAME:SUCCESS.0"
tmux select-layout -t "$SESSION_NAME:SUCCESS" even-vertical
tmux select-pane -t "$SESSION_NAME:SUCCESS.0" -T "Orchestrator"
tmux select-pane -t "$SESSION_NAME:SUCCESS.1" -T "Trainer"
tmux send-keys -t "$SESSION_NAME:SUCCESS.0" "tail -F ${LOG_DIR}/orchestrator.log 2>/dev/null | grep --line-buffered SUCCESS" C-m
tmux send-keys -t "$SESSION_NAME:SUCCESS.1" "tail -F ${LOG_DIR}/trainer.log 2>/dev/null | grep --line-buffered SUCCESS" C-m
# Window 3: Agent (claude code or codex) with log context
tmux new-window -t "$SESSION_NAME" -n "Agent"
AGENT_PROMPT="You are monitoring a prime-rl training run. The output directory is ${OUTPUT_DIR}. Log paths:
Trainer: ${LOG_DIR}/trainer.log
All nodes: ${LOG_DIR}/trainer/node_*.log
All ranks: ${LOG_DIR}/trainer/torchrun/*/*/*/*.log
Orchestrator: ${LOG_DIR}/orchestrator.log
Inference: ${LOG_DIR}/inference.log
Envs: ${LOG_DIR}/envs/*/*.log
Train envs: ${LOG_DIR}/envs/train/*.log
You are running inside tmux session \"${SESSION_NAME}\". The Launcher window (window 0) is where the user runs launch commands. You can read its contents with: tmux capture-pane -t ${SESSION_NAME}:Launcher -p
Help the user monitor and debug this run."
case "$AGENT" in
claude)
tmux send-keys -t "$SESSION_NAME:Agent" \
"claude --permission-mode auto --append-system-prompt \"${AGENT_PROMPT}\"" C-m
;;
codex)
tmux send-keys -t "$SESSION_NAME:Agent" \
"codex --yolo \"${AGENT_PROMPT}\"" C-m
;;
*)
echo "Error: unknown agent '$AGENT' (expected claude|codex)" >&2
exit 1
;;
esac
# Pane title styling
tmux set-option -t "$SESSION_NAME" -g pane-border-status top
tmux set-option -t "$SESSION_NAME" -g pane-border-format " #{pane_title} "
# Focus launcher window and attach
tmux select-window -t "$SESSION_NAME:Launcher"
exec tmux attach-session -t "$SESSION_NAME"
+1 -1
View File
@@ -17,7 +17,7 @@ uv run rl --model @ model.toml --data @ data.toml # nes
uv run rl @ base.toml --trainer @ trainer.toml --trainer.lr 1e-3 # mixed
```
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base.
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base. `output_dir` has one extra fallback: CLI > config files > `$PRL_OUTPUT_DIR` > `"outputs"`.
Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max_model_len`).
+126
View File
@@ -0,0 +1,126 @@
---
name: dashboard
description: Find, start, use, and stop the local run dashboard for metrics, configs, traces, logs, and reports. Use when asked for its URL, to watch or inspect a run, to control the open dashboard, or to create a cited dashboard report explicitly requested by the user.
---
# Run dashboard
`uv sync --extra dashboard && uv run dashboard [output_dir ...]` (default
`outputs/`, or `$PRL_OUTPUT_DIR` if set) serves a web UI at `http://localhost:7788`. It only reads run
dirs — safe against live runs — and installs anywhere (cluster head node,
laptop against a mounted outputs dir): GPU dependencies live behind the
`gpu` extra.
Every dashboard instance serves the dirs it was started with **plus** every dir
in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`, re-read
live). Launchers (`rl`, `sft`) register their output dir on every
start and, in interactive sessions, auto-start a dashboard only when none is
live — an already-running one absorbs the new dir automatically, whatever port
it is on. `--no-dashboard` opts a run out; non-interactive launches (CI, nohup)
register their dir but never spawn.
## Isolated mode
`--isolated` serves only the given dirs: no registry read or write, no
discovery claim, and launchers ignore the instance. Use it for focused views
(demos, debugging one run dir) or to keep a scratch dir out of the registry.
## Finding the live dashboard
The live port can differ from 7788 (a taken port bumps to the next free one),
so read the discovery file:
```bash
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
curl -sf $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/runs > /dev/null && echo live
ps aux | grep PRL::Dashboard # process title
```
Hand the researcher the `url` from `daemon.json`. Launcher logs also print it:
startup ends with a `Dashboard · <url>` banner. The auto-started instance logs
to `~/.cache/prime-rl/dashboard/daemon.log`.
## Stopping / restarting
```bash
kill $(jq -r .pid ~/.cache/prime-rl/dashboard/daemon.json) # the discovered instance
pkill -f PRL::Dashboard # every dashboard on the host
```
A clean exit releases `daemon.json`; a stale file from a dead process is taken
over by the next start. Killing a dashboard never affects runs (it only reads),
and killing a run never takes the dashboard down (it runs in its own session).
Restart by launching any run, or directly: `uv run dashboard`.
## Point the open dashboard
Use `POST /api/view` to show relevant run data in every connected dashboard
tab:
```bash
curl -sS -X POST $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/view \
-H 'content-type: application/json' -d '{
"run": "demo-rl", "tab": "traces",
"step": 0, "kind": "train", "subset": "effective",
"episode": "ep-s00-reverse-text-0",
"highlight": [{"node": 3, "quote": "hint: reverse the words", "reason": "tool result the policy conditioned on"}]
}'
```
`run` is required; other fields are optional and leave unspecified UI state
unchanged. For trace evidence, supply `step`, `kind`, and `subset` together and
address the episode by stable `id`. Use optional `trace` and `branch` indices
for multi-agent traces and `highlight` entries shaped as `{node, quote,
reason, field?}`. On `409`, tell the user to open the returned `url`; the stored
command applies when the tab connects.
## Write a report only when asked
Create a report only when the user explicitly asks for one. Otherwise answer
normally; use `/api/view` when showing trace evidence would help.
Write requested reports to `<run>/reports/<slug>.md`, then POST `{"run": ...,
"tab": "report", "report": "<slug>"}`. Use Markdown with a frontmatter
`title` and one-line JSON citation definitions:
```markdown
---
title: Why does reward dip at step 4?
---
The dip is provider errors, not policy regression [^err].
[^err]: {"step": 4, "kind": "train", "subset": "all", "episode": "ep-...", "node": 0, "quote": "engine overloaded", "note": "The failed call that emptied this step's batch."}
```
The frontmatter `title` is rendered as the report H1; do not repeat it with a
Markdown `#` heading. The inline renderer supports only HTTP(S) and anchor
links. Relative Markdown links render as literal text, so identify local source
files with inline code paths or link to a supported HTTP endpoint.
Each citation requires `step`, `kind`, `subset`, `episode`, `quote`, and `note`.
Use the top-level rollout record `id` returned by the dashboard episode-list
API—not a nested `traces[*].id`, and never `line`. Copy a short, distinctive
quote exactly; matching is case-sensitive and whitespace-insensitive. Keep
`note` to 1–2 sentences explaining why the quote supports the claim.
Cite major empirical, comparative, and diagnostic conclusions, but not routine
explanation. Use exact trace citations for trajectory-level claims. For
aggregate statistics, identify the run and source file; do not imply that one
example trajectory proves the aggregate.
Use adjacent markers (`[^a] [^b]`) only when one claim genuinely depends on
distinct passages, such as a comparison or corroboration. Use one citation
when one passage is sufficient.
Optional fields are `run`, `trace`, `branch`, `node`, `field`, `prefix`, and
`suffix`. Use `field: "content"` or `"reasoning"` only to disambiguate message
parts. Use verbatim adjacent `prefix`/`suffix` only when a quote repeats.
Ambiguous or mismatched citations remain broken and do not navigate.
Use Markdown; raw HTML is escaped.
Before handoff, reload the report and verify through the dashboard API that
every referenced citation resolves uniquely to its episode, node, and quote.
Confirm zero broken citations, one rendered title, and no unsupported relative
links.
+3 -1
View File
@@ -22,13 +22,15 @@ git submodule update --init --recursive
## Sync
```bash
uv sync # core only
uv sync # slim
uv sync --group dev # + pytest, ruff, pre-commit
uv sync --all-extras # + extras (flash-attn, flash-attn-cute, …)
uv sync --all-extras --all-packages # + all env packages (needed to train on them)
uv sync --package prime-rl --package gsm8k # core + just one env
```
`uv sync --group dev` installs the `pre-commit` package but leaves the git hook inert until it's wired up — run `uv run pre-commit install` once per clone (see `README.md`'s Development section).
Environment packages are uv **workspace members**. Those under `deps/prime-envs/environments/*/*` are auto-discovered — adding a new env there needs no `pyproject.toml` change. verifiers' example envs are enumerated explicitly in `[tool.uv.workspace].members` (only the ones prime-rl trains or tests on) — to use another, add its path to the list. Members are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
+39 -21
View File
@@ -9,7 +9,7 @@ description: Monitor an ongoing prime-rl training run — find the output direct
### On launch
1. Find the run dir and read the resolved configs at `{run_dir}/configs/` (start with `rl.json`). The run dir is `{output_dir}/{run_name}` — `run.name` auto-generates as `<envs>--<model>--<short-id>`, so if you only know the output dir, pick the most recently modified subdirectory (`ls -t {output_dir} | head -1`) or read `run.name` from the launch command.
1. Find the run dir and read the resolved configs at `{run_dir}/configs/resolved/` (start with `rl.json`, or `orchestrator.json` on local runs). The launch TOML is copied verbatim to `{run_dir}/configs/rl.toml`. The run dir is `{output_dir}/{run_name}` — `run.name` auto-generates as `<envs>--<model>--<short-id>`, so if you only know the output dir, pick the most recently modified subdirectory (`ls -t {output_dir} | head -1`) or read `run.name` from the launch command.
2. Confirm all processes are alive and the run is making progress.
3. Write the initial summary into `{run_dir}/STATUS.md`.
@@ -40,14 +40,7 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
**Never restart unless the researcher explicitly asked.** Confirm the exact restart command and the conditions that warrant one.
**Never** run kill or launch commands from your own shell. Dispatch them to the tmux **Launcher** window so the researcher sees what was executed:
```bash
SESSION=$(tmux display-message -p '#S')
tmux send-keys -t "$SESSION:Launcher" 'your command here' Enter
```
After a restart, verify all processes are back up and progress resumed before the next check-in.
**Never** run kill or launch commands yourself. Hand the researcher the exact command and let them run it; after a restart, verify all processes are back up and progress resumed before the next check-in.
---
@@ -55,10 +48,33 @@ After a restart, verify all processes are back up and progress resumed before th
### Where to find things
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the run dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
- `{run_dir}/configs/` — resolved configs, written as JSON so explicit None settings round-trip (`rl.json` has the full picture).
- `{run_dir}/configs/` — the launch TOML copied verbatim (`rl.toml`/`sft.toml`), plus `resolved/` with the per-component resolved configs, written as JSON so explicit None settings round-trip.
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved episodes (see Episodes below).
- `{run_dir}/rollouts/step_{n}/{train,eval}/` — saved episodes (see Episodes below).
### Dashboard
`uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR` if set; several dirs can be tracked at
once) serves a local web dashboard at `http://localhost:7788` with four views per run:
metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved config
files, a rollout trace viewer with a per-token advantage/logprob view, and merged
component logs. It only reads the run dirs — safe to run against a live run.
`--port`/`--host` pick the bind address; a taken port automatically bumps to the next
free one, so several dashboards run side by side without coordination. GPU deps live
behind the `gpu` extra, so `uv sync --extra dashboard && uv run dashboard` works
without the training stack (e.g. on a head node).
**Daemon (auto-start)**: launchers auto-start one dashboard per host per user and a
live one absorbs each new run's output dir automatically — see the `dashboard` skill
for discovery, kill/restart commands, and `--isolated`. The short version: the live
port can differ from 7788 (a taken port bumps), so read the discovery file:
```bash
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
ps aux | grep PRL::Dashboard # the daemon's process title
```
Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`.
### Logs
@@ -66,7 +82,7 @@ After a restart, verify all processes are back up and progress resumed before th
{run_dir}/logs/latest/
├── trainer.log # rank 0 stdout
├── orchestrator.log # orchestrator stdout
├── evals.log # SFT online-eval evals stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evals.log)
├── evals.log # SFT online-eval evals stdout
├── inference.log # vLLM stdout
├── trainer/
│ ├── node_*.log # per-node (multi-node only)
@@ -77,6 +93,8 @@ After a restart, verify all processes are back up and progress resumed before th
└── envs/{train,eval}/{env_name}.log # one log file per env
```
SLURM batch logs are under `{run_dir}/launcher/logs/*job_*.log`.
Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough. Drop into per-node or per-rank logs only when debugging. All logs are loguru with `HH:mm:ss LEVEL message`; levels: `DEBUG`, `INFO`, `SUCCESS`, `WARNING`, `ERROR`.
Scan for problems:
@@ -144,8 +162,8 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
### Episodes
```
{run_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per episode as it completes
{run_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
{run_dir}/rollouts/step_{n}/{train,eval}/all/traces.jsonl # appended per episode as it completes
{run_dir}/rollouts/step_{n}/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
```
JSONL files of native `vf.Episode` records (training tensors excluded), one line per episode.
@@ -164,7 +182,7 @@ jq '.traces[].rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.ok | not) | {id, env: .env.id, errors}' {run_dir}/rollouts/step_*/train/all/traces.jsonl
```
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
### Common failure modes
@@ -180,13 +198,13 @@ A few warnings are normal. Escalate when errors are persistent, growing, or hit
All processes use `setproctitle` so they're visible in `ps`/`htop`/`pstree`:
```
PRIME-RL::Launcher
├── PRIME-RL::Inference (vLLM server, GPU 0)
├── PRIME-RL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
PRL::Launcher
├── PRL::Inference (vLLM server, GPU 0)
├── PRL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
│ └── Verifiers::EnvWorker0..N
├── PRIME-RL::Orchestrator (CPU-only; connects to each env server)
├── PRL::Orchestrator (CPU-only; connects to each env server)
├── torchrun
│ └── PRIME-RL::Trainer (GPU 1+)
│ └── PRL::Trainer (GPU 1+)
└── tail trainer.log
```
+17 -1
View File
@@ -7,6 +7,8 @@ description: How to launch prime-rl training runs — the `rl`, `sft`, `inferenc
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory.
## Run directories
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, broadcasts, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
@@ -43,6 +45,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`)
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
- SLURM: single- and multi-node
- Multi-node SLURM stops after `.trainer.done` for trainer-only fake-data runs. Runs with inference stop after both `.trainer.done` and `.orchestrator.done`.
- Environment packages: before launching a config with a non-core verifier env id,
verify the package imports under `uv run` (for example
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
@@ -66,6 +69,7 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
- Config: `SFTConfig` (`packages/prime-rl-configs/src/prime_rl/configs/sft.py`)
- Entrypoint: `src/prime_rl/entrypoints/sft.py`
- SLURM: single- and multi-node
- Multi-node online evals use one SLURM job with `num_train_nodes + num_infer_nodes` nodes. The generated `launcher/sft.sbatch` assigns inference nodes first, then trainer nodes.
## `inference` — vLLM server
@@ -119,11 +123,15 @@ env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/envs/eval/{name}.log`.
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/latest/envs/eval/{name}.log`.
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
## Exporting checkpoints
Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`). Convert to HF safetensors with `uv run python tools/convert_dcp_to_bf16.py <run_dir>/checkpoints/step_{n}` (writes `<ckpt_dir>/weights`, serveable via `uv run inference --vllm.model <dir>`; model config auto-read from the run’s `configs/resolved/trainer.json`/`sft.json`; multi-rank via `torchrun --nproc-per-node N`; full fine-tunes only, LoRA rejected). Quantize a bf16 HF dir to blockwise FP8 with `tools/convert_bf16_to_fp8.py <dir>` (vLLM-native format), or straight from a checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (rank-parallel, writes only `<ckpt_dir>/weights-FP8`, no bf16 on disk); dequantize fp8-only releases with `tools/convert_fp8_to_bf16.py <dir>`. Caveat: on SM120 GPUs (RTX PRO 6000) vLLM 0.26 picks `CutlassFp8BlockScaledMMKernel` for blockwise-fp8 checkpoints and it silently degrades outputs — serve with `VLLM_DISABLED_KERNELS=CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel` to fall back to the Triton kernel.
## Summary
| Command | Purpose | Typical use |
@@ -139,3 +147,11 @@ env.agent.runtime.type = "subprocess"
- `packages/prime-rl-configs/src/prime_rl/configs/` — all config classes
- `configs/debug/` — minimal debug configs
- `examples/` — full example configs (e.g. `reverse-text/`)
## Dashboard
Interactive launches auto-start one shared dashboard daemon per user (process title
`PRL::Dashboard`) and end startup with a `Dashboard · <url>` banner. Relay
that URL to the researcher. Discovery: `~/.cache/prime-rl/dashboard/daemon.json` holds
the live `url` (the port can differ from 7788 when it was taken). `--no-dashboard`
opts a run out.
+31
View File
@@ -0,0 +1,31 @@
# Dashboard
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
directories (metrics, resolved configs, rollout traces, cited reports,
component logs) at
http://localhost:7788. The trace viewer includes transcript and synchronized
agent timeline views; timeline activities open the corresponding transcript
call. Needs the `dashboard` extra. Every instance also serves
the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
(one dashboard per host per user); `--isolated` serves only the given dirs and
skips the registry. See `skills/dashboard/SKILL.md` for discovery,
kill/restart commands, and the local view-command/report contract.
GPU dependencies live behind the `gpu` extra, so this works anywhere — a
cluster head node, a laptop against a mounted outputs dir:
```bash
uv sync --extra dashboard && uv run dashboard [output_dir ...]
```
The trace viewer's **Messages** mode keeps structured `message.content` and
`trace.tools` visibly separate. **Rendered** decodes each selected branch's
recorded post-renderer `token_ids` as one sequence, retaining special tokens;
it never reconstructs a chat template. The recorded IDs remain the source of
truth, and the viewer reports when IDs, the renderer model, or its tokenizer
are unavailable. Text, advantage, logprob, mask, and content signals apply to
both views; Rendered with Text uses the exact full-sequence decode.
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
The integration suite covers it end to end (`tests/integration/dashboard_smoke.py`
runs after every integration test).
View File
+1590
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 7.4 KiB

+242
View File
@@ -0,0 +1,242 @@
<!-- This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests. -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>prime-rl dashboard</title>
<link rel="icon" href="/static/butterfly-white.svg">
<link rel="stylesheet" href="/static/vendor/uPlot.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<header id="topbar">
<div class="brand">
<img src="/static/butterfly-white.svg" alt="Prime Intellect">
</div>
<select id="run-select" title="run"></select>
<div id="compare-wrap" class="dd-wrap">
<button id="compare-btn" class="btn dd-btn">compare</button>
<div id="compare-menu" class="dd-menu" hidden></div>
</div>
<nav id="tabs">
<button data-tab="config">Config</button>
<button data-tab="metrics" class="active">Metrics</button>
<button data-tab="traces">Traces</button>
<button data-tab="report">Report</button>
<button data-tab="logs">Logs</button>
</nav>
<label class="toggle" title="apply agent view commands as they arrive"><input type="checkbox" id="follow-toggle" checked><span class="dot"></span>follow</label>
<label class="toggle" title="poll for updates"><input type="checkbox" id="live-toggle" checked><span class="dot"></span>live</label>
</header>
<div id="run-overview"></div>
<main>
<section id="tab-metrics">
<div class="controls">
<div class="seg" id="metrics-mode">
<button data-mode="overview" class="active">Overview</button>
<button data-mode="all">All</button>
</div>
<input id="metrics-search" class="search" type="search" placeholder="regex filter, e.g. ^entropy/ or reward">
<label class="ctl">smooth <input id="smooth-range" type="range" min="1" max="50" value="1"><span id="smooth-val">off</span></label>
<span id="metrics-status" class="muted"></span>
<div class="spacer"></div>
<div class="seg" id="all-layout" hidden>
<button data-layout="flat">Flat</button>
<button data-layout="nested">Nested</button>
</div>
<button id="metrics-collapse" class="btn">collapse</button>
<button id="metrics-expand" class="btn">expand</button>
</div>
<div id="metrics-body"></div>
</section>
<section id="tab-config" hidden>
<div class="controls">
<div class="seg" id="config-format">
<button data-fmt="toml">TOML</button>
<button data-fmt="json">JSON</button>
</div>
<input id="config-search" class="search" type="search" placeholder="regex search, e.g. lora|lr">
<span id="config-hits" class="muted"></span>
</div>
<pre id="config-view"></pre>
</section>
<section id="tab-traces" hidden>
<div class="controls" id="step-bar">
<button id="step-prev" class="btn tm-nav" title="previous step">‹</button>
<div id="step-blocks"></div>
<button id="step-next" class="btn tm-nav" title="next step">›</button>
<span id="step-label" class="t-label"></span>
</div>
<div class="controls">
<div id="trace-filter-wrap" class="dd-wrap">
<button id="trace-filter-btn" class="btn dd-btn" title="filter &amp; sort">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
</button>
<div id="trace-filter-menu" class="dd-menu" hidden>
<label class="t-label">env</label>
<select id="trace-env"><option value="">all envs</option></select>
<label class="t-label">sort</label>
<select id="trace-sort">
<option value="line:asc">order: arrival</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="advantage:desc">advantage ↓</option>
<option value="advantage:asc">advantage ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
<option value="group:asc">group</option>
</select>
<label class="toggle"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<div class="seg" id="trace-kind">
<button data-kind="train" class="active">Train</button>
<button data-kind="eval">Eval</button>
</div>
<div class="seg" id="trace-subset">
<button data-subset="all">All</button>
<button data-subset="effective" class="active">Effective</button>
</div>
<span id="trace-status" class="muted"></span>
</div>
<div id="episode-table-wrap">
<table id="episode-table">
<thead><tr>
<th>#</th><th>env</th><th>group</th><th>reward</th><th>adv</th>
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>status</th>
</tr></thead>
<tbody></tbody>
</table>
</div>
</section>
<section id="tab-report" hidden>
<div class="controls">
<label class="t-label">report</label>
<select id="report-select"></select>
<span id="report-verify" class="muted"></span>
<div class="spacer"></div>
<span id="report-status" class="muted"></span>
</div>
<div id="report-wrap"><article id="report-body"></article></div>
</section>
<section id="tab-logs" hidden>
<div class="controls">
<label class="t-label">attempt</label>
<select id="attempt-select"></select>
<div id="log-comp-wrap" class="dd-wrap">
<button id="log-comp-btn" class="btn dd-btn">components</button>
<div id="log-comp-menu" class="dd-menu" hidden></div>
</div>
<div class="seg" id="log-view">
<button data-view="merge" class="active">Merge</button>
<button data-view="split">Split</button>
</div>
<div class="stepper" id="log-level" title="minimum log level">
<button id="log-level-down" title="more verbose">‹</button>
<span id="log-level-label">all</span>
<button id="log-level-up" title="less verbose">›</button>
</div>
<input id="log-search" class="search" type="search" placeholder="regex filter, e.g. ERROR|WARN">
<button id="log-older" class="btn">load older</button>
</div>
<div id="log-panes"></div>
</section>
</main>
<div id="drawer-backdrop" hidden></div>
<div id="trace-modal" hidden>
<aside id="tm-left">
<div class="tm-head tm-stephead">
<button id="tm-step-prev" class="btn tm-nav" title="previous step">‹</button>
<span id="tm-step-label"></span>
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
</div>
<div class="tm-head tm-ctlrow">
<div id="tm-filter-wrap" class="dd-wrap">
<button id="tm-filter-btn" class="btn dd-btn" title="filter &amp; sort">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
</button>
<div id="tm-filter-menu" class="dd-menu" hidden>
<label class="t-label">env</label>
<select id="tm-env"><option value="">all envs</option></select>
<label class="t-label">sort</label>
<select id="tm-sort">
<option value="line:asc">order: arrival</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="advantage:desc">advantage ↓</option>
<option value="advantage:asc">advantage ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
<option value="group:asc">group</option>
</select>
<label class="toggle"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
</div>
</div>
</div>
<div class="tm-head tm-ctlrow" id="tm-kind-row">
<div class="seg" id="tm-kind">
<button data-kind="train">Train</button>
<button data-kind="eval">Eval</button>
</div>
</div>
<div class="tm-head tm-ctlrow" id="tm-subset-row">
<div class="seg" id="tm-subset">
<button data-subset="all">All</button>
<button data-subset="effective">Effective</button>
</div>
</div>
<div class="tm-head">
<span class="t-label">episodes</span>
<span id="tm-count" class="badge"></span>
</div>
<div id="tm-list"></div>
</aside>
<section id="tm-main">
<div class="tm-head">
<span class="tm-title">Trace Viewer</span>
<button id="tm-back" class="btn" hidden title="back to the report">← report</button>
<div class="seg" id="tm-view">
<button data-view="transcript" class="active">Transcript</button>
<button data-view="timeline">Timeline</button>
</div>
<div class="spacer"></div>
<div class="seg" id="trace-view-mode">
<button data-mode="messages" class="active">Messages</button>
<button data-mode="rendered">Rendered</button>
</div>
<select id="token-signal" title="Choose the token signal for either view. Text is uncolored; other options color recorded tokens by advantage, log probability, training mask, or message-content membership.">
<option value="">Text</option>
<option value="advantage">Advantage</option>
<option value="logprob">Logprob</option>
<option value="mask">Mask</option>
<option value="is_content">Content</option>
</select>
<button id="tm-collapse" class="btn">collapse</button>
<button id="tm-expand" class="btn">expand</button>
<button id="drawer-close" class="btn">✕</button>
</div>
<div class="tm-head tm-tabs-row" id="tm-tabs-row" hidden>
<div id="tm-trace-tabs" class="seg" hidden></div>
<div id="tm-branch-tabs" class="seg" hidden></div>
</div>
<div id="tm-messages"></div>
<div id="tm-timeline" hidden></div>
</section>
<aside id="tm-right">
<div class="tm-head"><span class="tm-title">Overview</span></div>
<div id="tm-meta"></div>
</aside>
</div>
<script src="/static/vendor/uPlot.iife.min.js"></script>
<script src="/static/app.js"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
.uplot, .uplot *, .uplot *::before, .uplot *::after {box-sizing: border-box;}.uplot {font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";line-height: 1.5;width: min-content;}.u-title {text-align: center;font-size: 18px;font-weight: bold;}.u-wrap {position: relative;user-select: none;}.u-over, .u-under {position: absolute;}.u-under {overflow: hidden;}.uplot canvas {display: block;position: relative;width: 100%;height: 100%;}.u-axis {position: absolute;}.u-legend {font-size: 14px;margin: auto;text-align: center;}.u-inline {display: block;}.u-inline * {display: inline-block;}.u-inline tr {margin-right: 16px;}.u-legend th {font-weight: 600;}.u-legend th > * {vertical-align: middle;display: inline-block;}.u-legend .u-marker {width: 1em;height: 1em;margin-right: 4px;background-clip: padding-box !important;}.u-inline.u-live th::after {content: ":";vertical-align: middle;}.u-inline:not(.u-live) .u-value {display: none;}.u-series > * {padding: 4px;}.u-series th {cursor: pointer;}.u-legend .u-off > * {opacity: 0.3;}.u-select {background: rgba(0,0,0,0.07);position: absolute;pointer-events: none;}.u-cursor-x, .u-cursor-y {position: absolute;left: 0;top: 0;pointer-events: none;will-change: transform;}.u-hz .u-cursor-x, .u-vt .u-cursor-y {height: 100%;border-right: 1px dashed #607D8B;}.u-hz .u-cursor-y, .u-vt .u-cursor-x {width: 100%;border-bottom: 1px dashed #607D8B;}.u-cursor-pt {position: absolute;top: 0;left: 0;border-radius: 50%;border: 0 solid;pointer-events: none;will-change: transform;/*this has to be !important since we set inline "background" shorthand */background-clip: padding-box !important;}.u-axis.u-off, .u-select.u-off, .u-cursor-x.u-off, .u-cursor-y.u-off, .u-cursor-pt.u-off {display: none;}
+127
View File
@@ -0,0 +1,127 @@
"""Launcher-side dashboard auto-start.
Every launcher registers its output dir in a shared registry and makes sure one
dashboard is running: every dashboard instance serves its own dirs plus the
registry (re-read live), so each new run shows up on one URL - one dashboard
per host per user. If a live daemon already exists, its URL is reused instead
of starting another. Discovery goes through
``~/.cache/prime-rl/dashboard/daemon.json`` (pid + actual url), which survives
port spillover. The daemon also carries the process title ``PRL::Dashboard``.
Kept free of ``dashboard``-extra imports on purpose: the launcher must work
without the extra (then it registers the dir and points at the missing extra
instead of spawning). ``main`` is the ``dashboard`` console script, delegating
to the actual server.
"""
import fcntl
import importlib.util
import json
import os
import shutil
import subprocess
import sys
import time
import urllib.request
from contextlib import contextmanager
from pathlib import Path
from prime_rl.utils.pathing import CACHE_DIR
STATE_DIR = CACHE_DIR / "dashboard"
DAEMON_FILE = STATE_DIR / "daemon.json"
DIRS_FILE = STATE_DIR / "dirs.json"
DAEMON_LOG = STATE_DIR / "daemon.log"
SPAWN_TIMEOUT_S = 10.0
@contextmanager
def registry_lock():
"""Serialize read-modify-write cycles on the shared registry files: concurrent
launchers (or dashboard starts) must not drop each other's entries."""
STATE_DIR.mkdir(parents=True, exist_ok=True)
with open(STATE_DIR / ".lock", "w") as lock_file:
fcntl.flock(lock_file, fcntl.LOCK_EX)
yield
def register_output_dir(output_dir: Path) -> None:
"""Add the dir to the daemon's registry (idempotent, atomic)."""
with registry_lock():
try:
dirs = json.loads(DIRS_FILE.read_text())
except (OSError, ValueError):
dirs = []
entry = str(output_dir.resolve())
if entry in dirs:
return
dirs.append(entry)
tmp = DIRS_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(dirs))
tmp.replace(DIRS_FILE)
def find_daemon(timeout: float = 1.0) -> dict | None:
"""The live daemon's record ({pid, url, ...}), or None."""
try:
info = json.loads(DAEMON_FILE.read_text())
os.kill(info["pid"], 0)
except (OSError, ValueError, KeyError, TypeError):
return None
try:
with urllib.request.urlopen(f"{info['url']}/api/runs", timeout=timeout):
return info
except OSError:
return None
def ensure_dashboard(output_dir: Path, logger) -> str | None:
"""Register the run's output dir and make sure one dashboard daemon serves it.
Returns the dashboard URL (log it with ``log_dashboard_url``), or None when no
daemon could be found or started (missing extra, non-interactive session, or
startup failure).
"""
# The dir may not exist yet on a first run: create it up front, because the
# daemon only serves registered dirs that exist (and refuses to start with none).
output_dir.mkdir(parents=True, exist_ok=True)
register_output_dir(output_dir)
daemon = find_daemon()
if daemon is not None:
return daemon["url"]
if not sys.stdout.isatty():
logger.warning("Non-interactive session - not auto-starting a dashboard (the output dir stays registered)")
return None
# The console script exists even without the extra, so check the actual imports.
if importlib.util.find_spec("fastapi") is None or importlib.util.find_spec("uvicorn") is None:
logger.warning("Dashboard extra not installed - install with `uv sync --extra dashboard`")
return None
binary = shutil.which("dashboard")
if binary is None:
logger.warning("Dashboard entry point not found - install with `uv sync --extra dashboard`")
return None
with open(DAEMON_LOG, "ab") as log_file:
process = subprocess.Popen([binary], stdout=log_file, stderr=log_file, start_new_session=True)
deadline = time.monotonic() + SPAWN_TIMEOUT_S
while time.monotonic() < deadline:
daemon = find_daemon()
if daemon is not None:
return daemon["url"]
if process.poll() is not None:
break
time.sleep(0.25)
logger.warning(f"Dashboard daemon did not come up - see {DAEMON_LOG}")
return None
def log_dashboard_url(logger, url: str | None) -> None:
"""Banner pointing at the dashboard - meant as the launcher's last startup log."""
if url is None:
return
logger.opt(raw=True, colors=True).info(f"\n <b>Dashboard</b> · <green><u>{url}</u></green>\n\n")
def main() -> None:
from prime_rl.dashboard.server import main as server_main
server_main()
+3
View File
@@ -15,6 +15,9 @@ from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Evals")
config = cli(EvalsConfig)
from prime_rl.utils.pathing import write_launch_toml
write_launch_toml(config.output_dir, "evals")
from prime_rl.evals.evals import run_evals
asyncio.run(run_evals(config))
+10 -2
View File
@@ -10,7 +10,13 @@ from typing import Any
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_config_dir, latest_log_dir
from prime_rl.utils.pathing import (
format_log_message,
get_config_dir,
get_launcher_dir,
get_launcher_log_dir,
latest_log_dir,
)
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
@@ -71,6 +77,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.output_dir,
launcher_log_dir=get_launcher_log_dir(config.output_dir),
gpus_per_node=config.deployment.gpus_per_node,
dp_per_node=dp_per_node,
num_nodes=getattr(config.deployment, "num_nodes", 1),
@@ -116,6 +123,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
script = template.render(**template_vars)
script_path.parent.mkdir(parents=True, exist_ok=True)
get_launcher_log_dir(config.output_dir).mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
@@ -131,7 +139,7 @@ def inference_slurm(config: InferenceConfig):
config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node)
logger.info(f"Wrote config to {config_path}")
script_path = config.output_dir / INFERENCE_SBATCH
script_path = get_launcher_dir(config.output_dir) / INFERENCE_SBATCH
write_slurm_script(config, config_path, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
+24 -11
View File
@@ -14,6 +14,7 @@ from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
from prime_rl.entrypoints.inference import vllm_overrides_fragment
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import get_logger, setup_logger
@@ -23,9 +24,12 @@ from prime_rl.utils.pathing import (
format_log_message,
get_ckpt_dir,
get_config_dir,
get_launcher_dir,
get_launcher_log_dir,
latest_log_dir,
resolve_latest_ckpt_step,
validate_run_dir,
write_launch_toml,
)
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
@@ -120,6 +124,7 @@ def rl_local(config: RLConfig):
)
config_dir = get_config_dir(config.run_dir)
write_launch_toml(config.run_dir, "rl")
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
@@ -127,6 +132,8 @@ def rl_local(config: RLConfig):
logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs from deployment config
gpu_offset = 0
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
@@ -365,17 +372,12 @@ def rl_local(config: RLConfig):
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Monitor all processes for failures
logger.success("Startup complete. Showing orchestrator logs...")
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
tail_process = Popen(
f"tail -F '{log_dir / 'orchestrator.log'}'",
shell=True,
)
processes.append(tail_process)
# Check for errors from monitor threads
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
# Trainer and orchestrator completion is the successful stop condition.
completion_events = (stop_events["trainer"], stop_events["orchestrator"])
while not all(event.is_set() for event in completion_events):
if error_queue:
error = error_queue[0]
logger.error(f"Error: {error}")
@@ -462,6 +464,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
**config.slurm.template_vars,
config_path=config_dir / RL_CONFIG,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
gpus_per_node=config.deployment.gpus_per_node,
)
elif config.inference is not None and config.inference.deployment.type == "disaggregated":
@@ -473,6 +477,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
run_name=config.run.name,
config_dir=config_dir,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
nodes_per_infer_replica=infer_deploy.num_nodes,
@@ -514,6 +520,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
run_name=config.run.name,
config_dir=config_dir, # TODO: should prob have each subconfig path separately
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.total_infer_nodes,
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
@@ -546,6 +554,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
)
script_path.parent.mkdir(parents=True, exist_ok=True)
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
@@ -557,6 +566,7 @@ def rl_slurm(config: RLConfig):
)
config_dir = get_config_dir(config.run_dir)
write_launch_toml(config.run_dir, "rl")
log_dir = latest_log_dir(config.run_dir)
if config.deployment.type == "single_node":
@@ -593,7 +603,7 @@ def rl_slurm(config: RLConfig):
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
)
script_path = config.run_dir / RL_SBATCH
script_path = get_launcher_dir(config.run_dir) / RL_SBATCH
write_slurm_script(config, config_dir, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
@@ -601,6 +611,8 @@ def rl_slurm(config: RLConfig):
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
@@ -608,6 +620,7 @@ def rl_slurm(config: RLConfig):
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
log_dashboard_url(logger, dashboard_url)
def rl(config: RLConfig):
+76 -134
View File
@@ -12,6 +12,7 @@ from prime_rl.configs.evals import EvalsConfig, OnlineConfig
from prime_rl.configs.orchestrator import EvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.shared import LogConfig
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
from prime_rl.utils.config import cli, dump_resolved_config, find_package_resource
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import (
@@ -21,10 +22,12 @@ from prime_rl.utils.pathing import (
get_broadcast_dir,
get_ckpt_dir,
get_config_dir,
get_log_dir,
get_launcher_dir,
get_launcher_log_dir,
latest_log_dir,
resolve_latest_ckpt_step,
validate_run_dir,
write_launch_toml,
)
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
@@ -39,8 +42,6 @@ from prime_rl.utils.process import (
SFT_CONFIG = "sft.json"
SFT_SBATCH = "sft.sbatch"
EVAL_SBATCH = "eval.sbatch"
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
INFERENCE_CONFIG = "inference.json"
EVALS_CONFIG = "evals.json"
@@ -147,7 +148,11 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
assert config.slurm is not None
assert config.slurm.template_path is not None
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
template_dirs = [config.slurm.template_path.parent]
bundled_templates = find_package_resource("templates")
if bundled_templates is not None:
template_dirs.append(bundled_templates)
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
template = env.get_template(config.slurm.template_path.name)
trainer_env_vars = {
@@ -161,189 +166,126 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
gpus_per_node=config.deployment.gpus_per_node,
)
else:
online_eval = config.eval is not None
eval_vars = {}
if online_eval:
assert config.inference is not None
inference_env_vars = {
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
}
eval_vars = {
"router": config.inference.router,
"router_port": config.inference.server.port,
"backend_port": config.inference.backend_port,
"data_parallel_rpc_port": config.inference.vllm.data_parallel_rpc_port,
"dp_per_node": config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
"enable_expert_parallel": config.inference.vllm.enable_expert_parallel,
"inference_env_vars": inference_env_vars,
"evals_env_vars": {
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
},
"eval_env_names": [source.resolved_name for source, _ in eval_env_servers(config)],
}
script = template.render(
**config.slurm.template_vars,
config_path=config_path,
config_dir=get_config_dir(config.run_dir),
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
trainer_env_vars=trainer_env_vars,
num_nodes=config.deployment.num_train_nodes,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
gpus_per_node=config.deployment.gpus_per_node,
ranks_filter=",".join(map(str, config.log.ranks_filter)),
prl_run_id=prl_run_id,
run_name=config.run.name,
online_eval=online_eval,
use_nccl_broadcast=(
config.eval is not None
and config.weight_broadcast is not None
and config.weight_broadcast.type == "nccl"
),
**eval_vars,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Path, prl_run_id: str | None) -> None:
"""Write the SLURM script for the decoupled online-eval job (inference pool +
env servers + evals) to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
assert config.slurm.template_path is not None
assert config.deployment.type == "multi_node"
assert config.inference is not None
# The eval template is bundled next to the trainer templates; a custom
# slurm.template_path directory takes precedence so both can be overridden.
template_dirs = [config.slurm.template_path.parent]
bundled_templates = find_package_resource("templates")
if bundled_templates is not None:
template_dirs.append(bundled_templates)
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
template = env.get_template(EVAL_TEMPLATE)
inference_env_vars = {
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
}
evals_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
script = template.render(
**config.slurm.template_vars,
config_dir=config_dir,
output_dir=config.run_dir,
num_infer_nodes=config.deployment.num_infer_nodes,
gpus_per_node=config.deployment.gpus_per_node,
router=config.inference.router,
router_port=config.inference.server.port,
backend_port=config.inference.backend_port,
data_parallel_rpc_port=config.inference.vllm.data_parallel_rpc_port,
dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
enable_expert_parallel=config.inference.vllm.enable_expert_parallel,
inference_env_vars=inference_env_vars,
evals_env_vars=evals_env_vars,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
prl_run_id=prl_run_id,
run_name=config.run.name,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
)
script_path.parent.mkdir(parents=True, exist_ok=True)
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
def sft_slurm(config: SFTConfig):
"""Run SFT training via SLURM. With online evals on a multi-node deployment, the
trainer and the eval deployment (inference pool + evals) are two independent
SLURM jobs. The trainer publishes its rank-0 hostname through the shared run
directory so the eval deployment can join its NCCL weight-broadcast group."""
"""Run SFT training and its online-eval deployment in one SLURM allocation."""
assert config.slurm is not None
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
decoupled_eval = config.deployment.type == "multi_node" and config.eval is not None
online_eval = config.deployment.type == "multi_node" and config.eval is not None
config_dir = get_config_dir(config.run_dir)
write_launch_toml(config.run_dir, "sft")
config_path = config_dir / SFT_CONFIG
exclude = (
{"deployment", "slurm", "dry_run", "clean"}
if config.deployment.type == "multi_node"
else {"slurm", "dry_run", "clean"}
)
if decoupled_eval:
if online_eval:
# The trainer job only needs [eval] for the weight-broadcast cadence; the
# inference pool lives in the eval job.
# inference pool runs on its dedicated nodes in the same allocation.
exclude = exclude | {"inference"}
write_config(config, config_path, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
# Trainer and evals processes log to a single shared W&B run across both jobs,
# keyed by the launcher's run id.
# Trainer and evals processes log to a single shared W&B run.
prl_run_id: str | None = None
if decoupled_eval and config.monitors.wandb is not None:
if online_eval and config.monitors.wandb is not None:
prl_run_id = os.environ["PRL_RUN_ID"]
script_path = config.run_dir / SFT_SBATCH
write_slurm_script(config, config_path, script_path, prl_run_id)
logger.info(f"Wrote SLURM script to {script_path}")
# The trainer job is submitted first and the eval job depends on it having started:
# the trainer creates the shared W&B run, and the evals process's joiner init only
# retries for a bounded window — starting the evals process while the trainer job pends
# would crash it at wandb init.
script_paths = [script_path]
if decoupled_eval:
launcher_dir = get_launcher_dir(config.run_dir)
if online_eval:
write_eval_subconfigs(config, config_dir, strip_router=True)
logger.info(f"Wrote eval subconfigs to {config_dir}")
eval_script_path = config.run_dir / EVAL_SBATCH
write_eval_slurm_script(config, config_dir, eval_script_path, prl_run_id)
logger.info(f"Wrote eval SLURM script to {eval_script_path}")
script_paths = [script_path, eval_script_path]
script_path = launcher_dir / SFT_SBATCH
write_slurm_script(config, config_path, script_path, prl_run_id)
logger.info(f"Wrote SLURM script to {script_path}")
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
log_message = format_log_message(
log_dir=latest_log_dir(config.run_dir),
trainer=True,
num_train_nodes=num_nodes,
evals=online_eval,
inference=online_eval,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)] if online_eval else None,
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
)
if decoupled_eval:
# The eval job logs at stable (non-attempt) paths under the run dir.
log_message += "\n" + format_log_message(
log_dir=get_log_dir(config.run_dir),
evals=True,
inference=True,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
num_infer_nodes=config.deployment.num_infer_nodes,
).removeprefix("Logs:\n")
if config.dry_run:
if decoupled_eval:
trainer_submit = f" TRAIN_JOB_ID=$(sbatch --parsable {script_paths[0]} | cut -d';' -f1)"
eval_submit = f" sbatch --dependency=after:$TRAIN_JOB_ID {script_paths[1]}"
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
eval_submit = (
" sbatch --dependency=after:$TRAIN_JOB_ID "
f"--export=ALL,TRAIN_JOB_ID=$TRAIN_JOB_ID {script_paths[1]}"
)
submit = "\n".join((trainer_submit, eval_submit))
else:
submit = f" sbatch {script_paths[0]}"
note = (
"\n\nSubmit the trainer job first. The eval job starts after the trainer allocation is ready."
if decoupled_eval
else ""
)
logger.success(f"Dry run complete. To submit manually:\n\n{submit}{note}\n\n{log_message}")
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
submitted_job_ids: list[str] = []
for path in script_paths:
# --parsable prints ``<job_id>[;<cluster>]`` — the human-readable format varies
# (e.g. multi-cluster sbatch appends "on cluster <name>").
cmd = ["sbatch", "--parsable"]
if submitted_job_ids:
# Hold the eval job until the trainer job has started (not finished).
cmd.append(f"--dependency=after:{submitted_job_ids[-1]}")
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
cmd.append(f"--export=ALL,TRAIN_JOB_ID={submitted_job_ids[-1]}")
cmd.append(str(path))
logger.info(f"Submitting: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
for job_id in submitted_job_ids:
logger.warning(f"Cancelling already-submitted job {job_id}")
subprocess.run(["scancel", job_id], capture_output=True, text=True)
sys.exit(1)
job_id = result.stdout.strip().split(";")[0]
submitted_job_ids.append(job_id)
logger.success(f"Submitted batch job {job_id}")
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
logger.success(log_message)
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
log_dashboard_url(logger, dashboard_url)
def sft_local(config: SFTConfig):
@@ -353,6 +295,7 @@ def sft_local(config: SFTConfig):
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = get_config_dir(config.run_dir)
write_launch_toml(config.run_dir, "sft")
config_path = config_dir / SFT_CONFIG
write_config(config, config_path)
logger.info(f"Wrote config to {config_path}")
@@ -365,6 +308,8 @@ def sft_local(config: SFTConfig):
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
log_dir = create_attempt_log_dir(config.run_dir)
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
@@ -464,6 +409,7 @@ def sft_local(config: SFTConfig):
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
"PRL_LOG_DIR": str(log_dir),
**wandb_shared_env,
"WANDB_SHARED_LABEL": "evals",
},
@@ -503,12 +449,8 @@ def sft_local(config: SFTConfig):
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(
f"tail -F '{log_dir / 'trainer.log'}' | sed -u 's/^\\[[a-zA-Z]*[0-9]*\\]://'",
shell=True,
)
processes.append(tail_process)
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Wait for the trainer (and the evals process, which drains its final evals after
# the trainer's last checkpoint) while surfacing any process failure.
+129 -118
View File
@@ -2,11 +2,13 @@
Standalone (no ``[online]``), it runs one epoch of every configured eval
source against the weights the inference server currently serves, then exits.
With ``[online]``, it watches a broadcasts directory for new weight
broadcasts — the trainer writes ``broadcasts/step_{n}`` with a ``STABLE``
marker on completion — tells the inference server to receive each eligible
broadcast, and runs the configured evals against the updated weights,
sequentially per broadcast so every epoch measures exactly one policy version.
With ``[online]``, it watches a broadcasts directory for offered weight
broadcasts through a ``WeightReceiver`` (announced by their
``.sender_ready`` marker), moves the inference server onto each of them, and
runs the configured evals against the updated weights, sequentially per
broadcast so every epoch measures exactly one policy version. Every offered
broadcast must be received, even when no eval is due — the trainer blocks
inside the handshake until the receiver acknowledges.
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
@@ -26,27 +28,31 @@ import json
import os
import time
import uuid
from pathlib import Path
from subprocess import Popen
from prime_rl import monitors
from prime_rl.configs.evals import EvalsConfig
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.metrics import dispatch_failure_metrics
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.types import EvalBatch, Policy
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
from prime_rl.utils.client import InferencePool, init_nccl_broadcast
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.config import dump_resolved_config
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir, get_step_path
from prime_rl.utils.pathing import create_attempt_log_dir, get_all_ckpt_steps, get_config_dir
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
from prime_rl.utils.utils import clean_exit
@@ -56,15 +62,19 @@ monkey_patch_chat_completion_logprobs()
# How often to re-scan the broadcasts directory for new weight broadcasts.
POLL_INTERVAL_S = 2.0
# Served model name for adapter broadcasts of LoRA runs. Reloading the same name
# with fresh weights each step is supported (the server forces an in-place
# reload, see /load_lora_adapter).
LORA_NAME = "eval-adapter"
# Budget for the trainer's startup broadcast: it is always coming, but only
# after the trainer has finished loading the model.
STARTUP_BROADCAST_TIMEOUT_S = 1200
class Evals:
def __init__(self, config: EvalsConfig) -> None:
def __init__(self, config: EvalsConfig, log_dir: Path | None = None) -> None:
self.config = config
self.log_dir = log_dir or (
Path(os.environ["PRL_LOG_DIR"])
if "PRL_LOG_DIR" in os.environ
else create_attempt_log_dir(config.output_dir)
)
setup_logger(config.log.level, json_logging=config.log.json_logging)
intercept_vf_logging(logger="verifiers.v1", level="WARN")
mode = f"online (broadcasts_dir={config.online.broadcasts_dir})" if config.online is not None else "standalone"
@@ -76,12 +86,21 @@ class Evals:
self.env_server_procs: list[Popen] = []
self.dispatcher_task: asyncio.Task | None = None
# Assigned in setup(); None-initialized so stop() can tear down a
# partially completed setup with plain attribute checks.
self.clients: InferenceClient | None = None
self.admin_clients: AdminClients | None = None
self.dispatcher: Dispatcher | None = None
self.inference_metrics: InferenceMetricsCollector | None = None
self.periodic_logger: PeriodicLogger | None = None
async def setup(self) -> None:
config = self.config
set_default_executor()
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
producer="evals",
wandb=config.monitors.wandb,
file=config.monitors.file,
output_dir=config.output_dir,
@@ -95,7 +114,8 @@ class Evals:
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
self.pool = InferencePool(config.eval.client, model_name=config.model)
self.clients = InferenceClient(config.eval.client, model_name=config.model)
self.admin_clients = AdminClients(config.eval.client)
self.spawn_env_servers()
@@ -105,20 +125,23 @@ class Evals:
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
get_logger().info("Waiting for inference pool to be ready")
await self.pool.wait_for_ready(config.model)
await self.admin_clients.wait_for_ready(config.model)
get_logger().success("Inference pool ready")
weight_broadcast = config.weight_broadcast
if weight_broadcast is not None and weight_broadcast.type == "nccl":
self.receiver: WeightReceiver | None = None
if config.online is not None:
assert config.online.broadcasts_dir is not None
# A hand-written online config may omit the transport; broadcasts
# are then plain filesystem checkpoints.
weight_broadcast = config.weight_broadcast or FileSystemWeightBroadcastConfig()
get_logger().info(f"Initializing weight broadcast ({weight_broadcast})")
await init_nccl_broadcast(
self.pool.admin_clients,
weight_broadcast.host,
weight_broadcast.port,
weight_broadcast.timeout,
inference_world_size=weight_broadcast.inference_world_size,
quantize_in_weight_transfer=weight_broadcast.quantize_in_weight_transfer,
self.receiver = setup_weight_receiver(
config.online.broadcasts_dir,
weight_broadcast,
admin_clients=self.admin_clients.clients,
model_name=config.model,
)
await self.receiver.initialize()
is_resumed = config.online is not None and config.online.resume_step is not None
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=is_resumed)
@@ -134,7 +157,7 @@ class Evals:
eval_envs=self.eval_envs,
train_source=None,
eval_source=self.eval_source,
policy_pool=self.pool,
policy_clients=self.clients,
policy=self.policy,
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
@@ -152,11 +175,10 @@ class Evals:
get_inflight=lambda: self.dispatcher.current_inflight,
)
# The collector always polls — it feeds the concurrency controller;
# W&B mirroring is gated on the registered monitor.
# metrics fan out to every registered monitor.
self.inference_metrics = InferenceMetricsCollector(
self.pool.admin_clients,
self.admin_clients.clients,
on_load=self.concurrency.observe,
log_to_wandb=wandb_enabled,
)
# Fail fast when adaptivity has no signal: external API endpoints
# (e.g. Prime Inference) expose no vLLM /metrics, so without a probe
@@ -166,7 +188,7 @@ class Evals:
if not await self.inference_metrics.probe():
concurrency = config.eval.concurrency
if concurrency.min_inflight != concurrency.max_inflight:
urls = ", ".join(str(client.base_url) for client in self.pool.admin_clients)
urls = ", ".join(str(client.base_url) for client in self.admin_clients.clients)
raise ValueError(
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
@@ -193,7 +215,7 @@ class Evals:
config = self.config
addresses = config.eval.env_addresses
config_dir = get_config_dir(config.output_dir) / "envs" / "eval"
log_dir = get_log_dir(config.output_dir) / "envs" / "eval"
log_dir = self.log_dir / "envs" / "eval"
for source in config.eval.source:
if source.serve.address is not None:
continue
@@ -242,65 +264,55 @@ class Evals:
assert config.online is not None
online = config.online
# Rendezvous with the trainer's startup broadcast (v0 fresh, the
# checkpoint step on resume) — always, for every transport: an
# in-memory trainer blocks inside its startup broadcast until this
# receive, and for filesystem it guarantees the served weights match
# the trainer's incoming policy.
assert self.receiver is not None
startup_step = online.resume_step or 0
await self.receiver.sync_startup(startup_step, timeout=STARTUP_BROADCAST_TIMEOUT_S)
self.policy.version = startup_step
if online.resume_step is None:
# Base-model eval: the inference server starts with the untrained weights,
# so no reload is needed. The first trigger fires every env (policy v0)
# unless ``skip_first_step``.
# The first trigger fires every env (policy v0) unless ``skip_first_step``.
await self.maybe_run_evals(step=0)
elif config.eval.retrigger_on_resume:
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
# evals). The trainer rebroadcasts the resumed policy on startup, but only
# after loading the model — wait for that broadcast instead of checking
# once. A newer stable broadcast means the resume step's was already
# cleaned away (only the newest is kept) and can never reappear. The
# evals); the startup rendezvous above already loaded its weights. The
# final broadcast force-fires every env, exactly like the watch loop below.
assert online.broadcasts_dir is not None and online.resume_step is not None
while True:
if (get_step_path(online.broadcasts_dir, online.resume_step) / "STABLE").exists():
is_final = online.max_steps is not None and online.resume_step >= online.max_steps
await self.maybe_run_evals(step=online.resume_step, reload_weights=True, force=is_final)
break
newer_stable = any(
step > online.resume_step and (get_step_path(online.broadcasts_dir, step) / "STABLE").exists()
for step in get_all_ckpt_steps(online.broadcasts_dir)
)
if newer_stable:
get_logger().warning(
f"Broadcast for resume step {online.resume_step} was cleaned before it could be "
"re-evaluated (broadcast cleaning outpaced the evals process) - skipping the retrigger"
)
break
await asyncio.sleep(POLL_INTERVAL_S)
is_final = online.max_steps is not None and online.resume_step >= online.max_steps
await self.maybe_run_evals(step=online.resume_step, force=is_final)
get_logger().info(f"Watching {online.broadcasts_dir} for new weight broadcasts (max_steps={online.max_steps})")
while True:
assert online.broadcasts_dir is not None # resolved by the config validator
steps = get_all_ckpt_steps(online.broadcasts_dir)
stable = {step: (get_step_path(online.broadcasts_dir, step) / "STABLE").exists() for step in steps}
newest_stable = max((step for step in steps if stable[step]), default=None)
published = {step: self.receiver.is_published(step) for step in steps}
newest_published = max((step for step in steps if published[step]), default=None)
# Also walk eval-due steps that are no longer on disk: broadcast cleaning
# (the trainer keeps only the newest broadcast) can delete a step before
# this scan sees it, and a vanished step would otherwise be skipped
# without a trace.
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_stable)):
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_published)):
if step <= self.last_step:
continue
if step not in stable:
if step not in published:
get_logger().warning(
f"Weight broadcast for eval step {step} was deleted before it could be "
"evaluated (broadcast cleaning outpaced the evals process) - skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
if not stable[step]:
if not published[step]:
# The trainer writes broadcasts in ascending order, so a marker-less
# step below a stable one is an abandoned partial write (e.g. a crash
# mid-save), not one in progress — skip it instead of wedging on it.
if newest_stable is None or newest_stable < step:
# step below a published one is an abandoned partial write (e.g. a
# crash mid-save), not one in progress — skip it instead of wedging.
if newest_published is None or newest_published < step:
break # still being written — later steps can't be ready either
get_logger().warning(
f"Weight broadcast step {step} has no STABLE marker but newer stable "
"broadcasts exist - treating it as abandoned and skipping its evals"
f"Weight broadcast step {step} is not marked published but newer "
"broadcasts are - treating it as abandoned and skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
@@ -310,33 +322,42 @@ class Evals:
break
await asyncio.sleep(POLL_INTERVAL_S)
def deleted_due_steps(self, steps: list[int], newest_stable: int | None) -> set[int]:
"""Eval-due steps up to the newest stable broadcast that are missing from the
broadcasts dir — the trainer wrote them (it broadcasts at every due step), so
their absence means broadcast cleaning removed them before they were
def deleted_due_steps(self, steps: list[int], newest_published: int | None) -> set[int]:
"""Eval-due steps up to the newest published broadcast that are missing from
the broadcasts dir — the trainer wrote them (it broadcasts at every due step),
so their absence means broadcast cleaning removed them before they were
evaluated."""
if newest_stable is None:
if newest_published is None:
return set()
due = {
step
for interval in self.eval_source.intervals.values()
for step in range(interval, newest_stable + 1, interval)
for step in range(interval, newest_published + 1, interval)
}
return due - set(steps)
async def maybe_run_evals(self, step: int, *, reload_weights: bool = False, force: bool = False) -> None:
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
reloading the inference weights first. No-op when no env is due."""
reloading the inference weights first. No-op when no env is due — except
that a live transport's broadcast must always be received (the trainer
is blocked inside it), eval or no eval."""
if reload_weights:
assert self.config.online is not None and self.config.online.broadcasts_dir is not None
broadcast_dir = get_step_path(self.config.online.broadcasts_dir, step)
if not (broadcast_dir / "STABLE").exists():
get_logger().warning(f"No stable weight broadcast for step {step} ({broadcast_dir}) - skipping eval")
assert self.receiver is not None
broadcast_dir = self.receiver.step_dir(step)
if not self.receiver.is_published(step):
get_logger().warning(f"No published weight broadcast for step {step} ({broadcast_dir}) - skipping eval")
self.last_step = max(self.last_step, step)
return
fired = self.eval_source.trigger(step, force=force)
self.last_step = max(self.last_step, step)
if reload_weights:
# Every offered version must be received: the trainer blocks inside
# the handshake, so a failed receive fails the run loudly.
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
await self.receiver.receive(step)
if not fired:
return
@@ -348,24 +369,6 @@ class Evals:
for env_name in fired
)
if reload_weights:
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
# LoRA runs broadcast the raw adapter; load it under a fixed adapter name
# and serve the evals against that name (mirrors WeightWatcher).
lora_name = LORA_NAME if (broadcast_dir / "adapter_config.json").exists() else None
try:
await self.pool.update_weights(broadcast_dir, lora_name=lora_name, step=step)
except Exception as exc:
# Skip this step instead of killing the run; drain the queued examples
# so they don't leak into a later epoch with the wrong step.
while self.eval_source.next_task() is not None:
pass
get_logger().error(f"Failed to update inference weights to step {step} - skipping evals: {exc!r}")
return
if lora_name is not None:
self.pool.update_model_name(lora_name)
self.policy.model_name = lora_name
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
# between the trigger above and the weight reload completing.
self.policy.version = step
@@ -379,10 +382,15 @@ class Evals:
# An env with no examples emits no episodes, so its epoch can never finalize.
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
while pending:
episode = await self.dispatcher.out_q.get()
step = eval_work(episode).step
await monitors.log([episode], step, "eval", "all")
eval_batch = self.eval_sink.add(episode)
item = await self.dispatcher.out_q.get()
if isinstance(item, GroupCancellation):
raise RuntimeError("Eval dispatcher emitted a group cancellation")
if isinstance(item, DispatchFailure):
eval_batch = self.eval_sink.fail(item)
else:
step = eval_work(item).step
await monitors.log([item], step, "eval", "all")
eval_batch = self.eval_sink.add(item)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
pending.discard(eval_batch.env_name)
@@ -390,17 +398,24 @@ class Evals:
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
if not batch.episodes:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no episodes returned, skipping log")
if not batch.episodes and not batch.failures:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
return
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
if batch.episodes.effective:
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
episodes = batch.episodes
effective = episodes.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", episodes), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
total_attempts = len(episodes) + len(batch.failures)
metrics |= dispatch_failure_metrics(
batch.failures,
prefix=f"eval/{batch.env_name}/all",
total_attempts=total_attempts,
)
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
@@ -438,24 +453,22 @@ class Evals:
async def stop(self) -> None:
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
periodic_logger: PeriodicLogger | None = getattr(self, "periodic_logger", None)
if periodic_logger is not None:
await periodic_logger.stop()
inference_metrics: InferenceMetricsCollector | None = getattr(self, "inference_metrics", None)
if inference_metrics is not None:
await inference_metrics.stop()
dispatcher: Dispatcher | None = getattr(self, "dispatcher", None)
if dispatcher is not None:
await dispatcher.stop()
pool: InferencePool | None = getattr(self, "pool", None)
if pool is not None:
await pool.stop()
if self.periodic_logger is not None:
await self.periodic_logger.stop()
if self.inference_metrics is not None:
await self.inference_metrics.stop()
if self.dispatcher is not None:
await self.dispatcher.stop()
if self.clients is not None:
await self.clients.aclose()
if self.admin_clients is not None:
await self.admin_clients.aclose()
cleanup_processes(self.env_server_procs)
@clean_exit
async def run_evals(config: EvalsConfig) -> None:
evals = Evals(config)
async def run_evals(config: EvalsConfig, log_dir: Path | None = None) -> None:
evals = Evals(config, log_dir)
try:
await evals.run()
# Finalize only on a clean exit — a crashed evals must not mark the run completed.
@@ -465,11 +478,9 @@ async def run_evals(config: EvalsConfig) -> None:
def main() -> None:
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.entrypoints.evals import main as entrypoint_main
set_proc_title("Evals")
asyncio.run(run_evals(cli(EvalsConfig)))
entrypoint_main()
if __name__ == "__main__":
+8 -4
View File
@@ -92,10 +92,14 @@ async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: R
"""Wrapper around vLLM's /v1/load_lora_adapter.
prime-rl reloads a fixed-name adapter with fresh weights every step (the path
changes per policy version; the name is constant, see orchestrator.lora_name).
vLLM's native loader rejects a same-name reload unless ``load_inplace=True``,
so we force it here — that makes the worker re-read the new weights during
``add_lora``, reusing the existing ``lora_int_id``.
changes per policy version; the name is constant — the base model name, which
the adapter shadows: ``_maybe_get_adapters`` resolves ``lora_requests`` before
the base-model match, so requests keep addressing one stable name. If a future
vLLM rejects registering an adapter under a served model name, fall back to a
distinct constant adapter name set once at startup.) vLLM's native loader
rejects a same-name reload unless ``load_inplace=True``, so we force it here —
that makes the worker re-read the new weights during ``add_lora``, reusing the
existing ``lora_int_id``.
We then reset the stored request's flag back to ``False``. ``load_inplace`` is
a sticky field on the ``LoRARequest`` that ``_maybe_get_adapters`` hands to
+1 -1
View File
@@ -51,7 +51,7 @@ def receive_state_dict(communicator: PyNcclCommunicator) -> Generator[tuple[str,
# Split concatenated tensor back into individual tensors
offset = 0
for key, shape, numel in tensor_info_list:
tensor = concatenated[offset : offset + numel].view(shape).clone()
tensor = concatenated[offset : offset + numel].view(shape)
offset += numel
try:
yield key, tensor
+4 -3
View File
@@ -45,6 +45,7 @@ async def setup(
file: FileMonitorConfig | None = None,
*,
output_dir: Path,
producer: str | None = None,
run_config: BaseConfig | None = None,
train_env_names: list[str] | None = None,
eval_env_names: list[str] | None = None,
@@ -79,7 +80,7 @@ async def setup(
)
)
if file is not None:
monitors.append(("file", FileMonitor(file), dict(output_dir=output_dir)))
monitors.append(("file", FileMonitor(file), dict(output_dir=output_dir, producer=producer)))
if not monitors:
return
@@ -99,7 +100,7 @@ def get(monitor_cls: type[Monitor]) -> Monitor | None:
@overload
async def log(data: dict[str, Any], step: int) -> None: ...
async def log(data: dict[str, Any], step: int | None) -> None: ...
@overload
@@ -108,7 +109,7 @@ async def log(data: vf.Episode | list[vf.Episode], step: int, kind: Kind, subset
async def log(
data: dict[str, Any] | vf.Episode | list[vf.Episode],
step: int,
step: int | None,
kind: Kind = "train",
subset: Subset = "effective",
) -> None:
+6 -4
View File
@@ -24,7 +24,7 @@ class Monitor(ABC):
"""Initialize run. Overrides name their own kwargs."""
@overload
async def log(self, data: dict[str, Any], step: int) -> None: ...
async def log(self, data: dict[str, Any], step: int | None) -> None: ...
@overload
async def log(self, data: vf.Episode | list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None: ...
@@ -32,7 +32,7 @@ class Monitor(ABC):
async def log(
self,
data: dict[str, Any] | vf.Episode | list[vf.Episode],
step: int,
step: int | None,
kind: Kind = "train",
subset: Subset = "effective",
) -> None:
@@ -41,11 +41,13 @@ class Monitor(ABC):
await self.log_metrics(data, step=step)
else:
episodes = data if isinstance(data, list) else [data]
assert step is not None
await self.log_episodes(episodes, step=step, kind=kind, subset=subset)
@abstractmethod
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
"""Log scalar metrics."""
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
"""Log scalar metrics. ``step=None`` logs a time-keyed row (e.g. inference
metrics, which are sampled on wall time rather than the training step)."""
@abstractmethod
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
+7 -2
View File
@@ -22,15 +22,18 @@ class FileMonitor(Monitor):
config: FileMonitorConfig
file: TextIO
async def init(self, output_dir: Path) -> None:
async def init(self, output_dir: Path, producer: str | None = None) -> None:
self.output_dir = output_dir
self.producer = producer
self.path = output_dir / self.config.path
self.path.parent.mkdir(parents=True, exist_ok=True)
# Line-buffered append so a concurrently-running dashboard can tail the file.
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
"""``step=None`` logs a time-keyed row (e.g. inference metrics, which are
sampled on wall time rather than the training step)."""
sanitized, dropped = sanitize(metrics)
if dropped:
self.logger.warning(
@@ -38,6 +41,8 @@ class FileMonitor(Monitor):
)
row = {"step": step, "time": time.time(), **sanitized}
if self.producer is not None:
row["producer"] = self.producer
self.file.write(json.dumps(row) + "\n")
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
+5 -1
View File
@@ -5,6 +5,7 @@ import atexit
import io
import json
import os
import time
from datetime import datetime, timezone
from typing import Any, Coroutine
@@ -87,10 +88,13 @@ class PrimeMonitor(Monitor):
)
await self.run.create(name=self.config.name, **run_fields)
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
metrics, dropped = sanitize(metrics)
if dropped:
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
# every monitor stamps its own wall time; without it, step=None rows
# (e.g. inference metrics) reach the platform with no time anchor
metrics["_timestamp"] = time.time()
self.run.submit("metrics upload", self.run.log_metrics(metrics))
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
+18 -2
View File
@@ -42,6 +42,9 @@ class WandbMonitor(Monitor):
self.logger.debug(f"Found WANDB_ARGS in environment variables {wandb_args}")
sys.argv = json.loads(wandb_args)
# W&B advertises Weave on every init when it sees openai/verifiers imported.
os.environ.setdefault("WANDB_DISABLE_WEAVE", "1")
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
# requires a server connection and can't work offline.
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1" and os.environ.get("WANDB_MODE") not in (
@@ -113,6 +116,9 @@ class WandbMonitor(Monitor):
self.wandb = init_wandb(max_retries)
wandb.define_metric("*", step_metric="step")
# key prefixes that arrived via step=None (wall-time rows); their time axis
# is defined lazily on first sight in log_metrics
self._time_prefixes: set[str] = set()
# Provision the curated "overview" saved view once per project (the run's primary process
# in shared mode, else the single master). Best-effort: a workspaces/API failure must never
@@ -133,8 +139,18 @@ class WandbMonitor(Monitor):
self.logger.info(f"Logging metrics to W&B ({self.wandb.url})")
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
wandb.log({**metrics, "step": step})
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
# every log carries the monitor's own wall-time stamp
if step is None:
# time-keyed rows chart against wall time; whichever key prefixes show
# up this way get their time axis defined on first sight
for prefix in {key.split("/")[0] for key in metrics}:
if prefix not in self._time_prefixes:
self._time_prefixes.add(prefix)
wandb.define_metric(f"{prefix}/*", step_metric="_timestamp")
wandb.log({**metrics, "_timestamp": time.time()})
else:
wandb.log({**metrics, "step": step, "_timestamp": time.time()})
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
pass
+5
View File
@@ -1,5 +1,9 @@
"""Curated "overview" W&B saved view.
The dashboard mirrors these sections in `prime_rl/dashboard/static/app.js`
(buildSections + the *_METRICS/INFERENCE_PANELS constants) — keep the two in
sync when editing panels here.
prime-rl logs many metrics; the default workspace auto-generates a panel per key, which buries the
few that matter. These build a named saved view grouping the important metrics into sections, so a
new project gets a usable overview without hand-picking panels. Panels are untitled — each shows
@@ -29,6 +33,7 @@ OVERVIEW_NAME = "overview"
# agent. Only the score metric differs — train scores with "reward/mean", eval with "avg@k" (its k
# dynamic, so also a regex) — and each section builder prepends its own.
COMMON_METRICS = [
"all/dispatch_failure/mean",
"effective/num_total_tokens/mean",
"effective/num_turns/mean",
"effective/num_branches/mean",
+5 -5
View File
@@ -22,7 +22,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_pool
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_client
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
from prime_rl.orchestrator.algo.hierarchical_grpo import HierarchicalGRPOAlgorithm
@@ -35,7 +35,7 @@ from prime_rl.orchestrator.algo.sft import SFTDistillAlgorithm
if TYPE_CHECKING:
from prime_rl.configs.algorithm import AlgoConfig
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
# Runtime dispatch is keyed on ``algo.type`` — it names the algorithm, and
# each config class's defaults are its vetted parameterization.
@@ -51,7 +51,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
}
def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> Algorithm:
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
cls = ALGORITHM_CLASSES[config.type]
assert cls.action_loss_type == config.action_loss_type # config and runtime declare in two places
# The Algorithm is the runtime of the algorithm config's training signal
@@ -59,7 +59,7 @@ def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> Algorithm
# handed the live policy pool — opsd self-distills against it, others may
# judge against it or ignore it. Other models (a frozen teacher, a hint
# renderer) are built from the algorithm's own config in setup().
return cls(config, policy_pool)
return cls(config, clients)
__all__ = [
@@ -73,7 +73,7 @@ __all__ = [
"RAEAlgorithm",
"SFTDistillAlgorithm",
"build_algorithm",
"connect_frozen_pool",
"connect_frozen_client",
"assign_advantages",
"stamp_loss_routing",
]
+15 -16
View File
@@ -12,24 +12,24 @@ from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
async def connect_frozen_pool(
async def connect_frozen_client(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferencePool:
) -> InferenceClient:
"""Connect to an externally hosted frozen model and wait for it."""
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient, check_inference_ready
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
if renderer_config is not None:
pool = InferencePool(
clients = InferenceClient(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
pool = InferencePool(config, model_name=config.name)
await pool.wait_for_ready(config.name)
return pool
clients = InferenceClient(config, model_name=config.name)
await check_inference_ready(config, config.name)
return clients
def iter_trainable_traces(episodes: list[vf.Episode]):
@@ -52,18 +52,17 @@ class Algorithm:
action_loss_type: ClassVar[ActionLossType] = "rl"
def __init__(self, config: AlgoConfig, policy_pool: InferencePool):
self.policy_pool = policy_pool
self.connected_pools: list[InferencePool] = []
def __init__(self, config: AlgoConfig, clients: InferenceClient):
self.clients = clients
self.connected: InferenceClient | None = None
async def setup(self) -> None:
"""Connect resources owned by the algorithm."""
async def connect(self, reference: FrozenModelConfig) -> InferencePool:
"""Connect and track a frozen model pool owned by this algorithm."""
pool = await connect_frozen_pool(reference)
self.connected_pools.append(pool)
return pool
async def connect(self, reference: FrozenModelConfig) -> InferenceClient:
"""Connect and track the frozen model pool owned by this algorithm."""
self.connected = await connect_frozen_client(reference)
return self.connected
async def score_episode(self, episode: vf.Episode) -> None:
"""Assign rollout-local annotations to one finalized episode."""
+3 -3
View File
@@ -11,7 +11,7 @@ from prime_rl.utils.utils import import_object
if TYPE_CHECKING:
import verifiers.v1 as vf
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class EchoAlgorithm(GRPOAlgorithm):
@@ -22,8 +22,8 @@ class EchoAlgorithm(GRPOAlgorithm):
mask and its denominator. An optional user filter narrows the selection
per rollout (e.g. dropping tool-output warnings)."""
def __init__(self, config: EchoAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
def __init__(self, config: EchoAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.role_weights = {
role: role_config.alpha
for role in ("system", "user", "assistant", "tool")
+3 -3
View File
@@ -10,7 +10,7 @@ from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
from prime_rl.orchestrator.algo.routing import assign_advantages
if TYPE_CHECKING:
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class GRPOAlgorithm(Algorithm):
@@ -18,8 +18,8 @@ class GRPOAlgorithm(Algorithm):
policy per example; credit = reward minus the group mean (optionally
length-shaped); action tokens feed the ``rl`` loss."""
def __init__(self, config: GRPOAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
def __init__(self, config: GRPOAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.length_penalty = config.length_penalty
async def score_group(self, episodes: list[vf.Episode]) -> None:
@@ -10,7 +10,7 @@ from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
from prime_rl.orchestrator.algo.routing import assign_advantages
if TYPE_CHECKING:
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class HierarchicalGRPOAlgorithm(Algorithm):
@@ -26,8 +26,8 @@ class HierarchicalGRPOAlgorithm(Algorithm):
within one episode. Other roles are compared across the full rollout group.
A comparison group with one trace produces zero advantage."""
def __init__(self, config: HierarchicalGRPOAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
def __init__(self, config: HierarchicalGRPOAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.episode_agents = set(config.episode_agents)
async def score_group(self, episodes: list[vf.Episode]) -> None:
+8 -8
View File
@@ -11,7 +11,7 @@ from prime_rl.orchestrator.algo.routing import assign_reference_logprobs
from prime_rl.orchestrator.trajectories import iter_trainable_branches
if TYPE_CHECKING:
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class OPDAlgorithm(Algorithm):
@@ -26,20 +26,20 @@ class OPDAlgorithm(Algorithm):
action_loss_type = "ref_kl"
def __init__(self, config: OPDAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
def __init__(self, config: OPDAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.teacher = config.teacher
self.teacher_pool: InferencePool | None = None # frozen teacher endpoint, connected in setup()
self.teacher_clients: InferenceClient | None = None # frozen teacher endpoint, connected in setup()
async def setup(self) -> None:
self.teacher_pool = await self.connect(self.teacher)
self.teacher_clients = await self.connect(self.teacher)
async def score_episode(self, episode: vf.Episode) -> None:
pool = self.teacher_pool
assert pool is not None, "teacher pool not connected — Algorithm.setup() must run first"
teacher = self.teacher_clients
assert teacher is not None, "teacher not connected — Algorithm.setup() must run first"
branches = [
branch for _, trace in iter_trainable_traces([episode]) for branch, _ in iter_trainable_branches(trace)
]
scores = await asyncio.gather(*(pool.score(branch.token_ids) for branch in branches))
scores = await asyncio.gather(*(teacher.score(branch.token_ids) for branch in branches))
for branch, logprobs in zip(branches, scores, strict=True):
assign_reference_logprobs(branch, logprobs)
+7 -7
View File
@@ -14,7 +14,7 @@ from prime_rl.orchestrator.utils import episode_env_name
if TYPE_CHECKING:
from renderers.base import Renderer
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class OPSDAlgorithm(Algorithm):
@@ -33,8 +33,8 @@ class OPSDAlgorithm(Algorithm):
action_loss_type = "ref_kl"
def __init__(self, config: OPSDAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
def __init__(self, config: OPSDAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.demo_key = config.demo_key
self.template = config.template
self.renderer_config = config.renderer
@@ -42,7 +42,7 @@ class OPSDAlgorithm(Algorithm):
# Self-distillation: the teacher *is* the live policy. Scoring against
# the shared policy pool tracks its current weights, model name, and
# endpoint churn for free.
self.teacher_pool = self.policy_pool
self.teacher_clients = self.clients
async def setup(self) -> None:
"""Build opsd's own hint-block renderer from config — it is not handed
@@ -51,7 +51,7 @@ class OPSDAlgorithm(Algorithm):
identically to the policy's own prompts."""
from renderers.base import create_renderer, load_tokenizer
self.renderer = create_renderer(load_tokenizer(self.policy_pool.model_name), self.renderer_config)
self.renderer = create_renderer(load_tokenizer(self.clients.model_name), self.renderer_config)
def _demonstration(self, episode: vf.Episode, trace: vf.Trace) -> str:
demonstration = trace.info.get(self.demo_key)
@@ -66,13 +66,13 @@ class OPSDAlgorithm(Algorithm):
return demonstration
async def score_episode(self, episode: vf.Episode) -> None:
pool = self.teacher_pool
teacher = self.teacher_clients
renderer = self.renderer
assert renderer is not None, "renderer not built — Algorithm.setup() must run first"
for _, trace in iter_trainable_traces([episode]):
hint = self.template.format(demonstration=self._demonstration(episode, trace))
hint_block = renderer.render_ids([{"role": "system", "content": hint}], add_generation_prompt=False)
branches = [branch for branch, _ in iter_trainable_branches(trace)]
scores = await asyncio.gather(*(pool.score(hint_block + branch.token_ids) for branch in branches))
scores = await asyncio.gather(*(teacher.score(hint_block + branch.token_ids) for branch in branches))
for branch, full_logprobs in zip(branches, scores, strict=True):
assign_reference_logprobs(branch, full_logprobs[len(hint_block) :])
+3 -3
View File
@@ -10,7 +10,7 @@ from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
from prime_rl.orchestrator.algo.routing import assign_advantages
if TYPE_CHECKING:
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class RAEAlgorithm(Algorithm):
@@ -31,8 +31,8 @@ class RAEAlgorithm(Algorithm):
live in orchestrator memory: a restart re-warms them over ~1/(1 − decay)
traces per agent."""
def __init__(self, config: RAEAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
def __init__(self, config: RAEAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.decay = config.decay
self.baselines: dict[str, float] = defaultdict(float)
+1 -1
View File
@@ -5,7 +5,7 @@ from __future__ import annotations
import verifiers.v1 as vf
from prime_rl.configs.algorithm import ActionLossType
from prime_rl.transports.rollouts import TrainingSample
from prime_rl.transports.batch import TrainingSample
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import os
from collections.abc import Callable
from pathlib import Path
import httpx
@@ -40,8 +41,9 @@ class PrefillScorer:
await self._client.close()
class InferencePool:
"""Inference pool with a single data-plane endpoint and one admin client per server."""
class InferenceClient:
"""Data-plane clients for one inference endpoint (the router of the policy
deployment, or an external API for frozen models)."""
def __init__(
self,
@@ -59,7 +61,31 @@ class InferencePool:
renderer_model_name=renderer_model_name,
)
self.eval_client = setup_client(client_config, client_type=eval_client_type)
self._admin_clients = setup_admin_clients(client_config)
self._scorer = PrefillScorer()
self.model_name = model_name
async def score(self, token_ids: list[int]) -> list[float]:
"""Prefill-score ``token_ids`` under this endpoint's model (one logprob
per token, 0.0 for the leading token)."""
return await self._scorer.score(self.train_client, self.model_name, token_ids)
async def aclose(self) -> None:
await self._scorer.aclose()
class AdminClients:
"""Admin plane of the policy inference deployment: one httpx client per
engine process. The router serves no admin routes (pause/resume,
update_weights, init_broadcaster, load_lora_adapter live on the engines),
so these clients bypass it via ``admin_base_url``.
The client order is load-bearing: ``admin_base_url`` order must match the
GPU rank order — the ``rank_offset`` math in ``init_nccl_broadcast`` /
``init_nixl_broadcast`` and the metrics collector's role list index into
it."""
def __init__(self, client_config: ClientConfig):
self.clients = setup_admin_clients(client_config)
# When admin URLs bypass a router, also health-check the client-facing
# (router) endpoint - it only starts serving once its workers are healthy.
self._router_clients = (
@@ -69,33 +95,32 @@ class InferencePool:
)
self._skip_model_check = client_config.skip_model_check
self._wait_for_ready_timeout = client_config.wait_for_ready_timeout
self._scorer = PrefillScorer()
self.model_name = model_name
@property
def admin_clients(self) -> list[AsyncClient]:
return self._admin_clients
def update_model_name(self, model_name: str) -> None:
self.model_name = model_name
async def wait_for_ready(self, model_name: str, timeout: int | None = None) -> None:
await check_health(
self._admin_clients + self._router_clients,
timeout=timeout if timeout is not None else self._wait_for_ready_timeout,
async def wait_for_ready(self, model_name: str) -> None:
# The engines are waited on even when a router fronts them: the llm-d
# router (Envoy) 404s /health, which check_health treats as "no health
# route", so the router alone is not a readiness signal. The router
# owns the info-level waiting log; the per-engine waits log at debug.
await asyncio.gather(
check_health(self.clients, timeout=self._wait_for_ready_timeout, quiet=bool(self._router_clients)),
check_health(self._router_clients, timeout=self._wait_for_ready_timeout),
)
await maybe_check_has_model(self._admin_clients, model_name, skip_model_check=self._skip_model_check)
await maybe_check_has_model(self.clients, model_name, skip_model_check=self._skip_model_check)
async def update_weights(self, weight_dir: Path | None, lora_name: str | None = None, step: int = 0) -> None:
await update_weights(self._admin_clients, weight_dir, lora_name=lora_name, step=step)
async def aclose(self) -> None:
for client in self.clients + self._router_clients:
await client.aclose()
async def score(self, token_ids: list[int]) -> list[float]:
"""Prefill-score ``token_ids`` under this pool's model (one logprob per
token, 0.0 for the leading token). Delegates to the shared scorer."""
return await self._scorer.score(self.train_client, self.model_name, token_ids)
async def stop(self) -> None:
await self._scorer.aclose()
async def check_inference_ready(client_config: ClientConfig, model_name: str) -> None:
"""One-shot readiness check of an inference endpoint (health + model
listing) with transient clients — for frozen endpoints that never need a
persistent admin plane."""
admin = AdminClients(client_config)
try:
await admin.wait_for_ready(model_name)
finally:
await admin.aclose()
def setup_client(
@@ -172,8 +197,15 @@ async def maybe_check_has_model(
async def check_health(
admin_clients: list[AsyncClient], interval: int = 1, log_interval: int = 30, timeout: int = 1800
admin_clients: list[AsyncClient],
interval: int = 1,
log_interval: int = 30,
timeout: int = 1800,
quiet: bool = False,
) -> None:
"""Wait until every client's /health responds. With ``quiet``, the periodic
waiting lines log at debug instead of info - used for engines fronted by a
router, so startup logs one waiting line instead of one per engine."""
logger = get_logger()
async def _check_health(admin_client: AsyncClient) -> None:
@@ -190,9 +222,8 @@ async def check_health(
return
except Exception as e:
if wait_time % log_interval == 0 and wait_time > 0:
logger.info(
f"Waiting for inference server at {admin_client.base_url} to start up ({wait_time}s elapsed)"
)
log = logger.debug if quiet else logger.info
log(f"Waiting for inference server at {admin_client.base_url} to start up ({wait_time}s elapsed)")
logger.debug(f"Inference server at {admin_client.base_url} not reachable: {e!r}")
await asyncio.sleep(interval)
wait_time += interval
@@ -203,9 +234,6 @@ async def check_health(
await asyncio.gather(*[_check_health(admin_client) for admin_client in admin_clients])
NCCL_READY_MARKER = "NCCL_READY"
def _is_retryable_admin_error(exception: BaseException) -> bool:
"""Check if an exception should trigger a retry for an admin op (pause/resume/update_weights)."""
if isinstance(exception, httpx.HTTPStatusError):
@@ -275,50 +303,39 @@ async def _resume_engines(admin_clients: list[AsyncClient]) -> None:
async def update_weights(
admin_clients: list[AsyncClient],
weight_dir: Path | None,
lora_name: str | None = None,
step: int = 0,
on_paused: Callable[[], None] | None = None,
) -> None:
"""Update weights on static inference servers.
Pauses all engines first to drain in-flight requests, then performs the
weight update, then resumes. This ensures all DP workers are idle and can
participate in the collective weight transfer.
participate in the collective weight transfer. ``on_paused`` runs between
the pause and the update RPC — the NCCL receiver signals the trainer there.
Note: the prefix cache is intentionally not reset on weight update. The orchestrator
salts the prefix cache per weight version (``cache_salt`` in the sampling request, see
``orchestrator/envs.py``), so KV computed under old weights is never reused.
"""
logger = get_logger()
weight_dir_posix = weight_dir.as_posix() if weight_dir is not None else None
if lora_name is not None and weight_dir is not None:
await load_lora_adapter(admin_clients, lora_name, weight_dir)
else:
# Pause engines so all DP workers drain in-flight work and can join the NCCL broadcast
await _pause_engines(admin_clients, step=step)
try:
# Create ready marker before servers enter receive path (used by NCCL broadcast)
if weight_dir is not None:
nccl_ready_file = weight_dir / NCCL_READY_MARKER
nccl_ready_file.parent.mkdir(parents=True, exist_ok=True)
nccl_ready_file.touch()
logger.debug(f"Created NCCL_READY marker at {nccl_ready_file}")
await asyncio.gather(
*[
_admin_post(
admin_client,
"/update_weights",
json={"weight_dir": weight_dir_posix},
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
)
for admin_client in admin_clients
]
)
finally:
await _resume_engines(admin_clients)
await _pause_engines(admin_clients, step=step)
try:
if on_paused is not None:
on_paused()
await asyncio.gather(
*[
_admin_post(
admin_client,
"/update_weights",
json={"weight_dir": weight_dir_posix},
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
)
for admin_client in admin_clients
]
)
finally:
await _resume_engines(admin_clients)
def _is_retryable_lora_error(exception: BaseException) -> bool:
@@ -376,25 +393,12 @@ async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lo
await asyncio.gather(*[_load_lora_adapter(admin_client) for admin_client in admin_clients])
async def unload_lora_adapter(admin_clients: list[AsyncClient], lora_name: str) -> None:
"""Make a HTTP post request to the vLLM server to unload a LoRA adapter."""
logger = get_logger()
async def _unload_lora_adapter(admin_client: AsyncClient) -> None:
logger.debug(f"Sending request to unload LoRA adapter {lora_name}")
await admin_client.post("/v1/unload_lora_adapter", json={"lora_name": lora_name})
# TODO: The first one can fail, but subsequent ones should succeed.
# response.raise_for_status()
await asyncio.gather(*[_unload_lora_adapter(admin_client) for admin_client in admin_clients])
async def init_nccl_broadcast(
admin_clients: list[AsyncClient],
host: str,
port: int,
timeout: int,
inference_world_size: int | None = None,
inference_world_size: int,
quantize_in_weight_transfer: bool = False,
) -> None:
"""Initialize NCCL broadcast on all inference servers.
@@ -405,12 +409,6 @@ async def init_nccl_broadcast(
"""
logger = get_logger()
if inference_world_size is None:
inference_world_size = len(admin_clients)
logger.warning(
f"inference_world_size not provided, defaulting to {inference_world_size} (one GPU per admin client)"
)
gpus_per_server = inference_world_size // len(admin_clients)
logger.info(
+84 -68
View File
@@ -6,10 +6,10 @@
burst-capped so a raised (or drained) cap never lands all its prefills at
once.
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
- Emit-everything invariant: every dispatched episode eventually reaches
``out_q`` exactly once — as a native episode, or covered by its group's
single ``GroupCancellation`` message when the group is dropped. Failures
remain episode errors; sinks decide drop / partial-train policy.
- Every dispatched attempt reaches ``out_q`` exactly once: as the native
episode returned by the environment, as a ``DispatchFailure`` when no
episode was produced, or under the group's ``GroupCancellation`` when the
orchestrator abandons it.
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
schedule next. Transitions are level-triggered (driven by the eval
source's emptiness), so in-flight episodes of the opposite kind drain
@@ -38,11 +38,13 @@ from typing import Literal
import verifiers.v1 as vf
from aiolimiter import AsyncLimiter
from prime_rl.orchestrator.clients import InferenceClient
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.train_source import TrainSource
from prime_rl.orchestrator.types import (
CancelReason,
DispatchFailure,
DispatchResult,
GroupCancellation,
GroupState,
@@ -53,7 +55,6 @@ from prime_rl.orchestrator.types import (
)
from prime_rl.orchestrator.utils import min_fresh_version
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import get_logger
@@ -121,15 +122,6 @@ class DispatcherMetrics:
return keys
def _trace_task(task: vf.Task) -> vf.TraceTask:
return vf.TraceTask(
type=type(task).__name__,
data=task.data,
key=task.key,
hash=task.hash,
)
def _validate_episode_task(episode: vf.WireEpisode, task: vf.Task) -> None:
expected = (task.key, task.hash)
actual = (episode.task.key, episode.task.hash)
@@ -151,7 +143,7 @@ class Dispatcher:
eval_envs: EvalEnvs | None,
train_source: TrainSource | None,
eval_source: EvalSource | None,
policy_pool: InferencePool,
policy_clients: InferenceClient,
policy: Policy,
progress: Progress | None,
initial_max_inflight: int,
@@ -168,7 +160,7 @@ class Dispatcher:
self.eval_envs = eval_envs
# Train rollouts go to the env's generation source; eval always
# evaluates the policy.
self.policy_pool = policy_pool
self.policy_clients = policy_clients
self.train_source = train_source
self.eval_source = eval_source
self.max_off_policy_steps = max_off_policy_steps
@@ -202,7 +194,8 @@ class Dispatcher:
# Bounded so the dispatcher backpressures on a slow sink (unbounded
# when no hard ceiling is configured — the dynamic cap still bounds
# in-flight work). One entry per episode — the sinks count episodes,
# never loose traces — plus one ``GroupCancellation`` per dropped group.
# never loose traces — plus terminal dispatcher events for attempts
# that produced no episode.
maxsize = max(8, max_inflight_ceiling) if max_inflight_ceiling is not None else 0
self.out_q: asyncio.Queue[DispatchResult] = asyncio.Queue(maxsize=maxsize)
@@ -217,18 +210,20 @@ class Dispatcher:
# *why* — the orchestrator toggles this based on step / policy lead.
self.dispatch_allowed = asyncio.Event()
self.dispatch_allowed.set()
self.policy_update_pending = False
self.scheduling_lock = asyncio.Lock()
self.stopped = asyncio.Event()
self.task: asyncio.Task | None = None
def _train_generation_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
"""``(pool, model_name, is_live)`` for *train* rollouts of this env —
def _train_generation_for(self, env_name: str) -> tuple[InferenceClient, str, bool]:
"""``(clients, model_name, is_live)`` for *train* rollouts of this env —
eval always uses the policy."""
assert self.train_envs is not None # train groups only exist when train is configured
source = self.train_envs.get(env_name).generation_source
if source.uses_live_policy:
return source.pool, self.policy.model_name, True
return source.pool, source.pool.model_name, False
return source.clients, self.policy.model_name, True
return source.clients, source.clients.model_name, False
@property
def inflight_train_count(self) -> int:
@@ -353,7 +348,7 @@ class Dispatcher:
timeout=0.5, # wake periodically to re-check fill (mode flips)
)
for task in done:
await self.handle_completed_episode(task)
await self.handle_completed_request(task)
except asyncio.CancelledError:
return
@@ -378,6 +373,12 @@ class Dispatcher:
the resulting aborts are processed while the engine is still stepping —
otherwise the orphaned KV transfers crash the decode engine on resume
(see ``WeightWatcher.apply_policy_update``)."""
self.policy_update_pending = True
# Wait for a scheduling call that started before the pending update.
# No rollout can cross the inference weight swap after this barrier.
async with self.scheduling_lock:
pass
if self.train_envs is None or self.progress is None:
return
min_version = min_fresh_version(self.progress.step, self.max_off_policy_steps)
@@ -399,7 +400,8 @@ class Dispatcher:
)
async def on_new_version(self, step: int) -> None:
"""No-op: the dispatcher drains in ``on_version_pending`` (pre-pause)."""
"""Resume rollout scheduling after inference applies the new policy."""
self.policy_update_pending = False
async def fill_inflight(self) -> None:
"""Schedule new rollouts up to ``max_inflight``, honoring
@@ -408,28 +410,33 @@ class Dispatcher:
respects it. When ``PREFER_EVAL``'s source exhausts we flip back to
``PREFER_TRAIN`` so the eval tail drains alongside fresh train."""
while True:
if self.policy_update_pending:
return
if self.available_permits <= 0 or self.admission_budget() <= 0:
return
if self.mode == DispatcherMode.PREFER_EVAL:
# PREFER_EVAL is only entered when the orchestrator triggers
# eval, which requires ``eval_source`` to be configured
assert self.eval_source is not None
if not self.eval_has_work:
# Eval source + all eval groups fully dispatched. Flip
# to PREFER_TRAIN so any remaining permits go to train
# while the in-flight eval tail completes naturally
self.switch_mode(DispatcherMode.PREFER_TRAIN, reason="the eval queue drained")
continue
scheduled = await self.try_schedule("eval")
if not scheduled:
return
else: # PREFER_TRAIN — respects the orchestrator's dispatch gate
if not self.dispatch_allowed.is_set():
return
scheduled = await self.try_schedule("train")
if not scheduled:
async with self.scheduling_lock:
if self.policy_update_pending:
return
if self.mode == DispatcherMode.PREFER_EVAL:
# PREFER_EVAL is only entered when the orchestrator triggers
# eval, which requires ``eval_source`` to be configured
assert self.eval_source is not None
if not self.eval_has_work:
# Eval source + all eval groups fully dispatched. Flip
# to PREFER_TRAIN so any remaining permits go to train
# while the in-flight eval tail completes naturally
self.switch_mode(DispatcherMode.PREFER_TRAIN, reason="the eval queue drained")
continue
scheduled = await self.try_schedule("eval")
if not scheduled:
return
else: # PREFER_TRAIN — respects the orchestrator's dispatch gate
if not self.dispatch_allowed.is_set():
return
scheduled = await self.try_schedule("train")
if not scheduled:
return
def switch_mode(self, new_mode: DispatcherMode, *, reason: str) -> None:
if new_mode == self.mode:
@@ -500,14 +507,12 @@ class Dispatcher:
# goes through the eval client (chat-completions) so eval scores stay
# comparable.
if group.kind == "eval":
pool, model_name = self.policy_pool, self.policy.model_name
clients, model_name = self.policy_clients, self.policy.model_name
live_sourced = True
else:
pool, model_name, live_sourced = self._train_generation_for(group.env_name)
clients, model_name, live_sourced = self._train_generation_for(group.env_name)
if group.pinned_client is None:
group.pinned_client = pool.eval_client if group.kind == "eval" else pool.train_client
client = group.pinned_client
client = clients.eval_client if group.kind == "eval" else clients.train_client
env_collection = self.train_envs if group.kind == "train" else self.eval_envs
if env_collection is None:
@@ -560,34 +565,40 @@ class Dispatcher:
if refund_admission:
self.admissions_in_window = max(0, self.admissions_in_window - 1)
async def handle_completed_episode(self, task: asyncio.Task) -> None:
"""Emit every dispatched episode exactly once to ``out_q``."""
async def handle_completed_request(self, task: asyncio.Task) -> None:
"""Emit the terminal result of one dispatched environment request."""
meta = self.inflight.pop(task, None)
if meta is None:
return # already handled by drop_group / cancel_inflight_episodes
self.release(refund_admission=True)
group = self.groups.get(meta.group_id)
is_synth_exception = False
try:
episode: vf.WireEpisode = task.result()
except asyncio.CancelledError:
return
except Exception as exc:
get_logger().warning(f"Episode task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
episode = vf.WireEpisode(
env=vf.EnvInfo(id=meta.env_name),
task=_trace_task(meta.task),
ok=False,
errors=[
vf.Error(
get_logger().warning(f"Environment request failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
policy_version = self.complete_group_member(meta, group)
await self.out_q.put(
DispatchFailure(
kind=meta.kind,
env_name=meta.env_name,
group_id=str(meta.group_id),
step=meta.step,
policy_version=policy_version,
task_type=type(meta.task).__name__,
task_key=meta.task.key,
task_hash=meta.task.hash,
error=vf.Error(
type=type(exc).__name__,
message=str(exc),
traceback="".join(traceback.format_exception(exc)),
)
],
),
)
)
is_synth_exception = True
return
if not episode.traces and episode.ok:
episode.ok = False
@@ -603,19 +614,29 @@ class Dispatcher:
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
if trace.has_error:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if not is_synth_exception and trace.last_error is not None:
if trace.last_error is not None:
get_logger().warning(
f"Trace failed in group {meta.group_id} ({meta.env_name}) — "
f"{trace.last_error.type}: {trace.last_error.message}"
)
if not episode.ok and not episode.traces:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if not is_synth_exception and self.on_episode_complete is not None and meta.started_at > 0:
if self.on_episode_complete is not None and meta.started_at > 0:
self.on_episode_complete(
meta.env_name, meta.kind, episode.num_total_tokens, time.monotonic() - meta.started_at
)
await self.emit_episode(meta, group, episode)
def complete_group_member(self, meta: InflightEpisode, group: GroupState | None) -> int:
"""Advance group accounting and return the attempt's pinned policy version."""
policy_version = meta.policy_version
if group is not None:
policy_version = group.policy_version_at_start
group.emitted += 1
if group.emitted >= group.target_episodes:
self.groups.pop(meta.group_id, None)
return policy_version
async def emit_episode(
self,
meta: InflightEpisode,
@@ -624,12 +645,7 @@ class Dispatcher:
) -> None:
"""Stamp one completed episode with its dispatch provenance and emit it."""
_validate_episode_task(episode, meta.task)
policy_version = meta.policy_version
if group is not None:
policy_version = group.policy_version_at_start
group.emitted += 1
if group.emitted >= group.target_episodes:
self.groups.pop(meta.group_id, None)
policy_version = self.complete_group_member(meta, group)
episode.env.name = meta.env_name
episode.group = vf.GroupInfo(id=str(meta.group_id))
@@ -656,7 +672,7 @@ class Dispatcher:
# Sync claim phase: pop matching tasks from ``self.inflight`` and
# release their permits in one non-yielding sweep. After this loop
# the dropped tasks are no longer reachable from ``self.inflight``,
# so ``handle_completed_episode``'s existing None-guard makes the
# so ``handle_completed_request``'s existing None-guard makes the
# subsequent async emit phase race-free.
claimed: list[tuple[asyncio.Task, InflightEpisode]] = []
for task, meta in list(self.inflight.items()):
+10 -3
View File
@@ -179,6 +179,13 @@ class Envs(Generic[EnvT]):
async def start(self) -> None:
"""Connect to all env servers in parallel — every address is known up front,
so there's nothing to serialize on."""
# When several env.start()s load_dataset() concurrently, datasets' parallel arrow read
# (tqdm thread_map) races in ensure_lock's `del tqdm_class._lock` and crashes with
# `AttributeError: type object 'tqdm' has no attribute '_lock'`. Pre-seed the lock so it
# isn't created-and-deleted per call.
from datasets.utils import tqdm as hf_tqdm
hf_tqdm.set_lock(hf_tqdm.get_lock())
await asyncio.gather(*(env.start() for env in self))
@@ -192,7 +199,7 @@ class TrainEnvs(Envs[TrainEnv]):
configs: Sequence[TrainSourceConfig],
addresses: dict[tuple[str, str], str],
*,
policy_pool,
clients,
renderer_config=None,
):
self._envs: dict[str, TrainEnv] = {}
@@ -202,8 +209,8 @@ class TrainEnvs(Envs[TrainEnv]):
env = TrainEnv(
config,
addresses[("train", config.resolved_name)],
GenerationSource(config.algo.sampling, policy_pool, renderer_config),
build_algorithm(config.algo, policy_pool),
GenerationSource(config.algo.sampling, clients, renderer_config),
build_algorithm(config.algo, clients),
)
self._envs[env.name] = env
+55 -17
View File
@@ -8,7 +8,7 @@ import verifiers.v1 as vf
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.metrics import EvalEpisodes
from prime_rl.orchestrator.types import EvalBatch
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, eval_work
from prime_rl.utils.logger import get_logger
@@ -19,7 +19,9 @@ class EvalSink:
def __init__(self, *, eval_envs: EvalEnvs) -> None:
self.eval_envs = eval_envs
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
self.pending_group_failures: dict[str, list[DispatchFailure]] = defaultdict(list)
self.pending_batches: dict[tuple[str, int], list[vf.Episode]] = defaultdict(list)
self.pending_batch_failures: dict[tuple[str, int], list[DispatchFailure]] = defaultdict(list)
def add(self, episode: vf.Episode) -> EvalBatch | None:
env_name = episode_env_name(episode)
@@ -28,12 +30,32 @@ class EvalSink:
bkey = (env_name, eval_step)
group = self.pending_groups[group_id]
group.append(episode)
if len(group) >= self.group_size_for(env_name):
if self._group_size(group_id) >= self.group_size_for(env_name):
self.process_group(group_id)
if len(self.pending_batches[bkey]) >= self.batch_size_for(env_name):
if self._batch_size(bkey) >= self.batch_size_for(env_name):
return self.process_batch(bkey)
return None
def fail(self, failure: DispatchFailure) -> EvalBatch | None:
"""Count a request failure toward its group and eval epoch without
manufacturing a verifier episode."""
if failure.kind != "eval":
raise ValueError(f"EvalSink cannot process a {failure.kind} dispatch failure")
group_id = failure.group_id
bkey = (failure.env_name, failure.step)
self.pending_group_failures[group_id].append(failure)
if self._group_size(group_id) >= self.group_size_for(failure.env_name):
self.process_group(group_id)
if self._batch_size(bkey) >= self.batch_size_for(failure.env_name):
return self.process_batch(bkey)
return None
def _group_size(self, group_id: str) -> int:
return len(self.pending_groups[group_id]) + len(self.pending_group_failures[group_id])
def _batch_size(self, key: tuple[str, int]) -> int:
return len(self.pending_batches[key]) + len(self.pending_batch_failures[key])
def group_size_for(self, env_name: str) -> int:
return self.eval_envs.get(env_name).config.group_size
@@ -42,15 +64,23 @@ class EvalSink:
return len(env.examples) * env.config.group_size
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
batch_counts = {key: len(runs) for key, runs in self.pending_batches.items()}
keys = set(self.pending_batches) | set(self.pending_batch_failures)
batch_counts = {key: self._batch_size(key) for key in keys}
buffered: dict[tuple[str, int], int] = {}
for group in self.pending_groups.values():
if not group:
group_ids = set(self.pending_groups) | set(self.pending_group_failures)
for group_id in group_ids:
group = self.pending_groups[group_id]
failures = self.pending_group_failures[group_id]
if not group and not failures:
continue
episode = group[0]
eval_step = eval_work(episode).step
key = (episode_env_name(episode), eval_step)
buffered[key] = buffered.get(key, 0) + len(group)
if group:
env_name = episode_env_name(group[0])
eval_step = eval_work(group[0]).step
else:
env_name = failures[0].env_name
eval_step = failures[0].step
key = (env_name, eval_step)
buffered[key] = buffered.get(key, 0) + len(group) + len(failures)
return [
(
env_name,
@@ -64,12 +94,18 @@ class EvalSink:
def process_group(self, group_id: str) -> None:
group = self.pending_groups.pop(group_id, [])
if not group:
failures = self.pending_group_failures.pop(group_id, [])
if not group and not failures:
return
episode = group[0]
env_name = episode_env_name(episode)
eval_step = eval_work(episode).step
self.pending_batches[(env_name, eval_step)].extend(group)
if group:
env_name = episode_env_name(group[0])
eval_step = eval_work(group[0]).step
else:
env_name = failures[0].env_name
eval_step = failures[0].step
key = (env_name, eval_step)
self.pending_batches[key].extend(group)
self.pending_batch_failures[key].extend(failures)
traces = [trace for episode in group for trace in episode.traces]
survivors = [trace for trace in traces if not trace.has_error]
@@ -79,15 +115,17 @@ class EvalSink:
task_idx = next((trace.task.data.idx for trace in traces), None)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} "
f"eval_step={eval_step} | episodes={len(group)} traces={len(traces)} "
f"(errored={num_errored}) | reward={avg_reward:.4f}"
f"eval_step={eval_step} | episodes={len(group)} dispatch_failures={len(failures)} "
f"traces={len(traces)} (errored={num_errored + len(failures)}) | reward={avg_reward:.4f}"
)
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
env_name, step = key
episodes = self.pending_batches.pop(key, [])
failures = self.pending_batch_failures.pop(key, [])
return EvalBatch(
env_name=env_name,
step=step,
episodes=EvalEpisodes(episodes, group_size=self.group_size_for(env_name)),
failures=failures,
)
+4 -4
View File
@@ -1,7 +1,7 @@
"""EvalSource: trigger-driven, finite-per-epoch pull of eval examples.
The orchestrator pokes ``trigger(step)`` after each ship + once at
startup; the dispatcher pulls via ``next_task()`` until
The policy watcher calls ``trigger(step)`` after each applied policy,
including startup. The dispatcher pulls via ``next_task()`` until
``bool(source) == False``. Constructed only when eval is configured."""
from __future__ import annotations
@@ -37,8 +37,8 @@ class EvalSource:
self.queue: deque[TaskRequest] = deque()
# On resume we skip the startup eval; on fresh start the first
# trigger fires every env (subject to ``skip_first_step``)
# A fresh run evaluates the base policy. Resumed runs apply interval
# rules to the loaded checkpoint and later policies.
self.first_trigger = not is_resumed
def trigger(self, step: int, *, force: bool = False) -> list[str]:
+12 -14
View File
@@ -5,38 +5,36 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import FrozenModelConfig, SamplingConfig
from prime_rl.orchestrator.algo import connect_frozen_pool
from prime_rl.orchestrator.algo import connect_frozen_client
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.utils.client import InferencePool
from prime_rl.orchestrator.clients import InferenceClient
class GenerationSource:
"""One env's generation model and inference pool.
"""One env's generation model and inference clients.
``pool`` is the pool train rollouts are generated from: the policy pool,
swapped for a connected frozen pool in :meth:`setup` when the source is an
inline frozen model. A frozen source *generates* rollouts, so its pool uses
``clients`` is what train rollouts are generated from: the policy clients,
swapped for a connected frozen endpoint in :meth:`setup` when the source is
an inline frozen model. A frozen source *generates* rollouts, so it uses
the renderer (token-in/out) client (built from ``renderer_config``) — the
rollout must carry tokens for training."""
def __init__(
self, config: SamplingConfig, policy_pool: InferencePool, renderer_config: RendererConfig | None = None
):
def __init__(self, config: SamplingConfig, clients: InferenceClient, renderer_config: RendererConfig | None = None):
assert config.source is not None, "sampling.source must be resolved by config validation"
self.config = config
self.pool: InferencePool = policy_pool
self.clients: InferenceClient = clients
self.renderer_config = renderer_config
self.connected_pools: list[InferencePool] = [] # client pools connected in setup(); closed at shutdown
self.connected: InferenceClient | None = None # frozen clients connected in setup(); closed at shutdown
async def setup(self) -> None:
"""Connect a client pool to a frozen generation source and wait for
"""Connect clients to a frozen generation source and wait for
readiness. Must run before dispatching."""
if isinstance(self.config.source, FrozenModelConfig):
self.pool = await connect_frozen_pool(self.config.source, renderer_config=self.renderer_config)
self.connected_pools.append(self.pool)
self.clients = await connect_frozen_client(self.config.source, renderer_config=self.renderer_config)
self.connected = self.clients
@property
def uses_live_policy(self) -> bool:
@@ -7,10 +7,10 @@ from collections.abc import Callable
from dataclasses import dataclass, field
from statistics import mean, median
import wandb
from httpx import AsyncClient
from prometheus_client.parser import text_string_to_metric_families
from prime_rl import monitors
from prime_rl.orchestrator.concurrency import EngineLoadSample
from prime_rl.utils.logger import get_logger
@@ -279,7 +279,7 @@ class InferenceMetricsCollector:
admin_clients: list[AsyncClient],
roles: list[str | None] | None = None,
on_load: Callable[[list[EngineLoadSample]], None] | None = None,
log_to_wandb: bool = True,
log_metrics: bool = True,
):
self.endpoints = build_metrics_endpoints(admin_clients, roles=roles)
self.previous: dict[tuple[str, str], TimedSnapshot] = {}
@@ -287,16 +287,13 @@ class InferenceMetricsCollector:
self.task: asyncio.Task | None = None
self.has_pd_roles = {endpoint.role for endpoint in self.endpoints if endpoint.role is not None} == PD_ROLES
self.on_load = on_load
self.log_to_wandb = log_to_wandb
self.log_metrics = log_metrics
get_logger().info(
"Collecting inference metrics from "
+ ", ".join(f"{endpoint.name}={endpoint.key}" for endpoint in self.endpoints)
)
async def start(self):
if self.log_to_wandb:
wandb.define_metric("inference/*", step_metric="_timestamp")
async def poll_loop():
while True:
try:
@@ -346,7 +343,7 @@ class InferenceMetricsCollector:
return
await asyncio.gather(*[self.fetch_max_model_len(endpoint) for endpoint in self.endpoints])
metrics = self.build_metrics(samples) if self.log_to_wandb else {}
metrics = self.build_metrics(samples) if self.log_metrics else {}
load_samples = [self.build_load_sample(sample) for sample in samples]
for sample in samples:
self.previous[sample.key] = TimedSnapshot(timestamp=sample.timestamp, snapshot=sample.snapshot)
@@ -355,8 +352,10 @@ class InferenceMetricsCollector:
self.on_load(load_samples)
if metrics:
metrics["_timestamp"] = time.time()
wandb.log(metrics)
# Time-keyed rows (step=None): inference metrics are sampled on wall
# time, not the training step. Fans out to every registered monitor;
# each monitor stamps its own timestamp.
await monitors.log(metrics, step=None)
async def fetch_max_model_len(self, endpoint: MetricsEndpoint) -> None:
"""Cache the engine's max context length from ``/v1/models`` (set
+15 -2
View File
@@ -9,11 +9,25 @@ from typing import Any, Literal
import verifiers.v1 as vf
from prime_rl.orchestrator.algo.routing import is_trainable, scalar_advantage
from prime_rl.orchestrator.types import DispatchFailure
from prime_rl.orchestrator.utils import compute_pass_metrics, episode_env_name, episode_group_id
Subset = Literal["all", "effective"]
def dispatch_failure_metrics(failures: list[DispatchFailure], *, prefix: str, total_attempts: int) -> dict[str, float]:
"""Metrics for requests that failed outside the verifier episode boundary."""
if total_attempts == 0:
return {}
out = {f"{prefix}/dispatch_failure/mean": len(failures) / total_attempts}
error_types = [failure.error.type for failure in failures]
out |= {
f"{prefix}/dispatch_failure/{error_type}": float(error_types.count(error_type))
for error_type in sorted(set(error_types))
}
return out
@dataclass(frozen=True)
class TraceRecord:
"""A trace joined with its episode and training selection state.
@@ -317,8 +331,7 @@ class EpisodeMetrics:
def cancelled(self) -> Stat:
"""Per-episode pipeline-cancellation rate — same denominator as
``has_error``. Read from the id-set, not the trace records, so
trace-less episodes (synthetic error episodes inside a voided group)
still count."""
trace-less episodes still count."""
return Stat([float(episode.id in self.cancelled_ids) for episode in self.episodes])
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
+164 -175
View File
@@ -26,27 +26,26 @@ import uuid
from typing import TYPE_CHECKING
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 transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.orchestrator.ckpt import CheckpointManager
from prime_rl.transports.rollouts.base import MicroBatchSender
from prime_rl.transports.batch.base import BatchSender
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
from prime_rl import monitors
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.algo.routing import is_trainable
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.metrics import TrainEpisodes
from prime_rl.orchestrator.metrics import TrainEpisodes, dispatch_failure_metrics
from prime_rl.orchestrator.packing import BatchPacker
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
@@ -56,6 +55,7 @@ from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.train_sink import TrainSink
from prime_rl.orchestrator.train_source import TrainSource
from prime_rl.orchestrator.types import (
DispatchFailure,
EvalBatch,
GroupCancellation,
Policy,
@@ -66,23 +66,19 @@ from prime_rl.orchestrator.utils import (
episode_group_id,
episode_staleness,
eval_work,
get_weight_dir,
intercept_vf_logging,
set_default_executor,
trim_process_memory,
)
from prime_rl.orchestrator.watcher import WeightWatcher
from prime_rl.trainer.model import setup_tokenizer
from prime_rl.transports.rollouts import setup_micro_batch_sender
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
from prime_rl.transports.batch import setup_batch_sender
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
from prime_rl.utils.client import InferencePool, init_nccl_broadcast, init_nixl_broadcast
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.utils import (
clean_exit,
resolve_latest_ckpt_step,
)
from prime_rl.utils.pathing import get_broadcast_dir
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
monkey_patch_oai_iterable_types()
monkey_patch_chat_completion_logprobs()
@@ -121,8 +117,9 @@ class Orchestrator:
# Always set by ``setup()``
tokenizer: PreTrainedTokenizer
policy_inference: InferencePool
sender: MicroBatchSender | None
clients: InferenceClient | None
admin_clients: AdminClients | None
sender: BatchSender | None
packer: BatchPacker
train_envs: TrainEnvs
train_source: TrainSource
@@ -139,7 +136,7 @@ class Orchestrator:
eval_envs: EvalEnvs | None
eval_sink: EvalSink | None
eval_source: EvalSource | None
lora_name: str | None
receiver: WeightReceiver
resume_step: int | None
lag_task: asyncio.Task | None
@@ -165,11 +162,17 @@ class Orchestrator:
self.eval_triggered_at = {}
self.consecutive_empty_batches = 0
self.gate_closed_at = None
# Pulsed by the version hooks so a held ship can re-check ``policy.version``
# Pulsed after inference applies a policy so held work can re-check it.
self.version_advanced = asyncio.Event()
self.wait_for_policy_time = 0.0
self.eval_triggered_steps: set[int] = set()
self.component_tasks = []
# Always assigned by ``setup()``; None-initialized so teardown can run
# on a partially completed setup with plain attribute checks
self.clients = None
self.admin_clients = None
# Optional attributes — ``setup()`` populates them when the relevant
# config is present
self.heart = None
@@ -177,10 +180,8 @@ class Orchestrator:
self.eval_envs = None
self.eval_sink = None
self.eval_source = None
self.lora_name = None
self.resume_step = None
self.lag_task = None
self.model_express = None
# ── lifecycle ──────────────────────────────────────────────────────────
@@ -199,15 +200,17 @@ class Orchestrator:
# references are external endpoints — each env's Algorithm builds its
# own pools in ``setup()`` below.
get_logger().info(f"Initializing policy inference pool ({config.model})")
self.policy_inference = InferencePool(
self.clients = InferenceClient(
config.model.client,
model_name=config.model.name,
train_client_type="renderer",
eval_client_type="openai_chat_completions",
renderer_config=config.renderer,
)
self.admin_clients = AdminClients(config.model.client)
await monitors.setup(
producer="orch",
wandb=config.monitors.wandb,
prime=config.monitors.prime,
file=config.monitors.file,
@@ -230,7 +233,7 @@ class Orchestrator:
self.train_envs = TrainEnvs(
config.train.source,
config.env_addresses,
policy_pool=self.policy_inference,
clients=self.clients,
renderer_config=config.renderer,
)
if config.eval is not None:
@@ -245,8 +248,7 @@ class Orchestrator:
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
self.lora_name = config.model.lora.name if config.model.lora else None
self.policy.model_name = self.clients.model_name
# 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
@@ -261,12 +263,9 @@ class Orchestrator:
# Transports are local setup — initialize them before the env and inference waits.
self.packer = BatchPacker(config)
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
self.sender = setup_micro_batch_sender(
self.sender = setup_batch_sender(
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
)
if config.weight_broadcast.type == "filesystem":
# Nothing to set up client-side — the watcher polls the broadcast dir.
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
# Wait phase: envs, then inference, then the trainer's startup broadcast —
# the last things before the main loop starts.
@@ -290,7 +289,7 @@ class Orchestrator:
get_logger().info("Waiting for policy inference pool to be ready")
t0 = time.perf_counter()
await self.policy_inference.wait_for_ready(config.model.name)
await self.admin_clients.wait_for_ready(config.model.name)
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
# Build + ready pools for each env's frozen generation source and the
# algorithm's frozen reference model
@@ -299,76 +298,28 @@ class Orchestrator:
*(env.algorithm.setup() for env in self.train_envs),
)
# The in-memory broadcast transports rendezvous with live inference
# engines, so their setup must follow pool readiness.
if config.weight_broadcast.type in ("nccl", "nixl"):
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
if config.weight_broadcast.type == "nccl":
await init_nccl_broadcast(
self.policy_inference.admin_clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
inference_world_size=config.weight_broadcast.inference_world_size,
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
)
else:
await init_nixl_broadcast(
self.policy_inference.admin_clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
config.weight_broadcast.inference_world_size,
config.weight_broadcast.session_id,
)
self.model_express = ModelExpressSession(
client=MxClient(server_url=f"{config.weight_broadcast.host}:{config.weight_broadcast.port}"),
role="orchestrator",
rank=0,
session_id=config.weight_broadcast.session_id,
worker_id="orchestrator",
)
self.model_express.publish()
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
get_logger().debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
# A LoRA run's adapter is registered under the base model name: the
# single adapter shadows it (vLLM resolves lora_requests before the
# base-model match), so requests keep addressing one stable name.
self.receiver = setup_weight_receiver(
get_broadcast_dir(config.output_dir),
config.weight_broadcast,
admin_clients=self.admin_clients.clients,
model_name=config.model.name,
)
await self.receiver.initialize()
get_logger().debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
# 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).
# scratch). The startup broadcast is always coming, so wait for it rather
# than failing immediately when it is not there yet.
sync_version = self.resume_step if self.resume_step is not None else 0
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
t0 = time.perf_counter()
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
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
STARTUP_WEIGHT_WAIT_TIMEOUT_S
)
self.eval_source: EvalSource | None = (
EvalSource(
@@ -389,7 +340,7 @@ class Orchestrator:
eval_envs=self.eval_envs,
train_source=self.train_source,
eval_source=self.eval_source,
policy_pool=self.policy_inference,
policy_clients=self.clients,
policy=self.policy,
progress=self.progress,
initial_max_inflight=self.concurrency.max_inflight,
@@ -406,13 +357,12 @@ class Orchestrator:
on_overload=self.dispatcher.cancel_inflight,
)
# The collector always polls — it feeds the concurrency controller;
# W&B mirroring is gated on the registered monitor (the collector logs
# to the global W&B session, which only exists when init succeeded).
# metrics fan out to every registered monitor when collection is on.
self.inference_metrics = InferenceMetricsCollector(
self.policy_inference.admin_clients,
self.admin_clients.clients,
roles=config.inference_metrics_roles,
on_load=self.concurrency.observe,
log_to_wandb=wandb_enabled and config.collect_inference_metrics,
log_metrics=config.collect_inference_metrics,
)
await self.inference_metrics.start()
# One awaited scrape so the concurrency controller derives (and logs) its
@@ -430,14 +380,14 @@ class Orchestrator:
self.eval_sink = EvalSink(eval_envs=self.eval_envs) if self.eval_envs is not None else None
self.watcher = WeightWatcher(
config,
self.receiver,
policy=self.policy,
inference=self.policy_inference,
observers=[self.dispatcher, self],
lora_name=self.lora_name,
ckpt_step=self.policy.version,
model_express=self.model_express,
observers=[self.dispatcher],
ckpt_step=sync_version,
)
if self.eval_source is not None:
self.watcher.on_update(self.trigger_eval)
self.watcher.on_update(self.on_policy_update)
# Single periodic logger for the whole pipeline. It's the only
# consumer of ``dispatcher.metrics.drained()`` (which clears on read)
self.lag_monitor = EventLoopLagMonitor()
@@ -464,6 +414,11 @@ class Orchestrator:
wandb_enabled=wandb_enabled,
)
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
t0 = time.perf_counter()
await self.watcher.sync_startup(sync_version, timeout=wait_timeout)
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
async def start(self) -> None:
"""Run the orchestrator until shutdown. Drives setup, spawns the
background tasks, runs the main loop in this task, then cleans up."""
@@ -483,14 +438,6 @@ class Orchestrator:
asyncio.create_task(self.watcher.start(), name="watcher"),
]
# Base-model eval (policy v0) — fires before any train rollouts, logged at the first
# step, unless ``eval.skip_first_step=True``. On resume, defaults to assuming a clean
# exit (evals already completed); set ``eval.retrigger_on_resume=True`` to also re-fire
# interval-aligned evals at the checkpoint step (e.g. after a crash).
if config.eval is not None and config.eval.retrigger_on_resume and self.resume_step is not None:
self.maybe_trigger_eval(self.resume_step)
self.maybe_trigger_eval(self.progress.step)
# Anchor step-time clock so the first step measures startup → first batch
self.last_batch_at = time.perf_counter()
@@ -529,23 +476,16 @@ class Orchestrator:
get_logger().warning("Orchestrator cleanup complete (forced)")
trim_process_memory()
async def wait_for_final_broadcast(self) -> None:
"""Stay alive for the trainer's last in-memory broadcast (v{max_steps-1};
nothing samples from v{max_steps}, so it is never sent). An in-memory
broadcast is a blocking collective — tearing down the watcher before
the rendezvous would strand the trainer inside it."""
config = self.config
if config.weight_broadcast.type not in ("nccl", "nixl") or config.max_steps is None:
async def wait_for_version(self, version: int, reason: str) -> None:
"""Bounded wait until the watcher has applied v{version}."""
if self.policy.version >= version:
return
final_version = config.max_steps - 1
if self.policy.version >= final_version:
return
get_logger().info(f"Waiting for the trainer's final broadcast (v{final_version}) before shutdown")
get_logger().info(f"Waiting for inference to apply policy v{version} {reason}")
async def wait() -> None:
while self.policy.version < final_version:
while self.policy.version < version:
self.version_advanced.clear()
if self.policy.version >= final_version:
if self.policy.version >= version:
return
# A dead watcher can never deliver the broadcast — fail out
# instead of idling until the timeout.
@@ -555,18 +495,28 @@ class Orchestrator:
except asyncio.TimeoutError:
pass
timeout = self.config.weight_broadcast.timeout
try:
await asyncio.wait_for(wait(), timeout=config.weight_broadcast.timeout)
await asyncio.wait_for(wait(), timeout=timeout)
except asyncio.TimeoutError:
get_logger().warning(
f"Trainer did not broadcast v{final_version} within {config.weight_broadcast.timeout}s — "
"shutting down anyway"
)
get_logger().warning(f"Inference did not apply policy v{version} within {timeout}s — proceeding anyway")
async def wait_for_final_broadcast(self) -> None:
"""Stay alive for the trainer's last broadcast. Every broadcast is a
blocking rendezvous — tearing down the watcher before it would strand
the trainer inside the handshake."""
if self.config.max_steps is None:
return
await self.wait_for_version(self.config.max_steps, reason="before shutdown")
async def main_loop(self) -> None:
"""Consume completed episodes and ``GroupCancellation`` events from the
dispatcher and route them to the train / eval sink. The sinks return a
finalized batch (or ``None``); we just dispatch on the result."""
"""Consume dispatcher results and route them to the train / eval sink.
Native episodes are persisted as verifier artifacts. Dispatch failures
and group cancellations remain internal accounting events.
The sinks return a finalized batch (or ``None``); we just dispatch on
the result."""
while not self.stopped.is_set():
self._raise_if_component_stopped()
if self.draining and self.dispatcher.is_idle:
@@ -586,6 +536,17 @@ class Orchestrator:
if train_batch is not None and not self.draining and not self.stopped.is_set():
await self.finalize_train_batch(train_batch)
continue
if isinstance(item, DispatchFailure):
if item.kind == "eval":
assert self.eval_sink is not None
eval_batch = self.eval_sink.fail(item)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
else:
train_batch = await self.train_sink.fail(item)
if train_batch is not None and not self.draining and not self.stopped.is_set():
await self.finalize_train_batch(train_batch)
continue
episode = item
# Every completed rollout — errored, rejected, or never batched — lands in the
@@ -668,16 +629,16 @@ class Orchestrator:
f"({n_trainable / effective.num_traces:.1%}) — consider reviewing task difficulty"
)
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
# Ship batch ``step`` only once inference has applied v{step-1-TARGET_LAG}.
# Without this, fast envs fill batches from buffered rollouts and the
# orchestrator races arbitrarily far ahead of the trainer. Always
# satisfiable: the trainer broadcasts every version except v{max_steps},
# and ``wait_for_final_broadcast`` keeps the watcher alive through the
# last rendezvous after the pipeline drains.
# satisfiable: the trainer broadcasts every version, and
# ``wait_for_final_broadcast`` keeps the watcher alive through the last
# rendezvous after the pipeline drains.
required_version = step - 1 - TARGET_LAG
if self.policy.version < required_version:
get_logger().info(
f"Holding batch {step} until the trainer publishes policy v{required_version} "
f"Holding batch {step} until inference applies policy v{required_version} "
f"(currently v{self.policy.version})"
)
hold_start = time.perf_counter()
@@ -709,6 +670,20 @@ class Orchestrator:
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
for env_name, env_pool in pool.by_env().items():
metrics |= env_pool.metrics.to_wandb(prefix=f"train/{env_name}", subset=subset)
total_attempts = len(batch.episodes) + len(batch.failures)
metrics |= dispatch_failure_metrics(batch.failures, prefix="train/agg/all", total_attempts=total_attempts)
failures_by_env: dict[str, list[DispatchFailure]] = {}
for failure in batch.failures:
failures_by_env.setdefault(failure.env_name, []).append(failure)
episodes_by_env = batch.episodes.by_env()
for env_name in set(episodes_by_env) | set(failures_by_env):
env_failures = failures_by_env.get(env_name, [])
env_attempts = len(episodes_by_env.get(env_name, TrainEpisodes())) + len(env_failures)
metrics |= dispatch_failure_metrics(
env_failures,
prefix=f"train/{env_name}/all",
total_attempts=env_attempts,
)
# Progress / timing / env-share accounting (assembled here, not in the metrics
# objects). ``num_tokens`` is over the full arrival window; the input/output breakdown is over
@@ -718,7 +693,9 @@ class Orchestrator:
num_input = sum(record.trace.num_input_tokens for record in effective.records)
num_output = sum(record.trace.num_output_tokens for record in effective.records)
num_rollouts = batch.episodes.num_traces
num_unique_examples = len({episode_group_id(episode) for episode in batch.episodes})
group_ids = {episode_group_id(episode) for episode in batch.episodes}
group_ids.update(failure.group_id for failure in batch.failures)
num_unique_examples = len(group_ids)
metrics |= {
"progress/tokens": num_tokens,
"progress/input_tokens": num_input,
@@ -765,7 +742,8 @@ class Orchestrator:
self.log_train_batch(batch, step=step, step_time=step_time)
self.maybe_trigger_eval(self.progress.step)
if config.max_steps is not None and step >= config.max_steps:
await self.wait_for_version(step, reason="before shutdown")
# Drain right after shipping the final batch. Waiting for a further
# batch to fill would burn inference on data that can never train —
# and with a tight ``max_off_policy_steps`` it never fills at all (the
@@ -785,14 +763,18 @@ class Orchestrator:
f"train episode(s); any in-flight evals will complete)"
)
def maybe_trigger_eval(self, step: int) -> None:
async def trigger_eval(self, step: int) -> None:
"""Fire eligible eval epochs and flip to ``PREFER_EVAL`` if anything
fires. No-op when eval is not configured."""
if self.eval_source is None:
if self.eval_source is None or step in self.eval_triggered_steps:
return
fired = self.eval_source.trigger(step)
if self.resume_step == step and self.config.eval is not None and not self.config.eval.retrigger_on_resume:
return
is_final = self.config.max_steps is not None and step >= self.config.max_steps
fired = self.eval_source.trigger(step, force=is_final)
if not fired:
return
self.eval_triggered_steps.add(step)
reason = f"eval was triggered at step {step}"
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=reason)
now = time.perf_counter()
@@ -872,10 +854,10 @@ class Orchestrator:
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
Every quality metric (Reward, Trainable, Turns, Branches, Max Off-Policy, Truncation) is
computed over exactly the traces shipped to the trainer this step (``batch.cohort``).
``Error``, ``Cancelled``, and ``Ratio`` are rates over the step's full arrival window —
``Error``, ``Dispatch Failure``, ``Cancelled``, and ``Ratio`` describe the step's full arrival window —
over the shipped set they are 0/0/share-of-shipped by construction, so the window is the
only scope where they carry signal (and they stay disjoint: a cancellation is a pipeline
decision, not a rollout failure)."""
decision, an episode error came from the environment, and a dispatch failure produced no episode)."""
episodes = batch.episodes
effective = batch.cohort.effective
eff = effective.metrics
@@ -884,13 +866,16 @@ class Orchestrator:
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
trainable_rate = (n_trainable / n_effective) if n_effective else 0.0
max_off_policy_steps = max((episode_staleness(episode, step)[0] for episode in effective), default=0)
num_attempts = len(episodes) + len(batch.failures)
dispatch_failure_rate = len(batch.failures) / num_attempts if num_attempts else 0.0
head = (
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
f"Trainable {n_trainable}/{n_effective} ({trainable_rate:.1%}) | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max_off_policy_steps} | "
f"Error {episodes.metrics.has_error.mean():.1%} | Cancelled {episodes.metrics.cancelled.mean():.1%} | "
f"Error {episodes.metrics.has_error.mean():.1%} | Dispatch Failure {dispatch_failure_rate:.1%} | "
f"Cancelled {episodes.metrics.cancelled.mean():.1%} | "
f"Truncation {eff.is_truncated.mean():.1%}"
)
if len(self.train_envs) <= 1:
@@ -899,7 +884,10 @@ class Orchestrator:
window_by_env = episodes.by_env()
shipped_by_env = effective.by_env()
env_names = sorted(set(window_by_env) | set(shipped_by_env))
failures_by_env: dict[str, list[DispatchFailure]] = {}
for failure in batch.failures:
failures_by_env.setdefault(failure.env_name, []).append(failure)
env_names = sorted(set(window_by_env) | set(shipped_by_env) | set(failures_by_env))
name_width = max((len(name) for name in env_names), default=0)
lines = [head]
for env_name in env_names:
@@ -907,34 +895,36 @@ class Orchestrator:
env_eff_pool = shipped_by_env.get(env_name, TrainEpisodes())
env_eff = env_eff_pool.metrics
ratio = (pool.num_traces / n_generated) if n_generated else 0.0
env_failures = failures_by_env.get(env_name, [])
env_attempts = len(pool) + len(env_failures)
env_failure_rate = len(env_failures) / env_attempts if env_attempts else 0.0
lines.append(
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_eff.reward.mean():.4f} | "
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max((episode_staleness(episode, step)[0] for episode in env_eff_pool), default=0)} | "
f"Error {pool.metrics.has_error.mean():.1%} | Cancelled {pool.metrics.cancelled.mean():.1%} | "
f"Error {pool.metrics.has_error.mean():.1%} | Dispatch Failure {env_failure_rate:.1%} | "
f"Cancelled {pool.metrics.cancelled.mean():.1%} | "
f"Truncation {env_eff.is_truncated.mean():.1%}"
)
get_logger().success("\n\t\t ".join(lines))
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors."""
if not batch.episodes:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no episodes returned, skipping log")
if not batch.episodes and not batch.failures:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
return
# The non-errored subset is logged on epoch completion (multiple eval envs share the
# step's trace file — each epoch appends its cohort once, and every record carries
# ``env_name``); the full returned cohort already streamed into ``all`` on arrival.
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
if batch.episodes.effective:
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
policy_spans = [eval_work(episode).policy for episode in batch.episodes]
if any(span is None for span in policy_spans):
raise ValueError(f"Eval {batch.env_name} step {batch.step} is missing policy provenance")
policy_versions = {span.start for span in policy_spans if span is not None}
policy_versions.update(failure.policy_version for failure in batch.failures)
policy_version = min(policy_versions)
if len(policy_versions) > 1:
get_logger().warning(
f"Eval {batch.env_name} step {batch.step} had mixed policy versions: {sorted(policy_versions)}"
)
# Episode metrics over {all,effective} (eval batches are per-env, so no `agg` axis).
# ``effective`` = non-errored; pass@k / pass^k only over the effective set.
episodes = batch.episodes
@@ -942,6 +932,12 @@ class Orchestrator:
metrics: dict[str, float] = {}
for subset, pool in (("all", episodes), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
total_attempts = len(episodes) + len(batch.failures)
metrics |= dispatch_failure_metrics(
batch.failures,
prefix=f"eval/{batch.env_name}/all",
total_attempts=total_attempts,
)
metrics[f"eval/{batch.env_name}/policy_version"] = float(policy_version)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
@@ -952,7 +948,7 @@ class Orchestrator:
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
get_logger().success(
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"Evaluated {batch.env_name} | "
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
@@ -989,7 +985,7 @@ class Orchestrator:
if lead > TARGET_LAG:
if was_set:
get_logger().info(
f"Pausing dispatcher until the trainer publishes policy v{self.progress.step - 1 - TARGET_LAG} "
f"Pausing dispatcher until inference applies policy v{self.progress.step - 1 - TARGET_LAG} "
f"(currently v{self.policy.version})"
)
self.gate_closed_at = time.perf_counter()
@@ -1002,19 +998,10 @@ class Orchestrator:
self.gate_closed_at = None
gate.set()
async def on_version_pending(self, step: int) -> None:
"""``VersionObserver`` hook, fired at publish confirmation (pre-apply):
``policy.version`` already carries the new version, so wake a held ship."""
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
self.version_advanced.set()
async def on_new_version(self, step: int) -> None:
"""``VersionObserver`` hook: the weight update completed;
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
async def on_policy_update(self, _step: int) -> None:
"""Refresh policy-dependent state after inference applies new weights."""
self.update_dispatch_gate()
self.version_advanced.set()
async def stop(self) -> None:
"""Bounded best-effort teardown of all components. Has a global
@@ -1041,14 +1028,16 @@ class Orchestrator:
if self.inference_metrics is not None:
get_logger().debug("Stopping inference metrics collector")
await self.inference_metrics.stop()
if getattr(self, "policy_inference", None) is not None:
get_logger().debug("Stopping policy inference pool")
await self.policy_inference.stop()
if self.clients is not None:
await self.clients.aclose()
if self.admin_clients is not None:
await self.admin_clients.aclose()
if self.train_envs is not None:
get_logger().debug("Stopping generation source and algorithm pools")
get_logger().debug("Stopping generation source and algorithm clients")
for env in self.train_envs:
for pool in (*env.generation_source.connected_pools, *env.algorithm.connected_pools):
await pool.stop()
for clients in (env.generation_source.connected, env.algorithm.connected):
if clients is not None:
await clients.aclose()
get_logger().info("Stopping orchestrator components")
t0 = time.perf_counter()
+1 -1
View File
@@ -2,7 +2,7 @@ from transformers import AutoConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
from prime_rl.transports.rollouts.types import MicroBatch, TrainingSample
from prime_rl.transports.batch.types import MicroBatch, TrainingSample
from prime_rl.utils.logger import get_logger
+39 -15
View File
@@ -1,10 +1,10 @@
"""Training-side episode, group, and batch assembly.
``add()`` takes one completed episode and ``cancel()`` a dropped group's
``GroupCancellation``; both return ``TrainBatch | None``. Before every readiness
check the sink sweeps ``pending_batch`` for traces past ``max_off_policy_steps`` —
this sweep, not the dispatcher's in-flight cancel, is what guarantees nothing
stale ships."""
``add()`` takes one completed episode, ``fail()`` a request that produced no
episode, and ``cancel()`` a dropped group's ``GroupCancellation``. Before every
readiness check the sink sweeps ``pending_batch`` for traces past
``max_off_policy_steps`` — this sweep, not the dispatcher's in-flight cancel,
is what guarantees nothing stale ships."""
from __future__ import annotations
@@ -20,9 +20,9 @@ from prime_rl.orchestrator.algo.routing import stamp_loss_routing
from prime_rl.orchestrator.envs import TrainEnvs
from prime_rl.orchestrator.metrics import TrainEpisodes
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.orchestrator.types import GroupCancellation, Progress, TrainBatch
from prime_rl.orchestrator.types import DispatchFailure, GroupCancellation, Progress, TrainBatch
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, min_fresh_version, train_work
from prime_rl.transports.rollouts import TrainingSample
from prime_rl.transports.batch import TrainingSample
from prime_rl.utils.logger import get_logger
MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS = 10
@@ -87,7 +87,9 @@ class TrainSink:
self.on_result = on_result
self.pending_episodes = TrainEpisodes()
self.pending_failures: list[DispatchFailure] = []
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
self.pending_group_failures: dict[str, list[DispatchFailure]] = defaultdict(list)
# A dropped group's terminal marker; its ``count`` fills in for the
# episodes the group will never deliver.
self.pending_group_cancellations: dict[str, GroupCancellation] = {}
@@ -113,7 +115,9 @@ class TrainSink:
return self.pending_tokens, self.token_batch_size, "tokens"
def buffered_count(self) -> int:
return sum(len(group) for group in self.pending_groups.values())
episodes = sum(len(group) for group in self.pending_groups.values())
failures = sum(len(group) for group in self.pending_group_failures.values())
return episodes + failures
def pending_batch_by_env(self) -> dict[str, int]:
counts: dict[str, int] = defaultdict(int)
@@ -145,10 +149,22 @@ class TrainSink:
await self.process_group(cancellation.group_id)
return self._maybe_batch()
async def fail(self, failure: DispatchFailure) -> TrainBatch | None:
"""Count a request failure toward its group without presenting it as
an episode to the algorithm or curriculum."""
if failure.kind != "train":
raise ValueError(f"TrainSink cannot process a {failure.kind} dispatch failure")
self.pending_group_failures[failure.group_id].append(failure)
if not self._group_complete(failure.group_id, failure.env_name):
return None
await self.process_group(failure.group_id)
return self._maybe_batch()
def _group_complete(self, group_id: str, env_name: str) -> bool:
cancellation = self.pending_group_cancellations.get(group_id)
cancelled = cancellation.count if cancellation is not None else 0
return len(self.pending_groups[group_id]) + cancelled >= self.group_size_for(env_name)
failed = len(self.pending_group_failures[group_id])
return len(self.pending_groups[group_id]) + failed + cancelled >= self.group_size_for(env_name)
def _maybe_batch(self) -> TrainBatch | None:
"""Sweep stale queued traces, then cut a batch if the survivors still
@@ -209,18 +225,24 @@ class TrainSink:
async def process_group(self, group_id: str) -> None:
group = self.pending_groups.pop(group_id, [])
failures = self.pending_group_failures.pop(group_id, [])
cancellation = self.pending_group_cancellations.pop(group_id, None)
if not group and cancellation is None:
if not group and not failures and cancellation is None:
return
env_name = episode_env_name(group[0]) if group else cancellation.env_name
env_name = (
episode_env_name(group[0]) if group else (failures[0].env_name if failures else cancellation.env_name)
)
env = self.train_envs.get(env_name)
traces = [trace for episode in group for trace in episode.traces]
task_idx = next((trace.task.data.idx for trace in traces), None)
num_errored = sum(trace.has_error for trace in traces) + sum(
not episode.ok for episode in group if not episode.traces
num_errored = (
sum(trace.has_error for trace in traces)
+ sum(not episode.ok for episode in group if not episode.traces)
+ len(failures)
)
n_owed = len(group) + (cancellation.count if cancellation is not None else 0)
n_owed = len(group) + len(failures) + (cancellation.count if cancellation is not None else 0)
self.pending_failures.extend(failures)
# A stale drop voids the whole group: every member shares the dispatch
# version, so the arrived episodes are exactly as stale as the
@@ -367,6 +389,8 @@ class TrainSink:
cohort = TrainEpisodes(cohort_episodes, sampled_trace_ids=shipped_ids)
episodes = self.pending_episodes
failures = self.pending_failures
if samples:
self.pending_episodes = TrainEpisodes()
return TrainBatch(episodes=episodes, cohort=cohort, samples=samples)
self.pending_failures = []
return TrainBatch(episodes=episodes, cohort=cohort, samples=samples, failures=failures)
+2 -2
View File
@@ -20,8 +20,8 @@ from collections.abc import Iterator
import numpy as np
import verifiers.v1 as vf
from prime_rl.transports.rollouts import TrainingSample
from prime_rl.transports.rollouts.types import EncodedTensor, RoutedExperts
from prime_rl.transports.batch import TrainingSample
from prime_rl.transports.batch.types import EncodedTensor, RoutedExperts
from prime_rl.utils.logger import get_logger
+26 -7
View File
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Literal, Protocol, TypeAlias
import verifiers.v1 as vf
from prime_rl.transports.rollouts import TrainingSample
from prime_rl.transports.batch import TrainingSample
if TYPE_CHECKING:
from prime_rl.orchestrator.metrics import EvalEpisodes, TrainEpisodes
@@ -52,7 +52,22 @@ class GroupCancellation:
reason: CancelReason
DispatchResult: TypeAlias = vf.WireEpisode | GroupCancellation
@dataclass(frozen=True)
class DispatchFailure:
"""An environment request that failed before producing an episode."""
kind: WorkKind
env_name: str
group_id: str
step: int
policy_version: int
task_type: str
task_key: str
task_hash: str
error: vf.Error
DispatchResult: TypeAlias = vf.WireEpisode | DispatchFailure | GroupCancellation
@dataclass(frozen=True)
@@ -81,7 +96,7 @@ class InflightEpisode:
@dataclass
class GroupState:
"""Per-group dispatcher state with pinned run context and client."""
"""Per-group dispatcher state with its pinned run step."""
kind: WorkKind
env_name: str
@@ -91,27 +106,31 @@ class GroupState:
episodes_to_schedule: int
target_episodes: int
emitted: int = 0
pinned_client: vf.ClientConfig | None = None
policy_version_at_start: int = 0
@dataclass
class TrainBatch:
"""Observation and shipped-cohort reports plus the trainer payload."""
"""Returned episodes, dispatch failures, shipped cohort, and trainer payload."""
episodes: TrainEpisodes
cohort: TrainEpisodes
samples: list[TrainingSample]
failures: list[DispatchFailure]
@dataclass
class EvalBatch:
"""One env's eval epoch. ``episodes`` is the full returned cohort (errored included); its
``.effective`` / ``.metrics`` views drive logging."""
"""One env's eval epoch.
``episodes`` is the full returned cohort (errored included), while
``failures`` accounts for requests that returned no verifier artifact.
"""
env_name: str
step: int
episodes: EvalEpisodes
failures: list[DispatchFailure]
class VersionObserver(Protocol):
-52
View File
@@ -3,19 +3,12 @@ import ctypes
import gc
import logging
import math
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any
import verifiers.v1 as vf
from prime_rl.utils.logger import InterceptHandler, get_logger, setup_logger
from prime_rl.utils.utils import (
get_broadcast_dir,
get_ckpt_dir,
get_step_path,
)
def episode_env_name(episode: vf.Episode[Any, Any, Any]) -> str:
@@ -101,51 +94,6 @@ def trim_process_memory() -> None:
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
def get_weight_dir(output_dir: Path, step: int, check_exists: bool = True, wait_timeout: int | None = None) -> Path:
"""Get the weight directory for a given checkpoint step.
Args:
output_dir: The output directory for the run.
step: The checkpoint step.
check_exists: If True, raises FileNotFoundError if no weight directory exists.
If False, returns the broadcast directory path without checking existence
(useful for NCCL mode where weights are broadcasted, not stored on disk).
wait_timeout: Maximum time in seconds to wait for a stable directory to appear.
If None, no waiting is performed.
"""
ckpt_weight_dir = get_step_path(get_ckpt_dir(output_dir), step) / "weight"
broadcast_weight_dir = get_step_path(get_broadcast_dir(output_dir), step)
def find_stable_dir() -> Path | None:
# For checkpoint weights, check STABLE file in parent directory (checkpoints/step_{step}/STABLE)
ckpt_step_dir = get_step_path(get_ckpt_dir(output_dir), step)
if (ckpt_step_dir / "STABLE").exists() and ckpt_weight_dir.exists():
return ckpt_weight_dir
# For broadcast weights, check STABLE file in the broadcast directory itself
if (broadcast_weight_dir / "STABLE").exists() and broadcast_weight_dir.exists():
return broadcast_weight_dir
return None
# Check immediately, then wait if needed
result = find_stable_dir()
if result is None and wait_timeout:
start_time = time.time()
while time.time() - start_time < wait_timeout:
time.sleep(1)
result = find_stable_dir()
if result:
break
if result:
return result
if not check_exists:
return broadcast_weight_dir
raise FileNotFoundError(f"No weight directory found for checkpoint step {step}")
def compute_pass_metrics(rewards: list[float]) -> dict[str, float]:
"""Unbiased pass@k and pass^k for one example's binary (0/1) rewards.
+35 -73
View File
@@ -1,22 +1,17 @@
"""WeightWatcher: polls the broadcast dir, advances ``Policy``, notifies
observers (dispatcher → staleness cancel). Standalone async task; the
orchestrator's barrier bounds the in-flight lead."""
"""WeightWatcher: discovers new policy versions via the transport's receiver,
advances ``Policy``, and notifies observers (dispatcher → staleness cancel).
Standalone async task; the orchestrator's barrier bounds the in-flight lead."""
from __future__ import annotations
import asyncio
import time
from collections.abc import Awaitable, Callable
from modelexpress import p2p_pb2
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.types import Policy, VersionObserver
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
from prime_rl.transports.weights import WeightReceiver
from prime_rl.utils.async_utils import safe_cancel
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_broadcast_dir, get_step_path, wait_for_path
from prime_rl.utils.utils import get_latest_ckpt_step
class WeightWatcher:
@@ -24,24 +19,18 @@ class WeightWatcher:
def __init__(
self,
config: OrchestratorConfig,
receiver: WeightReceiver,
*,
policy: Policy,
inference: InferencePool,
observers: list[VersionObserver],
lora_name: str | None,
ckpt_step: int = 0,
poll_interval: float = 1.0,
model_express: ModelExpressSession | None = None,
) -> None:
self.config = config
self.receiver = receiver
self.policy = policy
self.inference = inference
self.observers = observers
self.lora_name = lora_name
self.ckpt_step = ckpt_step
self.poll_interval = poll_interval
self.model_express = model_express
self.last_update_weights_time: float = 0.0
self.last_wait_for_ckpt_time: float = 0.0
@@ -50,12 +39,25 @@ class WeightWatcher:
self.task: asyncio.Task | None = None
self.update_lock = asyncio.Lock()
self.stopped = asyncio.Event()
self.update_hooks: list[Callable[[int], Awaitable[None]]] = []
def on_update(self, hook: Callable[[int], Awaitable[None]]) -> None:
"""Register an async hook that runs after inference applies new weights."""
self.update_hooks.append(hook)
async def sync_startup(self, step: int, timeout: float) -> None:
"""Apply the startup policy and notify the registered update hooks."""
async with self.update_lock:
await self.receiver.sync_startup(step, timeout)
self.ckpt_step = step
self.policy.version = step
await self._notify_update(step)
async def start(self) -> None:
self.task = asyncio.current_task()
try:
while not self.stopped.is_set():
next_step = self.compute_next_ckpt_step()
next_step = self.receiver.next_version(self.ckpt_step)
if next_step > self.ckpt_step:
await self.apply_policy_update(next_step)
await asyncio.sleep(self.poll_interval)
@@ -74,20 +76,6 @@ class WeightWatcher:
await safe_cancel(self.task)
self.task = None
def compute_next_ckpt_step(self) -> int:
"""Return the next policy version exposed by the configured transport."""
if self.model_express is not None:
# The trainer broadcasts every version except v{max_steps}.
if self.config.max_steps is not None and self.ckpt_step >= self.config.max_steps - 1:
return self.ckpt_step
# ModelExpress status changes are unversioned, so its rendezvous advances
# exactly one policy version per READY/INITIALIZING cycle.
return self.ckpt_step + 1
broadcast_dir = get_broadcast_dir(self.config.output_dir)
latest_ckpt_step = get_latest_ckpt_step(broadcast_dir) or 0
return max(self.policy.version, latest_ckpt_step)
async def apply_policy_update(self, next_step: int) -> None:
async with self.update_lock:
if next_step <= self.ckpt_step:
@@ -95,24 +83,12 @@ class WeightWatcher:
return
t0 = time.perf_counter()
weights_path = None
if self.model_express is not None:
await self.wait_for_model_express_status(p2p_pb2.SOURCE_STATUS_READY)
else:
broadcast_dir = get_broadcast_dir(self.config.output_dir)
weights_path = get_step_path(broadcast_dir, next_step)
stable_marker = weights_path / "STABLE"
if not stable_marker.exists():
get_logger().info(f"Waiting for the trainer to broadcast policy v{next_step}")
await wait_for_path(stable_marker)
await self.receiver.wait_published(next_step, cancelled=self.stopped.is_set)
self.last_wait_for_ckpt_time = time.perf_counter() - t0
# Publish confirmed: the policy version advances here, before the
# apply — inference pauses during the update, so nothing can generate
# under the new number from the old weights, and a ship held on this
# version releases without waiting out the inference weight reload.
# Record the published version before notifying pending observers.
# ``policy.version`` advances only after inference applies it.
self.ckpt_step = next_step
self.policy.version = next_step
# Drain stale rollouts BEFORE pausing the inference engines.
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
@@ -134,39 +110,25 @@ class WeightWatcher:
get_logger().debug(f"Updating inference weights to policy v{next_step}")
t1 = time.perf_counter()
await self.inference.update_weights(weights_path, lora_name=self.lora_name, step=next_step)
await self.receiver.receive(next_step)
self.last_update_weights_time = time.perf_counter() - t1
self.update_count += 1
self.policy.version = next_step
get_logger().debug(
f"Updated inference weights to policy v{next_step} in {format_time(self.last_update_weights_time)}"
)
if self.lora_name is not None:
self.inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
await self._notify_update(next_step)
for observer in self.observers:
try:
await observer.on_new_version(next_step)
except Exception as exc:
get_logger().warning(
f"Observer {type(observer).__name__}.on_new_version({next_step}) raised: {exc!r}"
)
async def _notify_update(self, step: int) -> None:
for observer in self.observers:
try:
await observer.on_new_version(step)
except Exception as exc:
get_logger().warning(f"Observer {type(observer).__name__}.on_new_version({step}) raised: {exc!r}")
if self.model_express is not None:
await self.wait_for_model_express_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
async def wait_for_model_express_status(self, status: int) -> None:
while not self.stopped.is_set():
found = await asyncio.to_thread(
self.model_express.exists_role_with_status,
"trainer",
status,
)
if found:
return
await asyncio.sleep(self.poll_interval)
raise asyncio.CancelledError
for hook in self.update_hooks:
await hook(step)
def gauges(self) -> dict[str, float]:
return {
+2 -2
View File
@@ -18,8 +18,8 @@
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
# Exit immediately on any failed command so a crash anywhere releases the
# allocation instead of leaving zombie processes holding nodes.
+67 -27
View File
@@ -18,8 +18,8 @@
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
# Exit immediately on any failed command so a crash anywhere releases the
# allocation instead of leaving zombie processes holding nodes.
@@ -58,6 +58,7 @@ export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parall
export PROJECT_DIR={{ project_dir }}
export CONFIG_DIR={{ config_dir }}
export OUTPUT_DIR={{ output_dir }}
export LAUNCHER_DIR={{ launcher_dir }}
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
ATTEMPT=1
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
@@ -67,6 +68,16 @@ ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
ln -sfn inference/node_0.log $LOG_DIR/inference.log
# Clean exits do not trigger srun --kill-on-bad-exit. Each terminal component
# publishes its successful exit through the shared launcher directory. Every node
# uses the same completion condition before it tears down support processes.
export TRAINER_DONE=$LAUNCHER_DIR/.trainer.done
{% if num_infer_nodes > 0 -%}
export ORCHESTRATOR_DONE=$LAUNCHER_DIR/.orchestrator.done
{% endif -%}
mkdir -p "$LAUNCHER_DIR"
rm -f "$TRAINER_DONE"{% if num_infer_nodes > 0 %} "$ORCHESTRATOR_DONE"{% endif %}
export PRL_RUN_ID=${PRL_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")}
export PRL_RUN_NAME={{ run_name }}
export WANDB_RUN_ID=$PRL_RUN_ID
@@ -400,21 +411,28 @@ else
echo $HOSTNAMES_STR | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
WANDB_SHARED_LABEL=trainer uv run torchrun \
--role=trainer \
--nnodes=$NUM_TRAIN_NODES \
--nproc-per-node=$GPUS_PER_NODE \
--node-rank=$TRAIN_NODE_RANK \
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
--rdzv-id=job_$SLURM_JOB_ID \
--log-dir=$LOG_DIR/trainer/torchrun \
--tee=3 \
--redirects=3 \
--local-ranks-filter={{ ranks_filter }} \
-m prime_rl.trainer.rl.train \
@ $CONFIG_DIR/trainer.json \
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log &
(
WANDB_SHARED_LABEL=trainer uv run torchrun \
--role=trainer \
--nnodes=$NUM_TRAIN_NODES \
--nproc-per-node=$GPUS_PER_NODE \
--node-rank=$TRAIN_NODE_RANK \
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
--rdzv-id=job_$SLURM_JOB_ID \
--log-dir=$LOG_DIR/trainer/torchrun \
--tee=3 \
--redirects=3 \
--local-ranks-filter={{ ranks_filter }} \
-m prime_rl.trainer.rl.train \
@ $CONFIG_DIR/trainer.json \
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
COMPONENT_CODE=$?
if [ "$COMPONENT_CODE" -eq 0 ] && [ "$TRAIN_NODE_RANK" -eq 0 ]; then
touch "$TRAINER_DONE" || exit $?
fi
exit "$COMPONENT_CODE"
) &
{% if num_infer_nodes > 0 %} fi{% endif %}
{% if num_infer_nodes > 0 %}
# Launch the orchestrator on the node ORCH_ADDR points at (see the ORCH_PROCID
@@ -450,19 +468,41 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
{%- endfor %}
{%- endif %}
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $LOG_DIR/orchestrator.log &
(
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $LOG_DIR/orchestrator.log
COMPONENT_CODE=$?
if [ "$COMPONENT_CODE" -eq 0 ]; then
touch "$ORCHESTRATOR_DONE" || exit $?
fi
exit "$COMPONENT_CODE"
) &
fi
{% endif %}
# Wait for the first background job to exit and propagate its exit code. This
# turns background process crashes (router, orchestrator) into task failures
# that --kill-on-bad-exit=1 can broadcast to the other nodes so the whole job
# tears down instead of leaving zombies holding the allocation.
wait -n
EXIT_CODE=$?
# Every node watches the terminal components for successful completion.
{% if num_infer_nodes > 0 -%}
# Inference runs stop after both the trainer and orchestrator finish.
( until [ -f "$TRAINER_DONE" ] && [ -f "$ORCHESTRATOR_DONE" ]; do sleep 10; done ) &
{% else -%}
# Trainer-only runs stop when the trainer finishes.
( until [ -f "$TRAINER_DONE" ]; do sleep 10; done ) &
{% endif -%}
COMPLETION_PID=$!
# A clean component exit is not enough to stop the run. Keep waiting for the
# shared completion condition. Propagate any failure through
# --kill-on-bad-exit=1 so every node tears down.
while true; do
wait -n -p FINISHED_PID
EXIT_CODE=$?
if [ "$EXIT_CODE" -ne 0 ] || [ "${FINISHED_PID:-}" = "$COMPLETION_PID" ]; then
break
fi
done
REMAINING_PIDS=$(jobs -p)
{%- if cleanup_grace_period %}
# Cross-node teardown is driven by `srun --kill-on-bad-exit=1`, which reaps peer
+186 -70
View File
@@ -1,7 +1,7 @@
#!/bin/bash
#SBATCH --job-name={{ job_name }}
#SBATCH --nodes={{ num_nodes }}
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --partition={{ partition }}
@@ -18,21 +18,31 @@
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
# Exit immediately on any failed command so a crash on any node releases the
# allocation instead of leaving zombie processes holding nodes.
set -e
# Configs
export NUM_NODES={{ num_nodes }}
export NUM_TRAIN_NODES={{ num_train_nodes }}
export NUM_INFER_NODES={{ num_infer_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
{% if online_eval -%}
export ROUTER_PORT={{ router_port }}
export BACKEND_PORT={{ backend_port }}
export RPC_PORT={{ data_parallel_rpc_port }}
export DP_PER_NODE={{ dp_per_node }}
{%- endif %}
# Paths
export PROJECT_DIR={{ project_dir }}
export CONFIG_PATH={{ config_path }}
export CONFIG_DIR={{ config_dir }}
export TRAIN_CONFIG_PATH={{ config_path }}
export OUTPUT_DIR={{ output_dir }}
export LAUNCHER_DIR={{ launcher_dir }}
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
ATTEMPT=1
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
@@ -40,72 +50,90 @@ export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
mkdir -p $LOG_DIR/trainer
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
{% if online_eval -%}
mkdir -p $LOG_DIR/inference
ln -sfn inference/node_0.log $LOG_DIR/inference.log
{% endif %}
# Clean exits do not trigger srun --kill-on-bad-exit. Each terminal role
# publishes its successful exit so every node uses the same completion condition.
export TRAINER_DONE=$LAUNCHER_DIR/.sft_trainer_done_$SLURM_JOB_ID
{% if online_eval -%}
export EVAL_DONE=$LAUNCHER_DIR/.sft_eval_done_$SLURM_JOB_ID
{%- endif %}
mkdir -p "$LAUNCHER_DIR"
rm -f "$TRAINER_DONE"{% if online_eval %} "$EVAL_DONE"{% endif %}
{% if prl_run_id %}
# Trainer and evals (separate SLURM job) log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
# outlives the trainer) finalizes it.
# Trainer and evals log to one shared W&B run. The trainer creates the run,
# and the evals process finalizes it after the final epoch.
export PRL_RUN_ID={{ prl_run_id }}
export PRL_RUN_NAME={{ run_name }}
export WANDB_RUN_ID=$PRL_RUN_ID
export WANDB_SHARED_MODE=1
export WANDB_SHARED_PRIMARY=trainer
export WANDB_SHARED_FINISHER=evals
export WANDB_SHARED_LABEL=trainer
export WANDB_PROGRAM="uv run sft"
{% endif %}
# Networking
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
echo "HOSTNAMES=${HOSTNAMES[@]}"
export MASTER_ADDR="${HOSTNAMES[0]}"
# Networking. Inference nodes occupy the first ranks, followed by trainer nodes.
HOSTNAMES=( $(scontrol show hostnames $SLURM_JOB_NODELIST) )
TRAIN_HOSTS=( ${HOSTNAMES[@]:$NUM_INFER_NODES:$NUM_TRAIN_NODES} )
export ALL_HOSTNAMES_STR="${HOSTNAMES[*]}"
export MASTER_ADDR="${TRAIN_HOSTS[0]}"
export MASTER_PORT=29500
echo "HOSTNAMES=${HOSTNAMES[*]}"
echo "TRAIN_HOSTS=${TRAIN_HOSTS[*]}"
echo "MASTER_ADDR=${MASTER_ADDR}"
echo "MASTER_PORT=${MASTER_PORT}"
{% if use_nccl_broadcast %}
# The eval job has a separate allocation. Publish the trainer's NCCL host through
# the shared run directory under this job ID.
printf '%s\n' "$MASTER_ADDR" > "$OUTPUT_DIR/.sft_nccl_host_$SLURM_JOB_ID"
{% endif %}
{% if online_eval -%}
INFER_HOSTS=( ${HOSTNAMES[@]:0:$NUM_INFER_NODES} )
export HOSTNAMES_STR="${INFER_HOSTS[*]}"
INFER_URLS="http://${INFER_HOSTS[0]}:${ROUTER_PORT}/v1"
ADMIN_URLS=""
ROUTER_ARGS=""
for host in ${INFER_HOSTS[@]}; do
for ((d=0; d<DP_PER_NODE; d++)); do
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + d))/v1"
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))"
done
done
export INFER_URLS
export ADMIN_URLS
export ROUTER_ARGS
echo "INFER_HOSTS=${INFER_HOSTS[*]}"
echo "INFER_URLS=${INFER_URLS}"
echo "ADMIN_URLS=${ADMIN_URLS}"
{%- endif %}
# Install environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
source $PROJECT_DIR/.venv/bin/activate
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
{% if not shared_fs %}
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
# build the batch node, so srun runs it on every node (one task each) and blocks until
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): run the sync once on
# every node. Re-source .env because unexported vars do not cross srun.
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
SYNC_SH
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
cd $PROJECT_DIR && uv sync --all-extras --all-packages
# Shared venv: one sync on the batch node populates it for all nodes.
uv sync --all-extras --all-packages
{% endif %}
{% if pre_run_command %}
# Pre-run command
{{ pre_run_command }}
{% endif %}
# Cleanup stale node-local state from prior jobs. Orphan python/torchrun/vllm
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
# termination and cause the next launch to hang. Harmless on clean nodes.
#
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
# because the surviving literal `vllm` strings below appear in the cmdline.
# Cleanup stale node-local state from prior jobs. Orphan python, torchrun, and
# vLLM processes can otherwise retain GPUs or IPC files after SLURM termination.
srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[t]orchrun" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
pkill -9 -f "[v]llm" 2>/dev/null
pkill -9 -f "[p]rime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
# which pkill -f does not see because -f only matches the cmdline.
pkill -9 "vllm" 2>/dev/null
pkill -9 "vllm::.*" 2>/dev/null
sleep 2
@@ -115,53 +143,141 @@ srun bash -s <<'CLEANUP_SH'
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
CLEANUP_SH
# Run SFT
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a single trainer crash terminates the entire SLURM job instead of
# leaving the surviving ranks (and their nodes) idle.
#
# The body goes to bash on stdin through a quoted heredoc instead of a
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
# need no escaping. Nothing in the body reads stdin, which would otherwise eat
# the rest of the script.
# Run trainer and online-eval roles in one SLURM step. A non-zero exit on any
# node terminates the other roles. Clean trainer exits let the final eval drain.
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
set -o pipefail
# Setup environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
cd $PROJECT_DIR
[ -f .env ] && source .env
source $PROJECT_DIR/.venv/bin/activate
# Higher ulimit
ulimit -n 65536
# Infiniband setup
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
export NCCL_IB_HCA=$IB_HCA
IB_HCA=$(ibv_devinfo 2>/dev/null | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" | paste -sd,)
[ -n "$IB_HCA" ] && export NCCL_IB_HCA=$IB_HCA
{% if online_eval -%}
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
INFER_NODE_RANK=$SLURM_PROCID
LOCAL_IP=$(hostname -I | awk "{print \$1}")
CONFIG_PATH=$CONFIG_DIR/inference.json
# Inference env vars: launcher defaults + [env_vars] + [inference.env_vars]
{%- for key, value in inference_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
{% include '_launch_rank.sh.j2' %}
{% include '_launch_router.sh.j2' %}
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
| tee $LOG_DIR/inference/node_${INFER_NODE_RANK}.log
TP=$((GPUS_PER_NODE / DP_PER_NODE))
EP={{ "1" if enable_expert_parallel else "0" }}
for ((d=0; d<DP_PER_NODE; d++)); do
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
if [ "$EP" -eq 1 ] && [ "$DP_PER_NODE" -gt 1 ]; then
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
else
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
fi
done
if [ "$INFER_NODE_RANK" -eq 0 ]; then
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$LOG_DIR/inference/router.log"
{%- if eval_env_names %}
mkdir -p $LOG_DIR/envs/eval
{%- for name in eval_env_names %}
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.json \
> $LOG_DIR/envs/eval/{{ name }}.log 2>&1 &
{%- endfor %}
{%- endif %}
# Evals drives inference through the router and sends admin operations
# directly to each engine.
{%- for key, value in evals_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
(
PRL_LOG_DIR=$LOG_DIR WANDB_SHARED_LABEL=evals uv run evals \
@ $CONFIG_DIR/evals.json \
--eval.client.base-url $INFER_URLS \
--eval.client.admin-base-url $ADMIN_URLS \
{%- if use_nccl_broadcast %}
--weight-broadcast.host $MASTER_ADDR \
{%- endif %}
2>&1 | tee $LOG_DIR/evals.log
COMPONENT_CODE=$?
if [ "$COMPONENT_CODE" -eq 0 ]; then
touch "$EVAL_DONE" || exit $?
fi
exit "$COMPONENT_CODE"
) &
fi
else
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
{%- else %}
TRAIN_NODE_RANK=$SLURM_PROCID
{%- endif %}
# Trainer env vars: launcher defaults + [env_vars]
{%- for key, value in trainer_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
echo $HOSTNAMES | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
uv run torchrun \
--role=trainer \
--nnodes=$NUM_NODES \
--nproc-per-node=$GPUS_PER_NODE \
--node-rank=$TRAIN_NODE_RANK \
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
--rdzv-id=job_$SLURM_JOB_ID \
--log-dir=$LOG_DIR/trainer/torchrun \
--tee=3 \
--redirects=3 \
--local-ranks-filter={{ ranks_filter }} \
-m prime_rl.trainer.sft.train \
@ $CONFIG_PATH \
echo $ALL_HOSTNAMES_STR | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
(
WANDB_SHARED_LABEL=trainer uv run torchrun \
--role=trainer \
--nnodes=$NUM_TRAIN_NODES \
--nproc-per-node=$GPUS_PER_NODE \
--node-rank=$TRAIN_NODE_RANK \
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
--rdzv-id=job_$SLURM_JOB_ID \
--log-dir=$LOG_DIR/trainer/torchrun \
--tee=3 \
--redirects=3 \
--local-ranks-filter={{ ranks_filter }} \
-m prime_rl.trainer.sft.train \
@ $TRAIN_CONFIG_PATH \
{%- if use_nccl_broadcast %}
--weight-broadcast.host 0.0.0.0 \
--weight-broadcast.host 0.0.0.0 \
{%- endif %}
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
COMPONENT_CODE=$?
if [ "$COMPONENT_CODE" -eq 0 ] && [ "$TRAIN_NODE_RANK" -eq 0 ]; then
touch "$TRAINER_DONE" || exit $?
fi
exit "$COMPONENT_CODE"
) &
{% if online_eval %}fi{% endif %}
# Every node stays in the shared srun step until all terminal roles finish.
{% if online_eval -%}
( until [ -f "$TRAINER_DONE" ] && [ -f "$EVAL_DONE" ]; do sleep 10; done ) &
{% else -%}
( until [ -f "$TRAINER_DONE" ]; do sleep 10; done ) &
{% endif -%}
COMPLETION_PID=$!
# Ignore clean component exits until the shared completion condition is met.
# Propagate failures through --kill-on-bad-exit=1.
while true; do
wait -n -p FINISHED_PID
EXIT_CODE=$?
if [ "$EXIT_CODE" -ne 0 ] || [ "${FINISHED_PID:-}" = "$COMPLETION_PID" ]; then
break
fi
done
REMAINING_PIDS=$(jobs -p)
echo "[$(hostname)] completion condition met with code $EXIT_CODE - terminating remaining processes"
for pid in $REMAINING_PIDS; do
kill -TERM $pid 2>/dev/null || true
done
exit $EXIT_CODE
LAUNCH_SH
@@ -1,260 +0,0 @@
#!/bin/bash
#SBATCH --job-name={{ job_name }}-eval
#SBATCH --nodes={{ num_infer_nodes }}
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --partition={{ partition }}
{%- if account %}
#SBATCH --account={{ account }}
{%- endif %}
{%- if time %}
#SBATCH --time={{ time }}
{%- endif %}
{%- if nodelist %}
#SBATCH --nodelist={{ nodelist }}
{%- endif %}
{%- if exclude %}
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/eval_job_%j.log
#SBATCH --error={{ output_dir }}/eval_job_%j.log
# Online-eval job for a decoupled SFT run: the inference pool (one vLLM engine per
# DP rank behind a single router) plus the evals process and its env servers. The trainer
# runs in a separate SLURM job. This job exits after evaluating the final weight
# broadcast (max_steps).
# Exit immediately on any failed command so a crash anywhere releases the
# allocation instead of leaving zombie processes holding nodes.
set -e
# Configs
export NUM_NODES={{ num_infer_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
export ROUTER_PORT={{ router_port }}
export BACKEND_PORT={{ backend_port }}
export RPC_PORT={{ data_parallel_rpc_port }}
# Paths
export PROJECT_DIR={{ project_dir }}
export CONFIG_DIR={{ config_dir }}
export CONFIG_PATH=$CONFIG_DIR/inference.json
export OUTPUT_DIR={{ output_dir }}
# Move a previous job's inference logs aside instead of deleting them: rm of log
# files another job's processes still hold open can wedge in the NFS client and
# hang the whole job before srun even runs.
[ -d $OUTPUT_DIR/logs/inference ] && mv $OUTPUT_DIR/logs/inference $OUTPUT_DIR/logs/inference_prev_$(date +%s)
mkdir -p $OUTPUT_DIR/logs/inference
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
# A clean evals exit cannot trip srun --kill-on-bad-exit (which only propagates
# failures), so node 0 publishes completion through this job-scoped sentinel and the
# other nodes watch for it to release their engines. Stale sentinels from other job
# IDs are inert, so only this job's own path needs clearing.
export EVAL_DONE=$OUTPUT_DIR/.eval_done_$SLURM_JOB_ID
rm -f "$EVAL_DONE"
{% if prl_run_id %}
# Trainer (separate SLURM job) and evals log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
# outlives the trainer) finalizes it.
export PRL_RUN_ID={{ prl_run_id }}
export PRL_RUN_NAME={{ run_name }}
export WANDB_RUN_ID=$PRL_RUN_ID
export WANDB_SHARED_MODE=1
export WANDB_SHARED_PRIMARY=trainer
export WANDB_SHARED_FINISHER=evals
export WANDB_PROGRAM="uv run sft"
{% endif %}
# Networking
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
export HOSTNAMES_STR="${HOSTNAMES[*]}"
{% if use_nccl_broadcast %}
: "${TRAIN_JOB_ID:?TRAIN_JOB_ID is required for NCCL weight broadcast}"
TRAIN_HOST_FILE="$OUTPUT_DIR/.sft_nccl_host_$TRAIN_JOB_ID"
until [ -s "$TRAIN_HOST_FILE" ]; do sleep 1; done
export TRAIN_HOST=$(<"$TRAIN_HOST_FILE")
rm -f "$TRAIN_HOST_FILE"
echo "TRAIN_HOST=${TRAIN_HOST}"
{% endif %}
# Single global router on node 0 fronts every per-rank endpoint; admin ops
# (pause/update_weights/resume) bypass it and hit each rank directly.
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
DP_PER_NODE={{ dp_per_node }}
ADMIN_URLS=""
ROUTER_ARGS=""
for host in ${HOSTNAMES[@]}; do
for ((d=0; d<DP_PER_NODE; d++)); do
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + d))/v1"
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))"
done
done
export INFER_URLS
export ADMIN_URLS
export ROUTER_ARGS
echo "HOSTNAMES=${HOSTNAMES[@]}"
echo "INFER_URLS=${INFER_URLS}"
echo "ADMIN_URLS=${ADMIN_URLS}"
# Setup environment
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
{% if not shared_fs %}
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
# build the batch node, so srun runs it on every node (one task each) and blocks until
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
SYNC_SH
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
uv sync --all-extras --all-packages
{% endif %}
{% if pre_run_command %}
# Pre-run command
{{ pre_run_command }}
{% endif %}
# Cleanup stale node-local state from prior jobs. Orphan python/vllm processes and
# vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM termination and
# cause the next launch to hang. Harmless on clean nodes.
#
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
# because the surviving literal `vllm` strings below appear in the cmdline.
srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
pkill -9 -f "[v]llm" 2>/dev/null
pkill -9 -f "[p]rime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
# which pkill -f does not see because -f only matches the cmdline.
pkill -9 "vllm" 2>/dev/null
pkill -9 "vllm::.*" 2>/dev/null
sleep 2
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* 2>/dev/null
procs=$(ps -eo comm,args | grep -E "python|vllm|vllm::" | grep -v grep | wc -l)
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
CLEANUP_SH
# Run the eval deployment
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a crashed engine/router/evals terminates the SLURM job instead
# of leaving the surviving ranks holding nodes.
#
# The body goes to bash on stdin through a quoted heredoc instead of a
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
# (including in the shared _launch_*.sh.j2 includes) need no escaping. Nothing in
# the body reads stdin, which would otherwise eat the rest of the script.
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
# pipefail ensures `cmd | tee log` propagates `cmd` failures, and the
# wait/cleanup block at the end of this script surfaces background
# process crashes (router, engines) as task failures.
set -o pipefail
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
# Higher ulimit
ulimit -n 65536
# Infiniband setup
IB_HCA=$(ibv_devinfo 2>/dev/null | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" | paste -sd,)
[ -n "$IB_HCA" ] && export NCCL_IB_HCA=$IB_HCA
INFER_NODE_RANK=$SLURM_PROCID
LOCAL_IP=$(hostname -I | awk "{print \$1}")
# Inference env vars: launcher defaults + [env_vars] + [inference.env_vars]
{%- for key, value in inference_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
{% include '_launch_rank.sh.j2' %}
{% include '_launch_router.sh.j2' %}
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
DP_PER_NODE={{ dp_per_node }}
TP=$((GPUS_PER_NODE / DP_PER_NODE))
EP={{ "1" if enable_expert_parallel else "0" }}
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
# each pinned to its TP slice of GPUs. Each node is an independent replica, so any MoE EP
# group is node-local (rendezvous on LOCAL_IP); dense models run independent engines.
for ((d=0; d<DP_PER_NODE; d++)); do
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
if [ "$EP" -eq 1 ] && [ "$DP_PER_NODE" -gt 1 ]; then
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
else
# Dense or single-DP-rank EP (dp=1, e.g. EP within one tp=8 group):
# independent single-engine servers. vLLM rejects the external-LB DP
# args when data_parallel_size == 1; enable_expert_parallel in the
# inference config alone shards experts across the TP group.
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
fi
done
if [ "$INFER_NODE_RANK" -eq 0 ]; then
# Single global router on node 0 (external LB across all per-rank endpoints)
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
{%- if eval_env_names %}
# One env server per eval source next to the evals process, which connects to each
# source at its deterministic loopback address (so this node), polling until
# they are up - the servers and the evals process start in parallel.
{%- for name in eval_env_names %}
mkdir -p $OUTPUT_DIR/logs/envs/eval
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.json \
> $OUTPUT_DIR/logs/envs/eval/{{ name }}.log 2>&1 &
{%- endfor %}
{%- endif %}
# The evals process watches trainer broadcast markers and drives the pool:
# data plane through the router, admin ops per rank.
{%- for key, value in evals_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
WANDB_SHARED_LABEL=evals uv run evals \
@ $CONFIG_DIR/evals.json \
--eval.client.base-url $INFER_URLS \
--eval.client.admin-base-url $ADMIN_URLS \
{%- if use_nccl_broadcast %}
--weight-broadcast.host $TRAIN_HOST \
{%- endif %}
2>&1 | tee $OUTPUT_DIR/logs/evals.log &
EVALS_PID=$!
else
# Watch for the completion sentinel so this node's wait below returns when
# the evals process (on node 0) finishes cleanly.
( until [ -f "$EVAL_DONE" ]; do sleep 10; done ) &
fi
# Wait for the first background job to exit and propagate its exit code. This
# turns background process crashes (engines, router, env servers, evals)
# into task failures that --kill-on-bad-exit=1 can broadcast to the other nodes
# so the whole job tears down instead of leaving zombies holding the allocation.
wait -n -p FINISHED_PID
EXIT_CODE=$?
if [ "${FINISHED_PID:-}" = "${EVALS_PID:-none}" ]; then
# Publish completion so the sentinel watchers on the other nodes release too
# (a zero exit here never trips --kill-on-bad-exit).
touch "$EVAL_DONE"
fi
echo "[$(hostname)] component exited with code $EXIT_CODE - terminating remaining processes"
for pid in $(jobs -p); do
kill -TERM $pid 2>/dev/null || true
done
exit $EXIT_CODE
LAUNCH_SH
@@ -18,8 +18,8 @@
{%- if exclude %}
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
# Exit immediately if any setup command or the launcher fails so the SLURM job
# releases its allocation instead of holding nodes after a crash.
@@ -18,8 +18,8 @@
{%- if exclude %}
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
#SBATCH --output={{ launcher_log_dir }}/job_%j.log
#SBATCH --error={{ launcher_log_dir }}/job_%j.log
# Exit immediately if any setup command or the launcher fails so the SLURM job
# releases its allocation instead of holding nodes after a crash.
+1 -1
View File
@@ -6,7 +6,7 @@ from typing import Any
import numpy as np
from prime_rl.transports.rollouts.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
# Backfill value per component weight stream when a packed sample doesn't
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
-8
View File
@@ -55,14 +55,6 @@ class LoRAState:
"""Register an adapted module with its FQN prefix (e.g. "model.layers.0.self_attn.q_proj")."""
self._modules.append((prefix, module))
def named_adapter_parameters(self) -> list[tuple[str, nn.Parameter]]:
"""Named parameters of the adapter across all registered modules."""
params = []
for prefix, module in self._modules:
for name, param in module.named_parameters_for_adapter(0):
params.append((f"{prefix}.{name}.weight", param))
return params
def adapter_state_dict(self) -> dict[str, torch.Tensor]:
"""Adapter-only state dict, converted for HF compatibility when a converter is registered."""
state_dict = {}
+4 -4
View File
@@ -7,11 +7,11 @@ from torch import Tensor
from prime_rl.configs.trainer import FakeDataLoaderConfig
from prime_rl.trainer.world import get_world
from prime_rl.transports.rollouts import (
from prime_rl.transports.batch import (
BatchReceiver,
MicroBatch,
MicroBatchReceiver,
TransportConfig,
setup_micro_batch_receiver,
setup_batch_receiver,
)
@@ -174,7 +174,7 @@ class DataLoader:
non_dp_world_size = self.world.world_size // dp_world_size
dp_rank = self.world.rank // non_dp_world_size
self.receiver: MicroBatchReceiver = setup_micro_batch_receiver(output_dir, dp_rank, start_step, config)
self.receiver: BatchReceiver = setup_batch_receiver(output_dir, dp_rank, start_step, config)
def wait_for_batch(self) -> None:
self.receiver.wait()
+30 -32
View File
@@ -9,7 +9,7 @@ from datetime import timedelta
# ruff: noqa: I001
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
from prime_rl.transports.weights import setup_weight_broadcast
from prime_rl.transports.weights import prune_broadcasts_beyond, setup_weight_sender
from prime_rl.utils.act_offloading import maybe_activation_offloading
import torch
import torch.distributed as dist
@@ -84,7 +84,11 @@ def train(config: TrainerConfig):
# Setup the monitors
asyncio.run(
monitors.setup(
wandb=config.monitors.wandb, file=config.monitors.file, output_dir=config.output_dir, run_config=config
producer="trainer",
wandb=config.monitors.wandb,
file=config.monitors.file,
output_dir=config.output_dir,
run_config=config,
)
)
@@ -172,12 +176,12 @@ def train(config: TrainerConfig):
# Set up weight broadcast (skip when using fake data since there's no inference server)
if config.data.fake:
weight_broadcast = None
weight_sender = None
logger.info("Skipping weight broadcast setup (fake data mode)")
else:
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
weight_broadcast = setup_weight_broadcast(
weight_sender = setup_weight_sender(
config.output_dir,
config.weight_broadcast,
parallel_dims,
@@ -279,12 +283,15 @@ def train(config: TrainerConfig):
# rollouts so the trainer and inference pool join the same update lifecycle,
# and so a broken broadcast path fails at startup instead of after the first
# optimizer step.
if progress.step == start_step and weight_broadcast is not None:
logger.info(f"Broadcasting base policy weights (v{progress.step - 1}) to inference engines")
if progress.step == start_step and weight_sender is not None:
startup_version = progress.step - 1
if world.is_master:
prune_broadcasts_beyond(config.output_dir, startup_version)
logger.info(f"Broadcasting startup policy weights (v{startup_version}) to inference engines")
t0 = time.perf_counter()
weight_broadcast.broadcast_weights(model, step=progress.step - 1)
weight_sender.broadcast(model, startup_version)
logger.debug(
f"Broadcast base policy weights (v{progress.step - 1}) in {format_time(time.perf_counter() - t0)}"
f"Broadcast startup policy weights (v{startup_version}) in {format_time(time.perf_counter() - t0)}"
)
# Wait for the batch to be available
@@ -583,32 +590,23 @@ def train(config: TrainerConfig):
current_lr = optimizer.param_groups[0]["lr"]
forward_backward_time = time.perf_counter() - forward_backward_start_time
# Broadcast the model just produced (policy v{progress.step}) so the orchestrator can
# sample its next step from it. Only the final version is unused (nothing samples from
# v{max_steps}) — the orchestrator stays alive for every other in-memory rendezvous;
# filesystem broadcast still writes every version for resume.
if weight_broadcast is None:
# Broadcast the model just produced (policy v{progress.step}). The final
# broadcast keeps inference synchronized with the completed trainer.
if weight_sender is None:
broadcast_weights_time = 0
else:
broadcast_unused = (
config.weight_broadcast.type in ("nccl", "nixl")
and config.max_steps is not None
and progress.step >= config.max_steps
)
if not broadcast_unused:
broadcast_weights_start_time = time.perf_counter()
# The per-layer gather + fp8 conversion peaks ~50 GiB above the
# resident weights; release cached blocks (incl. offload-stream
# pools) so the broadcast gets the full headroom.
torch.cuda.empty_cache()
weight_broadcast.broadcast_weights(model, step=progress.step)
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
if config.weight_broadcast.type == "filesystem":
interval_to_keep = config.ckpt and config.ckpt.interval
weight_broadcast.maybe_clean(progress.step, interval_to_keep)
else:
broadcast_weights_time = 0
broadcast_weights_start_time = time.perf_counter()
# The per-layer gather + fp8 conversion peaks ~50 GiB above the
# resident weights; release cached blocks (incl. offload-stream
# pools) so the broadcast gets the full headroom. Drain all
# pending work first: empty_cache returns blocks to the driver,
# so a still-running kernel holding a cached block (e.g. the
# optimizer step's tail) faults with an illegal memory access
# once its block is freed under it.
torch.cuda.synchronize()
torch.cuda.empty_cache()
weight_sender.broadcast(model, step=progress.step)
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
# Checkpoint the step we just finished (model = policy v{progress.step}).
if (
+16 -23
View File
@@ -21,8 +21,7 @@ from prime_rl.trainer.ckpt import Progress, setup_ckpt_manager
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.transports.weights import setup_weight_broadcast
from prime_rl.transports.weights.filesystem import FileSystemWeightBroadcast
from prime_rl.transports.weights import prune_broadcasts_beyond, setup_weight_sender
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
@@ -77,6 +76,7 @@ def train(config: SFTConfig):
# Setup the monitors
asyncio.run(
monitors.setup(
producer="trainer",
wandb=config.monitors.wandb,
file=config.monitors.file,
output_dir=config.run_dir,
@@ -409,27 +409,24 @@ def train(config: SFTConfig):
def is_online_eval_step(step: int) -> bool:
return any(step % interval == 0 for interval in online_eval_intervals)
weight_broadcast = None
weight_sender = None
if online_eval_intervals:
assert config.weight_broadcast is not None
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
weight_broadcast = setup_weight_broadcast(
weight_sender = setup_weight_sender(
config.run_dir,
config.weight_broadcast,
parallel_dims,
config.model.lora,
)
if (
checkpoint_step is not None
and isinstance(weight_broadcast, FileSystemWeightBroadcast)
and not weight_broadcast.is_stable(checkpoint_step)
):
# Rebroadcast the resumed policy so the evals process can re-trigger at
# the resume step (older broadcasts may have been cleaned). Skipped when
# the previous run's broadcast survived: rewriting the same dir in place
# would race an evals process already reloading it.
weight_broadcast.broadcast_weights(model, step=checkpoint_step)
weight_broadcast.clean_older(checkpoint_step)
# Startup broadcast of the incoming policy: fails fast on a broken
# transport and lets the evals process re-trigger at the resume step
# (older broadcasts may have been cleaned).
startup_version = checkpoint_step or 0
if world.is_master:
prune_broadcasts_beyond(config.run_dir, startup_version)
logger.info(f"Broadcasting startup policy weights (v{startup_version}) for online evals")
weight_sender.broadcast(model, startup_version)
logger.info(f"Starting training loop (max_steps={config.max_steps or 'infinite'})")
max_memory = torch.cuda.mem_get_info()[1] / 1024**3 # GiB
@@ -574,12 +571,10 @@ def train(config: SFTConfig):
ckpt_manager.maybe_clean()
broadcast_weights_time = 0
if weight_broadcast is not None and not is_last_step and is_online_eval_step(progress.step):
if weight_sender is not None and not is_last_step and is_online_eval_step(progress.step):
logger.info(f"Broadcasting weights at step {progress.step}")
broadcast_start_time = time.perf_counter()
weight_broadcast.broadcast_weights(model, step=progress.step)
if isinstance(weight_broadcast, FileSystemWeightBroadcast):
weight_broadcast.clean_older(progress.step)
weight_sender.broadcast(model, step=progress.step)
broadcast_weights_time = time.perf_counter() - broadcast_start_time
# Optionally, dump memory snapshot
@@ -711,11 +706,9 @@ def train(config: SFTConfig):
ckpt_manager.maybe_clean()
# Broadcast the final weights so the evals process can run its forced final epoch
if weight_broadcast is not None:
if weight_sender is not None:
logger.info("Broadcasting final weights")
weight_broadcast.broadcast_weights(model, step=progress.step)
if isinstance(weight_broadcast, FileSystemWeightBroadcast):
weight_broadcast.clean_older(progress.step)
weight_sender.broadcast(model, step=progress.step)
if gradient_manager is not None:
gradient_manager.close()
-18
View File
@@ -19,7 +19,6 @@ from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_ckpt_dir
from prime_rl.utils.utils import get_step_path
if TYPE_CHECKING:
from prime_rl.configs.trainer import OptimizerInBackwardOffloadConfig
@@ -347,20 +346,3 @@ class MemoryProfiler:
f"Finished dumping memory snapshot in {time.monotonic() - begin:.2f} seconds, load {file_path} at https://docs.pytorch.org/memory_viz to visualize the memory usage"
)
self.step_num += 1
def maybe_clean(path: Path, step: int, interval_to_keep: int | None) -> None:
"""Delete the broadcast dir from 2 trainer steps ago.
With a 1-step async barrier, the orchestrator at trainer step ``step`` is still consuming the
ckpt from ``step - 1``; ``step - 2`` is therefore safe to remove unless it falls on a
checkpoint interval that we want to preserve.
"""
logger = get_logger()
candidate_step = max(step - 2, 0)
candidate_path = get_step_path(path, candidate_step)
if interval_to_keep and candidate_step % interval_to_keep == 0:
logger.debug(f"Keeping path {candidate_path} (on ckpt interval)")
return
logger.debug(f"Removing path {candidate_path}")
shutil.rmtree(candidate_path, ignore_errors=True)
+54
View File
@@ -0,0 +1,54 @@
from pathlib import Path
from prime_rl.configs.shared import TransportConfig
from prime_rl.transports.batch.base import BatchReceiver, BatchSender
from prime_rl.transports.batch.filesystem import (
FileSystemBatchReceiver,
FileSystemBatchSender,
)
from prime_rl.transports.batch.types import (
MicroBatch,
RoutedExperts,
TrainingSample,
)
from prime_rl.transports.batch.zmq import (
ZMQBatchReceiver,
ZMQBatchSender,
)
def setup_batch_sender(
output_dir: Path, data_world_size: int, current_step: int, transport: TransportConfig
) -> BatchSender:
if transport.type == "filesystem":
return FileSystemBatchSender(output_dir, data_world_size, current_step)
elif transport.type == "zmq":
return ZMQBatchSender(output_dir, data_world_size, current_step, transport)
else:
raise ValueError(f"Invalid transport type: {transport.type}")
def setup_batch_receiver(
output_dir: Path, data_rank: int, current_step: int, transport: TransportConfig
) -> BatchReceiver:
if transport.type == "filesystem":
return FileSystemBatchReceiver(output_dir, data_rank, current_step)
elif transport.type == "zmq":
return ZMQBatchReceiver(output_dir, data_rank, current_step, transport)
else:
raise ValueError(f"Invalid transport type: {transport.type}")
__all__ = [
"FileSystemBatchSender",
"FileSystemBatchReceiver",
"ZMQBatchSender",
"ZMQBatchReceiver",
"BatchReceiver",
"BatchSender",
"TrainingSample",
"MicroBatch",
"RoutedExperts",
"setup_batch_sender",
"setup_batch_receiver",
]
@@ -3,11 +3,11 @@ from pathlib import Path
import msgspec
from prime_rl.transports.rollouts.types import MicroBatch
from prime_rl.transports.batch.types import MicroBatch
from prime_rl.utils.logger import get_logger
class MicroBatchSender(ABC):
class BatchSender(ABC):
"""Base class for sending micro batches from the orchestrator to the train workers."""
def __init__(self, output_dir: Path, data_world_size: int):
@@ -26,7 +26,7 @@ class MicroBatchSender(ABC):
pass
class MicroBatchReceiver(ABC):
class BatchReceiver(ABC):
"""Base class for receiving micro batches from the orchestrator."""
def __init__(self, output_dir: Path, data_rank: int):

Some files were not shown because too many files have changed in this diff Show More