Compare commits

...
Author SHA1 Message Date
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
Mika SenghaasandGitHub 04e796d21b fix: treat a resume past max_steps as the last step (#3352)
## Summary

- A run resumed from a checkpoint at or beyond `max_steps` never matched
the `is_last_step ==` check, so the trainer idled forever waiting for a
batch that would not come. `>=` makes it exit as the last step.

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-08-22 19:32:45 -07:00
9f29e5388e chore: clean up trainer and orchestrator logging (#3345)
## Summary

Log audit of the trainer and orchestrator, from a side-by-side read of a
full run's logs and the code that emitted them.

**Conventions** (applied everywhere):
- Every potentially slow action logs an active-tense info line first
(`Initializing X`, `Waiting for X`) — the last info line always names
the action that crashed or hung.
- Each one is paired with a debug completion carrying `format_time`
timing (`Initialized X in 1.2s`). All debug timings now use
`format_time`.
- Component inits log exactly `Initializing X ({config})`. Monitors log
a names-only summary plus one full-config line per monitor, from
`monitors.setup`.

**Gaps filled** (previously silent hang points): startup weight sync
(can block minutes), orchestrator teardown (info + one debug line per
stage, so a wedged component is identifiable),
`setup_torch_distributed`, device mesh init, trainer startup broadcast,
W&B finalize.

**Setup reorder** (orchestrator): local init first — sender, filesystem
weight broadcast — then the waits last before the main loop (env servers
→ inference pool → NCCL/NIXL handshake → startup sync). The NCCL/NIXL
handshake stays post-readiness (it POSTs to live engines); the
checkpoint's curricula restore follows `envs.start()` (`TrainSource`
needs loaded tasksets). One awaited metrics scrape primes the
concurrency controller so `Derived initial max inflight` logs before
`Starting orchestrator loop`.

**Renames and demotions** (highlights):
- `waiting for trainer to broadcast checkpoint N` → `Waiting for the
trainer to broadcast policy v{N}`; steps vs 0-indexed policy versions
untangled throughout.
- The inference wait is info every 30 s (`Waiting for inference server
at {url} to start up (30s elapsed)`), error at debug — was a warning
every 10 s.
- One identity line on all three processes: `Starting from scratch` /
`Resuming from step {N}`; `Broadcasting base policy weights (v{N})`.
- Launcher: `Starting {name} server`, `Starting orchestrator` (no
"process").
- Removed the per-group success debug in the train sink (flooded one
line per group); drop-path logs stay, renamed `Dropped group | ... |
reason=...`.
- Demoted to debug: ZMQ sender/receiver init/close, `Using shared W&B
mode`, `Loading model config`, executor setup, GC line. LoRA debug no
longer dumps the full model repr.
- Punctuation/tense/indexing: `Saving final checkpoint at step N`, no
trailing `.`/`!` on finish lines, 1-indexed micro steps.

## Verification

Ran alphabet-sort debug-level runs on this branch (from scratch,
`--resume.step 2`, and post-merge): clean startup → steps → drain →
teardown on both processes, all lines rendering as intended, e.g.

```
INFO  Syncing inference to the trainer's startup broadcast (v0)
DEBUG Synced inference to policy v0 in 115ms
INFO  Stopping orchestrator components
DEBUG Stopping dispatcher
SUCCESS Orchestrator finished
```

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Mostly logging, but orchestrator setup order, resume-step timing,
NCCL/NIXL after pool ready, and an extra metrics probe change real
startup/teardown sequencing. A hang or resume mismatch would show up at
run start.
> 
> **Overview**
> Makes trainer/orchestrator/launcher logs follow a consistent pattern:
an **info** line for each potentially slow action (`Initializing` /
`Waiting`), then a **debug** completion with `format_time`. Identity
lines are aligned (`Starting from scratch` / `Resuming from step N`),
policy versions are labeled `v{N}`, and noisy lines (ZMQ init, GC,
per-group success, full model repr) are demoted or removed.
> 
> **Orchestrator `setup` is reordered**, not just reworded: local work
(packer, micro-batch sender, filesystem broadcast) runs first; env
servers, inference readiness, NCCL/NIXL handshake, and startup weight
sync wait last. Resume step is applied before those waits. Teardown now
logs each stage. An awaited `inference_metrics.probe()` primes the
concurrency controller before the loop starts.
> 
> Inference health wait is info every 30s (errors at debug). Drop-path
logs stay as `Dropped group | … | reason=…`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f1f33c0fc2fa3a2193118991c256cee0aae232ff. 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 16:59:26 -07:00
822db2902c feat: drop orchestrator-side renderer for trace-stamped mm token map (#3349)
## Summary

- Drop the orchestrator-side renderer: the orchestrator built a full
`Renderer` only to read `mm_token_type_id_map` off it and stamp
per-token modality markers in `trace_to_samples`. verifiers now stamps
the map onto the trace at turn commit and exposes the training-ready
stream as `Branch.mm_token_type_ids` (PrimeIntellect-ai/verifiers#2424)
— the orchestrator consumes that and builds no renderer at all.
- `trace_to_samples` reads `branch.mm_token_type_ids` directly; the
`mm_token_type_ids_mapping` parameter and its `TrainSink`/`Orchestrator`
plumbing are gone.
- `setup_policy_inference_pool` (now just an `InferencePool`
construction) is inlined into `Orchestrator.setup()`; its mock-based
unit test file is removed.
- Bumps `deps/verifiers` to verifiers main, which includes the merged
PrimeIntellect-ai/verifiers#2424. Rollout rendering is unchanged — it
already happens inside verifiers' renderer train client.

## Verification

Before/after 6-step multimodal RL runs (color-codeword,
`Qwen/Qwen3.5-4B`, 1 train + 1 infer GPU, batch 64, group 8):

- **Before** (main): rewards 0.17 → 0.36 across 6 steps, 0% errors, all
samples trainable, losses finite.
- **After** (this PR + vf#2424): rewards 0.13 → 0.42 across 6 steps, 0%
errors, all samples trainable, losses finite. The trainer hard-fails on
image samples missing `mm_token_type_ids` (`prepare_sample` raises), so
completing all steps proves the new path delivers them. The after-run's
orchestrator log contains no renderer initialization.
- Offline equivalence on the after-run's 833 dumped traces (2499
branches): every trace's stamped `mm_token_type_id_map` equals the
renderer map the orchestrator used to build (`{<|image_pad|>: 1,
<|video_pad|>: 2}`), and per-token ids computed the old way match
`Branch.mm_token_type_ids`' computation exactly.
- `tests/unit/orchestrator` green (the pre-existing `test_qwen3_vl_e2e`
failure needs a live vLLM and fails identically on main).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the multimodal training-sample path: missing or mismatched
`mm_token_type_ids` would fail trainer `prepare_sample`. Behavior now
depends on verifiers stamping the map correctly rather than a local
renderer.
> 
> **Overview**
> Stops building an orchestrator-side `Renderer` just to stamp
multimodal token types. Training samples now take `mm_token_type_ids`
from `branch.mm_token_type_ids` (stamped by verifiers at turn commit).
> 
> `setup_policy_inference_pool` is inlined as a direct `InferencePool`
construction. `TrainSink` / `Orchestrator` no longer plumb
`mm_token_type_ids_mapping`, and the helper’s unit tests are removed.
Rollout rendering is unchanged (still inside the renderer train client).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4e6fde2b910f91e80fd460704077f87c98329032. 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 16:36:48 -07:00
105 changed files with 6276 additions and 1361 deletions
@@ -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.
+6 -5
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
+4 -12
View File
@@ -81,7 +81,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| `--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,7 +198,7 @@ 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)
@@ -327,17 +327,9 @@ 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:
```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`.
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with four views per run: metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved configs, a rollout trace viewer with a per-token advantage/logprob view, and merged component logs. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node. On a machine that should not resolve the training dependencies (e.g. a cluster head node), run it standalone: `uv run --script src/prime_rl/dashboard/server.py [output_dir ...]` — an isolated script environment with only the dashboard's own small dependencies.
### 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",
@@ -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."""
@@ -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,
@@ -25,9 +26,6 @@ from prime_rl.utils.config import BaseConfig
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."""
@@ -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
@@ -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,
@@ -460,9 +463,13 @@ 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."
)
# The final version v{max_steps} is broadcast iff something consumes it:
# training never samples from it, but a configured final eval measures it.
broadcast_final = self.orchestrator.eval is not None
if self.weight_broadcast.type in ("nccl", "nixl"):
inference_world_size = (
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
@@ -474,6 +481,7 @@ class RLConfig(BaseConfig):
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
inference_world_size=inference_world_size,
broadcast_final=broadcast_final,
)
if self.weight_broadcast.type == "nccl":
transport_config = dict(
@@ -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, broadcast_final=broadcast_final
)
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig(
timeout=self.weight_broadcast.timeout, broadcast_final=broadcast_final
)
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
@@ -37,6 +37,18 @@ 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."""
broadcast_final: bool = True
"""Internal - stamped by the RL/SFT launcher, never set by users: whether the
trainer broadcasts the final version v{max_steps}. True iff something consumes
it (a configured final eval) - training itself never samples from the final
version."""
class RunConfig(BaseConfig):
name: str | None = None
"""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 +181,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,
@@ -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."""
@@ -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")
+7 -1
View File
@@ -34,7 +34,7 @@ dependencies = [
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.3.1.dev59",
"renderers",
"renderers>=0.1.10",
"dion",
"tilelang>=0.1.8",
"flash-linear-attention",
@@ -55,11 +55,16 @@ trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
evals = "prime_rl.entrypoints.evals:main"
env-server = "prime_rl.entrypoints.env_server:main"
dashboard = "prime_rl.dashboard.server:main"
[project.entry-points."vllm.general_plugins"]
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
[project.optional-dependencies]
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
@@ -107,6 +112,7 @@ 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",
-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"
+2
View File
@@ -29,6 +29,8 @@ uv sync --all-extras --all-packages # + all env packages (needed to train
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`.
+15 -11
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,11 +48,22 @@ After a restart, verify all processes are back up and progress resumed before th
### Where to find things
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the run dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
- `{run_dir}/configs/` — resolved configs, written as JSON so explicit None settings round-trip (`rl.json` has the full picture).
- `{run_dir}/configs/` — the launch TOML copied verbatim (`rl.toml`/`sft.toml`), plus `resolved/` with the per-component resolved configs, written as JSON so explicit None settings round-trip.
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved episodes (see Episodes below).
### Dashboard
`uv run dashboard [output_dir ...]` (default `outputs/`; 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. Without the
project's GPU deps (e.g. a head node), run it standalone:
`uv run --script src/prime_rl/dashboard/server.py [output_dir ...]`.
### Logs
```
+20
View File
@@ -0,0 +1,20 @@
# Dashboard
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
directories (metrics, resolved configs, rollout traces, component logs) at
http://localhost:7788. Needs the `dashboard` extra.
To run it without resolving the project's GPU dependencies (a cluster head
node, a laptop against a mounted outputs dir), use the standalone script form —
it resolves only a handful of small wheels into an isolated script environment:
```bash
uv run --script src/prime_rl/dashboard/server.py [output_dir ...]
```
The script needs its `static/` sibling directory, so copy this whole folder
when moving it to another machine.
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
+872
View File
@@ -0,0 +1,872 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "fastapi>=0.115",
# "uvicorn>=0.30",
# "orjson>=3.10",
# "tokenizers>=0.20",
# "huggingface_hub>=0.25",
# "rich>=14.0",
# ]
# ///
"""Local dashboard for prime-rl runs: logs, metrics, and rollout traces.
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.
Reads everything from run output directories (metrics.jsonl, logs/attempt_N,
rollouts/step_N) — no wandb or network required. Usage:
uv run dashboard [output_dir ...] [--port 7788] [--host 127.0.0.1]
Multiple output directories can be tracked at once.
"""
import argparse
import hashlib
import sys
import threading
import time
from collections import OrderedDict
from pathlib import Path
import orjson
try:
import uvicorn
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
except ModuleNotFoundError as error: # the dashboard ships as an extra
raise SystemExit(
"the dashboard needs the 'dashboard' extra - install with `uv sync --extra dashboard` "
"(or run the standalone script: `uv run --script src/prime_rl/dashboard/server.py`)"
) from error
STATIC_DIR = Path(__file__).parent / "static"
MASTER_LOGS = {"trainer.log", "orchestrator.log", "inference.log", "evals.log"}
MAX_LOG_CHUNK = 2_000_000
app = FastAPI()
output_dirs: list[Path] = [Path("outputs")]
# run id -> run dir, rebuilt on every /api/runs poll; ids are the run name,
# qualified with the output dir's basename when two dirs hold the same name
_run_registry: dict[str, Path] = {}
_lock = threading.Lock()
MAX_CACHED_FILES = 64
"""Per-cache LRU bound: paging through thousands of steps must not grow the
server without limit (each entry holds one traces file's offsets/summaries)."""
def _lru_get(cache: OrderedDict, key):
value = cache.get(key)
if value is not None:
cache.move_to_end(key)
return value
def _lru_put(cache: OrderedDict, key, value) -> None:
cache[key] = value
cache.move_to_end(key)
while len(cache) > MAX_CACHED_FILES:
cache.popitem(last=False)
# Append-only file caches keyed by absolute path: line-start offsets and per-episode summaries.
_offsets_cache: OrderedDict[Path, tuple[int, list[int]]] = OrderedDict()
_summaries_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
_tokenizer_cache: dict[str, object] = {}
_piece_cache: dict[tuple[str, int], str] = {}
_json_cache: dict[Path, tuple[tuple[int, float], dict]] = {}
_steps_cache: dict[Path, tuple[float, list[int]]] = {}
def is_run_dir(path: Path) -> bool:
if not path.is_dir() or path.name.startswith("."):
return False
return any((path / marker).exists() for marker in ("configs", "logs", "metrics.jsonl", "rollouts"))
def scan_runs() -> dict[str, Path]:
global _run_registry
by_name: dict[str, list[Path]] = {}
for base in output_dirs:
if not base.is_dir():
continue
for run_dir in sorted(base.iterdir()):
if is_run_dir(run_dir):
by_name.setdefault(run_dir.name, []).append(run_dir)
registry: dict[str, Path] = {}
for name, dirs in by_name.items():
if len(dirs) == 1:
registry[name] = dirs[0]
else:
for run_dir in dirs:
registry[f"{run_dir.parent.name}:{name}"] = run_dir # ":" survives a URL path segment, "/" does not
_run_registry = registry
return registry
def get_run_dir(run: str) -> Path:
run_dir = _run_registry.get(run) or scan_runs().get(run)
if run_dir is None or not run_dir.is_dir():
raise HTTPException(404, f"run {run} not found")
return run_dir
def safe_child(base: Path, rel: str, *, suffix: str | None = None) -> Path:
path = (base / rel).resolve()
if not path.is_relative_to(base.resolve()) or (suffix and path.suffix != suffix) or not path.is_file():
raise HTTPException(404, f"{rel} not found")
return path
def read_json(path: Path) -> dict:
"""Config reads are cached by (size, mtime) — they sit on every /api/runs poll."""
try:
stat = path.stat()
except OSError:
return {}
key = (stat.st_size, stat.st_mtime)
with _lock:
cached = _json_cache.get(path)
if cached and cached[0] == key:
return cached[1]
try:
data = orjson.loads(path.read_bytes())
except (OSError, ValueError):
data = {}
with _lock:
_json_cache[path] = (key, data)
return data
def numbered_dirs(parent: Path, prefix: str) -> list[tuple[int, Path]]:
return sorted(
(int(p.name.removeprefix(prefix)), p)
for p in parent.glob(f"{prefix}*")
if p.name.removeprefix(prefix).isdigit()
)
def size_etag(path: Path, etag: str | None) -> tuple[str, dict | None]:
"""Etag = file size: the trace files are append-only, so an unchanged size means
an unchanged response. Returns (current_etag, short-circuit response or None)."""
current = str(path.stat().st_size)
if etag is not None and etag == current:
return current, {"unchanged": True, "etag": current}
return current, None
def model_name(config: dict) -> str | None:
"""`model` is a string on eval configs, a {name} object on rl/sft ones."""
model = config.get("model")
return model if isinstance(model, str) else (model or {}).get("name")
def resolved_config_dir(run_dir: Path) -> Path:
"""Where the resolved JSON dumps live: `configs/resolved/`, or `configs/` on
runs from before the launch-TOML split."""
configs = run_dir / "configs"
resolved = configs / "resolved"
return resolved if resolved.is_dir() else configs
def main_config(run_dir: Path) -> tuple[str, dict]:
configs = resolved_config_dir(run_dir)
if (configs / "sft.json").exists():
return "sft", read_json(configs / "sft.json")
if (configs / "orchestrator.json").exists() or (configs / "trainer.json").exists():
return "rl", read_json(configs / "orchestrator.json") or read_json(configs / "trainer.json")
if (configs / "eval.json").exists(): # verifiers `uv run eval` run dir
return "eval", read_json(configs / "eval.json")
return "other", {}
def attempt_numbers(run_dir: Path) -> list[int]:
return [n for n, _ in numbered_dirs(run_dir / "logs", "attempt_")]
def step_numbers(run_dir: Path) -> list[int]:
"""Rollout step numbers, cached by the rollouts dir mtime (which changes when a
step dir is created) — polled per run on every /api/runs tick."""
rollouts = run_dir / "rollouts"
try:
mtime = rollouts.stat().st_mtime
except OSError:
return []
with _lock:
cached = _steps_cache.get(rollouts)
if cached and cached[0] == mtime:
return cached[1]
steps = [n for n, _ in numbered_dirs(rollouts, "step_")]
with _lock:
_steps_cache[rollouts] = (mtime, steps)
return steps
def run_meta(run_dir: Path) -> dict:
configs = run_dir / "configs"
run_type, config = main_config(run_dir)
resolved = resolved_config_dir(run_dir)
def envs(split: str) -> list[str]:
return sorted(p.stem for p in (resolved / "envs" / split).glob("*.json"))
steps = step_numbers(run_dir)
metrics_path = run_dir / "metrics.jsonl"
started = updated = None
if metrics_path.is_file():
updated = metrics_path.stat().st_mtime
# read fresh every time: a relaunch replaces the file, and a cached
# first-row time from the previous run makes the duration absurd
with metrics_path.open("rb") as f:
try:
started = orjson.loads(f.readline()).get("time")
except orjson.JSONDecodeError:
started = None
root_traces = run_dir / "traces.jsonl"
if updated is None and root_traces.is_file(): # eval runs have no metrics.jsonl
updated = root_traces.stat().st_mtime
started = configs.stat().st_mtime if configs.is_dir() else None
return {
"name": run_dir.name,
"type": run_type,
"model": model_name(config),
"dataset": (config.get("data") or {}).get("name"),
"env": ((config.get("env") or {}).get("taskset") or {}).get("id"),
"total_episodes": (config.get("num_tasks") or 0) * (config.get("num_rollouts") or 0) or None,
"max_steps": config.get("max_steps"),
"train_envs": envs("train"),
"eval_envs": envs("eval"),
"has_metrics": metrics_path.exists(),
"last_step": max(steps, default=None),
"started": started,
"updated": updated,
"created": configs.stat().st_mtime if configs.is_dir() else run_dir.stat().st_mtime,
"mtime": run_dir.stat().st_mtime,
}
@app.get("/api/runs")
def list_runs() -> dict:
runs = []
for run_id, run_dir in scan_runs().items():
meta = run_meta(run_dir)
meta["name"] = run_id
runs.append(meta)
runs.sort(key=lambda r: r["mtime"], reverse=True)
return {"output_dir": ", ".join(str(d.resolve()) for d in output_dirs), "runs": runs}
@app.get("/api/runs/{run}")
def get_run(run: str) -> dict:
return run_meta(get_run_dir(run))
# ---------------------------------------------------------------------------- logs
def log_component(rel: Path) -> tuple[str, str]:
"""Map a path relative to the attempt dir to (component, label)."""
parts = rel.parts
if len(parts) == 1:
return {
"trainer.log": ("trainer", "trainer"),
"orchestrator.log": ("orch", "orchestrator"),
"inference.log": ("infer", "inference"),
"evals.log": ("evals", "evals"),
"eval.log": ("evals", "eval"),
}.get(parts[0], ("other", parts[0]))
if parts[0] == "trainer":
if parts[1] == "torchrun": # trainer/torchrun/<rdzv>/attempt_0/<rank>/std{out,err}.log
return "trainer", f"rank{parts[-2]}/{rel.stem}"
return "trainer", rel.stem
if parts[0] == "inference":
return "infer", rel.stem
if parts[0] == "envs" and len(parts) == 3: # envs/<split>/<env>.log
return f"env:{rel.stem}", f"{rel.stem} ({parts[1]})"
return "other", str(rel.with_suffix(""))
@app.get("/api/runs/{run}/logfiles")
def list_logfiles(run: str, attempt: str = "latest") -> dict:
run_dir = get_run_dir(run)
attempts = attempt_numbers(run_dir)
if attempt == "latest":
latest = (run_dir / "logs" / "latest").resolve()
attempt_num = (
int(latest.name.removeprefix("attempt_")) if latest.is_dir() else (attempts[-1] if attempts else 0)
)
else:
attempt_num = int(attempt)
attempt_dir = run_dir / "logs" / f"attempt_{attempt_num}"
files = []
def add(path: Path, component: str, label: str) -> None:
real = path.resolve() # multi-node masters are symlinks to node_0 logs
if not real.is_file():
return
files.append(
{
"id": str(path.relative_to(run_dir)),
"component": component,
"label": label,
"size": real.stat().st_size,
"master": path.name in MASTER_LOGS and path.parent == attempt_dir,
}
)
if attempt_dir.is_dir():
for path in sorted(attempt_dir.rglob("*.log")):
component, label = log_component(path.relative_to(attempt_dir))
add(path, component, label)
# The evals process writes its env-server logs outside attempt_N (logs/envs/eval/*.log).
for path in sorted((run_dir / "logs" / "envs").rglob("*.log")):
add(path, f"env:{path.stem}", f"{path.stem} (evals)")
return {"attempt": attempt_num, "attempts": attempts, "files": files}
@app.get("/api/runs/{run}/log")
def read_log(run: str, file: str, start: int | None = None, end: int | None = None, tail: int | None = None) -> dict:
path = safe_child(get_run_dir(run), file)
size = path.stat().st_size
if tail is not None:
start = max(0, size - tail)
start = min(start or 0, size)
with path.open("rb") as f:
f.seek(start)
data = f.read(min(MAX_LOG_CHUNK, (end if end is not None else size) - start))
if tail is not None and start > 0: # snap the head to a line boundary
cut = data.find(b"\n")
if cut != -1:
start += cut + 1
data = data[cut + 1 :]
chunk_end = start + len(data)
if end is None and chunk_end == size:
# Read to EOF: drop a partially-written trailing line so follow-mode gets whole lines.
last_nl = data.rfind(b"\n")
if last_nl != -1 and last_nl + 1 < len(data):
data = data[: last_nl + 1]
chunk_end = start + len(data)
return {"text": data.decode("utf-8", errors="replace"), "start": start, "end": chunk_end}
# ------------------------------------------------------------------------- configs
CONFIG_ORDER = ["rl", "sft", "eval", "evals", "orchestrator", "trainer", "inference"]
def config_rank(name: str) -> tuple[int, str]:
stem = name.split("/")[0].removesuffix(".toml")
return (CONFIG_ORDER.index(stem) if stem in CONFIG_ORDER else len(CONFIG_ORDER), name)
@app.get("/api/runs/{run}/configs")
def list_configs(run: str) -> dict:
"""Two views of a run's config: each launch TOML (verbatim, as the run was
started) and one "resolved" document concatenating every resolved JSON dump."""
run_dir = get_run_dir(run)
configs_dir = run_dir / "configs"
files = sorted((p.name for p in configs_dir.glob("*.toml")), key=config_rank) if configs_dir.is_dir() else []
if any(resolved_config_dir(run_dir).rglob("*.json")):
files.append("resolved")
return {"files": files}
@app.get("/api/runs/{run}/config")
def read_config(run: str, file: str) -> dict:
run_dir = get_run_dir(run)
if file == "resolved":
base = resolved_config_dir(run_dir)
names = sorted((str(p.relative_to(base).with_suffix("")) for p in base.rglob("*.json")), key=config_rank)
doc = {name: read_json(base / f"{name}.json") for name in names}
return {"file": file, "content": orjson.dumps(doc).decode()}
path = safe_child(run_dir / "configs", file, suffix=".toml")
return {"file": file, "content": path.read_text()}
# ------------------------------------------------------------------------- metrics
MAX_METRICS_CHUNK = 4 * 1024 * 1024
"""Per-response cap on /metrics: huge runs stream in chunks the client loops over,
so the first charts paint long before a 100MB metrics.jsonl finishes loading."""
@app.get("/api/runs/{run}/metrics")
def read_metrics(run: str, offset: int = 0) -> dict:
path = get_run_dir(run) / "metrics.jsonl"
if not path.is_file():
return {"rows": [], "offset": 0, "size": 0}
size = path.stat().st_size
if offset > size: # file was truncated/replaced
offset = 0
rows = []
with path.open("rb") as f:
f.seek(offset)
data = f.read(MAX_METRICS_CHUNK)
if data and b"\n" not in data: # a single line larger than the chunk
data += f.readline()
consumed = data.rfind(b"\n") + 1 # leave a partially-written last line for the next poll
for line in data[:consumed].splitlines():
try:
rows.append(orjson.loads(line))
except orjson.JSONDecodeError:
continue
return {"rows": rows, "offset": offset + consumed, "size": size}
# ------------------------------------------------------------------------ rollouts
RECENT_STEPS = 64
_avail_cache: dict[Path, dict[str, bool]] = {} # step dir -> known-present subsets
_avail_scan_counter = 0
EVAL_ROOT_STEP = (0, "eval", "all")
"""The virtual address of a stepless `uv run eval` run's root traces.jsonl —
the one convention shared by the step listing and traces_path."""
def eval_root_traces(run_dir: Path) -> Path | None:
root = run_dir / "traces.jsonl"
return root if root.is_file() and root.stat().st_size > 0 else None
def rollout_steps(run_dir: Path) -> list[dict]:
"""Presence only — never reads trace files. Presence is monotonic (files only
appear), so known-present subsets are cached forever; absent ones re-stat every
poll only for the newest steps — older gaps (an eval landing late at its trigger
step) are picked up by a full rescan every 10th call."""
global _avail_scan_counter
_avail_scan_counter += 1
full_rescan = _avail_scan_counter % 10 == 1
numbered = numbered_dirs(run_dir / "rollouts", "step_")
recent_cutoff = numbered[-1][0] - RECENT_STEPS if numbered else 0
steps = []
for number, step_dir in numbered:
available = _avail_cache.setdefault(step_dir, {})
if len(available) < 4 and (full_rescan or number >= recent_cutoff):
for kind in ("train", "eval"):
for subset in ("all", "effective"):
key = f"{kind}/{subset}"
if key in available:
continue
path = step_dir / kind / subset / "traces.jsonl"
if path.is_file() and path.stat().st_size > 0:
available[key] = True
if available:
steps.append({"step": number, "available": available})
root = eval_root_traces(run_dir)
if not steps and root is not None:
steps.append({"step": EVAL_ROOT_STEP[0], "available": {f"{EVAL_ROOT_STEP[1]}/{EVAL_ROOT_STEP[2]}": True}})
return steps
def line_offsets(path: Path) -> list[int]:
size = path.stat().st_size
with _lock:
cached_size, offsets = _lru_get(_offsets_cache, path) or (0, [])
if cached_size > size: # rewritten (e.g. resume cleanup): rebuild
cached_size, offsets = 0, []
if cached_size == size:
return offsets
# re-scan from the last recorded line (it may have been partial) into a local
# list, then merge under the lock: the shared list only ever grows by strictly
# increasing appends, so concurrent readers' indices stay valid and concurrent
# growers can't double-append the same line start
scan_from = offsets[-1] if offsets else 0
found = []
with path.open("rb") as f:
f.seek(scan_from)
pos = scan_from
for line in f:
if line.strip():
found.append(pos)
pos += len(line)
with _lock:
cached_size, current = _lru_get(_offsets_cache, path) or (0, offsets)
if cached_size > size:
current = []
for offset in found:
if not current or offset > current[-1]:
current.append(offset)
_lru_put(_offsets_cache, path, (max(size, cached_size), current))
return current
def walk_timing(obj: dict, prefix: str, out: dict[str, float]) -> None:
"""Flatten a trace timing tree to phase -> seconds (same walk as the viewer)."""
if isinstance(obj.get("duration"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + obj["duration"]
elif isinstance(obj.get("start"), (int, float)) and isinstance(obj.get("end"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + (obj["end"] - obj["start"])
for key, value in obj.items():
if isinstance(value, dict):
walk_timing(value, f"{prefix}/{key}" if prefix else key, out)
def summarize_episode(line: int, rec: dict) -> dict:
rewards, advantages = [], []
input_tokens = output_tokens = turns = branches = 0
stop_condition = None
reward_parts: dict[str, list[float]] = {}
metric_parts: dict[str, list[float]] = {}
timing: dict[str, float] = {}
costs: list[float] = []
for trace in rec.get("traces") or []:
costs.extend(
usage["cost"]
for call in trace.get("calls") or []
if isinstance(usage := call.get("usage") or {}, dict) and isinstance(usage.get("cost"), (int, float))
)
nodes = trace.get("nodes") or []
parents = {node.get("parent") for node in nodes if "parent" in node}
branches += max(0, len(nodes) - len(parents))
if trace.get("rewards"): # skip reward-less seats (e.g. a judge) in the episode mean
rewards.append(
sum(
(r.get("score") or 0) * (r.get("weight") if r.get("weight") is not None else 1)
for r in trace["rewards"].values()
if isinstance(r, dict)
)
)
for name, r in (trace.get("rewards") or {}).items():
if isinstance(r, dict) and isinstance(r.get("score"), (int, float)):
reward_parts.setdefault(name, []).append(r["score"])
for name, value in (trace.get("metrics") or {}).items():
if isinstance(value, (int, float)):
metric_parts.setdefault(name, []).append(value)
if isinstance(trace.get("timing"), dict):
walk_timing(trace["timing"], "", timing)
advantage = (trace.get("info") or {}).get("advantage")
if advantage is not None:
advantages.append(advantage)
for node in nodes:
n_tokens = len(node.get("token_ids") or [])
if node.get("sampled"):
output_tokens += n_tokens
else:
input_tokens += n_tokens
if (node.get("message") or {}).get("role") == "assistant":
turns += 1
stop_condition = trace.get("stop_condition", stop_condition)
if input_tokens == 0 and output_tokens == 0: # some eval traces carry no token arrays
for call in trace.get("calls") or []:
usage = call.get("usage") or {}
input_tokens += usage.get("prompt_tokens") or 0
output_tokens += usage.get("completion_tokens") or 0
return {
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
"metrics": {name: sum(v) / len(v) for name, v in metric_parts.items()},
"timing": timing,
"cost": sum(costs) if costs else None,
"line": line,
"id": rec.get("id"),
"env": (rec.get("env") or {}).get("id") or (rec.get("env") or {}).get("name"),
"group": (rec.get("group") or {}).get("id"),
"ok": rec.get("ok"),
"num_errors": len(rec.get("errors") or []),
"reward": sum(rewards) / len(rewards) if rewards else None,
"advantage": sum(advantages) / len(advantages) if advantages else None,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"turns": turns,
"branches": branches,
"stop_condition": stop_condition,
}
def episode_summaries(path: Path) -> list[dict]:
offsets = line_offsets(path)
with _lock:
cached_count, summaries = _lru_get(_summaries_cache, path) or (0, [])
if cached_count > len(offsets):
cached_count, summaries = 0, []
if cached_count == 0:
loaded = load_sidecar(path)
if loaded is not None:
cached_count, summaries = len(loaded), loaded
cached_count = min(cached_count, len(offsets))
if cached_count == len(offsets):
with _lock:
_lru_put(_summaries_cache, path, (cached_count, summaries))
return summaries[:cached_count] if len(summaries) != cached_count else summaries
summaries = list(summaries[:cached_count])
with path.open("rb") as f:
f.seek(offsets[cached_count])
for line_no in range(cached_count, len(offsets)):
raw = f.readline()
try:
summaries.append(summarize_episode(line_no, orjson.loads(raw)))
except orjson.JSONDecodeError:
summaries.append({"line": line_no, "id": None, "error": "unparseable"})
with _lock:
_lru_put(_summaries_cache, path, (len(offsets), summaries))
write_sidecar(path, offsets, summaries)
return summaries
# ------------------------------------------------------- summary sidecars
# Parsing a step's traces file for the table can mean reading gigabytes; the
# result is persisted outside the run dir (the dashboard never writes there),
# so a revisit — or a dashboard restart — skips the parse entirely.
SIDECAR_DIR = Path.home() / ".cache" / "prime-rl" / "dashboard"
SIDECAR_WRITE_INTERVAL_S = 20.0
_sidecar_written: dict[Path, tuple[float, int]] = {} # path -> (last write time, count)
def sidecar_path(path: Path) -> Path:
digest = hashlib.sha256(str(path.resolve()).encode()).hexdigest()[:24]
return SIDECAR_DIR / f"{digest}.json"
def load_sidecar(path: Path) -> list[dict] | None:
data = read_json(sidecar_path(path))
try:
if data.get("path") != str(path.resolve()) or path.stat().st_size < data["size"]:
return None # different file, or rewritten smaller (relaunch)
return data["summaries"]
except (KeyError, OSError):
return None
def write_sidecar(path: Path, offsets: list[int], summaries: list[dict]) -> None:
now = time.monotonic()
last_time, last_count = _sidecar_written.get(path, (0.0, -1))
if len(summaries) == last_count or now - last_time < SIDECAR_WRITE_INTERVAL_S:
return
_sidecar_written[path] = (now, len(summaries))
SIDECAR_DIR.mkdir(parents=True, exist_ok=True)
consumed = offsets[len(summaries) - 1] if summaries else 0
payload = {"path": str(path.resolve()), "size": consumed, "summaries": summaries}
target = sidecar_path(path)
tmp = target.with_suffix(".tmp")
tmp.write_bytes(orjson.dumps(payload))
tmp.replace(target)
def traces_path(run: str, step: int, kind: str, subset: str) -> Path:
if kind not in ("train", "eval") or subset not in ("all", "effective"):
raise HTTPException(400, "kind must be train|eval, subset all|effective")
run_dir = get_run_dir(run)
path = run_dir / "rollouts" / f"step_{step}" / kind / subset / "traces.jsonl"
if path.is_file():
return path
if (step, kind, subset) == EVAL_ROOT_STEP:
root = eval_root_traces(run_dir)
if root is not None:
return root
raise HTTPException(404, "no traces for this step/kind/subset")
@app.get("/api/runs/{run}/rollouts")
def list_rollouts(run: str) -> dict:
return {"steps": rollout_steps(get_run_dir(run))}
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}")
def list_episodes(
run: str,
step: int,
kind: str,
subset: str,
limit: int = Query(default=5000, le=5000),
env: str | None = None,
errors_only: bool = False,
sort: str = "line",
order: str = "asc",
etag: str | None = None,
) -> dict:
path = traces_path(run, step, kind, subset)
current_etag, unchanged = size_etag(path, etag)
if unchanged:
return unchanged
summaries = episode_summaries(path)
envs = sorted({s["env"] for s in summaries if s.get("env")})
if env:
summaries = [s for s in summaries if s.get("env") == env]
if errors_only:
summaries = [s for s in summaries if s.get("num_errors") or not s.get("ok")]
if sort in ("reward", "advantage", "output_tokens", "turns", "group"):
summaries = sorted(summaries, key=lambda s: (s.get(sort) is None, s.get(sort) or 0), reverse=(order == "desc"))
return {"total": len(summaries), "etag": current_etag, "envs": envs, "episodes": summaries[:limit]}
def get_tokenizer(model: str):
with _lock:
if model in _tokenizer_cache:
return _tokenizer_cache[model]
try:
from tokenizers import Tokenizer
tokenizer = Tokenizer.from_pretrained(model)
except Exception:
tokenizer = None
with _lock:
_tokenizer_cache[model] = tokenizer
return tokenizer
def decode_pieces(model: str, ids: list[int]) -> list[str] | None:
tokenizer = get_tokenizer(model)
if tokenizer is None:
return None
pieces = []
for token_id in ids:
piece = _piece_cache.get((model, token_id))
if piece is None:
piece = tokenizer.decode([token_id], skip_special_tokens=False)
_piece_cache[(model, token_id)] = piece
pieces.append(piece)
return pieces
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/series")
def episode_series(run: str, step: int, kind: str, subset: str, etag: str | None = None, after: int = 0) -> dict:
"""Per-episode series over a traces file (x = episode order): reward, shape, and the
nested rewards/metrics/timing keys — the metrics view for eval runs. `after` returns
only episodes past that index, so a growing file ships increments, not the world."""
path = traces_path(run, step, kind, subset)
current_etag, unchanged = size_etag(path, etag)
if unchanged:
return unchanged
summaries = episode_summaries(path)
keys: set[str] = set()
for s in summaries:
keys.update(
k
for k in ("reward", "advantage", "cost", "turns", "branches", "input_tokens", "output_tokens")
if s.get(k) is not None
)
for group in ("rewards", "metrics", "timing"):
keys.update(f"{group}/{name}" for name in s.get(group) or {})
def value(s: dict, key: str):
group, _, name = key.partition("/")
return (s.get(group) or {}).get(name) if name else s.get(key)
tail = summaries[max(0, after) :]
series = {key: [value(s, key) for s in tail] for key in sorted(keys)}
return {"etag": current_etag, "count": len(summaries), "after": max(0, after), "series": series}
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/{line}")
def get_episode(run: str, step: int, kind: str, subset: str, line: int, tokens: bool = False) -> dict:
path = traces_path(run, step, kind, subset)
offsets = line_offsets(path)
if not 0 <= line < len(offsets):
raise HTTPException(404, "episode line out of range")
with path.open("rb") as f:
f.seek(offsets[line])
rec = orjson.loads(f.readline())
if not tokens:
return rec
fallback_model = model_name(main_config(get_run_dir(run))[1])
for trace in rec.get("traces") or []:
client = ((trace.get("agent") or {}).get("config") or {}).get("client") or {}
model = client.get("renderer_model_name") or fallback_model
if not model:
continue
for node in trace.get("nodes") or []:
if node.get("token_ids"):
node["token_strs"] = decode_pieces(model, node["token_ids"])
return rec
# -------------------------------------------------------------------------- static
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
@app.get("/")
def index() -> FileResponse:
return FileResponse(STATIC_DIR / "index.html")
def render_status(url: str):
"""The startup console: the URL plus each tracked dir with its discovered runs."""
from rich.text import Text
text = Text()
text.append("\n prime-rl dashboard", style="bold white")
text.append(" · ", style="dim")
text.append(url + "\n", style="underline #B6FF3C")
runs = scan_runs()
for base in output_dirs:
text.append(f"\n {base.resolve()}/\n", style="dim")
names = sorted(name for name, run_dir in runs.items() if run_dir.parent == base) or ["(no runs yet)"]
for i, name in enumerate(names):
connector = "└── " if i == len(names) - 1 else "├── "
text.append(f" {connector}{name}\n", style="dim")
return text
def free_port(host: str, start: int) -> int:
"""The first free port at or above `start`, so several dashboards on one node
(e.g. a cluster head node) never collide."""
import socket
for port in range(start, start + 100):
with socket.socket() as sock:
try:
sock.bind((host, port))
except OSError:
continue
return port
raise SystemExit(f"no free port in [{start}, {start + 100})")
def main() -> None:
global output_dirs
parser = argparse.ArgumentParser(description="prime-rl run dashboard")
parser.add_argument("output_dirs", nargs="*", default=[Path("outputs")], type=Path, metavar="output_dir")
parser.add_argument("--port", type=int, default=7788)
parser.add_argument("--host", default="127.0.0.1")
args = parser.parse_args()
output_dirs = [d for d in args.output_dirs if d.is_dir()]
for missing in set(args.output_dirs) - set(output_dirs):
print(f"warning: output dir {missing} does not exist", file=sys.stderr)
if not output_dirs:
raise SystemExit("no existing output dir given")
port = free_port(args.host, args.port)
if port != args.port:
print(f"port {args.port} is taken - serving on {port}", file=sys.stderr)
args.port = port
url = f"http://localhost:{args.port}"
live = None
stop = threading.Event()
if sys.stdout.isatty():
# live console: re-scan every few seconds so new runs show up as tracked
from rich.console import Console
from rich.live import Live
live = Live(render_status(url), console=Console(), refresh_per_second=1)
live.start()
def watch() -> None:
while not stop.wait(3):
live.update(render_status(url))
threading.Thread(target=watch, daemon=True).start()
else:
dirs = ", ".join(str(d.resolve()) for d in output_dirs)
print(f"\n prime-rl dashboard · {dirs}\n {url}\n", flush=True)
try:
# short graceful-shutdown window: a Ctrl-C must not hang on the browser's
# open keep-alive connections
uvicorn.run(app, host=args.host, port=args.port, log_level="warning", timeout_graceful_shutdown=2)
finally:
# always unwind the Live display - it hides the terminal cursor, and an
# interrupt that skips its exit path would leave the shell cursorless
stop.set()
if live is not None:
live.stop()
if __name__ == "__main__":
main()
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

+199
View File
@@ -0,0 +1,199 @@
<!-- 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="logs">Logs</button>
</nav>
<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 class="seg" id="trace-kind">
<button data-kind="train" class="active">Train</button>
<button data-kind="eval">Eval</button>
</div>
<div class="seg" id="trace-subset">
<button data-subset="all">All</button>
<button data-subset="effective" class="active">Effective</button>
</div>
<span id="trace-status" class="muted"></span>
<div class="spacer"></div>
<div id="trace-filter-wrap" class="dd-wrap">
<button id="trace-filter-btn" class="btn dd-btn" title="filter &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>
<div id="trace-empty" hidden></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-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-filterhead">
<div class="seg" id="tm-kind">
<button data-kind="train">Train</button>
<button data-kind="eval">Eval</button>
</div>
<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 class="spacer"></div>
<button id="tm-prev" class="btn tm-nav" title="previous episode">↑</button>
<button id="tm-next" class="btn tm-nav" title="next episode">↓</button>
</div>
<div id="tm-list"></div>
</aside>
<section id="tm-main">
<div class="tm-head">
<span class="tm-title">Trace Viewer</span>
<div class="spacer"></div>
<select id="token-signal">
<option value="">text view</option>
<option value="advantage">tokens: advantage</option>
<option value="logprob">tokens: logprob</option>
<option value="mask">tokens: mask</option>
<option value="is_content">tokens: is_content</option>
</select>
<button id="tm-collapse" class="btn">collapse</button>
<button id="tm-expand" class="btn">expand</button>
<button id="drawer-close" class="btn">✕</button>
</div>
<div class="tm-head tm-tabs-row" id="tm-tabs-row" hidden>
<div id="tm-trace-tabs" class="seg" hidden></div>
<div id="tm-branch-tabs" class="seg" hidden></div>
</div>
<div id="tm-messages"></div>
</section>
<aside id="tm-right">
<div class="tm-head"><span class="tm-title">Overview</span></div>
<div id="tm-meta"></div>
</aside>
</div>
<script src="/static/vendor/uPlot.iife.min.js"></script>
<script src="/static/app.js"></script>
</body>
</html>
+803
View File
@@ -0,0 +1,803 @@
/* This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
Prime Intellect design language (prime-context: colors_and_type.css / brand.md).
Mono dominant, #111 canvas, lime accent used categorically, hairline dividers,
border-radius 0 everywhere, no shadows or gradients. ABC Favorit Mono is licensed
and not vendored here; the stack falls back to JetBrains Mono / system mono. */
:root {
--grey-1: #111111;
--grey-2: #1c1c1c;
--grey-3: #3a3a3a;
--grey-4: #767676;
--grey-5: #bcbcbc;
--grey-6: #ffffff;
--accent: #b6ff3c;
--negative: #ff4539;
--positive: #b6ff3c;
--infra: #4a9eff;
--risk: #ff6b4a;
--chart-1: #78f8a5;
--chart-2: #b7a6fa;
--chart-3: #fcdaa4;
--hairline: rgba(255, 255, 255, 0.1);
--hairline-faint: rgba(255, 255, 255, 0.06);
--font-mono: "ABC Favorit Mono", "JetBrains Mono", ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;
--track-mono: 0.04em;
--track-caps: 0.12em;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
summary { list-style: none; cursor: pointer; user-select: none; }
summary::-webkit-details-marker { display: none; }
html, body { height: 100%; }
body {
margin: 0;
background: var(--grey-1);
color: var(--grey-5);
font: 400 13px/1.5 var(--font-mono);
letter-spacing: var(--track-mono);
font-variant-numeric: tabular-nums lining-nums;
-webkit-font-smoothing: antialiased;
display: flex;
flex-direction: column;
}
.muted { color: var(--grey-4); font-size: 11px; }
.spacer { flex: 1; }
/* mono caps label — the house label style */
.t-label {
font-size: 11px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--grey-4);
}
/* ---------------------------------------------------------------- topbar */
#topbar {
display: flex;
align-items: center;
gap: 16px;
padding: 0 20px;
height: 52px;
border-bottom: 1px solid var(--hairline);
background: var(--grey-1);
position: sticky;
top: 0;
z-index: 20;
}
.brand { display: flex; align-items: center; gap: 10px; user-select: none; }
.brand img { height: 18px; display: block; }
#tabs { display: flex; gap: 2px; margin-left: 8px; align-self: stretch; }
#tabs button {
background: none;
border: none;
border-bottom: 1px solid transparent;
margin-bottom: -1px;
color: var(--grey-4);
font: 400 11px var(--font-mono);
letter-spacing: var(--track-caps);
text-transform: uppercase;
padding: 0 14px;
cursor: pointer;
}
#tabs button:hover { color: var(--grey-6); }
#tabs button.active { color: var(--accent); border-bottom-color: var(--accent); }
#topbar .toggle { margin-left: auto; }
select, .search, .btn {
background: transparent;
color: var(--grey-5);
border: 1px solid var(--grey-3);
border-radius: 0;
height: 28px;
padding: 0 10px;
font: 400 12px var(--font-mono);
letter-spacing: var(--track-mono);
outline: none;
}
/* flat selects: no native chrome, hairline chevron */
select {
appearance: none;
-webkit-appearance: none;
background-color: var(--grey-1);
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='5' viewBox='0 0 8 5'%3E%3Cpath d='M1 1l3 3 3-3' fill='none' stroke='%23767676' stroke-width='1.2'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 9px center;
padding-right: 26px;
cursor: pointer;
}
select:hover { border-color: var(--grey-6); color: var(--grey-6); }
option { background: var(--grey-1); color: var(--grey-5); }
select:focus, .search:focus { border-color: var(--grey-6); }
/* dropdown-opening buttons carry a caret; menus share one flat panel style */
.dd-btn { display: inline-flex; align-items: center; gap: 6px; }
.dd-btn::after {
content: "";
width: 8px;
height: 5px;
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='5' viewBox='0 0 8 5'%3E%3Cpath d='M1 1l3 3 3-3' fill='none' stroke='%23767676' stroke-width='1.2'/%3E%3C/svg%3E") no-repeat center;
}
.dd-wrap { position: relative; }
.dd-btn.active { color: var(--accent); border-color: var(--accent); }
/* selects dressed as dropdowns: lowercase label with ellipsis, scrollable options */
.dd-select .dd-btn { text-transform: none; letter-spacing: var(--track-mono); font-size: 12px; max-width: 340px; }
.dd-select .dd-btn span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dd-optlist { min-width: 100%; max-height: 320px; overflow-y: auto; padding: 4px 0; white-space: nowrap; }
.dd-opt { padding: 5px 12px; font-size: 12px; cursor: pointer; color: var(--grey-5); }
.dd-opt:hover { background: var(--grey-2); color: var(--grey-6); }
.dd-opt.active { color: var(--accent); }
.dd-opt.disabled { color: var(--grey-3); cursor: default; }
.dd-menu {
position: absolute;
top: 34px;
z-index: 40;
background: var(--grey-1);
border: 1px solid var(--grey-3);
padding: 8px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
}
.btn {
cursor: pointer;
text-transform: uppercase;
font-size: 11px;
letter-spacing: var(--track-caps);
color: var(--grey-5);
}
.btn:hover { border-color: var(--grey-6); color: var(--grey-6); }
.btn:active { background: rgba(255, 255, 255, 0.04); }
#run-select { max-width: 340px; font-size: 12px; }
.badge {
font: 400 10px var(--font-mono);
letter-spacing: var(--track-caps);
text-transform: uppercase;
padding: 3px 8px;
border: 1px solid var(--grey-3);
border-radius: 0;
color: var(--grey-5);
}
/* run overview card — platform-style run header shown on every tab */
#run-overview {
padding: 16px 20px 14px;
border-bottom: 1px solid var(--hairline);
display: flex;
flex-direction: column;
gap: 14px;
}
.ov-top { display: flex; align-items: flex-end; gap: 48px; flex-wrap: wrap; }
.ov-field { display: flex; flex-direction: column; gap: 6px; }
.ov-field .lbl {
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--grey-4);
}
.ov-field .val {
font-size: 13px;
color: var(--grey-6);
max-width: 280px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.st-running { color: var(--accent); border-color: rgba(182, 255, 60, 0.5); background: rgba(182, 255, 60, 0.08); }
.st-completed { color: var(--chart-1); border-color: rgba(120, 248, 165, 0.4); }
.st-stopped { color: var(--grey-4); }
/* slider controls (smoothing, pane size) */
.ctl {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--grey-4);
}
.ctl input[type="range"] { width: 110px; accent-color: var(--accent); }
.ctl span { color: var(--grey-5); min-width: 24px; }
.toggle {
display: inline-flex;
align-items: center;
gap: 8px;
cursor: pointer;
color: var(--grey-4);
font-size: 11px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
user-select: none;
}
.toggle input { display: none; }
.toggle .dot { width: 10px; height: 10px; border: 1px solid var(--grey-3); background: transparent; }
.toggle input:checked + .dot { background: var(--accent); border-color: var(--accent); }
/* the LIVE indicator is a pulsing circle */
#topbar .toggle .dot { width: 7px; height: 7px; border-radius: 50%; }
#topbar .toggle input:checked + .dot { animation: live-pulse 2s ease-out infinite; }
@keyframes live-pulse {
0% { box-shadow: 0 0 0 0 rgba(182, 255, 60, 0.55); }
70% { box-shadow: 0 0 0 5px rgba(182, 255, 60, 0); }
100% { box-shadow: 0 0 0 0 rgba(182, 255, 60, 0); }
}
/* ------------------------------------------------------------------ main */
main { flex: 1; min-height: 0; display: flex; flex-direction: column; }
main > section { flex: 1; min-height: 0; display: flex; flex-direction: column; padding: 16px 20px; gap: 12px; }
.controls { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.seg { display: inline-flex; border: 1px solid var(--grey-3); flex-shrink: 0; }
/* arrow stepper (log level): ‹ label › */
.stepper { display: inline-flex; align-items: center; border: 1px solid var(--grey-3); height: 28px; }
.stepper button { background: none; border: none; color: var(--grey-4); width: 24px; height: 100%; cursor: pointer; font: 400 13px var(--font-mono); }
.stepper button:hover:not(:disabled) { color: var(--grey-6); }
.stepper button:disabled { opacity: 0.3; cursor: default; }
.stepper span {
font-size: 11px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--grey-5);
min-width: 52px;
text-align: center;
}
.seg button {
white-space: nowrap;
background: transparent;
border: none;
color: var(--grey-4);
height: 26px;
padding: 0 12px;
font: 400 11px var(--font-mono);
letter-spacing: var(--track-caps);
text-transform: uppercase;
cursor: pointer;
}
.seg button + button { border-left: 1px solid var(--grey-3); }
.seg button.active { background: var(--grey-2); color: var(--accent); }
.seg button:disabled { opacity: 0.35; cursor: default; }
/* checkbox rows (compare menu, filter menus) */
.file-item { display: flex; align-items: center; gap: 8px; padding: 3px 4px; cursor: pointer; font-size: 11px; }
.file-item:hover { background: var(--grey-2); }
.file-item input { appearance: none; width: 9px; height: 9px; border: 1px solid var(--grey-3); margin: 0; flex-shrink: 0; }
.file-item input:checked { background: var(--accent); border-color: var(--accent); }
/* multi-run compare menu */
#compare-menu {
left: 0;
min-width: 320px;
max-height: 50vh;
overflow-y: auto;
}
/* --------------------------------------------------------------- metrics */
/* stable gutter: no layout shift when collapsing sections hides the scrollbar */
#metrics-body { flex: 1; overflow-y: auto; scrollbar-gutter: stable; min-height: 0; padding-right: 10px; }
.chart-card.dragging { opacity: 0.45; }
/* one 12px rhythm everywhere: section-to-section, header-to-panes, pane-to-pane */
details.section { margin-bottom: 12px; }
/* nested sections (all-mode key tree) indent one step */
details.section details.section { margin-left: 14px; }
details.section:not([open]) > summary { margin-bottom: 0; }
/* section headers are full-width bars so the clickable region is obvious */
details.section > summary {
font: 400 11px var(--font-mono);
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--grey-5);
margin: 0 0 12px;
padding: 7px 12px;
background: var(--grey-2);
border: 1px solid var(--hairline);
display: flex;
align-items: center;
gap: 10px;
}
details.section > summary:hover { color: var(--grey-6); border-color: var(--grey-3); }
details.section .sec-chev { margin-left: auto; transition: transform 0.12s; font-size: 10px; color: var(--grey-4); }
details.section[open] .sec-chev { transform: rotate(90deg); }
.chart-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(var(--pane-min, 260px), 1fr)); gap: 12px; }
/* eval runs: running-average stat cards instead of x/y chart panes */
.stat-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; }
.stat-card { background: var(--grey-2); border: 1px solid var(--hairline); padding: 12px 14px; min-width: 0; }
.stat-card:hover { border-color: var(--grey-3); }
.stat-label {
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--grey-4);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.stat-value { font-size: 20px; color: var(--grey-6); margin: 6px 0 0; }
.eval-progress { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
.ep-bar { flex: 1; height: 6px; background: var(--grey-2); border: 1px solid var(--hairline); }
.ep-fill { height: 100%; background: var(--accent); }
.ep-label {
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--grey-4);
white-space: nowrap;
}
.chart-card {
position: relative;
background: var(--grey-2);
border: 1px solid var(--hairline);
padding: 8px 10px 8px;
min-width: 0;
}
.chart-card:hover { border-color: var(--grey-3); }
.chart-head { display: flex; align-items: baseline; gap: 10px; margin-bottom: 2px; cursor: grab; }
.chart-title {
font-size: 10px;
letter-spacing: var(--track-mono);
color: var(--grey-4);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex: 1;
}
.chart-last { font-size: 12px; font-weight: 500; color: var(--grey-6); }
.chart-empty {
height: 120px;
display: flex;
align-items: center;
justify-content: center;
color: var(--grey-4);
font-size: 11px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
/* minimal empty state, shared by every "nothing here" case: just dim text */
.empty-box {
margin: 64px auto;
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
text-align: center;
white-space: normal;
}
.empty-title {
font-size: 11px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--grey-4);
}
.empty-detail {
font-size: 11px;
letter-spacing: var(--track-mono);
color: var(--grey-4);
word-break: break-word;
}
.u-cursor-pt { display: none !important; }
/* hover highlight dot on the snapped data point */
.u-dot {
position: absolute;
top: 0;
left: 0;
width: 6px;
height: 6px;
border-radius: 50%;
pointer-events: none;
will-change: transform;
}
/* drag-to-zoom selection highlight */
.u-select { background: rgba(182, 255, 60, 0.1); outline: 1px solid rgba(182, 255, 60, 0.35); }
/* hover popover with x/y values */
.u-tip {
position: absolute;
top: 0;
left: 0;
z-index: 5;
pointer-events: none;
background: var(--grey-1);
border: 1px solid var(--grey-3);
padding: 6px 9px;
font: 10.5px var(--font-mono);
letter-spacing: var(--track-mono);
white-space: nowrap;
}
.u-tip-x {
color: var(--grey-4);
font-size: 9.5px;
text-transform: uppercase;
letter-spacing: var(--track-caps);
margin-bottom: 3px;
}
.u-tip-row { display: flex; align-items: center; gap: 6px; padding: 1px 0; }
.u-tip-row .sw { width: 7px; height: 7px; flex-shrink: 0; }
.u-tip-row .sw-band { border: 1px dotted; background: transparent; }
.u-tip-l { color: var(--grey-4); }
.u-tip-v { color: var(--grey-6); margin-left: auto; padding-left: 10px; }
/* metrics regex filter (overview + all) */
#metrics-search, #config-search, #log-search { flex: 1; max-width: 460px; }
/* wandb-style resize handles on every chart card: right edge = width, bottom
edge = height, corner = both. Resizing one pane resizes all of them. */
.rz { position: absolute; opacity: 0; }
.chart-card:hover .rz { opacity: 1; }
.rz-e { top: 0; right: 0; bottom: 16px; width: 6px; cursor: ew-resize; }
.rz-s { left: 0; right: 16px; bottom: 0; height: 6px; cursor: ns-resize; }
.rz-e:hover, .rz-s:hover { background: rgba(255, 255, 255, 0.08); }
.rz-se {
right: 0;
bottom: 0;
width: 16px;
height: 16px;
cursor: nwse-resize;
background:
linear-gradient(135deg, transparent 0 50%, var(--grey-3) 50% calc(50% + 1px), transparent calc(50% + 1px) 100%) no-repeat 3px 3px / 10px 10px,
linear-gradient(135deg, transparent 0 50%, var(--grey-3) 50% calc(50% + 1px), transparent calc(50% + 1px) 100%) no-repeat 7px 7px / 10px 10px;
}
body.resizing { user-select: none; }
/* ---------------------------------------------------------------- config */
#config-view {
flex: 1;
overflow: auto;
background: var(--grey-2);
border: 1px solid var(--hairline);
padding: 14px 16px;
margin: 0;
font-size: 12px;
line-height: 1.55;
white-space: normal;
}
/* collapsible JSON tree */
#config-view .j-line { white-space: pre; padding: 0 6px; }
/* TOML (launch config) lines: whitespace preserved, minimal highlighting */
#config-view .t-line { white-space: pre-wrap; padding: 0 6px; min-height: 1.55em; }
#config-view .t-line:hover { background: rgba(255, 255, 255, 0.05); }
.t-section { color: var(--accent); }
#config-view div.j-line:hover, #config-view summary.j-line:hover { background: rgba(255, 255, 255, 0.05); }
.j-ellip { color: var(--grey-4); }
details.j-fold[open] > summary .j-ellip { display: none; }
mark.hit {
background: rgba(182, 255, 60, 0.22);
color: var(--grey-6);
outline: 1px solid rgba(182, 255, 60, 0.4);
}
.j-key { color: var(--grey-6); }
.j-str { color: var(--chart-1); }
.j-num { color: var(--chart-2); }
.j-lit { color: var(--chart-3); }
.j-punc { color: var(--grey-4); }
/* ------------------------------------------------------------------ logs */
/* vertical stack of component panes (trainer / orchestrator / inference / envs) */
/* split view always fills the tab: panes share the height equally */
#log-panes { flex: 1; display: flex; flex-direction: column; gap: 10px; min-height: 0; }
.log-pane {
flex: 1 1 0;
min-height: 80px;
display: flex;
flex-direction: column;
border: 1px solid var(--hairline);
background: var(--grey-1);
min-width: 0;
}
#log-panes.maxed { overflow: hidden; }
#log-panes.maxed .log-pane { display: none; }
#log-panes.maxed .log-pane.maximized { display: flex; flex: 1; height: auto; }
#log-comp-menu {
left: 0;
min-width: 220px;
}
.log-pane-head {
display: flex;
align-items: center;
gap: 10px;
padding: 5px 10px;
border-bottom: 1px solid var(--hairline);
background: var(--grey-2);
}
.lp-title {
font-size: 10px;
font-weight: 500;
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--grey-5);
}
.lp-file { height: 24px; font-size: 11px; max-width: 280px; }
.lp-count { font-size: 10px; color: var(--grey-4); }
.lp-max { height: 24px; padding: 0 8px; }
.log-pane-stream {
flex: 1;
overflow: auto;
padding: 8px 12px;
font-size: 11.5px;
line-height: 1.55;
white-space: pre-wrap;
word-break: break-word;
font-family: var(--font-mono);
}
.ll { display: flex; gap: 8px; }
.ll:hover { background: var(--grey-2); }
.ll .ltext { flex: 1; min-width: 0; }
/* merge view: right-aligned component badge column */
.ll .lgb {
flex-shrink: 0;
width: 112px;
display: flex;
justify-content: flex-end;
align-items: flex-start;
padding-top: 1px;
user-select: none;
}
.ll .lgb-badge {
font-size: 9px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--grey-4);
background: var(--grey-2);
border: 1px solid var(--hairline);
padding: 0 5px;
line-height: 14px;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* ANSI — mapped onto the PI palette */
.a-bold { font-weight: 500; color: var(--grey-6); }
.a-dim { opacity: 0.55; }
.fg30 { color: var(--grey-3); } .fg31 { color: var(--negative); } .fg32 { color: var(--chart-1); }
.fg33 { color: var(--chart-3); } .fg34 { color: var(--infra); } .fg35 { color: var(--chart-2); }
.fg36 { color: #7adfff; } .fg37 { color: var(--grey-5); }
.fg90 { color: var(--grey-4); } .fg91 { color: var(--risk); } .fg92 { color: var(--chart-1); }
.fg93 { color: var(--chart-3); } .fg94 { color: var(--infra); } .fg95 { color: var(--chart-2); }
.fg96 { color: #7adfff; } .fg97 { color: var(--grey-6); }
/* ---------------------------------------------------------------- traces */
/* step selector: one block per rollout step, filled up to the selection */
#step-blocks { flex: 1; display: flex; gap: 2px; height: 16px; min-width: 0; margin-bottom: 4px; }
.sb-cell { position: relative; flex: 1; min-width: 0; background: var(--grey-2); border: 1px solid var(--hairline); cursor: pointer; }
.sb-cell:hover { border-color: var(--grey-6); }
.sb-cell.on { background: var(--accent); border-color: var(--accent); }
/* eval steps carry a small dot under the block (same mark as the step label) */
.sb-cell.eval::after {
content: "";
position: absolute;
left: 50%;
bottom: -6px;
width: 3px;
height: 3px;
margin-left: -1.5px;
border-radius: 50%;
background: var(--grey-5);
}
.sb-cell.eval:hover::after { background: var(--grey-6); }
#trace-filter-menu {
right: 0;
min-width: 240px;
display: flex;
flex-direction: column;
gap: 8px;
}
#step-label { display: inline-flex; align-items: center; gap: 7px; color: var(--grey-5); }
.eval-dot { display: inline-block; width: 4px; height: 4px; border-radius: 50%; background: var(--grey-5); }
#episode-table-wrap { flex: 1; overflow: auto; border: 1px solid var(--hairline); background: var(--grey-1); min-height: 0; }
#episode-table .vpad td { padding: 0; border: 0; }
#episode-table { width: 100%; border-collapse: collapse; font-size: 11.5px; }
#episode-table th {
text-align: left;
font: 400 10px var(--font-mono);
text-transform: uppercase;
letter-spacing: var(--track-caps);
color: var(--grey-4);
padding: 9px 10px;
border-bottom: 1px solid var(--grey-3);
position: sticky;
top: 0;
background: var(--grey-1);
z-index: 1;
}
#episode-table td { padding: 5px 10px; border-bottom: 1px solid var(--hairline-faint); white-space: nowrap; }
#episode-table tbody tr { cursor: pointer; }
#episode-table tbody tr:hover { background: var(--grey-2); }
.r-pos { color: var(--positive); }
.r-neg { color: var(--negative); }
.r-zero { color: var(--grey-4); }
.status-ok { color: var(--positive); }
.status-err { color: var(--negative); }
/* ----------------------------------------------------- trace viewer modal */
#drawer-backdrop { position: fixed; inset: 0; background: rgba(17, 17, 17, 0.8); z-index: 30; }
#trace-modal {
position: fixed;
inset: 3vh 2vw;
background: var(--grey-1);
border: 1px solid var(--grey-3);
z-index: 31;
display: grid;
grid-template-columns: 280px minmax(0, 1fr) 320px;
}
.tm-head {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 14px;
border-bottom: 1px solid var(--hairline);
min-height: 48px;
}
.tm-title { font-size: 12px; font-weight: 500; color: var(--grey-6); white-space: nowrap; }
#tm-left { border-right: 1px solid var(--hairline); display: flex; flex-direction: column; min-height: 0; }
#tm-left .search { margin: 10px 14px 6px; }
#tm-list { flex: 1; overflow-y: auto; padding: 4px 8px 10px; }
.tm-item {
display: flex;
align-items: center;
gap: 8px;
padding: 5px 10px;
cursor: pointer;
white-space: nowrap;
font-size: 11.5px;
color: var(--grey-5);
border: 1px solid transparent;
}
.tm-item .tm-num { flex-shrink: 0; }
/* env names never wrap - they clip with an ellipsis so every row is one line */
.tm-item .tm-env { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tm-item .tm-reward { flex-shrink: 0; }
.tm-item:hover { background: var(--grey-2); }
.tm-item.active { background: var(--grey-2); border-color: var(--grey-3); color: var(--grey-6); }
.tm-item .tm-reward { margin-left: auto; }
.tm-nav { padding: 0 8px; height: 24px; }
.tm-stephead { justify-content: space-between; background: var(--grey-2); min-height: 40px; }
#step-label, #tm-step-label { white-space: nowrap; }
#tm-step-label { color: var(--grey-6); }
.tm-filterhead { gap: 8px; }
.tm-filterhead .seg button { height: 22px; padding: 0 9px; font-size: 10px; }
#tm-step-label {
font-size: 11px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--grey-6);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
#tm-step-label .muted { text-transform: none; letter-spacing: var(--track-mono); }
#tm-main { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
#tm-messages { flex: 1; overflow-y: auto; padding: 14px 16px; }
#tm-right { border-left: 1px solid var(--hairline); overflow-y: auto; min-height: 0; }
#tm-meta { padding: 12px 14px; }
/* numbered collapsible message entries */
details.entry { border: 1px solid var(--hairline); margin-bottom: 8px; }
details.entry > summary {
display: flex;
align-items: center;
gap: 10px;
padding: 7px 12px;
background: var(--grey-2);
min-width: 0;
}
details.entry[open] > summary { border-bottom: 1px solid var(--hairline); }
.entry-num { font-size: 10px; color: var(--grey-4); letter-spacing: var(--track-mono); }
.entry-role {
font-size: 10px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: var(--track-caps);
color: var(--accent);
white-space: nowrap;
}
.entry-preview {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--grey-4);
font-size: 11px;
}
details.entry[open] > summary > .entry-preview { visibility: hidden; }
.entry-chev { color: var(--grey-4); font-size: 10px; transition: transform 0.12s; }
details.entry[open] .entry-chev { transform: rotate(90deg); }
.entry-body { padding: 10px 14px; font-size: 12px; white-space: pre-wrap; word-break: break-word; color: var(--grey-5); }
.chip {
font-size: 10px;
border: 1px solid var(--grey-3);
padding: 1px 7px;
color: var(--grey-4);
letter-spacing: var(--track-mono);
white-space: nowrap;
}
.icon-btn {
background: none;
border: none;
color: var(--grey-4);
cursor: pointer;
font-size: 12px;
padding: 2px 4px;
line-height: 1;
}
.icon-btn:hover { color: var(--grey-6); }
.icon-btn.copied { color: var(--accent); }
/* nested sub-blocks (reasoning) */
details.sub { border: 1px solid var(--hairline); margin: 8px 12px; }
details.sub > summary {
display: flex;
align-items: center;
gap: 10px;
padding: 5px 10px;
font-size: 10.5px;
color: var(--grey-5);
background: rgba(255, 255, 255, 0.03);
}
details.sub .sub-name { font-weight: 500; color: var(--grey-6); }
details.sub > .entry-body { border-top: 1px solid var(--hairline); }
/* right pane: overview metadata */
.tm-reward-big { color: var(--positive); }
.tm-reward-big.neg { color: var(--negative); }
.tm-reward-big.na { color: var(--grey-4); }
.meta-sec {
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
color: var(--accent);
margin: 16px 0 6px;
}
.meta-row { display: flex; align-items: center; gap: 8px; padding: 3px 0; font-size: 11.5px; }
.meta-row .k { color: var(--grey-4); }
.meta-row .k .tree { color: var(--grey-3); }
.meta-row .v { margin-left: auto; color: var(--grey-6); text-align: right; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 60%; }
.meta-row .v.id { font-size: 10.5px; color: var(--grey-5); border: 1px solid var(--hairline); padding: 2px 6px; }
details.meta-fold { border: 1px solid var(--hairline); margin: 8px 0; }
details.meta-fold > summary { padding: 6px 10px; font-size: 10.5px; color: var(--grey-5); }
details.meta-fold > pre { margin: 0; border: none; border-top: 1px solid var(--hairline); }
/* tool calls: green-terminal block */
.tool-call {
margin: 8px 12px 10px;
padding: 7px 10px;
background: #0b1403;
border: 1px solid rgba(182, 255, 60, 0.22);
color: var(--accent);
font-size: 12px;
white-space: pre-wrap;
word-break: break-word;
}
.tok { padding: 0 1px; }
.tok:hover { outline: 1px solid var(--grey-6); }
.tok-tip {
position: fixed;
z-index: 100;
pointer-events: none;
background: var(--grey-1);
border: 1px solid var(--grey-3);
padding: 4px 8px;
font: 400 11px var(--font-mono);
color: var(--grey-5);
white-space: nowrap;
}
pre.json { background: var(--grey-2); border: 1px solid var(--hairline); padding: 12px; font-size: 11px; overflow-x: auto; }
::-webkit-scrollbar { width: 10px; height: 10px; }
::-webkit-scrollbar-thumb { background: var(--grey-3); }
::-webkit-scrollbar-thumb:hover { background: var(--grey-4); }
::-webkit-scrollbar-track { background: transparent; }
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;}
+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))
+5 -2
View File
@@ -26,6 +26,7 @@ from prime_rl.utils.pathing import (
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 +121,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}")
@@ -252,7 +254,7 @@ def rl_local(config: RLConfig):
for split, source, address in env_servers(config):
name = source.resolved_name
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
logger.info(f"Starting {split} env server {name} at {address}")
logger.info(f"Starting {name} server")
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
env_server_log.parent.mkdir(parents=True, exist_ok=True)
@@ -282,7 +284,7 @@ def rl_local(config: RLConfig):
monitor_threads.append(monitor_thread)
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()]
logger.info("Starting orchestrator process")
logger.info("Starting orchestrator")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
with open(log_dir / "orchestrator.log", "w") as log_file:
orchestrator_process = Popen(
@@ -557,6 +559,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":
+5 -2
View File
@@ -25,6 +25,7 @@ from prime_rl.utils.pathing import (
latest_log_dir,
resolve_latest_ckpt_step,
validate_run_dir,
write_launch_toml,
)
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
@@ -248,6 +249,7 @@ def sft_slurm(config: SFTConfig):
decoupled_eval = config.deployment.type == "multi_node" and config.eval is not None
config_dir = get_config_dir(config.run_dir)
write_launch_toml(config.run_dir, "sft")
config_path = config_dir / SFT_CONFIG
exclude = (
{"deployment", "slurm", "dry_run", "clean"}
@@ -353,6 +355,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}")
@@ -446,7 +449,7 @@ def sft_local(config: SFTConfig):
# deterministic address, polling until the server is up.
for source, address in eval_env_servers(config):
name = source.resolved_name
logger.info(f"Starting eval env server {name} at {address}")
logger.info(f"Starting {name} server")
start_process(
f"env/eval/{name}",
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
@@ -455,7 +458,7 @@ def sft_local(config: SFTConfig):
)
if config.eval is not None:
logger.info("Starting evals process")
logger.info("Starting evals")
start_process(
"evals",
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
+96 -102
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``,
@@ -30,6 +32,8 @@ 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
@@ -43,10 +47,10 @@ from prime_rl.orchestrator.patches import (
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.types import EvalBatch, 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 get_all_ckpt_steps, get_config_dir, get_log_dir
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
from prime_rl.utils.utils import clean_exit
@@ -56,10 +60,9 @@ 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:
@@ -76,12 +79,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 +107,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 +118,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 +150,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 +168,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 +181,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); "
@@ -242,65 +257,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 +315,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 +362,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
@@ -438,18 +434,16 @@ 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)
+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
+16 -7
View File
@@ -9,6 +9,7 @@ down training.
from __future__ import annotations
import os
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, overload
@@ -18,7 +19,7 @@ from prime_rl.monitors.file import FileMonitor
from prime_rl.monitors.prime import PrimeMonitor
from prime_rl.monitors.wandb import WandbMonitor
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
if TYPE_CHECKING:
import verifiers.v1 as vf
@@ -44,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,
@@ -60,12 +62,13 @@ async def setup(
if rank != 0:
return
monitors: list[tuple[Monitor, dict[str, Any]]] = []
monitors: list[tuple[str, Monitor, dict[str, Any]]] = []
if prime is not None:
monitors.append((PrimeMonitor(prime), dict(config=run_config)))
monitors.append(("prime", PrimeMonitor(prime), dict(config=run_config)))
if wandb is not None:
monitors.append(
(
"wandb",
WandbMonitor(wandb),
dict(
output_dir=output_dir,
@@ -77,11 +80,17 @@ async def setup(
)
)
if file is not None:
monitors.append((FileMonitor(file), dict(output_dir=output_dir)))
monitors.append(("file", FileMonitor(file), dict(output_dir=output_dir, producer=producer)))
if not monitors:
return
for monitor, init_kwargs in monitors:
get_logger().info(f"Initializing monitors ({', '.join(name for name, _, _ in monitors)})")
t0 = time.perf_counter()
for name, monitor, init_kwargs in monitors:
get_logger().info(f"Initializing {name} monitor ({monitor.config})")
await monitor.init(**init_kwargs)
MONITORS.append(monitor)
get_logger().debug(f"Initialized monitors in {format_time(time.perf_counter() - t0)}")
def get(monitor_cls: type[Monitor]) -> Monitor | None:
@@ -91,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
@@ -100,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:
+8 -3
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 to {self.path} and episodes to {output_dir / 'rollouts'}")
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:
+20 -4
View File
@@ -16,6 +16,7 @@ from prime_rl.configs.monitors import WandbMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.monitors.wandb.overview import ensure_overview_view
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import format_time
if TYPE_CHECKING:
import verifiers.v1 as vf
@@ -63,7 +64,7 @@ class WandbMonitor(Monitor):
x_primary=primary,
x_update_finish_state=finisher,
)
self.logger.info(f"Using shared W&B mode ({label=}, {primary=}, {finisher=})")
self.logger.debug(f"Using shared W&B mode ({label=}, {primary=}, {finisher=})")
is_online = True
else:
run_id = None
@@ -112,6 +113,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
@@ -130,16 +134,28 @@ class WandbMonitor(Monitor):
except Exception as e:
self.logger.warning(f"Failed to create W&B overview view - {e}")
self.logger.info(f"Logging metrics to W&B run {self.wandb.id} ({self.wandb.url})")
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
async def finalize(self) -> None:
self.logger.info(f"Finalizing W&B run {self.wandb.id}")
t0 = time.perf_counter()
# Explicit finish: in (experimental) shared mode the SDK's atexit finish does
# not land the run state - without this, even clean runs decay to "crashed".
await asyncio.to_thread(wandb.finish, exit_code=0)
self.logger.debug(f"Finalized W&B run in {format_time(time.perf_counter() - t0)}")
+4
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
+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,13 +197,20 @@ async def maybe_check_has_model(
async def check_health(
admin_clients: list[AsyncClient], interval: int = 1, log_interval: int = 10, 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:
wait_time = 0
logger.debug("Starting pinging /health to check health")
logger.debug("Pinging /health until the inference server is ready")
while wait_time < timeout:
try:
response = await admin_client.get("/health")
@@ -190,9 +222,9 @@ async def check_health(
return
except Exception as e:
if wait_time % log_interval == 0 and wait_time > 0:
logger.warning(
f"Inference server was not reached after {wait_time} seconds (Error: {e}) on {admin_client.base_url}"
)
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
msg = f"Inference server is not ready after {wait_time} (>{timeout}) seconds. Aborting..."
@@ -202,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):
@@ -253,7 +282,7 @@ async def _admin_post(client: AsyncClient, path: str, *, timeout_s: float = ADMI
async def _pause_engines(admin_clients: list[AsyncClient], *, step: int) -> None:
"""Pause all inference engines, waiting for in-flight requests to drain."""
logger = get_logger()
logger.info(f"Updating policy in-flight to v{step}")
logger.debug(f"Pausing inference engines to update weights to policy v{step}")
await asyncio.gather(
*[_admin_post(client, "/pause", params={"mode": "keep", "clear_cache": "false"}) for client in admin_clients]
)
@@ -274,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:
@@ -375,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.
@@ -404,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(
+11 -13
View File
@@ -38,6 +38,7 @@ 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
@@ -53,7 +54,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
@@ -151,7 +151,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 +168,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
@@ -221,14 +221,14 @@ class Dispatcher:
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:
@@ -500,14 +500,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:
@@ -678,7 +676,7 @@ class Dispatcher:
env_name = group.env_name if group is not None else claimed[-1][1].env_name
self.metrics.record_cancellation(kind=kind, env_name=env_name, n=cancelled)
get_logger().debug(
f"drop {kind} | group={str(group_id)[:8]} env={env_name} reason={reason} | "
f"Dropped {kind} group | group={str(group_id)[:8]} env={env_name} reason={reason} | "
f"cancelled={cancelled} (inflight={inflight_cancelled} unscheduled={unscheduled_cancelled})"
)
await self.out_q.put(
+8 -5
View File
@@ -20,6 +20,7 @@ keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
from __future__ import annotations
import asyncio
import time
from collections.abc import Iterator, Sequence
from itertools import islice
from typing import Generic, TypeVar
@@ -30,7 +31,7 @@ from verifiers.v1.serve import EnvClient
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
from prime_rl.orchestrator.generation_source import GenerationSource
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
# Max wait for the env server to answer health. Generous because the launcher spawns
# servers concurrently with the orchestrator, and a server imports its env package
@@ -68,6 +69,7 @@ class Env:
async def start(self) -> None:
"""Connect to the env server and load the taskset client-side."""
get_logger().debug(f"Connecting {self.name} to env server {self.address}")
t0 = time.perf_counter()
self._env_client = EnvClient(address=self.address)
# The server may still be coming up (the launcher spawns it concurrently with
# the orchestrator), so poll until it answers.
@@ -82,7 +84,7 @@ class Env:
self.tasks = iter(materialized)
self.num_tasks = len(materialized)
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks}")
get_logger().info(f"Env {self.name} ready in {format_time(time.perf_counter() - t0)} (num_tasks={num_tasks})")
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
sampling = {**self.sampling_args}
@@ -190,17 +192,18 @@ class TrainEnvs(Envs[TrainEnv]):
configs: Sequence[TrainSourceConfig],
addresses: dict[tuple[str, str], str],
*,
policy_pool,
clients,
renderer_config=None,
):
self._envs: dict[str, TrainEnv] = {}
for config in configs:
assert config.algo is not None, "TrainSourceConfig.algo must be resolved before env construction"
get_logger().info(f"Initializing {config.algo.type} algorithm for {config.resolved_name}")
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
+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
+149 -165
View File
@@ -26,22 +26,19 @@ 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 renderers.base import Renderer
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.orchestrator.ckpt import CheckpointManager
from prime_rl.transports.rollouts.base import MicroBatchSender
from prime_rl.utils.client import InferencePool
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
@@ -68,22 +65,21 @@ from prime_rl.orchestrator.utils import (
episode_group_id,
episode_staleness,
eval_work,
get_weight_dir,
intercept_vf_logging,
set_default_executor,
setup_policy_inference_pool,
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 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.pathing import get_broadcast_dir
from prime_rl.utils.utils import (
clean_exit,
final_broadcast_version,
resolve_latest_ckpt_step,
)
@@ -124,8 +120,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
@@ -137,14 +134,12 @@ class Orchestrator:
periodic_logger: PeriodicLogger
# Set by ``setup()`` only when relevant config is present
renderer: Renderer | None
mm_token_type_ids_mapping: dict[int, int] | None
heart: Heartbeat | None
inference_metrics: InferenceMetricsCollector | None
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
@@ -154,8 +149,7 @@ class Orchestrator:
# Route the in-process v1 library logging through our handler. The
# env server runs in a child process, so its logging is separate.
intercept_vf_logging(logger="verifiers.v1", level="WARN")
algorithms = sorted({env.algo.type for env in config.train.source if env.algo is not None})
get_logger().info(f"Starting orchestrator (algorithm: {', '.join(algorithms)})")
get_logger().info("Starting orchestrator")
self.progress = Progress()
self.ckpt_manager = setup_ckpt_manager(config.output_dir, config.ckpt)
@@ -176,19 +170,20 @@ class Orchestrator:
self.wait_for_policy_time = 0.0
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.renderer = None
self.mm_token_type_ids_mapping = None
self.heart = None
self.inference_metrics = None
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,25 +194,25 @@ class Orchestrator:
set_default_executor()
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
t0 = time.perf_counter()
self.tokenizer = setup_tokenizer(config.tokenizer)
get_logger().debug(f"Initialized tokenizer in {format_time(time.perf_counter() - t0)}")
# The one model prime-rl hosts: the live policy. Frozen model
# references are external endpoints — each env's Algorithm builds its
# own pools in ``setup()`` below.
get_logger().info(
f"Initializing policy inference pool (base_url={config.model.client.base_url}, model={config.model.name})"
get_logger().info(f"Initializing policy inference pool ({config.model})")
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.renderer, self.policy_inference = await setup_policy_inference_pool(
config=config, tokenizer=self.tokenizer
)
self.mm_token_type_ids_mapping = (
getattr(self.renderer, "mm_token_type_id_map", None) if self.renderer is not None else None
)
if self.mm_token_type_ids_mapping == {}:
self.mm_token_type_ids_mapping = None
self.admin_clients = AdminClients(config.model.client)
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
producer="orch",
wandb=config.monitors.wandb,
prime=config.monitors.prime,
file=config.monitors.file,
@@ -237,25 +232,14 @@ class Orchestrator:
if config.heartbeat is not None:
self.heart = Heartbeat(config.heartbeat.url)
get_logger().info("Loading training environments")
self.train_envs = TrainEnvs(
config.train.source,
config.env_addresses,
policy_pool=self.policy_inference,
clients=self.clients,
renderer_config=config.renderer,
)
get_logger().debug(
f"Loaded {len(self.train_envs)} training environment(s) ({', '.join(self.train_envs.names)})"
)
await self.train_envs.start()
get_logger().success("Train environment(s) ready")
if config.eval is not None:
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.eval.source, config.env_addresses)
get_logger().debug(f"Loaded {len(self.eval_envs)} eval environment(s) ({', '.join(self.eval_envs.names)})")
await self.eval_envs.start()
get_logger().success("Eval environment(s) ready")
if config.resume is not None:
if config.resume.dir is not None:
@@ -266,11 +250,49 @@ 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.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
# trainer even when ``ckpt.skip_progress`` leaves the counter unrestored. The curricula
# themselves are restored below, once the envs are loaded.
if self.resume_step is not None:
self.progress.step = self.resume_step + 1
get_logger().info(f"Resuming from step {self.resume_step}")
else:
get_logger().info("Starting from scratch")
# 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_batch_sender(
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
)
# Wait phase: envs, then inference, then the trainer's startup broadcast —
# the last things before the main loop starts.
get_logger().info(f"Loading train environments ({', '.join(self.train_envs.names)})")
t0 = time.perf_counter()
await self.train_envs.start()
get_logger().success(f"Train environments ready in {format_time(time.perf_counter() - t0)}")
if self.eval_envs is not None:
get_logger().info(f"Loading eval environments ({', '.join(self.eval_envs.names)})")
t0 = time.perf_counter()
await self.eval_envs.start()
get_logger().success(f"Eval environments ready in {format_time(time.perf_counter() - t0)}")
self.train_source = TrainSource(self.train_envs)
if self.resume_step is not None:
resume = self.config.resume
resume_path = resume.dir / "orchestrator" if resume is not None and resume.dir is not None else None
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step, path=resume_path)
self.progress.step = self.resume_step + 1
get_logger().info("Waiting for policy inference pool to be ready")
await self.policy_inference.wait_for_ready(config.model.name)
get_logger().success("Policy inference pool ready")
t0 = time.perf_counter()
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
await asyncio.gather(
@@ -279,89 +301,32 @@ class Orchestrator:
)
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
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,
)
elif config.weight_broadcast.type == "nixl":
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)
self.lora_name = config.model.lora.name if config.model.lora else None
self.train_source = TrainSource(self.train_envs)
if self.resume_step is not None:
resume = self.config.resume
resume_path = resume.dir / "orchestrator" if resume is not None and resume.dir is not None else None
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step, path=resume_path)
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
self.progress.step = self.resume_step + 1
get_logger().info(f"Resuming orchestrator from checkpoint step {self.resume_step}")
else:
get_logger().info("Training from scratch")
self.packer = BatchPacker(config)
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
self.sender = setup_micro_batch_sender(
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
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
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
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
t0 = time.perf_counter()
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
STARTUP_WEIGHT_WAIT_TIMEOUT_S
)
await self.receiver.sync_startup(sync_version, timeout=wait_timeout)
self.policy.version = sync_version
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
self.eval_source: EvalSource | None = (
EvalSource(
@@ -382,7 +347,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,
@@ -399,20 +364,21 @@ 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
# initial limit before the loop-start line; failures are tolerated.
await self.inference_metrics.probe()
self.train_sink = TrainSink(
config,
tokenizer=self.tokenizer,
train_envs=self.train_envs,
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
progress=self.progress,
batch_size=config.batch_size,
token_batch_size=config.token_batch_size,
@@ -421,13 +387,10 @@ 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,
)
# Single periodic logger for the whole pipeline. It's the only
# consumer of ``dispatcher.metrics.drained()`` (which clears on read)
@@ -511,32 +474,32 @@ class Orchestrator:
# first ship).
if self.config.ckpt is not None and self.progress.step > 1:
self.progress.step -= 1
get_logger().info("Writing final checkpoint")
get_logger().info(f"Saving final checkpoint at step {self.progress.step}")
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
await self.stop()
if clean_exit:
get_logger().success("Orchestrator finished.")
get_logger().success("Orchestrator finished")
else:
get_logger().warning("Orchestrator cleanup complete (forced).")
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:
@property
def final_version(self) -> int | None:
"""Newest policy version the trainer will ever broadcast."""
if self.config.max_steps is None:
return None
return final_broadcast_version(self.config.max_steps, self.config.weight_broadcast.broadcast_final)
async def wait_for_version(self, version: int, reason: str) -> None:
"""Bounded wait until the watcher has applied v{version}."""
if self.policy.version >= version:
return
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 the trainer to broadcast 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.
@@ -546,13 +509,19 @@ 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"Trainer did not broadcast v{version} within {timeout}s — proceeding anyway")
async def wait_for_final_broadcast(self) -> None:
"""Stay alive for the trainer's last broadcast. Every broadcast is a
blocking rendezvous — tearing down the watcher before it would strand
the trainer inside the handshake."""
if self.final_version is None:
return
await self.wait_for_version(self.final_version, reason="before shutdown")
async def main_loop(self) -> None:
"""Consume completed episodes and ``GroupCancellation`` events from the
@@ -756,6 +725,13 @@ class Orchestrator:
self.log_train_batch(batch, step=step, step_time=step_time)
# The final eval must measure the final weights: hold until the
# trainer's last broadcast (v{max_steps} when evals consume it) has
# been applied before triggering it. Satisfiable — the trainer
# broadcasts right after consuming the batch this call just shipped.
if config.eval is not None and config.max_steps is not None and step >= config.max_steps:
assert self.final_version is not None
await self.wait_for_version(self.final_version, reason="for the final eval")
self.maybe_trigger_eval(self.progress.step)
# Drain right after shipping the final batch. Waiting for a further
# batch to fill would burn inference on data that can never train —
@@ -980,13 +956,14 @@ class Orchestrator:
if lead > TARGET_LAG:
if was_set:
get_logger().info(
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
f"Pausing dispatcher until the trainer publishes policy v{self.progress.step - 1 - TARGET_LAG} "
f"(currently v{self.policy.version})"
)
self.gate_closed_at = time.perf_counter()
gate.clear()
else:
if not was_set:
get_logger().info("Resuming dispatcher")
get_logger().info(f"Resuming dispatcher (policy v{self.policy.version})")
if self.gate_closed_at is not None:
self.wait_for_policy_time += time.perf_counter() - self.gate_closed_at
self.gate_closed_at = None
@@ -995,15 +972,11 @@ class Orchestrator:
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)
self.update_dispatch_gate()
async def stop(self) -> None:
@@ -1012,10 +985,13 @@ class Orchestrator:
training artifacts are already persisted before this is reached."""
async def teardown() -> None:
get_logger().debug("Closing micro batch sender")
self.sender.close()
if self.dispatcher is not None:
get_logger().debug("Stopping dispatcher")
await self.dispatcher.stop()
if self.watcher is not None:
get_logger().debug("Stopping weight watcher")
await self.watcher.stop()
if self.periodic_logger is not None:
await self.periodic_logger.stop()
@@ -1026,14 +1002,21 @@ class Orchestrator:
await safe_cancel(task)
self.component_tasks.clear()
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:
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 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()
task = asyncio.create_task(teardown())
_, pending = await asyncio.wait({task}, timeout=SHUTDOWN_TIMEOUT_S)
if pending:
@@ -1043,6 +1026,7 @@ class Orchestrator:
)
os._exit(0)
await task
get_logger().debug(f"Stopped orchestrator components in {format_time(time.perf_counter() - t0)}")
@clean_exit
+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
+6 -20
View File
@@ -22,7 +22,7 @@ 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.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
@@ -70,7 +70,6 @@ class TrainSink:
*,
tokenizer,
train_envs: TrainEnvs,
mm_token_type_ids_mapping: dict[int, int] | None,
progress: Progress,
batch_size: int | None,
token_batch_size: int | None,
@@ -82,7 +81,6 @@ class TrainSink:
self.config = config
self.tokenizer = tokenizer
self.train_envs = train_envs
self.mm_token_type_ids_mapping = mm_token_type_ids_mapping
self.progress = progress
self.batch_size = batch_size
self.token_batch_size = token_batch_size
@@ -232,8 +230,8 @@ class TrainSink:
self.pending_episodes.extend(group, admitted=False, cancelled=True)
self._record_zero_output(group, [], n_owed)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | dropped: cancelled (stale)"
f"Dropped group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reason=cancelled (stale)"
)
return
@@ -246,20 +244,15 @@ class TrainSink:
self._record_zero_output(group, survivors, n_owed)
reason = "no trainable survivors" if not survivors else "rejected by curriculum"
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | dropped: {reason}"
f"Dropped group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reason={reason}"
)
return
samples_by_trace: dict[str, list[TrainingSample]] = {}
temperature = env.sampling_args["temperature"]
for trace in survivors:
samples = await asyncio.to_thread(
trace_to_samples,
trace,
env_name=env_name,
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
)
samples = await asyncio.to_thread(trace_to_samples, trace, env_name=env_name)
for sample in samples:
sample.temperatures = [temperature] * len(sample.token_ids)
stamp_loss_routing(sample, env.algorithm.action_loss_type)
@@ -292,13 +285,6 @@ class TrainSink:
self.zero_output_units = 0
self.reported_zero_output_windows = 0
rewards = [trace.reward for trace in survivors if trace.id in samples_by_trace]
avg_reward = sum(rewards) / len(rewards)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reward={avg_reward:.4f}"
)
def _trace(self, trace_id: str) -> vf.Trace:
episode = self.episode_by_trace[trace_id]
return next(trace for trace in episode.traces if trace.id == trace_id)
+7 -15
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
@@ -108,12 +108,7 @@ def _loss_weights(branch: vf.Branch, name: str, trained_nodes: set[int]) -> list
return weights if any(weights) else None
def trace_to_samples(
trace: vf.Trace,
*,
env_name: str = "",
mm_token_type_ids_mapping: dict[int, int] | None = None,
) -> list[TrainingSample]:
def trace_to_samples(trace: vf.Trace, *, env_name: str = "") -> list[TrainingSample]:
"""Convert a v1 `Trace` into `TrainingSample`s — one per branch.
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
@@ -121,21 +116,18 @@ def trace_to_samples(
the trainable (model-sampled) tokens, the context tokens between completions stay masked
out. Errored traces are dropped upstream (`TrainSink.process_episode`), so no error
handling happens here. A branch carrying images also gets `mm_kwargs` (the concatenated
pixel tensors) and `mm_token_type_ids` (the renderer's `mm_token_type_id_map` applied to
the branch tokens). Branches with no sampled tokens (e.g. an openai client carrying none)
yield nothing.
pixel tensors) and `mm_token_type_ids` (`branch.mm_token_type_ids`, computed from the
trace's renderer-stamped `mm_token_type_id_map`). Branches with no sampled tokens
(e.g. an openai client carrying none) yield nothing.
"""
samples: list[TrainingSample] = []
trained_loss_nodes: dict[str, set[int]] = {"rl": set(), "ce": set(), "ref_kl": set()}
for branch, mask in iter_trainable_branches(trace):
token_ids = branch.token_ids
mm_kwargs: dict[str, EncodedTensor] | None = None
mm_token_type_ids: list[int] | None = None
mmd = branch.multi_modal_data
if mmd is not None:
mm_kwargs = _encode_mm_kwargs(mmd.mm_items)
mapping = mm_token_type_ids_mapping or {}
mm_token_type_ids = [mapping.get(t, 0) for t in token_ids]
samples.append(
TrainingSample(
token_ids=token_ids,
@@ -145,7 +137,7 @@ def trace_to_samples(
env_name=env_name,
ref_logprobs=branch.reference_logprobs,
mm_kwargs=mm_kwargs,
mm_token_type_ids=mm_token_type_ids,
mm_token_type_ids=branch.mm_token_type_ids,
routed_experts=_encode_routed_experts(branch.routed_experts, len(token_ids)),
rl_weights=_loss_weights(branch, "rl", trained_loss_nodes["rl"]),
ce_weights=_loss_weights(branch, "ce", trained_loss_nodes["ce"]),
+2 -3
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
@@ -81,7 +81,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,7 +91,6 @@ class GroupState:
episodes_to_schedule: int
target_episodes: int
emitted: int = 0
pinned_client: vf.ClientConfig | None = None
policy_version_at_start: int = 0
+1 -85
View File
@@ -3,21 +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.configs.orchestrator import OrchestratorConfig
from prime_rl.utils.client import InferencePool
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:
@@ -70,36 +61,6 @@ def episode_staleness(episode: vf.Episode[Any, Any, Any], training_step: int) ->
return total, in_flight, in_queue
async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
"""Build the live policy inference pool + matching renderer. Returns
``(renderer, inference_pool)``.
Training is renderer-only: the renderer object is the canonical
messages → token ids path (sft backfill, opsd scoring prefixes, echo role
attribution) and is always built. The renderer-client sampling path is
wired onto the pool; when no train env samples from the live policy the
renderer is still kept for client-side tokenization and the pool's evals
use plain chat-completions."""
from renderers.base import create_renderer
client_config = config.model.client
model_name = config.model.name
renderer = create_renderer(tokenizer, config.renderer)
get_logger().info(f"Initialized {type(renderer).__name__} for {model_name}")
if config.any_policy_sourced:
get_logger().info("Using direct renderer rollout client")
else:
get_logger().info("No policy-sourced train env — renderer kept for client-side tokenization only")
inference_pool = InferencePool(
client_config,
model_name=model_name,
train_client_type="renderer",
eval_client_type="openai_chat_completions",
renderer_config=config.renderer,
)
return renderer, inference_pool
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
"""Intercepts verifiers logging and routes through prime-rl logger with optional prefix."""
vf_logger = logging.getLogger(logger)
@@ -120,7 +81,7 @@ def setup_env_server_logging(log_level: str, json_logging: bool = False) -> None
def set_default_executor(max_workers: int = 64) -> None:
"""Scale the default asyncio thread pool so asyncio.to_thread has enough capacity."""
get_logger().info(f"Setting default executor to ThreadPoolExecutor(max_workers={max_workers})")
get_logger().debug(f"Setting default executor to ThreadPoolExecutor(max_workers={max_workers})")
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=max_workers))
@@ -133,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.
+13 -68
View File
@@ -1,22 +1,16 @@
"""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 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 +18,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
@@ -55,7 +43,7 @@ class WeightWatcher:
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 +62,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,19 +69,7 @@ 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"Orchestrator paused: waiting for trainer to broadcast checkpoint {next_step}. "
"Training is progressing normally."
)
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
@@ -135,16 +97,14 @@ class WeightWatcher:
f"Observer {type(observer).__name__}.on_version_pending({next_step}) raised: {exc!r}"
)
get_logger().debug(f"Updating weights to step {next_step}")
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
get_logger().debug(f"Updated weights to step {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
get_logger().debug(
f"Updated inference weights to policy v{next_step} in {format_time(self.last_update_weights_time)}"
)
for observer in self.observers:
try:
@@ -154,21 +114,6 @@ class WeightWatcher:
f"Observer {type(observer).__name__}.on_new_version({next_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
def gauges(self) -> dict[str, float]:
return {
"watcher/policy_version": float(self.policy.version),
+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
+3 -3
View File
@@ -21,7 +21,7 @@ from prime_rl.configs.shared import ResumeConfig
from prime_rl.configs.trainer import CheckpointConfig
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path
@@ -194,7 +194,7 @@ class CheckpointManager:
# Save sharded state
dcp_save(state_dict, checkpoint_id=path)
self.logger.debug(f"Training checkpoint saved in {time.perf_counter() - start_time:.2f} seconds")
self.logger.debug(f"Saved training checkpoint in {format_time(time.perf_counter() - start_time)}")
def load_from_path(
self,
@@ -232,7 +232,7 @@ class CheckpointManager:
)
dataloader.load_state_dict(torch.load(dataloader_path, weights_only=False))
self.logger.debug(f"Training checkpoint loaded in {time.perf_counter() - start_time:.2f} seconds")
self.logger.debug(f"Loaded training checkpoint in {format_time(time.perf_counter() - start_time)}")
def load(
self,
+1 -9
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 = {}
@@ -241,7 +233,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
)
raise RuntimeError("Cannot apply LoRA to FSDP-wrapped model. Apply LoRA before setup_fsdp().")
logger.debug(f"Applying LoRA to model: {model} for {config.target_modules}")
logger.debug(f"Applying LoRA to {type(model).__name__} (target_modules={config.target_modules})")
target_modules = _find_target_modules(model, config.target_modules)
logger.debug(
f"Found {len(target_modules)} target modules for LoRA: {target_modules[:10]} ... {target_modules[-10:]}"
+3 -3
View File
@@ -595,7 +595,7 @@ def get_model(
config: ModelConfig, device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.bfloat16
) -> nn.Module:
logger = get_logger()
logger.info(
logger.debug(
f"Loading model config (name={config.name}, attn={config.attn}, trust_remote_code={config.trust_remote_code})"
)
@@ -778,7 +778,7 @@ def get_model(
trust_remote_code=config.trust_remote_code,
**dtype_kwarg,
)
logger.debug(f"Loaded model {config.name} in {time.perf_counter() - load_model_start_time:.2f} seconds")
logger.debug(f"Loaded model {config.name} in {format_time(time.perf_counter() - load_model_start_time)}")
assert model.lm_head.weight.dtype == dtype, (
f"LM head dtype wasnt loaded correctly {model.lm_head.weight.dtype} != {dtype}"
@@ -1057,7 +1057,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
generator = torch.Generator(device="cuda").manual_seed(seed_tensor.item())
for module in lora_modules:
module._init_lora_parameters(generator)
logger.debug(f"Loaded weights using HF DCP in {time.perf_counter() - load_dcp_start_time:.2f} seconds")
logger.debug(f"Loaded weights using HF DCP in {format_time(time.perf_counter() - load_dcp_start_time)}")
def can_reinit_empty_buffers(model: nn.Module):
+6 -1
View File
@@ -17,6 +17,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import time
from dataclasses import dataclass
from functools import cached_property
@@ -25,7 +26,7 @@ from torch._utils import _get_available_device_type
from torch.distributed.device_mesh import DeviceMesh, init_device_mesh
from prime_rl.configs.trainer import ModelConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
device_type = _get_available_device_type() or "cuda"
@@ -105,7 +106,9 @@ class ParallelDims:
names.append(name)
self.logger.info(f"Building {len(dims)}-D device mesh with {names}, {dims}")
t0 = time.perf_counter()
mesh = init_device_mesh(device_type, dims, mesh_dim_names=names)
self.logger.debug(f"Built device mesh in {format_time(time.perf_counter() - t0)}")
# Create all the submesh here to ensure all required process groups are
# initialized:
@@ -163,7 +166,9 @@ class ParallelDims:
names.append(name)
self.logger.info(f"Building {len(dims)}-D device mesh with {names}, {dims}")
t0 = time.perf_counter()
mesh = init_device_mesh(device_type, dims, mesh_dim_names=names)
self.logger.debug(f"Built device mesh in {format_time(time.perf_counter() - t0)}")
# Create all the submesh here to ensure all required process groups are
# initialized:
+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()
+50 -38
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
@@ -67,7 +67,7 @@ from prime_rl.utils.metrics_server import HealthServer, MetricsServer
from prime_rl import monitors
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
from prime_rl.utils.utils import clean_exit, final_broadcast_version, resolve_latest_ckpt_step
from ring_flash_attn import substitute_hf_flash_attn
@@ -79,13 +79,16 @@ def train(config: TrainerConfig):
config.log.level,
json_logging=config.log.json_logging,
)
logger.info(f"Starting RL trainer in {world} in {config.output_dir}")
logger.info(f"Starting RL trainer in {world} (output_dir={config.output_dir})")
# Setup the monitors
logger.info(f"Initializing monitors ({config.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,
)
)
@@ -140,19 +143,21 @@ def train(config: TrainerConfig):
# Initialize the model and tokenizer
logger.info(f"Initializing model ({config.model})")
t0 = time.perf_counter()
loading_from_ckpt_later = checkpoint_step is not None
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
logger.debug(f"Initialized model in {format_time(time.perf_counter() - t0)}")
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
raise ValueError("Packed multimodal training requires model support")
# Set up the loss function for the RL loss type (ce / ref_kl are fixed)
logger.info(f"Setting up loss function ({config.loss})")
logger.info(f"Initializing loss function ({config.loss})")
rl_loss_fn = setup_rl_loss_fn(config.loss)
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
t0 = time.perf_counter()
optimizer, gradient_manager = setup_optimizer(
config.optim,
list(model.named_parameters()),
@@ -164,22 +169,25 @@ def train(config: TrainerConfig):
get_full_offload_dtype_policy(model, config.model) if config.model.full_offload is not None else None
),
)
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
logger.debug(f"Initialized optimizer in {format_time(time.perf_counter() - t0)}")
logger.info(f"Using `{config.scheduler.type}` scheduler ({config.scheduler})")
logger.info(f"Initializing scheduler ({config.scheduler})")
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
# 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})")
weight_broadcast = setup_weight_broadcast(
t0 = time.perf_counter()
weight_sender = setup_weight_sender(
config.output_dir,
config.weight_broadcast,
parallel_dims,
config.model.lora,
)
logger.debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
if parallel_dims.cp_enabled:
cp_group = parallel_dims.world_mesh["cp"].get_group()
@@ -228,14 +236,16 @@ def train(config: TrainerConfig):
)
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
progress.step += 1
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
logger.info(
f"Starting from step {progress.step} (total_tokens={progress.total_tokens}, total_samples={progress.total_samples})"
)
logger.info(
f"Resuming from step {checkpoint_step} "
f"(total_tokens={progress.total_tokens}, total_samples={progress.total_samples})"
)
else:
logger.info("Starting from scratch")
# Set up the data loader (Optionally, use a fake data loader for debugging)
logger.info(f"Initializing data loader ({config.data})")
t0 = time.perf_counter()
if config.data.fake:
dataloader = FakeDataLoader(config.data.fake, config.model.seq_len, parallel_dims.get_mesh("dp").size())
else:
@@ -245,6 +255,7 @@ def train(config: TrainerConfig):
parallel_dims.get_mesh("dp").size(),
config.rollout_transport,
)
logger.debug(f"Initialized data loader in {format_time(time.perf_counter() - t0)}")
token_exporter = setup_token_exporter(config, parallel_dims, world, logger)
@@ -263,7 +274,7 @@ def train(config: TrainerConfig):
torch.cuda.reset_peak_memory_stats()
if gc_handler is not None:
gc_handler.run(progress.step)
is_last_step = config.max_steps is not None and progress.step == config.max_steps
is_last_step = config.max_steps is not None and progress.step >= config.max_steps
logger.debug(f"Starting training step {progress.step}")
step_start_time = time.perf_counter()
@@ -272,23 +283,30 @@ 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 startup policy weights (v{progress.step - 1}) to inference engines")
weight_broadcast.broadcast_weights(model, step=progress.step - 1)
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_sender.broadcast(model, startup_version)
logger.debug(
f"Broadcast startup policy weights (v{startup_version}) in {format_time(time.perf_counter() - t0)}"
)
# Wait for the batch to be available
logger.debug("Waiting for training batch to arrive")
wait_for_batch_start_time = time.perf_counter()
dataloader.wait_for_batch()
wait_for_batch_time = time.perf_counter() - wait_for_batch_start_time
logger.debug(f"Waited for batch to arrive for {wait_for_batch_time:.2f} seconds")
logger.debug(f"Waited for batch for {format_time(wait_for_batch_time)}")
# Load the training batch
logger.debug("Loading batch")
load_data_start_time = time.perf_counter()
micro_batches = dataloader.get_batch()
load_data_time = time.perf_counter() - load_data_start_time
logger.debug(f"Loaded batch in {load_data_time:.2f} seconds")
logger.debug(f"Loaded batch in {format_time(load_data_time)}")
batch_size = len(micro_batches)
memory_profiler = None
@@ -539,7 +557,7 @@ def train(config: TrainerConfig):
tensors[key].append(loss_tensor.detach().to("cpu"))
# Debug log with *local, micro step* stats
micro_step_message = f"Micro Step {micro_step}/{len(micro_batches)} | Loss {tensors['loss'][-1].mean().item():.4f} | Entropy {tensors['entropy/all'][-1].mean().item():.4f}"
micro_step_message = f"Micro Step {micro_step + 1}/{len(micro_batches)} | Loss {tensors['loss'][-1].mean().item():.4f} | Entropy {tensors['entropy/all'][-1].mean().item():.4f}"
if has_mismatch_tokens:
micro_step_message += f" | Mismatch KL {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
if "max_vio" in tensors:
@@ -573,16 +591,14 @@ def train(config: TrainerConfig):
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:
# sample its next step from it. Every broadcast is a handshake with the consumer, so
# versions past the last consumed one are skipped (``final_broadcast_version``:
# training never samples v{max_steps}, but a configured final eval measures it).
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
broadcast_unused = config.max_steps is not None and progress.step > final_broadcast_version(
config.max_steps, config.weight_broadcast.broadcast_final
)
if not broadcast_unused:
broadcast_weights_start_time = time.perf_counter()
@@ -590,12 +606,8 @@ def train(config: TrainerConfig):
# 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)
weight_sender.broadcast(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
@@ -726,7 +738,7 @@ def train(config: TrainerConfig):
# Write final checkpoint
if config.ckpt is not None:
logger.info("Writing final checkpoint")
logger.info(f"Saving final checkpoint at step {progress.step}")
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
ckpt_manager.maybe_clean()
@@ -734,7 +746,7 @@ def train(config: TrainerConfig):
gradient_manager.close()
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
logger.success("RL trainer finished!")
logger.success("RL trainer finished")
# Stop metrics/health server if configured
if metrics_server is not None:
+27 -33
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
@@ -72,12 +71,12 @@ def train(config: SFTConfig):
config.log.level,
json_logging=config.log.json_logging,
)
logger.info(f"Starting SFT trainer in {world}")
logger.info(f"Starting SFT trainer in {world} (output_dir={config.run_dir})")
# Setup the monitors
logger.info(f"Initializing monitors ({config.monitors})")
asyncio.run(
monitors.setup(
producer="trainer",
wandb=config.monitors.wandb,
file=config.monitors.file,
output_dir=config.run_dir,
@@ -184,7 +183,7 @@ def train(config: SFTConfig):
renderer = create_renderer(tokenizer, config.renderer)
if processor is not None and hasattr(renderer, "_processor"):
renderer._processor = processor
logger.info(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
logger.debug(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
@@ -208,7 +207,7 @@ def train(config: SFTConfig):
if config.max_steps is not None and (config.ckpt and config.ckpt.skip_scheduler and checkpoint_step is not None)
else config.max_steps
)
logger.info(f"Setting up {config.scheduler.type} scheduler with {scheduler_steps} steps ({config.scheduler})")
logger.info(f"Initializing scheduler with {scheduler_steps} steps ({config.scheduler})")
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
# Set up the dataset and dataloader
@@ -237,16 +236,18 @@ def train(config: SFTConfig):
dataloader=dataloader if not skip.skip_dataloader else None,
path=resume_dir / "trainer" if resume_dir is not None else None,
)
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
if not skip.skip_progress:
progress.step += 1
# This redundant setup is necessary because loading the optimizer's state has side effects on the scheduler state dict
if skip.skip_scheduler:
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
logger.info(
f"Starting from step {progress.step} (total_tokens={progress.total_tokens}, total_samples={progress.total_samples}, dataset_state={get_dataset_state(dataloader)})"
)
logger.info(
f"Resuming from step {checkpoint_step} (total_tokens={progress.total_tokens}, "
f"total_samples={progress.total_samples}, dataset_state={get_dataset_state(dataloader)})"
)
else:
logger.info("Starting from scratch")
# Create the iterator only after a potential resume: iter() forks workers with a
# copy of the dataset's *current* state, so a later load_state_dict never reaches
@@ -408,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
@@ -573,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
@@ -705,22 +701,20 @@ def train(config: SFTConfig):
# Write final checkpoint
if config.ckpt is not None:
logger.info("Writing final checkpoint")
logger.info(f"Saving final checkpoint at step {progress.step}")
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
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()
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
logger.success("SFT trainer finished!")
logger.success("SFT trainer finished")
def main():
+5 -20
View File
@@ -17,9 +17,8 @@ from torchtitan.distributed.utils import clip_grad_norm_ as torch_clip_grad_norm
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.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
@@ -52,7 +51,7 @@ class GarbageCollection:
def _collect(self, generation: int = 1):
begin = time.monotonic()
gc.collect(generation)
get_logger().info(f"[GC] collection took {time.monotonic() - begin:.2f}s")
get_logger().debug(f"Collected garbage in {format_time(time.monotonic() - begin)}")
def prepare_gradient_offload(
@@ -172,6 +171,8 @@ def setup_full_cpu_optimizer_offload(config: "OptimizerInBackwardOffloadConfig")
def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: bool = False):
get_logger().info(f"Initializing torch distributed (timeout={int(timeout.total_seconds())}s)")
t0 = time.perf_counter()
device_id = get_world().local_rank
torch.cuda.set_device(device_id)
# Use Gloo backend for CPU and NCCL for GPU when CPU offloading is enabled
@@ -189,6 +190,7 @@ def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: b
dist.distributed_c10d.default_pg_timeout = timeout
dist.init_process_group(backend=backend, timeout=timeout, device_id=device_id)
get_logger().debug(f"Initialized torch distributed in {format_time(time.perf_counter() - t0)}")
def print_sample(input_ids: list[int], loss_mask: list[bool], tokenizer: PreTrainedTokenizer):
@@ -344,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):
@@ -1,12 +1,12 @@
import asyncio
from pathlib import Path
from prime_rl.transports.rollouts.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transports.rollouts.types import MicroBatch
from prime_rl.transports.batch.base import BatchReceiver, BatchSender
from prime_rl.transports.batch.types import MicroBatch
from prime_rl.utils.pathing import get_rollout_dir, get_step_path, sync_wait_for_path
class FileSystemMicroBatchSender(MicroBatchSender):
class FileSystemBatchSender(BatchSender):
"""Filesystem-based micro batch sender that writes micro batches to disk."""
def __init__(self, output_dir: Path, data_world_size: int, current_step: int = 0):
@@ -35,7 +35,7 @@ class FileSystemMicroBatchSender(MicroBatchSender):
tmp_path.rename(step_path / f"rank_{data_rank}.bin")
class FileSystemMicroBatchReceiver(MicroBatchReceiver):
class FileSystemBatchReceiver(BatchReceiver):
"""Filesystem-based micro batch receiver that reads micro batches from disk."""
def __init__(self, output_dir: Path, data_rank: int, current_step: int = 0):
@@ -4,11 +4,11 @@ import zmq
import zmq.asyncio
from prime_rl.configs.shared import ZMQTransportConfig
from prime_rl.transports.rollouts.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transports.rollouts.types import MicroBatch
from prime_rl.transports.batch.base import BatchReceiver, BatchSender
from prime_rl.transports.batch.types import MicroBatch
class ZMQMicroBatchSender(MicroBatchSender):
class ZMQBatchSender(BatchSender):
def __init__(self, output_dir: Path, data_world_size: int, current_step: int, transport: ZMQTransportConfig):
"""ZMQ micro batch sender that publishes per-rank micro batches to the trainers.
There is one sender (in the orchestrator process) for the entire data world.
@@ -35,9 +35,9 @@ class ZMQMicroBatchSender(MicroBatchSender):
self._ready = False
self.logger.info(
f"ZMQ micro batch sender initialized: endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm}"
self.logger.debug(
f"Initialized ZMQ micro batch sender (endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm})"
)
self._topic_prefix = b"data_rank|"
@@ -84,10 +84,10 @@ class ZMQMicroBatchSender(MicroBatchSender):
self.socket.close(linger=0)
self.ready_socket.close(linger=0)
finally:
self.logger.info("ZMQ micro batch sender closed")
self.logger.debug("Closed ZMQ micro batch sender")
class ZMQMicroBatchReceiver(MicroBatchReceiver):
class ZMQBatchReceiver(BatchReceiver):
def __init__(self, output_dir: Path, data_rank: int, current_step: int, transport: ZMQTransportConfig):
"""ZMQ micro batch receiver that receives micro batches from the orchestrator. There is one receiver per data rank."""
super().__init__(output_dir, data_rank)
@@ -111,9 +111,9 @@ class ZMQMicroBatchReceiver(MicroBatchReceiver):
# Announce readiness after connect+subscribe are set
self.ready_socket.send(str(data_rank).encode("utf-8"))
self.logger.info(
f"ZMQ micro batch receiver initialized: endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm}"
self.logger.debug(
f"Initialized ZMQ micro batch receiver (endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm})"
)
self._current_step = current_step
@@ -138,4 +138,4 @@ class ZMQMicroBatchReceiver(MicroBatchReceiver):
self.socket.close(linger=0)
self.ready_socket.close(linger=0)
finally:
self.logger.info("ZMQ micro batch receiver closed")
self.logger.debug("Closed ZMQ micro batch receiver")
@@ -1,54 +0,0 @@
from pathlib import Path
from prime_rl.configs.shared import TransportConfig
from prime_rl.transports.rollouts.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transports.rollouts.filesystem import (
FileSystemMicroBatchReceiver,
FileSystemMicroBatchSender,
)
from prime_rl.transports.rollouts.types import (
MicroBatch,
RoutedExperts,
TrainingSample,
)
from prime_rl.transports.rollouts.zmq import (
ZMQMicroBatchReceiver,
ZMQMicroBatchSender,
)
def setup_micro_batch_sender(
output_dir: Path, data_world_size: int, current_step: int, transport: TransportConfig
) -> MicroBatchSender:
if transport.type == "filesystem":
return FileSystemMicroBatchSender(output_dir, data_world_size, current_step)
elif transport.type == "zmq":
return ZMQMicroBatchSender(output_dir, data_world_size, current_step, transport)
else:
raise ValueError(f"Invalid transport type: {transport.type}")
def setup_micro_batch_receiver(
output_dir: Path, data_rank: int, current_step: int, transport: TransportConfig
) -> MicroBatchReceiver:
if transport.type == "filesystem":
return FileSystemMicroBatchReceiver(output_dir, data_rank, current_step)
elif transport.type == "zmq":
return ZMQMicroBatchReceiver(output_dir, data_rank, current_step, transport)
else:
raise ValueError(f"Invalid transport type: {transport.type}")
__all__ = [
"FileSystemMicroBatchSender",
"FileSystemMicroBatchReceiver",
"ZMQMicroBatchSender",
"ZMQMicroBatchReceiver",
"MicroBatchReceiver",
"MicroBatchSender",
"TrainingSample",
"MicroBatch",
"RoutedExperts",
"setup_micro_batch_sender",
"setup_micro_batch_receiver",
]
+34 -9
View File
@@ -1,26 +1,51 @@
from pathlib import Path
import torch
from httpx import AsyncClient
from prime_rl.configs.trainer import LoRAConfig, WeightBroadcastConfig
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.transports.weights.filesystem import FileSystemWeightBroadcast
from prime_rl.transports.weights.nccl import NCCLWeightBroadcast
from prime_rl.transports.weights.nixl import NIXLWeightBroadcast
from prime_rl.transports.weights.base import WeightReceiver, WeightSender, prune_broadcasts_beyond
from prime_rl.transports.weights.filesystem import FileSystemWeightReceiver, FileSystemWeightSender
from prime_rl.transports.weights.nccl import NCCLWeightReceiver, NCCLWeightSender
from prime_rl.transports.weights.nixl import NIXLWeightReceiver, NIXLWeightSender
__all__ = [
"WeightReceiver",
"WeightSender",
"prune_broadcasts_beyond",
"setup_weight_receiver",
"setup_weight_sender",
]
def setup_weight_broadcast(
def setup_weight_sender(
output_dir: Path,
config: WeightBroadcastConfig,
parallel_dims: ParallelDims,
lora_config: LoRAConfig | None = None,
) -> WeightBroadcast:
) -> WeightSender:
if config.type == "nccl":
return NCCLWeightBroadcast(output_dir, config, torch.cuda.current_device())
return NCCLWeightSender(output_dir, config, torch.cuda.current_device())
elif config.type == "filesystem":
return FileSystemWeightBroadcast(output_dir, config, lora_config)
return FileSystemWeightSender(output_dir, config, lora_config)
elif config.type == "nixl":
return NIXLWeightBroadcast(output_dir, config, parallel_dims)
return NIXLWeightSender(output_dir, config, parallel_dims)
else:
raise ValueError(f"Invalid weight broadcast type: {config.type}")
def setup_weight_receiver(
broadcast_dir: Path,
config: WeightBroadcastConfig,
admin_clients: list[AsyncClient],
model_name: str,
) -> WeightReceiver:
if config.type == "nccl":
return NCCLWeightReceiver(broadcast_dir, config, admin_clients, model_name)
elif config.type == "filesystem":
return FileSystemWeightReceiver(broadcast_dir, config, admin_clients, model_name)
elif config.type == "nixl":
return NIXLWeightReceiver(broadcast_dir, config, admin_clients, model_name)
else:
raise ValueError(f"Invalid weight broadcast type: {config.type}")
+157 -6
View File
@@ -1,18 +1,169 @@
import asyncio
import shutil
import time
from abc import ABC, abstractmethod
from collections.abc import Callable
from pathlib import Path
from typing import final
import torch.nn as nn
from httpx import AsyncClient
from prime_rl.configs.trainer import LoRAConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_broadcast_dir, get_step_path
# Broadcast-dir sentinels. Every transport goes through the same four stages:
# the trainer resets the step dir and raises ``.sender_ready``, the consumer
# joins the transfer and replies ``.receiver_ready`` (for NCCL with the
# engines paused inside the receive RPC), the trainer raises ``.started`` and
# moves the weights, then raises ``.finished`` — for filesystem, the weights
# are fully on disk.
SENDER_READY_MARKER = ".sender_ready"
RECEIVER_READY_MARKER = ".receiver_ready"
STARTED_MARKER = ".started"
FINISHED_MARKER = ".finished"
class WeightBroadcast(ABC):
def __init__(self, output_dir: Path, lora_config: LoRAConfig | None = None):
def prune_broadcasts_beyond(output_dir: Path, step: int) -> None:
"""Remove broadcast dirs beyond ``step``. Resume hygiene, run by the
trainer master before its startup broadcast: stale leftovers of a longer
crashed run would otherwise steer the consumer past the resume point."""
broadcast_dir = get_broadcast_dir(output_dir)
for old_step in get_all_ckpt_steps(broadcast_dir):
if old_step > step:
shutil.rmtree(get_step_path(broadcast_dir, old_step), ignore_errors=True)
class WeightSender(ABC):
"""Trainer-side weight publisher. ``broadcast`` wraps the transport's
``_broadcast`` with the shared sentinel handshake: every version is
offered (``.sender_ready``), acknowledged by the consumer
(``.receiver_ready``), transferred (``.started``), and committed
(``.finished``). The trainer therefore runs in lockstep with its consumer
on every transport — a broadcast nobody receives blocks and then fails."""
def __init__(self, output_dir: Path, timeout: int):
self.logger = get_logger()
self.world = get_world()
self.output_dir = output_dir
self.lora_config = lora_config
self.timeout = timeout
@final
def broadcast(self, model: nn.Module, step: int) -> None:
"""Broadcast policy v{step} to the inference pool."""
start_time = time.perf_counter()
step_dir = self.step_dir(step)
if self.world.is_master:
# Reset per attempt so a re-broadcast (e.g. on resume) never trips
# the consumer or the trainer on stale markers of a previous run.
shutil.rmtree(step_dir, ignore_errors=True)
step_dir.mkdir(parents=True)
(step_dir / SENDER_READY_MARKER).touch()
self._wait_for_receiver_ready(step_dir)
(step_dir / STARTED_MARKER).touch()
self._broadcast(model, step, step_dir)
if self.world.is_master:
(step_dir / FINISHED_MARKER).touch()
self._clean(step)
self.logger.debug(f"Broadcasted weights for step {step} in {time.perf_counter() - start_time:.2f}s")
def step_dir(self, step: int) -> Path:
return get_step_path(get_broadcast_dir(self.output_dir), step)
def _wait_for_receiver_ready(self, step_dir: Path) -> None:
"""Wait for the consumer to acknowledge the offered version. Bounded:
a consumer that dies mid-handshake must fail the run instead of
stranding the trainer forever."""
ready_file = step_dir / RECEIVER_READY_MARKER
self.logger.debug(f"Waiting for the receiver at {ready_file}")
start = time.monotonic()
last_log = start
while not ready_file.exists():
now = time.monotonic()
if now - start > self.timeout:
raise TimeoutError(f"No receiver joined the broadcast within {self.timeout}s ({ready_file})")
if now - last_log > 60:
# A busy consumer (e.g. an evals process mid-epoch) can lag legitimately;
# raise weight_broadcast.timeout if this trips on long eval epochs.
self.logger.warning(f"Still waiting for the broadcast receiver after {now - start:.0f}s")
last_log = now
time.sleep(0.1)
self.logger.debug("Receiver ready, starting the transfer")
@abstractmethod
def broadcast_weights(self, model: nn.Module, step: int):
pass
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
"""Move v{step}'s weights to the consumer. Rank synchronization is the
transport's own job — non-master ranks must be held back until the
master finished the handshake (see ``NCCLWeightSender._broadcast``)."""
def _clean(self, step: int) -> None:
"""Remove old broadcast dirs, keeping ``step`` and ``step - 1`` (a
lagging consumer may still be reading it). Broadcasts are purely
transitive — run state persistence is the checkpoint's job."""
broadcast_dir = get_broadcast_dir(self.output_dir)
for old_step in get_all_ckpt_steps(broadcast_dir):
if old_step < step - 1:
shutil.rmtree(get_step_path(broadcast_dir, old_step), ignore_errors=True)
class WeightReceiver(ABC):
"""Consumer-side counterpart of ``WeightSender`` — moves the inference
engines onto trainer-offered policy versions. It runs in the consumer
process (the RL orchestrator, or the SFT evals process): the weight
watcher, the orchestrator's startup rendezvous, and the evals process all
drive the same object instead of hand-rolling transport branches. The
engines' in-process receive hooks are its data plane, reached through the
admin clients."""
def __init__(
self,
broadcast_dir: Path,
config: WeightBroadcastConfig,
admin_clients: list[AsyncClient],
model_name: str,
) -> None:
self.logger = get_logger()
self.broadcast_dir = broadcast_dir
self.config = config
self.admin_clients = admin_clients
self.model_name = model_name
async def initialize(self) -> None:
"""One-time transport bootstrap (rendezvous groups, sessions)."""
def step_dir(self, step: int) -> Path:
return get_step_path(self.broadcast_dir, step)
def is_published(self, step: int) -> bool:
"""Whether the trainer has offered v{step}."""
return (self.step_dir(step) / SENDER_READY_MARKER).exists()
def next_version(self, current: int) -> int:
"""Newest version offered beyond ``current``; ``current`` if none."""
published = [step for step in get_all_ckpt_steps(self.broadcast_dir) if self.is_published(step)]
return max(published, default=current)
async def wait_published(self, step: int, cancelled: Callable[[], bool] | None = None) -> None:
"""Block until the trainer offers v{step}. Runs before the orchestrator
advances ``policy.version`` — the version must never move ahead of a
confirmed offer."""
sender_ready = self.step_dir(step) / SENDER_READY_MARKER
while not sender_ready.exists():
if cancelled is not None and cancelled():
raise asyncio.CancelledError
await asyncio.sleep(0.2)
def _ack(self, step: int) -> None:
"""Acknowledge the offered version — unblocks the waiting trainer."""
(self.step_dir(step) / RECEIVER_READY_MARKER).touch()
@abstractmethod
async def receive(self, step: int) -> None:
"""Acknowledge the offered v{step} and move the engines onto it."""
async def sync_startup(self, step: int, timeout: float) -> None:
"""Rendezvous with the trainer's startup broadcast of v{step}."""
await asyncio.wait_for(self.wait_published(step), timeout=timeout)
await self.receive(step)
+34 -50
View File
@@ -1,5 +1,3 @@
import shutil
import time
from pathlib import Path
import torch.distributed as dist
@@ -7,11 +5,10 @@ import torch.nn as nn
from torch.distributed.tensor import DTensor
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig, LoRAConfig
from prime_rl.orchestrator.clients import load_lora_adapter, update_weights
from prime_rl.trainer.lora import get_lora_state, save_lora_config
from prime_rl.trainer.utils import maybe_clean
from prime_rl.trainer.world import get_world
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.utils.utils import get_all_ckpt_steps, get_broadcast_dir, get_step_path
from prime_rl.transports.weights.base import FINISHED_MARKER, WeightReceiver, WeightSender
from prime_rl.utils.pathing import wait_for_path
from prime_rl.utils.weights import (
convert_state_dict_to_hf,
gather_weights_parallel,
@@ -20,27 +17,22 @@ from prime_rl.utils.weights import (
)
class FileSystemWeightBroadcast(WeightBroadcast):
"""Broadcast weights into the inference engine via shared filesystem."""
class FileSystemWeightSender(WeightSender):
"""Broadcast weights by saving a HF-compatible checkpoint (or, for LoRA
runs, the PEFT-shaped adapter) to a shared filesystem."""
def __init__(
self, output_dir: Path, config: FileSystemWeightBroadcastConfig, lora_config: LoRAConfig | None = None
self,
output_dir: Path,
config: FileSystemWeightBroadcastConfig,
lora_config: LoRAConfig | None = None,
):
super().__init__(output_dir, lora_config)
self.world = get_world()
self.logger.debug("Filesystem broadcast initialized")
super().__init__(output_dir, config.timeout)
self.lora_config = lora_config
self.logger.debug("Initialized filesystem weight broadcast")
def broadcast_weights(self, model: nn.Module, step: int) -> None:
"""Broadcast weights by saving a HF-compatible checkpoint to shared filesystem and notifies the orchestrator."""
self.logger.debug("Starting broadcasting weights to inference engine via shared filesystem")
start_time = time.perf_counter()
adapter_only = self.lora_config is not None
save_dir = get_step_path(get_broadcast_dir(self.output_dir), step)
if self.world.is_master:
save_dir.mkdir(parents=True, exist_ok=True)
if adapter_only:
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
if self.lora_config is not None:
# All ranks must participate in DTensor gathering, but only master saves
state_dict = get_lora_state().adapter_state_dict()
for key, value in state_dict.items():
@@ -49,11 +41,11 @@ class FileSystemWeightBroadcast(WeightBroadcast):
if self.world.is_master:
state_dict[key] = value.to("cpu", non_blocking=False)
if self.world.is_master:
self.logger.debug(f"Saving weights to {save_dir}")
save_state_dict(state_dict, save_dir, save_sharded=False, adapter=True)
self.logger.debug(f"Saving adapter to {step_dir}")
save_state_dict(state_dict, step_dir, save_sharded=False, adapter=True)
save_lora_config(
model,
save_dir,
step_dir,
rank=self.lora_config.rank,
alpha=self.lora_config.alpha,
dropout=self.lora_config.dropout,
@@ -62,30 +54,22 @@ class FileSystemWeightBroadcast(WeightBroadcast):
dist.barrier()
state_dict = gather_weights_parallel(model)
state_dict = convert_state_dict_to_hf(model, state_dict)
self.logger.debug(f"Saving weights to {save_dir}")
save_state_dict_parallel(state_dict, save_dir)
self.logger.debug(f"Saving weights to {step_dir}")
save_state_dict_parallel(state_dict, step_dir)
if self.world.is_master:
self._notify_orchestrator(save_dir)
self.logger.debug(f"Weights broadcasted in {time.perf_counter() - start_time:.2f}s")
def _notify_orchestrator(self, save_dir: Path):
"""Notify the orchestrator that the weights have been broadcast by writing a 'STABLE' file to a shared filesystem."""
stable_file = save_dir / "STABLE"
stable_file.touch()
class FileSystemWeightReceiver(WeightReceiver):
"""Loads broadcasts from the shared filesystem. The acknowledgement lets
the trainer start writing; the engines are only touched once the weights
are fully on disk. An adapter broadcast (PEFT dir) is hot-swapped under
live traffic — an in-place adapter reload is a vLLM-native op that needs
no engine pause; a full checkpoint pauses the engines for the load."""
def maybe_clean(self, step: int, interval_to_keep: int | None):
maybe_clean(get_broadcast_dir(self.output_dir), step, interval_to_keep)
def is_stable(self, step: int) -> bool:
"""Whether a complete broadcast for ``step`` is already on disk."""
return (get_step_path(get_broadcast_dir(self.output_dir), step) / "STABLE").exists()
def clean_older(self, step: int) -> None:
"""Remove all broadcast dirs older than ``step``, keeping only the newest."""
if not self.world.is_master:
return
broadcast_dir = get_broadcast_dir(self.output_dir)
for old_step in get_all_ckpt_steps(broadcast_dir):
if old_step < step:
shutil.rmtree(get_step_path(broadcast_dir, old_step), ignore_errors=True)
async def receive(self, step: int) -> None:
weights_dir = self.step_dir(step)
self._ack(step)
await wait_for_path(weights_dir / FINISHED_MARKER)
if (weights_dir / "adapter_config.json").exists():
await load_lora_adapter(self.admin_clients, self.model_name, weights_dir)
else:
await update_weights(self.admin_clients, weights_dir, step=step)
+40 -44
View File
@@ -1,5 +1,4 @@
import pickle
import time
from pathlib import Path
from typing import Callable, Generator, cast
@@ -12,15 +11,13 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
from vllm.distributed.utils import StatelessProcessGroup
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
from prime_rl.orchestrator.clients import init_nccl_broadcast, update_weights
from prime_rl.trainer.conversion_utils import get_max_layer_num
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.utils import get_world
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.utils.client import NCCL_READY_MARKER
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
from prime_rl.utils.logger import get_logger
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
from prime_rl.utils.pathing import sync_wait_for_path
from prime_rl.utils.utils import get_broadcast_dir, get_step_path
from prime_rl.utils.vlm import get_layer_prefix
@@ -108,7 +105,7 @@ def preprocess_layer_quantized(
return model.convert_layer_to_vllm_kernel(layer_state_dict, layer_idx, quantize_fp8=True)
class NCCLWeightBroadcastSender:
class NCCLBroadcaster:
def __init__(
self,
host: str,
@@ -117,12 +114,11 @@ class NCCLWeightBroadcastSender:
world_size: int,
device: int | str | torch.device,
timeout: int,
dtype: torch.dtype = torch.bfloat16,
quantize_in_weight_transfer: bool = False,
):
self.logger = get_logger()
self.world = get_world()
self.dtype = dtype
self.dtype = torch.bfloat16
self.quantize_in_weight_transfer = quantize_in_weight_transfer
if self.world.is_master:
@@ -132,12 +128,12 @@ class NCCLWeightBroadcastSender:
host=host, port=port, rank=rank, world_size=world_size, store_timeout=timeout
)
self.communicator = PyNcclCommunicator(pg, device=device)
self.logger.debug("NCCL broadcast initialized on master rank")
self.logger.debug("Initialized NCCL broadcast on master rank")
else:
self.logger.debug("NCCL broadcast initialized on non-master rank (no communicator)")
self.logger.debug("Initialized NCCL broadcast on non-master rank (no communicator)")
@torch.no_grad()
def broadcast_weights(self, model: nn.Module, step: int) -> None:
def send(self, model: nn.Module) -> None:
"""Broadcast the state dict of a model into the inference pool using NCCL."""
state_dict = model.state_dict()
layer_prefix = get_layer_prefix(model.config)
@@ -167,7 +163,7 @@ class NCCLWeightBroadcastSender:
return state_dict
class NCCLWeightBroadcast(WeightBroadcast):
class NCCLWeightSender(WeightSender):
"""Broadcast weights into the inference engine using NCCL."""
def __init__(
@@ -175,50 +171,50 @@ class NCCLWeightBroadcast(WeightBroadcast):
output_dir: Path,
config: NCCLWeightBroadcastConfig,
device: int | str | torch.device,
dtype: torch.dtype = torch.bfloat16,
):
super().__init__(output_dir)
self.logger = get_logger()
self.world = get_world()
self.nccl_broadcast_sender = NCCLWeightBroadcastSender(
super().__init__(output_dir, config.timeout)
self.nccl_broadcast_sender = NCCLBroadcaster(
config.host,
config.port,
0,
config.inference_world_size + 1,
device,
config.timeout,
dtype,
quantize_in_weight_transfer=config.quantize_in_weight_transfer,
)
@torch.no_grad()
def broadcast_weights(self, model: nn.Module, step: int) -> None:
"""Broadcast the state dict of a model into the inference pool using NCCL and notifies the orchestrator."""
self.logger.debug("Starting broadcasting weights to inference engine via NCCL")
start_time = time.perf_counter()
# Only the master touches the filesystem to notify the orchestrator, but all
# ranks must wait for the inference pool before entering the broadcast path:
# the broadcast preparation (DTensor resolution, quantization) enqueues
# collectives on non-master ranks, and if those ranks start prep before
# the orchestrator has paused inference, the collectives sit unmatched
# until NCCL's watchdog kills the process after 10 min.
save_dir = get_step_path(get_broadcast_dir(self.output_dir), step)
if self.world.is_master:
self._notify_orchestrator(save_dir)
self._wait_for_nccl_ready(save_dir)
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
# The master enters only after the receiver acknowledged the handshake,
# but all ranks must be held back until then: the broadcast preparation
# (DTensor resolution, quantization) enqueues collectives on non-master
# ranks, and if those start before the receiver has paused inference,
# the collectives sit unmatched until NCCL's watchdog kills the process.
if self.world.world_size > 1:
dist.barrier()
self.nccl_broadcast_sender.broadcast_weights(model, step)
self.logger.debug(f"Weights broadcasted in {time.perf_counter() - start_time:.2f}s")
self.nccl_broadcast_sender.send(model)
def _notify_orchestrator(self, save_dir: Path) -> None:
"""Create the STABLE marker the orchestrator's weight watcher polls for."""
save_dir.mkdir(parents=True, exist_ok=True)
(save_dir / "STABLE").touch()
def _wait_for_nccl_ready(self, save_dir: Path):
"""Wait for inference workers to signal they are ready to receive NCCL broadcast."""
nccl_ready_file = save_dir / NCCL_READY_MARKER
self.logger.debug(f"Waiting for NCCL_READY marker at {nccl_ready_file}")
sync_wait_for_path(nccl_ready_file, interval=0.1, log_interval=10)
self.logger.debug("Inference workers ready for NCCL broadcast")
class NCCLWeightReceiver(WeightReceiver):
"""Joins the trainer's NCCL collective. The receiver pauses the engines,
acknowledges, and sends them into the receive RPC — only then does the
trainer enter the collective, so the handshake can never race a stale
marker."""
async def initialize(self) -> None:
await init_nccl_broadcast(
self.admin_clients,
self.config.host,
self.config.port,
self.config.timeout,
inference_world_size=self.config.inference_world_size,
quantize_in_weight_transfer=self.config.quantize_in_weight_transfer,
)
async def receive(self, step: int) -> None:
await update_weights(
self.admin_clients,
self.step_dir(step),
step=step,
on_paused=lambda: self._ack(step),
)
@@ -1,5 +1,5 @@
"""NIXL weight broadcasting and transfer helpers."""
from prime_rl.transports.weights.nixl.nixl import NIXLWeightBroadcast
from prime_rl.transports.weights.nixl.nixl import NIXLWeightReceiver, NIXLWeightSender
__all__ = ["NIXLWeightBroadcast"]
__all__ = ["NIXLWeightReceiver", "NIXLWeightSender"]
+60 -7
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
import re
import time
from collections import defaultdict
@@ -20,10 +21,10 @@ from torch.distributed.tensor import DTensor
from torch.distributed.tensor._utils import compute_local_shape_and_global_offset
from prime_rl.configs.trainer import NIXLWeightBroadcastConfig
from prime_rl.orchestrator.clients import init_nixl_broadcast, update_weights
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.utils import get_world
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
from prime_rl.transports.weights.nixl.agent import NixlAgent, make_agent_name, set_ucx_env_defaults
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
size_cuda_buffers,
@@ -67,12 +68,16 @@ class TransferGroupIndex:
layer_to_group: dict[int, int]
class NIXLWeightBroadcast(WeightBroadcast):
def __init__(self, output_dir: Path, config: NIXLWeightBroadcastConfig, parallel_dims: ParallelDims) -> None:
super().__init__(output_dir)
class NIXLWeightSender(WeightSender):
def __init__(
self,
output_dir: Path,
config: NIXLWeightBroadcastConfig,
parallel_dims: ParallelDims,
) -> None:
super().__init__(output_dir, config.timeout)
self.config = config
self.parallel_dims = parallel_dims
self.world = get_world()
if self.is_serving_rank:
set_ucx_env_defaults()
self.nixl_agent = NixlAgent(make_agent_name("trainer", self.world.rank))
@@ -82,6 +87,8 @@ class NIXLWeightBroadcast(WeightBroadcast):
self.staged_shards_by_group: dict[int, list[StagedTensorShard]] = {}
self.staging_arenas: dict[torch.dtype, torch.Tensor] = {}
self.staging_buffer_count: int
self.model_express: ModelExpressSession | None = None
self.buffer_sessions: list[ModelExpressSession] = []
@property
def is_serving_rank(self) -> bool:
@@ -405,7 +412,7 @@ class NIXLWeightBroadcast(WeightBroadcast):
dist.barrier()
@torch.no_grad()
def broadcast_weights(self, model: nn.Module, step: int) -> None:
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
self.initialize_transfer(model)
start = time.perf_counter()
@@ -463,3 +470,49 @@ class NIXLWeightBroadcast(WeightBroadcast):
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
dist.barrier()
self.logger.info(f"NIXL+ModelExpress policy v{step} synchronized in {time.perf_counter() - start:.2f}s")
class NIXLWeightReceiver(WeightReceiver):
"""Drives the orchestrator's side of the ModelExpress rendezvous. Version
discovery runs on the shared sentinels; the unversioned ModelExpress
statuses only choreograph the transfer itself."""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.session = ModelExpressSession(
client=MxClient(server_url=f"{self.config.host}:{self.config.port}"),
role="orchestrator",
rank=0,
session_id=self.config.session_id,
worker_id="orchestrator",
)
async def initialize(self) -> None:
await init_nixl_broadcast(
self.admin_clients,
self.config.host,
self.config.port,
self.config.timeout,
self.config.inference_world_size,
self.config.session_id,
)
self.session.publish()
await self.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
async def set_status(self, status: int) -> None:
await asyncio.to_thread(self.session.set_status, status)
async def receive(self, step: int) -> None:
# ACK the trainer (it waits for the orchestrator's READY before the
# engines' INITIALIZING), run the transfer, then close the cycle.
self._ack(step)
await self.set_status(p2p_pb2.SOURCE_STATUS_READY)
await update_weights(self.admin_clients, None, step=step)
await self.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
await asyncio.to_thread(
self.session.wait_for,
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
timeout=self.config.timeout,
)
+23 -1
View File
@@ -91,7 +91,29 @@ def format_log_message(
def get_config_dir(output_dir: Path) -> Path:
return output_dir / "configs"
"""Resolved per-component config dumps (JSON). The launch TOML copy lives one
level up, at `configs/<entrypoint>.toml`."""
return output_dir / "configs" / "resolved"
def write_launch_toml(run_dir: Path, name: str) -> None:
"""Copy the launch `@` TOML file(s) verbatim to `configs/<name>.toml`."""
import sys
argv = sys.argv[1:]
paths = []
for i, arg in enumerate(argv):
# root config references only: `@ file`; a `--flag @ file` / `--flag @file`
# is a nested reference and belongs under its flag, not in the launch copy
if arg == "@" and i + 1 < len(argv) and (i == 0 or not argv[i - 1].startswith("--")):
paths.append(Path(argv[i + 1]))
tomls = [(p, p.read_text()) for p in paths if p.suffix == ".toml" and p.is_file()]
if not tomls:
return
texts = [text for _, text in tomls] if len(tomls) == 1 else [f"# @ {p}\n{text}" for p, text in tomls]
config_dir = run_dir / "configs"
config_dir.mkdir(parents=True, exist_ok=True)
(config_dir / f"{name}.toml").write_text("\n".join(texts))
def get_ckpt_dir(output_dir: Path) -> Path:
+5 -9
View File
@@ -163,15 +163,11 @@ def get_free_port() -> int:
return port
def get_latest_ckpt_step(weights_dir: Path) -> int | None:
step_dirs = list(weights_dir.glob("step_*"))
if len(step_dirs) == 0:
return None
steps = sorted([int(step_dir.name.split("_")[-1]) for step_dir in step_dirs])
for latest_step in steps[::-1]:
if Path(weights_dir / f"step_{latest_step}" / "STABLE").exists():
return latest_step
return None
def final_broadcast_version(max_steps: int, broadcast_final: bool) -> int:
"""Newest policy version the trainer will ever broadcast: v{max_steps} when
something consumes it (a configured final eval), else v{max_steps - 1} -
training never samples from the final version."""
return max_steps if broadcast_final else max_steps - 1
@contextmanager
+139
View File
@@ -0,0 +1,139 @@
"""Browser smoke test for the run dashboard, run against real integration-run artifacts.
Launched at the end of each integration test so that any change to the on-disk
artifacts (metrics.jsonl rows, Episode records, config JSONs, log layout) that
breaks the dashboard fails the same CI run that produced them.
"""
import socket
import subprocess
import sys
import time
from pathlib import Path
DASHBOARD_STARTUP_TIMEOUT_S = 30
PAGE_SETTLE_MS = 4000
def _free_port() -> int:
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
def _install_browser() -> None:
subprocess.run(
["uv", "run", "playwright", "install", "--with-deps", "--only-shell", "chromium"],
check=True,
capture_output=True,
timeout=600,
)
def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
"""Serve ``output_dir`` and assert the dashboard renders the run end to end."""
from playwright.sync_api import sync_playwright
_install_browser()
port = _free_port()
server = subprocess.Popen(
["uv", "run", "dashboard", output_dir.as_posix(), "--port", str(port)],
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT,
)
try:
deadline = time.monotonic() + DASHBOARD_STARTUP_TIMEOUT_S
while time.monotonic() < deadline:
try:
with socket.create_connection(("127.0.0.1", port), timeout=1):
break
except OSError:
time.sleep(0.5)
else:
raise AssertionError("dashboard did not start listening")
errors: list[str] = []
with sync_playwright() as playwright:
browser = playwright.chromium.launch()
page = browser.new_page(viewport={"width": 1600, "height": 1000})
page.on("console", lambda m: errors.append(f"console: {m.text}") if m.type == "error" else None)
page.on("pageerror", lambda e: errors.append(f"page: {e}"))
base = f"http://127.0.0.1:{port}"
# metrics: the run resolves and the overview renders charts with data
page.goto(f"{base}/#run={run_name}&tab=metrics")
page.wait_for_timeout(PAGE_SETTLE_MS)
status = page.locator("#run-overview .badge").first.inner_text()
assert status, "overview card did not render a status"
fields = page.evaluate(
"""() => Object.fromEntries([...document.querySelectorAll('#run-overview .ov-field')]
.map(f => [f.querySelector('.lbl').innerText, f.querySelector('.val, .badge').innerText]))"""
)
run_type = fields.get("TYPE")
assert run_type in ("RL", "SFT", "EVAL"), f"overview type field did not render: {fields!r}"
if run_type == "EVAL":
assert fields.get("EPISODES", "").isdigit(), f"overview episodes field did not render: {fields!r}"
cards = page.locator(".stat-card").count()
assert cards >= 5, f"expected >=5 stat cards, got {cards}"
else:
assert "/" in fields.get("STEP", ""), f"overview step field did not render: {fields!r}"
charts = page.locator(".chart-card").count()
assert charts >= 5, f"expected >=5 metric panels, got {charts}"
with_data = page.evaluate("""() => [...document.querySelectorAll('.chart-card .u-wrap')].length""")
assert with_data >= 5, f"expected >=5 mounted charts, got {with_data}"
# config: the default view renders (launch TOML on new runs), and the
# resolved concatenated document renders as a tree
page.click("#tabs [data-tab=config]")
page.wait_for_timeout(1500)
assert page.eval_on_selector("#config-view", "e => e.innerText.length") > 100, "config view did not render"
page.click("#config-format [data-fmt=json]")
page.wait_for_timeout(1500)
assert page.locator("#config-view .j-line").count() > 10, "resolved config tree did not render"
# traces: when the run saved rollouts, episodes must render and open
rollout_steps = page.evaluate(
f"""fetch('{base}/api/runs/{run_name}/rollouts').then(r => r.json()).then(d => d.steps.length)"""
)
if rollout_steps:
page.click("#tabs [data-tab=traces]")
page.wait_for_timeout(3000)
rows = page.locator("#episode-table tbody tr").count()
assert rows > 0, "traces table rendered no episodes"
page.click("#episode-table tbody tr >> nth=0")
page.wait_for_timeout(3000)
entries = page.locator("#tm-messages details.entry").count()
assert entries > 0, "episode viewer rendered no messages"
reward = page.locator(".tm-reward-big").first.inner_text()
assert reward not in ("", "n/a"), f"episode reward did not render: {reward!r}"
page.keyboard.press("Escape")
# logs: the merged pane shows lines
page.click("#tabs [data-tab=logs]")
page.wait_for_timeout(PAGE_SETTLE_MS)
log_lines = page.locator(".log-pane .ll").count()
assert log_lines > 10, f"log pane rendered only {log_lines} lines"
browser.close()
assert not errors, f"dashboard raised browser errors: {errors[:5]}"
finally:
server.terminate()
try:
server.wait(timeout=10)
except subprocess.TimeoutExpired:
server.kill()
print(f"Dashboard smoke passed for {run_name} ({output_dir})", file=sys.stderr)
def make_dashboard_test(process_fixture: str, run_name: str):
"""The per-file dashboard smoke: `test_dashboard = make_dashboard_test("rl_process", RUN_NAME)`.
Depends on the module's (module-scoped) training-process fixture, so it runs
against the artifacts that run just produced."""
import pytest
@pytest.mark.usefixtures(process_fixture)
def test_dashboard(output_dir: Path) -> None:
check_dashboard_smoke(output_dir, run_name)
return test_dashboard
+4
View File
@@ -4,6 +4,7 @@ from typing import Callable
import pytest
from tests.conftest import ProcessResult
from tests.integration.dashboard_smoke import make_dashboard_test
from tests.utils import (
check_avg_mismatch_kl_in_range,
check_no_error,
@@ -83,3 +84,6 @@ def test_mismatch_kl_in_range(rl_process: ProcessResult, test_no_error, run_dir:
with open(run_dir / "logs" / "latest" / "trainer.log", "r") as f:
trainer_stdout = strip_escape_codes(f.read()).splitlines()
check_avg_mismatch_kl_in_range(trainer_stdout, last_n_steps=5, max_threshold=0.15)
test_dashboard = make_dashboard_test("rl_process", RUN_NAME)
+4
View File
@@ -4,6 +4,7 @@ from typing import Callable
import pytest
from tests.conftest import ProcessResult
from tests.integration.dashboard_smoke import make_dashboard_test
from tests.utils import (
check_avg_mismatch_kl_in_range,
check_no_error,
@@ -126,3 +127,6 @@ def test_reward_in_range_resume(rl_resume_process: ProcessResult, test_no_error_
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
check_reward_in_range(orchestrator_stdout, min_threshold=0.6)
test_dashboard = make_dashboard_test("rl_process", RUN_NAME)
@@ -10,6 +10,7 @@ import pytest
from prime_rl.utils.process import cleanup_process
from tests.conftest import ProcessResult
from tests.integration.dashboard_smoke import make_dashboard_test
from tests.utils import check_final_eval_reward_above, check_no_error, strip_escape_codes
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
@@ -122,3 +123,6 @@ def test_eval_reward_converges(rl_opd_process: ProcessResult, test_no_error, run
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
check_final_eval_reward_above(orchestrator_stdout, env_name="reverse-text", min_threshold=0.5)
test_dashboard = make_dashboard_test("rl_opd_process", RUN_NAME)
@@ -10,6 +10,7 @@ import pytest
from prime_rl.utils.process import cleanup_process
from tests.conftest import ProcessResult
from tests.integration.dashboard_smoke import make_dashboard_test
from tests.utils import check_final_eval_reward_above, check_no_error, strip_escape_codes
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
@@ -121,3 +122,6 @@ def test_eval_reward_converges(rl_sft_process: ProcessResult, test_no_error, run
with open(run_dir / "logs" / "latest" / "orchestrator.log", "r") as f:
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
check_final_eval_reward_above(orchestrator_stdout, env_name="reverse-text", min_threshold=0.5)
test_dashboard = make_dashboard_test("rl_sft_process", RUN_NAME)
@@ -6,6 +6,7 @@ import torch
from torch.distributed.checkpoint.format_utils import dcp_to_torch_save
from tests.conftest import ProcessResult
from tests.integration.dashboard_smoke import make_dashboard_test
from tests.utils import check_loss_goes_down, strip_escape_codes
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
@@ -170,3 +171,6 @@ def test_full_offload_model_only_resume_preserves_weights(
assert torch.equal(before[key].to(torch.bfloat16), after[key].to(torch.bfloat16)), (
f"Weight mismatch after model-only resume: {key}"
)
test_dashboard = make_dashboard_test("sft_process", RUN_NAME)
@@ -4,6 +4,7 @@ from typing import Callable
import pytest
from tests.conftest import ProcessResult
from tests.integration.dashboard_smoke import make_dashboard_test
from tests.utils import check_loss_goes_down, strip_escape_codes
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
@@ -112,3 +113,6 @@ def test_loss_goes_down_resume(sft_lora_resume_process: ProcessResult, run_dir:
with open(trainer_log_path, "r") as f:
trainer_stdout = strip_escape_codes(f.read()).splitlines()
check_loss_goes_down(trainer_stdout)
test_dashboard = make_dashboard_test("sft_lora_process", RUN_NAME)
+3 -3
View File
@@ -153,14 +153,14 @@ def _scalar(episode: vf.Episode) -> float:
def _grpo(group: list[vf.Episode], length_penalty=None) -> list[float]:
"""Drive ``GRPOAlgorithm.score_group`` and read back each per-rollout scalar."""
algo = GRPOAlgorithm(GRPOAlgoConfig(length_penalty=length_penalty), policy_pool=None)
algo = GRPOAlgorithm(GRPOAlgoConfig(length_penalty=length_penalty), clients=None)
asyncio.run(algo.score_group(group))
return [_scalar(episode) for episode in group]
def _max_rl(group: list[vf.Episode]) -> list[float]:
"""Drive ``MaxRLAlgorithm.score_group`` and read back each per-rollout scalar."""
algo = MaxRLAlgorithm(MaxRLAlgoConfig(), policy_pool=None)
algo = MaxRLAlgorithm(MaxRLAlgoConfig(), clients=None)
asyncio.run(algo.score_group(group))
return [_scalar(episode) for episode in group]
@@ -223,7 +223,7 @@ def test_linear_context_term_penalizes_more_context():
_build_episode(1.0, sampled_lengths=[10], obs_lengths=[]),
_build_episode(1.0, sampled_lengths=[10], obs_lengths=[100]),
]
asyncio.run(GRPOAlgorithm(GRPOAlgoConfig(length_penalty=cfg), policy_pool=None).score_group(group))
asyncio.run(GRPOAlgorithm(GRPOAlgoConfig(length_penalty=cfg), clients=None).score_group(group))
advs = [_scalar(episode) for episode in group]
assert advs[0] > advs[1]
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
+1 -1
View File
@@ -10,7 +10,7 @@ from verifiers.v1.types import AssistantMessage, ToolMessage, UserMessage
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
from prime_rl.orchestrator.algo import EchoAlgorithm, assign_advantages, stamp_loss_routing
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.transports.rollouts.types import TrainingSample
from prime_rl.transports.batch.types import TrainingSample
FROZEN = {"name": "org/ref-model", "base_url": "http://ref:8001/v1"}
+1 -1
View File
@@ -4,7 +4,7 @@ import numpy as np
import pytest
from prime_rl.trainer.batch import _is_multimodal_sample, build_bin_cost, pad_micro_batch, prepare_batch, prepare_sample
from prime_rl.transports.rollouts.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
def _routed_experts(data, dtype=np.uint8):

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