Compare commits

...
Author SHA1 Message Date
2441fd5142 feat: drop on in-queue staleness + first-class cancellation type (#3313)
## Summary

Refactors staleness handling around the exact consumption-lag definition
(#3050's framing), toward #3310.

- **Exact measurement**: `episode_staleness()` decomposes each trained
episode's staleness from its `PolicySpan` into the in-flight share (`end
- start`, weight updates during generation) and the in-queue remainder
(buffered between completion and ship). New per-step metrics:
`off_policy/{mean,max}`, `off_policy/{in_flight,in_queue}/{mean,max}`,
`off_policy/dropped`; the step log line's `Max Off-Policy` uses the
exact definition. Every quality metric in the step log and the wandb
`effective` subset is computed over exactly the traces shipped to the
trainer this step (`batch.cohort`); only `Error`/`Cancelled`/`Ratio` are
arrival-window rates, since over the shipped set they are
0/0/share-of-shipped by construction.
- **In-queue enforcement**: previously only in-flight episodes were aged
and dropped — an episode that finished quickly and sat in the sink
accumulated staleness that was measured at ship but never enforced. Now
the sink sweeps `pending_batch` before every readiness check and voids
anything past `max_off_policy_steps`, so the bound is a hard guarantee
on trained data. The dispatcher's version-boundary sweep remains as a
compute saver (it must run before the engine pause for KV-abort safety)
and uses the same exact step-based formula.
- **Tail semantics**: the trainer now broadcasts every version except
`v{max_steps}` (the only one nothing can sample from), instead of
skipping the final `TARGET_LAG+1`. The orchestrator stays alive for the
last rendezvous (`wait_for_final_broadcast`), so `max_off_policy_steps`
holds exactly on every step including the final batch, and the tail
special-casing this used to need is gone (the dispatch gate's
final-batch exception and the watcher's shortened ModelExpress window).
Draining now starts right after shipping the final batch — the old
trigger needed a further batch to *fill*, which burned a batch of
inference and, under a tight `max_off_policy_steps`, never filled at all
(end-of-run livelock).
- **First-class cancellation**: dropped groups emit one typed
`Cancellation(group_id, count, reason)` on `out_q` instead of
per-episode synthetic `Cancelled`-error episodes; queue-voided episodes
are tracked in a `cancelled` id-set on the episode collections,
alongside `sampled`/`admitted`. Cancellations no longer confound error
metrics: `has_error` stays pure (overload cuts and staleness drops are
no longer counted as errors), the effective subset excludes cancelled
episodes explicitly, and the step log / wandb gain separate `Cancelled`
rates. A stale-voided group also bypasses curriculum admission — a
pipeline decision is not a task result.

## Breaking

- **wandb**: new `train/*/all/**/cancelled/mean` and per-step
`off_policy/*` keys; cancellations no longer appear under
`*/error/Cancelled` or inflate `has_error/mean`.
`dispatcher/off_policy_level/{mean,max}` →
`dispatcher/off_policy/{mean,max}`, now reporting the exact step-based
staleness of in-flight work instead of the aged in-flight counter.
- **Zero-output abort accounting**: cancelled groups still advance the
zero-output budget (by their full owed episode count), but stale-voided
groups no longer feed the curriculum via `on_result`.
- **Trainer broadcast schedule**: in-memory transports now broadcast
`v{max_steps-1}` (previously skipped); the orchestrator waits for it
before tearing down. The final drain no longer requires (or generates) a
throwaway post-final batch.
- **The bound's meaning tightened**: staleness now counts queue time,
not just weight updates during generation. A config tuned under the old
in-flight-only definition drops more aggressively at the same numeric
value; `max_off_policy_steps = 0` now means strictly synchronous (heavy
oversampling drops), where the old `0` only meant "no update
mid-generation".

## Verification

- Behavioral smoke (stubbed envs, no GPU): stale `Cancellation` voids
arrived episodes without reading as error; a fully-cancelled group still
advances the zero-output budget by its owed count; overload cancellation
finalizes the partial group and its survivors still train; the queue
sweep un-fills a batch, marks the episode cancelled, and counts drops;
the dispatcher drops exactly the groups past the bound and emits one
typed `Cancellation`; `effective` excludes cancelled while
`has_error`/`cancelled` stay disjoint.
- `tests/unit/orchestrator`, `tests/unit/test_configs.py`,
`tests/unit/transports`: 201 passed (the `test_qwen3_vl_e2e` failure is
pre-existing on `main`).
- `ruff check` and `ruff format --check` clean.
- E2E: 15-step reverse-text run with
`--orchestrator.max-off-policy-steps 0` (true on-policy), clean exit in
3m 21s. **All 15 step lines report `Max Off-Policy 0` and `Error 0.0%`**
— including the final batch, which now trains on the freshly-broadcast
`v{max_steps-1}`. Both enforcement layers fired throughout (45
queue-sweep drops, 14 in-flight cancel sweeps) with per-step `Cancelled`
up to 70% and zero genuine rollout failures — e.g. `Step 2 | … | Max
Off-Policy 0 | Error 0.0% | Cancelled 70.3% | …`; under the old
error-marker representation those cancellations would have read as
`Error ~70%`. Draining started immediately at the final ship (`Shipped
the final batch — draining pipeline`). Reward climbed 0.14 → ~0.77.
- E2E (filesystem broadcast): 8-step reverse-text run with
`--weight-broadcast.type filesystem --orchestrator.max-off-policy-steps
0`, clean exit for both processes. All 8 steps report `Max Off-Policy 0`
and `Error 0.0%` — including the final batch, since filesystem writes
every version (no skip path) and the final-broadcast wait is correctly
inert (0 occurrences). Drain fired at the final ship; the trainer wrote
all broadcast dirs and finished cleanly. NIXL is safe by construction
(trainer skip window and the watcher's ModelExpress guard both derive
from `max_steps` and moved in lockstep) but has not been exercised
end-to-end.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 14:55:24 -07:00
967fbf25ef fix(sft): resumed runs restart the data stream with num_workers > 0 (#3332)
## Summary

Since #3299 made `data.num_workers` default to 1, **every resumed SFT
run silently restarts the training data from the beginning** and freezes
the data position it writes into subsequent checkpoints.

Root cause: `train()` called `iter(dataloader)` before the resume path's
`ckpt_manager.load(..., dataloader=dataloader)`. With worker processes,
`iter()` forks the worker with a copy of the dataset in its *initial*
state; the later `load_state_dict` only stashes state for a future
iterator that is never created. Two symptoms:

- the resumed run consumes the dataset from row 0 again (visible as a
loss-slope kink at every resume — repeated data);
- `state_dict()` keeps returning the stashed loaded state, so every
post-resume checkpoint stores the resume-point position instead of the
live one, compounding across restarts.

Fix: create the iterator only after the potential resume load, with a
comment stating the constraint.

Also: `get_dataset_state` unpacked exactly one worker snapshot, crashing
**any** run with `num_workers > 1` at the startup log line (start or
resume) — it now returns positions keyed per worker, and stops dumping
`pending_sample` token buffers into the log. It keeps parsing the
loader's stashed state rather than the dataset object: after a resume
the restored position exists only there (the main-process dataset object
stays at position 0; workers receive the state on fork). This is now the
single code path: `num_workers = 0` (the only case with a different,
inline state layout) is no longer supported.

## Breaking

- `data.num_workers = 0` is rejected at config time (`ge=1`). Inline
main-process data loading is gone; use `num_workers = 1` (the default).

## Verification

A/B on `configs/ci/integration/reverse-text-sft/{start,resume}.toml`
(Qwen3-0.6B, 1 node, 2 GPUs, 5 steps + resume to 10), comparing
`checkpoints/step_N/trainer/dataloader/rank_0.pt` worker-snapshot
dataset state:

| variant | ckpt step_5 | ckpt step_10 (post-resume) |
|---|---|---|
| main, `num_workers=1` | `{'step': 213}` | `{'step': 213}` — frozen,
data restarted from row 0 |
| main, `num_workers=2` | — | crashes at startup (`ValueError: too many
values to unpack` in `get_dataset_state`) |
| this PR, `num_workers=1` | `{'step': 213}` | `{'step': 407}` —
advanced correctly |
| this PR, `num_workers=2` | `{'worker_0': 111, 'worker_1': 111}` |
`{'worker_0': 213, 'worker_1': 213}` — per-worker state restored and
advanced; workers consume disjoint shards |

Discovered on a production 500-step GLM-4.5-Air SFT run (india): after
two crash-resumes, both post-resume checkpoints carried the identical
dataset position (`{'step': 6657}` at step 150 *and* step 300) and the
loss slope steepened at each resume boundary from re-trained data.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 14:04:58 -07:00
e6d2b3f252 fix: meta load order (#3333)
* test(trainer): add xfail demonstrating buffer-reinit-after-load bug

load_dcp_from_hf runs init_buffers_post_meta() after dcp_load() writes
checkpoint values into persistent buffers, so any model whose reinit
touches a persistent buffer (e.g. Laguna's MoE expert_bias) has the
loaded value silently clobbered back to its reinit default.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(trainer): reinit buffers before loading checkpoint, not after

load_dcp_from_hf ran init_buffers_post_meta()/fix_model_post_empty()
after dcp_load() had already copied checkpoint values into persistent
buffers, silently clobbering any buffer both a reinit hook touches and
a checkpoint legitimately ships (e.g. Laguna's MoE expert_bias). Move
the call to run once, immediately after to_empty(), matching the
existing correct ordering in setup_model's checkpoint-deferred branch.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(trainer): rename test_model_load_order.py to models/test_state_loading.py

Group it with the other cross-cutting model-mechanism tests
(test_checkpointing.py, test_fused_moe.py) rather than the top-level
train/ dir, and name it for what it covers (weight-checkpoint state
loading) since models/test_checkpointing.py already covers activation
checkpointing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 16:41:15 -04:00
Konstantin DunasandGitHub 13553dd88a refactor(orchestrator): rename sampler to generation source (#3330) 2026-08-21 20:36:15 +02:00
Konstantin DunasandGitHub d37b57ba6e docs(training): correct saved episode references (#3329) 2026-08-21 20:36:08 +02:00
Konstantin DunasandGitHub 802a364e6a fix(orchestrator): label eval avg@k by episode group size (#3328) 2026-08-21 20:36:03 +02:00
Konstantin DunasandGitHub 9b9de2f1bc fix(orchestrator): apply taskset system_prompt override on the RL path (#3327) 2026-08-21 19:42:57 +02:00
fe38722e8b feat: enable nccl for sft online evals (#3323)
* enable nccl for sft online evals

* support multi-node sft nccl evals

* fix: enforce NCCL-requires-inference at the launcher, not the model validator

The launcher strips [inference] and [deployment] from the trainer sub-config
of a decoupled multi-node deployment, so the re-parsed sub-config tripped the
validator's guard and crashed every trainer rank at startup.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: remove accidentally committed gitlink

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: broken line continuation in NCCL sbatch template blocks

The {% if %} blocks left a whitespace-only line after the backslash
continuation, terminating the launch command early: the trainer/evals
processes ran without their tee pipelines (empty node_*.log/evals.log)
and the stray '2>&1 | tee ... &' ran as a separate command, mis-assigning
EVALS_PID.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* share weight broadcast config policy

* revert shared weight broadcast policy

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 22:34:32 -07:00
minh hoangandGitHub c69f5b0389 feat: support Qwen3.8 (#3314)
Qwen3.8 reuses the Qwen3.5 architecture verbatim — the dense 27B reports
`model_type: qwen3_5` / `Qwen3_5ForConditionalGeneration`, the 2.4T-A95B
reports `qwen3_5_moe_text` — but both places that enable Qwen3.5 keyed off
the repo name, so neither picked it up.

Trainer: gate the three Qwen3.5 patches on the loaded config's `model_type`
instead of a substring of `model.name`. The name check missed
`Qwen/Qwen3.8-27B` and the `qwen3_5_moe` fallback only caught the MoE
sibling, so the dense 27B trained without `_patch_qwen3_5_linear_attn_varlen`
— GatedDeltaNet gets no cu_seqlens, conv/SSM state leaks across packed
sequences, and 48 of its 64 layers are linear attention. model_type also
covers Qwen3.6 and renamed fine-tunes, which the name check missed too.

Parsers: `^Qwen/Qwen3\.5-` doesn't match the dotted 3.6/3.8 names and the
`^Qwen/Qwen3-` catch-all only matches hyphenated ones, so both parsers
auto-resolved to None and vLLM launched without either flag. Qwen3.8's chat
template opens `<think>` at the generation prompt, so reasoning would land
in `content` and tool calls would go unparsed.
2026-08-20 21:59:40 -07:00
29e4222767 feat: remove weight checkpointing (#3316)
* feat!: remove weight checkpointing

The trainer saves only DCP checkpoints. HF weights on disk exist in two
forms: weight broadcasts — the transient trainer-to-inference transport,
which SFT now ships for online evals (same filesystem component RL
uses, broadcast at eval steps, newest kept only) — and offline
conversion of DCP checkpoints via scripts/dcp_to_hf.py (full models and
LoRA adapters).

WeightCheckpointManager, the weights/step_N dirs, and the ckpt.weights
config surface (weights, weights_only, skip_gather_master_weights,
save_adapter_separately) are removed. The evals process watches
broadcasts/step_N (OnlineConfig.weights_dir renamed to broadcasts_dir)
and loads adapter broadcasts of LoRA runs via /load_lora_adapter. The
weight save/gather helpers move to prime_rl.utils.weights.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: wait for the resume-step broadcast before retriggering

The trainer rebroadcasts the resumed policy only after loading the
model, so a one-shot STABLE check usually lost the race and the watch
loop never retried (last_step is pre-seeded to the resume step). Wait
for the broadcast; give up only when a newer stable broadcast proves it
was already cleaned away.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: enable LoRA on the eval inference server

SFT LoRA online evals reload raw adapter broadcasts via
/load_lora_adapter, which requires enable_lora on the server. Mirror
the RL validator: set enable_lora and max_lora_rank when LoRA is on,
warn when inference is externally managed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: defer offline DCP->HF converter to a follow-up

The converter needs more standalone testing (incl. GPU-free use) and will
land in its own PR. The resume-preserves-weights test now compares the DCP
checkpoints directly via dcp_to_torch_save; the PEFT adapter-export tests
move to the follow-up with the script.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: DCP comparison keys and dtypes in resume test; idempotent rebroadcast

The trainer wraps DCP state as {app: {model: ...}}, so the converted
torch save must be indexed through 'app' — the bare 'model' lookup
raised KeyError. The two compared runs also train in different compute
dtypes (fp32 vs bf16 under full offload), so compare in bf16, which is
what the resumed model actually loaded.

The SFT startup rebroadcast now skips when the resume step's broadcast
already exists with STABLE: rewriting the same dir in place would race
an evals process already reloading it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 20:29:42 -07:00
e3e3a87dea feat: rank-parallel sharded save for filesystem broadcast (#3315)
* feat: rank-parallel sharded save for filesystem broadcast

Gather full weights cooperatively and let every rank convert and write
its own layer-aligned slice as safetensors shards, instead of funneling
everything through the master rank. D2H copies go through persistent
pinned buffers and overlap the per-tensor all-gathers. The broadcast is
always sharded safetensors now; the save_sharded and save_format knobs
are gone.

Laguna-XS.2 (68GB bf16) on 2 GPUs: gather 25.1s -> 2.7s, total save
83.1s -> 51.9s (the write phase is disk-bound on a single NVMe;
rank-parallel writes scale with per-node writers on shared
filesystems).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: create save dir in save_state_dict_parallel

Callers no longer need to pre-create the directory; a fresh save dir
made every rank's shard write fail with a safetensors I/O error.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: note the same-stream invariant on the staging copy

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: clarify HF conversion branches and resolve_fqn

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: blocking D2H copies in the parallel gather

Drop the pinned staging buffers and non-blocking copies: their safety
rested on same-stream allocator-reuse ordering, which is subtle to
maintain. Each rank still copies only its slice, and the parallel shard
writes — the dominant cost at scale — are unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: derive layer ownership from the module tree

Replace the FQN regex with prefixes taken from the children of every
'layers' ModuleList. State-dict keys and module names come from the
same tree traversal, so the prefixes match keys verbatim, wrapper
components and all.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Revert "refactor: derive layer ownership from the module tree"

This reverts commit 740059c835ac8025af00ab58cdbe1aef941168ee.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 20:29:14 -07:00
NeoandGitHub 65e4b915ba Relock prime-kernels after refreshing the v0.8.0 wheels (#3321) 2026-08-21 01:44:20 +02:00
a686a90405 Add custom vendored kernels (#3154)
* Add custom vendored kernels

* Add fused MoE kernel

* Fix comments, simplify kernel toml metadata, make sure deps for prime-kernels match prime-rl directly

* Update to latest fused moe kernel

* Add prime-flash-moe integration in addition to locally compiled kernels

* Add mxfp8 routing support for prime-flash-moe

* Fix MXFP8 backward for fused MoE for correctly group aligned experts

* Torch fused grouped_mm backward for fused MoE forward

* Fix release upload in kernel build: install gh in container, grant contents write

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Set GH_REPO for release upload: container checkout trips git dubious-ownership

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Pin prime-kernels at the v0.8.0 prebuilt wheels behind a kernels extra

The wheels were backfilled onto v0.8.0 from this branch
(build_kernels.yaml run 31429866271); uv sync --extra kernels now
installs them instead of requiring a local nvcc build.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Format kernel MoE files with ruff 0.13

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Fix memory corruption of triton kernel for large numel quants, where N >= 2^31=INT_MAX

* Make the kernel a git-submodule

* Move the kernels into the prime-kernels submodule

The `prime-kernels` wheel — build system, registry and every kernel's Python
surface — now lives in its own monorepo, PrimeIntellect-ai/prime-kernels,
checked out here as the `kernels/` submodule. flash_moe's C++/CUDA sources,
previously a nested prime-flash-moe submodule, are committed there too, so one
non-recursive init brings in everything a source build needs.

Integration is unchanged: `uv sync --extra kernels` still resolves the prebuilt
wheels from a prime-rl release, `uv pip install --no-build-isolation -e kernels`
still builds from source, and build_kernels.yaml still attaches the wheels to
every release. Its `paths` trigger moves from `kernels/**` to the `kernels`
gitlink, which is the only path prime-rl tracks now, and ruff excludes the whole
submodule rather than just the vendored sources.

* Update kernels

* Fix comments

* Add tests for the fused MoE

* Bump prime-kernels to 2ceaf9e

* Remove stray uv.lock for prime-rl-configs

* Verify mxfp8 grad values and needs_input_grad handling

* Print epsilons in tests

* Print epsilons in tests

* Print epsilons in tests

* Print epsilons in tests

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 01:28:32 +02:00
991b925e6e validate scheduler steps at config time (#3318)
A linear scheduler with warmup_steps + decay_steps > max_steps only
failed deep into trainer setup, via a bare assert in
setup_linear_scheduler. Add validate_scheduler to the configs package
and call it from TrainerConfig and SFTConfig so the run fails at
config validation instead. Also covers cosine schedulers, which need
max_steps and warmup_steps < max_steps.

The runtime assert stays as a backstop (SFT resume with skip_scheduler
shrinks the step budget at runtime) but now carries a message.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 15:06:34 -07:00
Konstantin DunasandGitHub 03cdc51575 refactor(orchestrator): score native episodes (#3297) 2026-08-21 00:06:29 +02:00
NeoandGitHub cb5f1e72bb Turn fused adamw on by default except when we do cpu offloading (#3305) 2026-08-20 09:01:59 -07:00
samsjaandGitHub 52eebada92 fix(tests): seed qwen3_moe parity test RNG and widen grad tolerance (#3290)
test_qwen3_moe compares HF and prime-rl gradients in bf16 with an
unseeded random draw; FA2 backward is not bit-deterministic, so the
embedding grad diff (observed 512-1344) occasionally crosses the
atol=1000 threshold, failing CI with 'Max grad diff: 1024.0' on main
and unrelated PRs.

- autouse fixture pins torch.manual_seed(0) so the input/init draw is
  deterministic (verified grad diff stays in 512-768 on this seed)
- bump grad atol 1000 -> 2048 to absorb FA2 backward reduction-order
  noise that seeding cannot remove (60/60 random seeds pass at 2048,
  worst observed 1344)
2026-08-19 20:30:47 -07:00
NeoandGitHub 5d0fc8ba2e Mario/cpu optimization dataloader (#3299)
* USe dataloder threads and pinnd memory tranfers async

* Fix PRNG

* Reset fused lm head token chunk size to 4k

* Revert lm head chunk size to default, another PR does this

* Remove unused prefetch factor

* Fix PRNG bug
2026-08-19 20:26:12 -07:00
Mika SenghaasandGitHub c2a25f0622 feat: soft and hard kv cap (#3307)
* Split kv trims into soft and hard tiers

A trim at the 0.8 trigger now only lowers the cap and lets completions
drain the pool — at that level there is still headroom, and at steady
state completions usually outrun in-place context growth, so
cancelling immediately pays a certain cost to avoid a merely possible
one. Only if usage climbs past 0.9 despite the closed gate does the
trim also cancel the excess (the prior behavior), preserving the
thrash-cliff guarantee: worst case, a soft trim escalates to a hard
one a cooldown later, still well before the cliff. Emergency cuts are
unchanged.

* Add 2-node concurrency debug config

GLM-4.5-Air scaleswe on the bash harness, 1 train + 1 infer node,
default concurrency, 100-instance SWE-Bench eval.

* Rename trim thresholds to KV_USAGE_SOFT_CAP / KV_USAGE_HARD_CAP

* Fix stale header in the concurrency debug config
2026-08-19 16:00:14 -07:00
bc9e186963 feat: adaptive concurrency for online evals (#3309)
* feat: first-class evaluator with adaptive concurrency

Promote the evaluator out of the orchestrator package into
prime_rl.evaluator and let it run standalone multi-env evals (no
[online] block: one epoch against the served weights, then exit) as
well as SFT online evals ([online]: watch the weights dir per
checkpoint; the sft launcher writes this config).

Scheduling reuses the orchestrator pipeline 1:1: an eval-only
Dispatcher sized by the adaptive ConcurrencyController
([eval.concurrency], replaces eval.max_inflight_episodes), fed by the
InferenceMetricsCollector's /metrics polls. Overload cuts only block
admission - eval episodes are measurements and always run to
completion.

The evaluator spawns an env server per source without an explicit
serve.address; the sft launcher keeps spawning its own and stamps the
derived addresses into the evaluator config.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: stop evaluator collectors before monitor finalize

The periodic logger and the inference-metrics collector log to the W&B
run, so a poll landing after monitors.finalize() warns about a finished
run - mirror the orchestrator and stop them on the clean path first.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: fail fast when adaptive concurrency has no metrics

External inference APIs (e.g. Prime Inference) expose no vLLM /metrics,
so the concurrency controller never bootstraps and the cap would
silently sit at min_inflight forever. The evaluator now probes /metrics
once at startup: no engine metrics + an adaptive band raises with the
fix (pin min_inflight = max_inflight); a pinned band runs fixed with a
warning. A successful probe also bootstraps the controller before the
first dispatch.

Add examples/evals/swe.toml: SWE-bench Verified + Terminal-Bench 2
against deepseek/deepseek-v4-flash on Prime Inference, 1h agent cap,
pinned band.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: rename evaluator command and configs to evals

Per review: the command is uv run evals, the config classes are
EvalsConfig / EvalsEvalConfig in prime_rl.configs.evals, the package is
prime_rl.evals, and the launcher artifacts follow (evals.json,
evals.log, shared-W&B labels). Docs section is Evals. Add EvalsConfig
to the config-load CI check so examples/evals/*.toml are validated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: drop the Evaluator name entirely

Class Evals in prime_rl.evals.evals, run_evals wrapper, Evals proc
title and log lines; prose refers to the evals process. No identifier
or doc references evaluator anymore.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: drop the standalone evals section for now

Keep the online-evals doc updates (command rename, [eval.concurrency])
and the start-run skill runbook.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: reject skip_first_step on standalone evals

The first trigger honors skip_first_step, and standalone mode has only
that trigger - the run would exit successfully without evaluating
anything. Reject the combination at config time.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: cap CI concurrency at 128 in-flight episodes

The adaptive ramp on CI's small engine floods the router until its
circuit breakers open (ProviderError: No available workers) - 512 is
still past what the deployment sustains.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: lower wiki-search initial_inflight to the CI cap

initial_inflight must not exceed max_inflight.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 15:05:19 -07:00
NeoandGitHub bfb0fe346e Remove pipeline sync in inner loss function loop by replacing the bra… (#3294)
* Remove pipeline sync in inner loss function loop by replacing the branch with branchless code

* Ruff format
2026-08-19 12:56:19 -07:00
NeoandGitHub 2acb19eccd Increase chunk size to 8k (#3302) 2026-08-19 12:53:00 -07:00
69308b88cb chore: move transport code to prime_rl.transports (#3308)
Consolidate the two send/recv stacks under one package:

- prime_rl.transport (rollouts, orch -> trainer) is now
  prime_rl.transports.rollouts
- prime_rl.trainer.rl.broadcast (weights, trainer -> orch -> infer)
  is now prime_rl.transports.weights

Both keep the base.py + concrete implementations structure. The vLLM
worker extensions and the orchestrator weight watcher stay in place
and import the shared primitives from the new location.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 12:14:21 -07:00
148 changed files with 4582 additions and 2855 deletions
+155
View File
@@ -0,0 +1,155 @@
name: Build Kernels
# Builds the `prime-kernels` wheel for x86_64 and aarch64 from the deps/prime-kernels submodule.
# Runs on every bump of that submodule to catch build breakage, and with `release_tag` to
# attach the wheels to a GitHub release — which is how they are consumed (see the `kernels`
# skill).
#
# `tag-and-release.yaml` calls this for every release, before it promotes the draft, so a
# published release always carries the wheels its `[tool.uv.sources]` pin can point at.
# `workflow_dispatch` does the same by hand, for backfilling an already published release.
#
# No GPU is needed: nvcc cross compiles for the architectures kernels.toml declares.
on:
pull_request:
paths:
- "deps/prime-kernels"
- ".gitmodules"
- ".github/workflows/build_kernels.yaml"
push:
branches: [main]
paths:
- "deps/prime-kernels"
- ".gitmodules"
- ".github/workflows/build_kernels.yaml"
workflow_dispatch:
inputs:
release_tag:
description: "Existing release tag to attach the wheels to (e.g. v0.7.0). Empty = artifacts only."
required: false
type: string
ref:
description: "Ref to build the kernels from. Empty = the ref the workflow was started on."
required: false
type: string
workflow_call:
inputs:
release_tag:
description: "Release tag to attach the wheels to. The release may still be a draft."
required: false
type: string
ref:
description: "Ref to build the kernels from. Empty = the caller's ref."
required: false
type: string
env:
# Keep in sync with the CUDA the prime-rl image is built against (Dockerfile.cuda);
# the job container image below must be edited alongside it (no env context there).
CUDA_TAG: cu128
jobs:
build:
name: Build wheel (${{ matrix.arch }})
# Uploading the wheels to a release needs write; on workflow_call the caller
# must grant it too (tag-and-release.yaml does).
permissions:
contents: write
strategy:
fail-fast: false
matrix:
include:
- runner: image-builder
arch: x86_64
- runner: image-builder-arm-2204
arch: aarch64
runs-on: ${{ matrix.runner }}
container: nvidia/cuda:12.8.1-devel-ubuntu24.04
steps:
- name: Install build tooling
run: |
apt-get update
apt-get install -y --no-install-recommends git curl ca-certificates build-essential gh
- name: Checkout
uses: actions/checkout@v5
with:
submodules: false
ref: ${{ inputs.ref }}
# deps/prime-kernels is the prime-kernels submodule and carries every kernel's sources.
- name: Init the kernels submodule
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
git submodule update --init -- deps/prime-kernels
- name: Install uv
run: |
curl -LsSf https://astral.sh/uv/install.sh | env INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR=/usr/local/bin sh
uv --version
# The wheel only imports under the exact torch it was compiled against, so build
# against the torch prime-rl resolves rather than whatever is newest today.
- name: Create build environment
env:
UV_TORCH_BACKEND: ${{ env.CUDA_TAG }}
run: |
TORCH_PIN=$(grep -A1 '^name = "torch"$' uv.lock | sed -n 's/^version = "\([^"+]*\).*"$/\1/p' | head -n1)
if [ -z "$TORCH_PIN" ]; then
echo "Could not read torch's version from uv.lock" >&2
exit 1
fi
echo "Building against torch==$TORCH_PIN"
uv venv --python 3.12 /tmp/build-env
VIRTUAL_ENV=/tmp/build-env uv pip install "torch==$TORCH_PIN" setuptools wheel ninja
# torch C++ extensions are bound to the torch and CUDA they were compiled against, so
# the wheel carries both in its local version.
- name: Stamp ABI into the version
run: |
TORCH_VERSION=$(/tmp/build-env/bin/python -c 'import torch; print(torch.__version__.split("+")[0])')
LOCAL="${CUDA_TAG}torch${TORCH_VERSION}"
sed -i -E "s/^version = \"([^\"]+)\"$/version = \"\1+${LOCAL}\"/" deps/prime-kernels/pyproject.toml
grep '^version' deps/prime-kernels/pyproject.toml
- name: Build wheel
env:
VIRTUAL_ENV: /tmp/build-env
CUDA_HOME: /usr/local/cuda
PRIME_KERNELS_REQUIRE: "1"
MAX_JOBS: "8"
run: uv build --wheel --no-build-isolation --out-dir dist deps/prime-kernels
- name: Inspect wheel
run: |
ls -lh dist/
/tmp/build-env/bin/python - <<'PY'
import pathlib, zipfile
wheel = next(pathlib.Path("dist").glob("*.whl"))
extensions = [n for n in zipfile.ZipFile(wheel).namelist() if n.endswith(".so")]
assert extensions, f"{wheel.name} contains no compiled kernels"
print(wheel.name, *extensions, sep="\n ")
PY
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: prime-kernels-${{ matrix.arch }}
path: dist/*.whl
if-no-files-found: error
- name: Attach to release
if: inputs.release_tag != ''
env:
GH_TOKEN: ${{ github.token }}
# gh must not resolve the repo from the checkout: inside the container the
# workspace is owned by another uid, which git rejects as dubious ownership.
GH_REPO: ${{ github.repository }}
TAG: ${{ inputs.release_tag }}
run: |
gh release upload "$TAG" dist/*.whl --clobber
# The `[tool.uv.sources]` pin has to name the wheel exactly, ABI suffix and all.
WHEEL=$(basename dist/*.whl)
URL="https://github.com/${GITHUB_REPOSITORY}/releases/download/${TAG}/${WHEEL}"
echo "\`{ url = \"$URL\", marker = \"platform_machine == '${{ matrix.arch }}'\" },\`" >> "$GITHUB_STEP_SUMMARY"
+37 -8
View File
@@ -113,9 +113,22 @@ jobs:
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
release-from-auto-tag:
# Wheels are attached while the release is still a draft, so it is never published without
# them — `[tool.uv.sources]` pins prime-kernels at a release asset, and an install that
# resolves to a wheel-less release would fall back to compiling CUDA from source.
kernels-from-auto-tag:
needs: auto-tag-on-main
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
permissions:
contents: write
uses: ./.github/workflows/build_kernels.yaml
with:
release_tag: ${{ needs.auto-tag-on-main.outputs.tag }}
ref: ${{ needs.auto-tag-on-main.outputs.tag }}
release-from-auto-tag:
needs: [auto-tag-on-main, kernels-from-auto-tag]
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
runs-on: ubuntu-latest
permissions:
contents: write
@@ -138,13 +151,12 @@ jobs:
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
tag-and-release:
resolve-release:
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
outputs:
tag: ${{ steps.release.outputs.tag }}
version: ${{ steps.release.outputs.version }}
steps:
- name: Checkout tagged release (dispatch)
if: github.event_name == 'workflow_dispatch'
@@ -207,11 +219,28 @@ jobs:
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
kernels-from-tag:
needs: resolve-release
permissions:
contents: write
uses: ./.github/workflows/build_kernels.yaml
with:
release_tag: ${{ needs.resolve-release.outputs.tag }}
ref: ${{ needs.resolve-release.outputs.tag }}
publish-release:
needs: [resolve-release, kernels-from-tag]
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
steps:
- name: Publish draft release
id: publish
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
TAG: ${{ needs.resolve-release.outputs.tag }}
run: |
STATE=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft --jq '.isDraft' 2>/dev/null || echo "missing")
if [ "$STATE" = "missing" ]; then
@@ -232,6 +261,6 @@ jobs:
if: steps.publish.outputs.published == 'true'
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
TAG: ${{ needs.resolve-release.outputs.tag }}
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
+3
View File
@@ -10,3 +10,6 @@
[submodule "pydantic-config"]
path = deps/pydantic-config
url = https://github.com/PrimeIntellect-ai/pydantic-config
[submodule "prime-kernels"]
path = deps/prime-kernels
url = https://github.com/PrimeIntellect-ai/prime-kernels
+113
View File
@@ -0,0 +1,113 @@
#!/usr/bin/env python3
"""
Time the routed-expert compute three ways: the fused MoE kernel (bf16 and mxfp8) against
the grouped-mm path a `model.moe_fused_kernel=false` run takes.
Forward and backward are timed separately, because only the forward is a kernel — the
backward is prime-rl's own closed-form bf16 gradients or, for mxfp8, autograd through the
grouped-mm reference. A speedup on the forward can be spent again on the backward.
uv run benchmarks/scripts/bench_fused_moe.py
uv run benchmarks/scripts/bench_fused_moe.py --tokens 16384 --num-experts 128
"""
from __future__ import annotations
import argparse
import torch
from prime_rl.trainer.models.layers.moe import _FusedMoE, _load_fused_moe_kernel, _run_experts_fused_reference
MODES = ("grouped_mm", "fused_bf16", "fused_mxfp8")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--tokens", type=int, default=8192, help="routed tokens (batch * seq)")
parser.add_argument("--dim", type=int, default=2048, help="model dim; must be a multiple of 256")
parser.add_argument("--hidden-dim", type=int, default=768, help="expert intermediate size; multiple of 128")
parser.add_argument("--num-experts", type=int, default=64)
parser.add_argument("--top-k", type=int, default=8)
parser.add_argument("--iters", type=int, default=20)
parser.add_argument("--warmup", type=int, default=5)
return parser.parse_args()
def make_inputs(args: argparse.Namespace) -> tuple[torch.Tensor, ...]:
torch.manual_seed(0)
randn = lambda *shape: torch.randn(*shape, device="cuda", dtype=torch.bfloat16)
x = (randn(args.tokens, args.dim) * 0.2).requires_grad_(True)
w1 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
w3 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
w2 = (randn(args.num_experts, args.dim, args.hidden_dim) * 0.05).requires_grad_(True)
logits = torch.randn(args.tokens, args.num_experts, device="cuda", dtype=torch.float32)
top_scores, selected = torch.softmax(logits, dim=-1).topk(args.top_k, dim=-1)
return x, w1, w2, w3, selected, top_scores.requires_grad_(True)
def run_forward(mode: str, inputs: tuple[torch.Tensor, ...], num_experts: int) -> torch.Tensor:
x, w1, w2, w3, selected, top_scores = inputs
if mode == "grouped_mm":
return _run_experts_fused_reference(x, w1, w2, w3, selected, top_scores, num_experts)
return _FusedMoE.apply(x, w1, w2, w3, selected, top_scores, num_experts, mode == "fused_mxfp8")
def time_mode(mode: str, inputs: tuple[torch.Tensor, ...], args: argparse.Namespace) -> tuple[float, float, float]:
"""Median forward ms, median backward ms, peak MiB."""
forward_ms, backward_ms = [], []
grad_out = torch.randn(args.tokens, args.dim, device="cuda", dtype=torch.bfloat16)
start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
torch.cuda.reset_peak_memory_stats()
for i in range(args.warmup + args.iters):
for tensor in inputs[:4] + (inputs[5],):
tensor.grad = None
torch.cuda.synchronize()
start.record()
out = run_forward(mode, inputs, args.num_experts)
end.record()
torch.cuda.synchronize()
if i >= args.warmup:
forward_ms.append(start.elapsed_time(end))
start.record()
out.backward(grad_out)
end.record()
torch.cuda.synchronize()
if i >= args.warmup:
backward_ms.append(start.elapsed_time(end))
median = lambda values: sorted(values)[len(values) // 2]
return median(forward_ms), median(backward_ms), torch.cuda.max_memory_allocated() / 2**20
def main() -> None:
args = parse_args()
if not torch.cuda.is_available():
raise SystemExit("no CUDA device")
kernel = _load_fused_moe_kernel()
for mxfp8 in (False, True):
reason = kernel.unsupported_shape_reason(args.dim, args.hidden_dim, mxfp8=mxfp8)
if reason is not None:
raise SystemExit(f"shape unsupported by the fused kernel: {reason}")
inputs = make_inputs(args)
print(
f"tokens={args.tokens} dim={args.dim} hidden_dim={args.hidden_dim} "
f"experts={args.num_experts} top_k={args.top_k} "
f"({args.iters} iters, {args.warmup} warmup, median)\n"
)
print(f"{'mode':<12} {'fwd ms':>9} {'bwd ms':>9} {'total ms':>9} {'speedup':>9} {'peak MiB':>10}")
baseline = None
for mode in MODES:
forward, backward, peak = time_mode(mode, inputs, args)
total = forward + backward
baseline = baseline or total
print(f"{mode:<12} {forward:>9.3f} {backward:>9.3f} {total:>9.3f} {baseline / total:>8.2f}x {peak:>10.0f}")
if __name__ == "__main__":
main()
+1 -1
View File
@@ -20,7 +20,7 @@ batch_size = 128
group_size = 8
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 384
@@ -15,15 +15,12 @@ lr = 5e-5
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
@@ -12,15 +12,12 @@ lr = 5e-5
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
@@ -23,7 +23,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -25,7 +25,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.algo]
type = "opd"
@@ -25,7 +25,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.algo]
type = "sft"
@@ -5,9 +5,6 @@ max_steps = 10
[resume]
step = 5
[ckpt.weights]
save_adapter_separately = true
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -2,9 +2,6 @@ max_steps = 5
[ckpt]
[ckpt.weights]
save_adapter_separately = true
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -23,7 +23,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -20,7 +20,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
+1 -1
View File
@@ -19,7 +19,7 @@ batch_size = 512
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[[orchestrator.train.source]]
name = "alphabet-sort"
+1 -1
View File
@@ -19,7 +19,7 @@ group_size = 8
seq_len = 8192
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[[orchestrator.train.source]]
name = "hendrycks-math"
+1 -1
View File
@@ -19,7 +19,7 @@ batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[[orchestrator.train.source]]
name = "reverse-text"
+2 -2
View File
@@ -19,8 +19,8 @@ batch_size = 512
group_size = 16
[orchestrator.concurrency]
initial_inflight = 512
max_inflight = 512
initial_inflight = 128
max_inflight = 128
[[orchestrator.train.source]]
name = "wiki-search"
+1 -1
View File
@@ -19,7 +19,7 @@ batch_size = 512
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[[orchestrator.train.source]]
name = "wordle"
@@ -18,7 +18,7 @@ batch_size = 256
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 64
-3
View File
@@ -70,9 +70,6 @@ lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
-3
View File
@@ -75,9 +75,6 @@ lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
+153
View File
@@ -0,0 +1,153 @@
# Concurrency-controller debug run: GLM-4.5-Air on the v1 `scaleswe` SWE taskset,
# bash harness on a prime sandbox runtime, 1 train + 1 infer node, eval on 100
# SWE-Bench Verified instances. Concurrency is fully default: the controller
# derives its start from the measured KV budget and adapts from there — watch
# the concurrency/* gauges in W&B or the "Concurrency ..." lines in the
# orchestrator log.
#
# Inference serves FP8 via online per-tensor quantization of the bf16
# checkpoint; weight broadcasts re-quantize through the same path on every
# update. The trainer fits on one node via cp=4 (ulysses), full CPU optimizer
# offload with the stateless sign-SGD optimizer, plus the memory improvements
# from the GLM-5.1 prod run: LM-head token chunking, activation checkpointing
# (freq=1) + activation offloading (max_inflight=1), and skip-gather /
# skip-optimizer checkpointing. Router replay is enabled — GLM-4.5-Air is a
# glm4_moe model, which supports routed_experts.
#
# GRPO uses the linear length penalty with the input-token and turns
# coefficients set to 0.1.
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "debug-concurrency"
partition = "all"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "debug-concurrency" -y || true'
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
num_infer_replicas = 1
[monitors.wandb]
project = "swe-ablations"
name = "debug-concurrency"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
[resume]
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
optim_cpu_offload = false
full_offload = true
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "sign_sgd"
# --- Orchestrator ---
[orchestrator]
batch_size = 128
group_size = 8
max_off_policy_steps = 32
[orchestrator.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
[[orchestrator.train.source]]
name = "scaleswe"
[orchestrator.train.source.env.taskset]
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
labels = ["debug-concurrency"]
[monitors.prime]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
num_examples = 100
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["debug-concurrency"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
# --- Inference ---
[inference]
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
quantization = "fp8"
enable_return_routed_experts = true
Vendored Submodule
+1
Submodule deps/prime-kernels added at 2ceaf9eccb
+1 -1
+1 -6
View File
@@ -115,12 +115,7 @@ dropout = 0.0
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. To save the raw adapter alongside the merged HF weights:
```toml
[ckpt.weights]
save_adapter_separately = true
```
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
## Disaggregated Prefill/Decode Inference
+21 -19
View File
@@ -153,25 +153,25 @@ type = "echo"
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_rl.orchestrator.sampler`) from the `sampling` component — the pool rollouts are generated from, and the home of future sampling strategies like replay buffers or branching — and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
| `grpo` | `GRPOAlgorithm` | `score_group`: group-norm credit (optional length penalty) |
| `echo` | `EchoAlgorithm` | `score_rollout`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
| `echo` | `EchoAlgorithm` | `score_episode`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
| `max_rl` | `MaxRLAlgorithm` | `score_group`: mean-normalized group credit |
| `rae` | `RAEAlgorithm` | `score_group`: per-agent EMA-baseline credit |
| `hierarchical_grpo` | `HierarchicalGRPOAlgorithm` | `score_group`: GRPO baseline per episode for solvers, per group for the proposer |
| `opd` | `OPDAlgorithm` | `score_rollout`: own-context prefill under the teacher |
| `opsd` | `OPSDAlgorithm` | `score_rollout`: demo-conditioned prefill under the live policy |
| `opd` | `OPDAlgorithm` | `score_episode`: own-context prefill under the teacher |
| `opsd` | `OPSDAlgorithm` | `score_episode`: demo-conditioned prefill under the live policy |
| `sft` | `SFTDistillAlgorithm` | no credit assignment; CE on sampled tokens |
Each class owns its hooks outright — reading one top to bottom reads the algorithm, and everything on the class is an override point. The two hooks are one scope-and-timing ladder — the wider scope is unlocked by a later barrier, so the two axes coincide. Each is handed the `Rollout` directly — the env's typed trace (`reward`, `nodes`, `num_turns`, ...) with `samples` attached, plus `assign_advantages` to write credit:
Algorithms operate on native verifier artifacts and annotate their message graphs directly:
- `async score_rollout(rollout)` — one rollout, **on arrival** (as it's tokenized, before its group is complete): rollout-local credit (`rollout.assign_advantages(...)`, scalar broadcast or per-token), observation ce weights, **or** model I/O — query a reference pool (e.g. `self.teacher_pool`, connected in `setup()` via `self.connect(...)`, or the live `self.policy_pool` for opsd) and attach per-token results (e.g. teacher logprobs) with bounded concurrency. No siblings. `echo` weights observation tokens here, identifying env-provided observation nodes by their non-sampled status and source step role attribution, applying the optional user filter, and writing the `ce_weights` stream.
- `score_group(group)` — the completed cohort, synchronous: group-relative credit (GRPO/MaxRL baselines). `group` is a list of `Rollout`.
- `async score_episode(episode)` — rollout-local scoring as one episode arrives.
- `async score_group(episodes)` — group-relative scoring after the cohort completes.
The pipeline drives the hooks through two non-virtual methods it never looks inside: `algorithm.finalize_rollout(rollout)` per arrival (rollout-local scoring + reference I/O) and `algorithm.finalize_group(rollouts)` per group (scoring + wire stamping; after this the records are frozen — groups die at stamping). Sample construction (interleaving) is pure pipeline — observation-token provenance is available through structural attribution (`node.sampled`, `node.is_content`) for any algorithm that trains on env-provided tokens.
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`.
@@ -420,30 +420,32 @@ Both of `kuhn-poker`'s agents late-bind to the run's own model — shared-policy
### Authoring an Algorithm
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class. The hook receives the group's `Rollout`s (each the env's typed `verifiers.Trace` — turns, tool calls, metadata in `info` — with `samples` attached) and writes credit via `assign_advantages`:
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class:
```python
# src/prime_rl/orchestrator/algo/my_algo.py
import torch
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.orchestrator.algo.routing import assign_advantages
class MyAlgorithm(Algorithm):
async def score_group(self, group):
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
advantages = ... # one value per rollout
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
rollout.assign_advantages(advantage)
async def score_group(self, episodes):
traces = [trace for episode in episodes for trace in episode.traces]
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
advantages = ... # one value per trace
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
assign_advantages(trace, advantage)
```
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick the hook by *when* your signal is ready: `score_rollout` for per-arrival credit or credit that needs a model call (it's `async`), `score_group` for group-relative credit (GRPO/MaxRL). `assign_advantages` takes a scalar (broadcast over the rollout's trainable tokens — the common case) or a full-length per-token list aligned to the concatenated sample token_ids (process rewards, step-level credit; `0.0` off-mask).
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick `score_episode` for rollout-local work or model calls, and `score_group` for group-relative credit. `assign_advantages` takes a scalar or a list aligned to the trace graph's sampled tokens.
Each per-token list must match the rollout's completion-token count exactly — validated loudly when the view writes it. Curriculum admission and metrics can inspect these streams after group scoring. Signals that depend on the live policy's weights (like OPD's reverse KL) cannot be precomputed here; those are reference-scoring algorithms, evaluated in the trainer.
Curriculum admission and metrics can inspect the resulting graph-native streams after group scoring.
### Reference Scoring
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_rollout`: as each rollout arrives they query a reference (the sample's own context for `opd`, the demo-conditioned context for `opsd`) and attach per-token reference logprobs to each sample. Rollouts are consumed serially by the orchestrator's main loop and each carries only a handful of samples, so the in-flight request count is naturally bounded — no explicit concurrency cap:
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_episode`: as each episode arrives they query a reference and attach sampled-token reference logprobs to its graph nodes:
- `opd` — score each sample's own context under the `teacher` (a frozen [model reference](#model-references)) via prefill; fills `ref_logprobs` for the `ref_kl` loss component (on-policy distillation). The `teacher` is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero).
- `opsd` — SDFT: prepend an expert demonstration as a leading system message (`template`, with a `{demonstration}` placeholder) and score the sample under that demo-conditioned context. The sample is scored verbatim (`hint_block + token_ids`, slicing the hint's logprobs back off), so the join is BPE-clean and it's robust to tool/multimodal prompts and any number of turns. The scoring reference *is* the live policy — self-distillation names no teacher. opsd builds its own renderer to tokenize the hint block: the tokenizer is always the live policy's (not configurable — there is no separate model), and only the `renderer` family is settable (defaults to `"auto"`, resolved from the policy tokenizer; set it to match a non-auto policy renderer). The demonstration is read from the example's `info[demo_key]`, falling back to a top-level rollout field of the same name (e.g. `answer`).
@@ -454,13 +456,13 @@ type = "opsd"
demo_key = "demonstration"
```
Scoring runs at arrival, before curriculum admission, so a rollout that is later rejected still costs its reference compute.
Scoring runs before curriculum admission, so a rollout that is later rejected still costs its reference compute.
By default, zero-advantage RL tokens are removed after a complete batch cohort has been collected and before its payload is packed for the trainer. This does not backfill the batch. Samples that still carry CE or reference-KL components are retained, while pure zero-advantage RL samples are not shipped. Removing an RL token also removes its trainer/inference mismatch-KL contribution. Set `orchestrator.train.filter_zero_advantages = false` to retain them.
## Curricula
Each training source has a `Curriculum` composed from one `TaskSampler` and any number of named `AdmissionGate`s. The sampler chooses tasks and observes every finalized result. Every gate evaluates every result; the group trains only if every gate admits it. Rejected groups remain observable while the orchestrator samples again to fill the batch.
Each training source has a `Curriculum` composed from one `TaskSampler` and any number of named `AdmissionGate`s. The sampler chooses tasks and observes every finalized `list[vf.Episode]`; each gate inspects the same native episodes. The group trains only if every gate admits it. Rejected groups remain observable while the orchestrator samples again to fill the batch.
Samplers and gates can be stateful. Their `state_dict`, `load_state_dict`, and `metrics` methods are included in orchestrator checkpoints and logged under `curriculum/<env>/`.
+1 -1
View File
@@ -109,7 +109,7 @@ uv run sft \
--data.name PrimeIntellect/Reverse-Text-SFT \
--max_steps 200 \
--optim.lr 1e-4 \
--ckpt.weights
--ckpt
```
Then run the full RL stack on reverse-text:
+1 -1
View File
@@ -211,7 +211,7 @@ The orchestrator continuously sizes how many episodes run against the inference
The controller's idea is to treat the engines as ground truth and probe, instead of modeling episode cost: while the engines show headroom, admit a little more; when they show pressure, back off. Three behaviors, in increasing severity:
- **Grow**: while the engines look healthy and the current cap is fully used, raise it multiplicatively. Growth is clocked by the pipeline itself — the cap rises by a fixed factor each time the in-flight pool has turned over once — so a fast single-turn workload ramps in seconds while a slow agentic workload ramps at its own pace, with no tuning per workload.
- **Trim**: episodes grow their context *while running*, so a pool that fit comfortably an hour ago can outgrow memory without a single new admission. When KV usage nears the ceiling, the controller shrinks the cap *and* the pool, cancelling the youngest episodes (least work lost) until the engines are comfortable again.
- **Trim**: episodes grow their context *while running*, so a pool that fit comfortably an hour ago can outgrow memory without a single new admission. When KV usage nears the ceiling, the controller first lowers the cap and lets completions drain the pool naturally (soft — no work lost); only if usage keeps climbing despite the closed gate does it also cancel the youngest episodes (hard — least work lost).
- **Cut**: when the engines are demonstrably overloaded — requests being preempted, or piling up in the waiting queue — cut the pool hard, cancel the excess, and hold further cuts until the system settles.
The cap starts from a safe bound derived from the engines (KV capacity divided by the maximum context length), or from `initial_inflight` when a good value is known, and always stays within `[min_inflight, max_inflight]`.
+1 -1
View File
@@ -32,7 +32,7 @@ Train an SFT-warmed `Qwen3-0.6B` on the `reverse-text` task — the env is bundl
uv run rl @ examples/basic/reverse-text/rl.toml
```
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into the run directory at `outputs/<run_name>/logs/{trainer,orchestrator,inference}.log` (`run.name` auto-generates as `<envs>--<model>--<short-id>`; pass `--run.name <name>` for a predictable path). Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes and final HF-compatible weights land at `outputs/<run_name>/weights/step_20`.
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into the run directory at `outputs/<run_name>/logs/{trainer,orchestrator,inference}.log` (`run.name` auto-generates as `<envs>--<model>--<short-id>`; pass `--run.name <name>` for a predictable path). Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes with a final DCP checkpoint at `outputs/<run_name>/checkpoints/step_20`.
## Documentation
+5 -16
View File
@@ -59,7 +59,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|---|---|
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | How many distinct policies may have contributed to one rollout before it's discarded (default 8). The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `errored_rollouts` and `mismatch_kl/all/mean` when tuning. |
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
@@ -204,17 +204,17 @@ num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an `evaluator` process next to the trainer. The handoff is the filesystem, not NCCL: the trainer writes an HF weight checkpoint at every step an eval env is due (in addition to `ckpt.interval`), and the evaluator watches `weights/step_{n}`, points the inference server at each stable checkpoint (`/update_weights` reload from disk), and runs the due envs against it — sequentially per checkpoint, so every epoch measures exactly one policy version. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final checkpoint always fires every env.
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).
#### Multi-Node (Decoupled Trainer and Inference Pool)
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two independent SLURM jobs**. `deployment.num_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evaluator:
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two separate SLURM jobs**. `deployment.num_train_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2 # trainer job
num_infer_nodes = 1 # eval job (inference pool + evaluator)
num_infer_nodes = 1 # eval job (inference pool + evals)
[inference.vllm]
tensor_parallel_size = 8
@@ -223,7 +223,7 @@ tensor_parallel_size = 8
job_name = "my-run"
```
The only coupling is weight checkpoints on the shared filesystem, so the jobs' lifetimes are independent: when training finishes, the trainer job exits and releases its nodes even while evals are still running; the eval job keeps draining pending checkpoints and exits after evaluating the final one (`max_steps` — without it the eval job never sees a final checkpoint and holds its allocation until walltime). Trainer and evaluator log to a single shared W&B run across both jobs — the trainer creates it, the evaluator finalizes it. Any train × inference layout works: `num_nodes` and `num_infer_nodes` are fully independent.
The launcher submits the eval job after the trainer allocation starts. The trainer publishes its rank-0 hostname in the shared run directory, and the eval job uses it to join the NCCL weight-broadcast group. Each weight transfer is synchronous, but eval rollout execution overlaps with later training steps. After the final transfer, the trainer job releases its nodes while the eval job finishes the final epoch and exits. Without `max_steps`, the eval job never sees a final broadcast and holds its allocation until walltime. Trainer and evals log to one shared W&B run — the trainer creates it, and the evals process finalizes it. Any trainer-to-inference node layout works because `num_train_nodes` and `num_infer_nodes` are independent.
### SFT-Specific Knobs
@@ -272,7 +272,6 @@ Checkpointing is split across processes because the orchestrator and trainer can
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_N/trainer/` |
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_N/orchestrator/` |
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
| Trainer (HF weights) | HF-compatible weight snapshot for serving | `<run_dir>/weights/step_N/` |
### Enabling Checkpoints
@@ -304,16 +303,6 @@ uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
--resume.dir outputs/my-run/checkpoints/step_10
```
### Serving Checkpoints
HF-compatible weight snapshots are written under `<run_dir>/weights/step_N/` whenever a full checkpoint runs (or you can write weights-only via `--ckpt.weights-only` for cheaper snapshots). Upload directly:
```bash
uv run hf upload <user>/<model>-RL outputs/<run_name>/weights/step_100
```
For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write the raw adapter alongside the merged weights — useful when serving the adapter through a separate `/load_lora_adapter` call.
## Observability
### Log Files
@@ -59,7 +59,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
-2
View File
@@ -76,7 +76,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
@@ -142,7 +141,6 @@ rollout = 3600
[inference]
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
@@ -60,7 +60,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
-1
View File
@@ -55,7 +55,6 @@ max_inflight_activations = 1
[trainer.ckpt]
skip_optimizer = true
skip_gather_master_weights = true
[trainer.optim]
type = "adamw"
@@ -56,7 +56,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
+1 -5
View File
@@ -98,11 +98,7 @@ uv run rl @ examples/basic/alphabet-sort/rl.toml \
--monitors.wandb.name ...
```
This will write a weight checkpoint in `outputs/rl/weights/step_100`. Upload it to HF to be able to use it as the final model for evaluation.
```bash
uv run hf upload <user>/Qwen3-4B-Instruct-AlphabetSort-RL outputs/rl/weights/step_100
```
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_100`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL`](https://huggingface.co/PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL).
+5 -23
View File
@@ -60,11 +60,7 @@ uv run torchrun \
--monitors.wandb.name ...
```
This should write a weight checkpoint in `outputs/sft/weights/step_100`. Upload it to HF to be able to use it as the base model for RL.
```bash
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT outputs/sft/weights/step_100
```
This should write a DCP checkpoint in `outputs/sft/checkpoints/step_100`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT).
@@ -83,11 +79,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
--monitors.wandb.name ...
```
This will write a weight checkpoint in `outputs/rl/weights/step_20`. As before, let's upload it to HF.
```bash
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-RL outputs/rl/weights/step_20
```
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_20`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL).
@@ -134,17 +126,7 @@ Exec into the trainer pod and run SFT:
```bash
kubectl exec -it my-exp-trainer-0 -- bash
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs --run.name sft
# This will save checkpoints to /data/outputs/sft/weights/step_100
```
Upload the checkpoint to HuggingFace or use it directly from shared storage:
```bash
# Option 1: Upload to HuggingFace (from within the pod)
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT /data/outputs/sft/weights/step_100
# Option 2: Use local checkpoint path in RL config
# Update the model.name in the RL configs to point to /data/outputs/sft/weights/step_100
# This will save DCP checkpoints to /data/outputs/sft/checkpoints/step_100
```
### Step 3: Deploy RL Training
@@ -212,11 +194,11 @@ kubectl exec -it my-exp-trainer-0 -- bash
# If inference server isn't running with the RL model, start it in another terminal:
kubectl exec -it my-exp-inference-0 -- bash
uv run inference --vllm.model /data/outputs/weights/step_20
uv run inference --vllm.model /data/outputs/weights_hf/step_20
# Back in trainer pod, run evaluation
uv run eval reverse-text --harness.id null \
-m /data/outputs/weights/step_20 \
-m /data/outputs/weights_hf/step_20 \
--client.base-url $INFERENCE_URL \
-n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
+1 -5
View File
@@ -103,11 +103,7 @@ The unified config file automatically configures:
- **Orchestrator**: Rollout generation with tool calling enabled
- **Inference**: vLLM server for Qwen3-4B-Instruct-2507 with tool parsing enabled
This will write weight checkpoints in `outputs/rl/weights/step_*`. Upload the final checkpoint to HuggingFace:
```bash
uv run hf upload <user>/Qwen3-4B-Instruct-WikiSearch-RL outputs/rl/weights/step_500
```
This will write DCP checkpoints in `outputs/rl/checkpoints/step_*`.
## Evaluation
+2 -10
View File
@@ -62,11 +62,7 @@ uv run torchrun \
--monitors.wandb.name ...
```
After training completes, you will find the final weight checkpoint in `outputs/sft/weights/step_20`. Upload it to HF to be able to use it as the base model for RL we will do in the next section.
```bash
uv run hf upload <user>/Qwen3-1.7B-Wordle-SFT outputs/sft/weights/step_20
```
After training completes, you will find the final DCP checkpoint in `outputs/sft/checkpoints/step_20`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-SFT).
@@ -86,11 +82,7 @@ uv run rl @ examples/basic/wordle/rl.toml \
--monitors.wandb.name ...
```
This will write a weight checkpoint in `outputs/rl/weights/step_100`. As before, let's upload it to HF.
```bash
uv run hf upload <user>/Qwen3-1.7B-Wordle-RL outputs/rl/weights/step_100
```
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_100`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-RL).
+44
View File
@@ -0,0 +1,44 @@
# Standalone SWE evals: SWE-bench Verified + Terminal-Bench 2, one epoch each,
# against DeepSeek V4 Flash on Prime Inference.
#
# export PRIME_API_KEY=<your Prime Inference key>
# uv run evals @ examples/evals/swe.toml
#
# The tasksets run in prime sandboxes (the default runtime), so the key also
# authenticates sandbox creation. External API endpoints expose no vLLM
# /metrics, so adaptive concurrency has no load signal - the band must be
# pinned (min_inflight = max_inflight) or the evals process refuses to start.
model = "deepseek/deepseek-v4-flash"
[eval.client]
base_url = "https://api.pinference.ai/api/v1"
api_key_var = "PRIME_API_KEY"
[eval.concurrency]
min_inflight = 32
max_inflight = 32
[[eval.source]]
name = "swebench-verified"
[eval.source.env.taskset]
id = "swebench-verified"
[eval.source.env.agent.harness]
id = "bash"
[eval.source.env.agent.timeout]
rollout = 3600
[[eval.source]]
name = "terminal-bench-2"
[eval.source.env.taskset]
id = "terminal-bench-2"
[eval.source.env.agent.harness]
id = "bash"
[eval.source.env.agent.timeout]
rollout = 3600
-2
View File
@@ -1,8 +1,6 @@
max_steps = 20
[ckpt]
[ckpt.weights]
save_adapter_separately = true
[model]
name = "Qwen/Qwen3.5-0.8B"
-2
View File
@@ -47,8 +47,6 @@ lr = 1e-5
[ckpt]
interval = 200
[ckpt.weights]
save_adapter_separately = true
[deployment]
type = "single_node"
@@ -0,0 +1,114 @@
from pathlib import Path
from pydantic import Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.utils.config import BaseConfig
class EvalsEvalConfig(EvalConfig):
"""Evals against a live inference server. Extends the orchestrator ``EvalConfig``
(sources, sampling, intervals) with the client of the inference deployment and
evals-side knobs."""
client: ClientConfig = ClientConfig()
"""Client of the inference server evals run against. Auto-wired from the
``[inference]`` block when the launcher manages the server."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the eval source at position ``i`` is
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
keep it instead, without shifting the other sources' ports."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: sources with an explicit
``serve.address`` are externally managed; the evals process spawns an env server at
the derived address for every other source."""
return {
("eval", source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, source in enumerate(self.source)
}
class OnlineConfig(BaseConfig):
"""Broadcast-driven online evals: watch a broadcasts directory for new weight
broadcasts and evaluate each eligible one. Without this block the evals process runs
every eval source once against the weights the inference server currently serves,
then exits."""
broadcasts_dir: Path | None = None
"""Directory to watch for ``step_{n}`` weight broadcasts. Defaults to
``<output_dir>/broadcasts``."""
max_steps: int | None = None
"""Trainer step at which the run ends. The final checkpoint always fires every
eval env, and the evals process exits after processing it. If None, the evals process
runs until terminated."""
resume_step: int | None = None
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
this step."""
class EvalsConfig(BaseConfig):
"""``uv run evals``: run the configured evals against a live inference server.
Standalone (no ``[online]``), one epoch of every eval source runs against the
served weights and the evals process exits. With ``[online]``, the evals process watches a
broadcasts directory for new weight broadcasts, updates the inference server through
the configured transport, and runs the configured evals against the updated weights.
The ``sft`` launcher writes this config; filesystem mode also works standalone against
any trainer that writes ``broadcasts/step_{n}`` directories with ``STABLE`` markers."""
model: str = "Qwen/Qwen3-0.6B"
"""Name the inference server serves the model under — the ``model`` field of every
eval request and the startup model check. Auto-filled from ``model.name`` by the
``sft`` launcher; the name stays fixed across weight updates (weights are
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
eval: EvalsEvalConfig
"""Eval sources, sampling, intervals, concurrency, and the inference client."""
online: OnlineConfig | None = None
"""Checkpoint watching (``[online]``). None runs the evals once and exits."""
weight_broadcast: WeightBroadcastConfig | None = None
"""Weight transport for online evals. The ``sft`` launcher fills this from its
resolved trainer transport. None uses filesystem reloads."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer for online evals."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
@model_validator(mode="after")
def auto_setup_broadcasts_dir(self):
if self.online is not None and self.online.broadcasts_dir is None:
self.online.broadcasts_dir = self.output_dir / "broadcasts"
return self
@model_validator(mode="after")
def validate_skip_first_step_is_online_only(self):
"""``skip_first_step`` gates the base-model eval between checkpoints; a
standalone run has only that one epoch, so skipping it would exit
successfully without evaluating anything."""
if self.online is None and self.eval.skip_first_step:
raise ValueError(
"eval.skip_first_step only applies to online evals - a standalone run "
"would skip its only eval epoch. Remove it or add an [online] block."
)
return self
@@ -1,84 +0,0 @@
from pathlib import Path
from pydantic import Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig
from prime_rl.utils.config import BaseConfig
class OnlineEvalConfig(EvalConfig):
"""Online evals against a live inference server, driven by weight checkpoints
on disk. Extends the orchestrator ``EvalConfig`` (sources, sampling, intervals)
with the client of the inference deployment and evaluator-side knobs."""
client: ClientConfig = ClientConfig()
"""Client of the inference server evals run against. Auto-wired from the
``[inference]`` block when the launcher manages the server."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the eval source at position ``i`` is
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
keep it instead, without shifting the other sources' ports."""
max_inflight_episodes: int = Field(128, ge=1)
"""Maximum eval episodes in flight — one episode is one agent run against an env server."""
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: the launcher binds env
servers at exactly these addresses and the evaluator connects to them."""
return {
("eval", source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, source in enumerate(self.source)
}
class EvaluatorConfig(BaseConfig):
"""``uv run evaluator``: watch a weights directory for new HF checkpoints, point
the inference server at each one (``/update_weights`` from disk), and run the
configured evals against the updated weights. The ``sft`` launcher writes this
config; it can also be run standalone against any trainer that writes
``weights/step_{n}`` HF checkpoints with ``STABLE`` markers."""
model: str = "Qwen/Qwen3-0.6B"
"""Name the inference server serves the model under — the ``model`` field of every
eval request and the startup model check. Auto-filled from ``model.name`` by the
``sft`` launcher; the name stays fixed across checkpoint reloads (weights are
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
eval: OnlineEvalConfig
"""Eval sources, sampling, intervals, and the inference client."""
weights_dir: Path | None = None
"""Directory to watch for ``step_{n}`` HF weight checkpoints. The ``sft`` launcher
fills it from ``ckpt.output_dir`` when checkpoints are redirected to another volume;
defaults to ``<output_dir>/weights``."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer."""
max_steps: int | None = None
"""Trainer step at which the run ends. The final checkpoint always fires every
eval env, and the evaluator exits after processing it. If None, the evaluator
runs until terminated."""
resume_step: int | None = None
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
this step."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
@model_validator(mode="after")
def auto_setup_weights_dir(self):
if self.weights_dir is None:
self.weights_dir = self.output_dir / "weights"
return self
@@ -530,7 +530,7 @@ class OrchestratorConfig(BaseConfig):
"""Maximum training steps. If None, runs indefinitely."""
max_off_policy_steps: int = Field(8, ge=0)
"""Maximum policies allowed to generate a single rollout. Rollouts generated more than ``max_off_policy_steps`` ahead of training are discarded. Higher values yield better throughput at the cost of off-policy noise."""
"""Maximum staleness of a trained rollout: the version a batch trains on (v{step-1}) minus the oldest version that generated the rollout (a rollout can span several weight updates), queue time included. Episodes past the bound are dropped, in-flight and queued; a group shares one dispatch version, so its episodes age out together. Higher values yield better throughput at the cost of off-policy noise."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
@@ -8,7 +8,7 @@ from pydantic import AliasChoices, Field, model_validator
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
from renderers.base import MODEL_RENDERER_MAP
from prime_rl.configs.evaluator import OnlineEvalConfig
from prime_rl.configs.evals import EvalsEvalConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
@@ -23,11 +23,15 @@ from prime_rl.configs.trainer import (
AdamWConfig,
CheckpointConfig,
ConstantSchedulerConfig,
FileSystemWeightBroadcastConfig,
GCConfig,
ModelConfig,
NCCLWeightBroadcastConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
WeightBroadcastConfig,
validate_scheduler,
)
from prime_rl.utils.config import BaseConfig, find_package_resource
@@ -42,6 +46,9 @@ class BaseDataConfig(BaseConfig):
micro_batch_size: int = Field(1, ge=1)
"""Per-step micro batch size. ``batch_size`` must be divisible by this."""
num_workers: int = Field(1, ge=1)
"""Number of dataloader worker processes. Batches are prepared and pinned in the background so tokenization/packing overlaps with training."""
@model_validator(mode="after")
def validate_batch_size(self):
if self.batch_size % self.micro_batch_size != 0:
@@ -60,6 +67,9 @@ class FakeDataConfig(BaseDataConfig):
input_ids: Literal["increasing", "random"] = "increasing"
"""Token id generator: ``increasing`` for deterministic sequences, ``random`` for random ids."""
seed: int = 0
"""Seed for the per-rank packing/token generator, combined with the data rank."""
class LossMaskConfig(BaseConfig):
system: bool = False
@@ -166,9 +176,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
num_infer_nodes: int = Field(0, ge=0, validation_alias=AliasChoices("num_infer_nodes", "num_eval_nodes"))
"""Inference nodes for online evals (alias: ``num_eval_nodes``). Submitted as a separate SLURM job, decoupled
from the trainer job: the handoff is weight checkpoints on the shared filesystem,
so the eval job can outlive the trainer job (evals drain after training ends) and
exits after evaluating the final checkpoint."""
from the trainer job. The eval job can outlive the trainer job while it evaluates
the final weight broadcast."""
nodes_per_fsdp_group: int | None = None
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
@@ -195,15 +204,18 @@ class SFTConfig(BaseConfig):
val: SFTValConfig | None = None
"""Validation configuration. If None, no validation runs."""
eval: OnlineEvalConfig | None = None
eval: EvalsEvalConfig | None = None
"""Online evaluation configuration: rollout-based evals against a live inference
server that reloads the trainer's HF weight checkpoints from disk. If None, no
online evals run."""
server that receives the trainer's weight broadcasts. If None, no online evals run."""
inference: InferenceConfig | None = None
"""Inference server for online evals. If None (with ``eval`` set), the launcher
does not start a server and evals connect to ``eval.client.base_url``."""
weight_broadcast: WeightBroadcastConfig | None = None
"""Trainer-to-inference weight transport for online evals. Defaults to NCCL.
LoRA and external inference use filesystem broadcast."""
optim: OptimizerConfig = AdamWConfig()
scheduler: SchedulerConfig = ConstantSchedulerConfig()
@@ -343,37 +355,47 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_online_eval(self):
"""Wire online evals: require weight checkpoints (the disk handoff to
inference) and connect the eval client to the launcher-managed server."""
"""Wire online evals and the trainer-to-inference weight transport."""
if self.eval is None:
if self.inference is not None:
raise ValueError("[inference] is only used for online evals — add an [eval] block or remove it.")
return self
# The trainer's HF weight checkpoints are how inference picks up new policies.
if self.ckpt is None:
self.ckpt = CheckpointConfig()
if self.ckpt.weights is None or self.ckpt.skip_gather_master_weights:
raise ValueError(
"Online evals require HF weight checkpoints. Enable ckpt.weights and "
"disable ckpt.skip_gather_master_weights."
)
# LoRA runs broadcast the raw adapter, which evals reload via /load_lora_adapter
if self.model.lora is not None:
if self.inference is not None:
self.inference.vllm.enable_lora = True
self.inference.vllm.max_lora_rank = self.model.lora.rank
else:
warnings.warn(
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
"make sure to set --enable_lora and --max-lora-rank.",
stacklevel=2,
)
if self.ckpt.keep_last is not None or self.ckpt.keep_interval is not None:
warnings.warn(
"ckpt.keep_last / ckpt.keep_interval can delete a weight checkpoint before the "
"evaluator consumes it when evals run slower than training - such steps are "
"skipped with a warning instead of evaluated.",
stacklevel=2,
)
if self.weight_broadcast is None:
if self.model.lora is not None or self.inference is None:
self.weight_broadcast = FileSystemWeightBroadcastConfig()
else:
self.weight_broadcast = NCCLWeightBroadcastConfig()
if self.weight_broadcast.type != "filesystem":
if self.weight_broadcast.type == "nixl":
raise ValueError("NIXL weight broadcast is not supported for SFT online evals.")
if self.model.lora is not None:
raise ValueError(
"LoRA training is not yet supported with in-memory weight broadcast. "
"Set weight_broadcast.type = 'filesystem'."
)
if self.eval.retrigger_on_resume:
raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
if self.deployment.type == "multi_node":
# Decoupled deployment: the launcher submits a dedicated SLURM job running the
# inference pool (one engine per DP rank behind a router) plus the evaluator.
# inference pool (one engine per DP rank behind a router) plus the evals process.
if self.inference is None:
raise ValueError(
"Multi-node online evals require an [inference] block - the launcher submits "
"a dedicated SLURM job running the inference pool and the evaluator."
"a dedicated SLURM job running the inference pool and the evals process."
)
if self.deployment.num_infer_nodes < 1:
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
@@ -392,13 +414,14 @@ class SFTConfig(BaseConfig):
f"deployment.gpus_per_node ({self.deployment.gpus_per_node}) must be divisible by "
f"inference.vllm.tensor_parallel_size ({self.inference.vllm.tensor_parallel_size})."
)
if self.inference.weight_broadcast.type != "filesystem":
raise ValueError(
"Online evals reload weights from disk — inference.weight_broadcast.type must be 'filesystem'."
if self.weight_broadcast.type == "nccl":
self.weight_broadcast.inference_world_size = (
self.deployment.num_infer_nodes * self.deployment.gpus_per_node
)
self.inference.weight_broadcast.type = self.weight_broadcast.type
if self.max_steps is None:
warnings.warn(
"Online evals without max_steps: the evaluator never sees a final checkpoint, "
"Online evals without max_steps: the evals process never sees a final checkpoint, "
"so the eval SLURM job holds its allocation until its walltime.",
stacklevel=2,
)
@@ -411,7 +434,7 @@ class SFTConfig(BaseConfig):
"Online evals are configured without an [inference] block - the launcher will not "
f"start an inference server. Make sure one is running at eval.client.base_url "
f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', "
"otherwise the evaluator will hang waiting for it. If a router fronts the "
"otherwise the evals process will hang waiting for it. If a router fronts the "
"deployment, set eval.client.admin_base_url to the engine URLs - admin ops "
"(pause/update_weights/resume) must bypass the router.",
stacklevel=2,
@@ -444,10 +467,9 @@ class SFTConfig(BaseConfig):
vllm.data_parallel_size = num_infer_gpus // vllm.tensor_parallel_size
if vllm.api_server_count < vllm.data_parallel_size and not vllm.enable_lora:
vllm.api_server_count = vllm.data_parallel_size
if self.inference.weight_broadcast.type != "filesystem":
raise ValueError(
"Online evals reload weights from disk — inference.weight_broadcast.type must be 'filesystem'."
)
if self.weight_broadcast.type == "nccl":
self.weight_broadcast.inference_world_size = vllm.data_parallel_size * vllm.tensor_parallel_size
self.inference.weight_broadcast.type = self.weight_broadcast.type
host = self.inference.server.host or "localhost"
client = self.eval.client
@@ -539,14 +561,8 @@ class SFTConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_lora_adapter_saving(self):
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
lora_enabled = self.model and self.model.lora
if not lora_enabled:
raise ValueError(
"save_adapter_separately=True requires LoRA to be enabled. "
"Set model.lora or disable save_adapter_separately."
)
def validate_scheduler_steps(self):
validate_scheduler(self.scheduler, self.max_steps)
return self
@model_validator(mode="after")
@@ -242,6 +242,9 @@ class ModelConfig(BaseModelConfig):
moe_use_grouped_mm: bool = True
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
moe_fused_kernel: bool = False
"""Run MoE routed experts through the vendored fused MoE CUDA kernel (``prime_kernels.flash_moe``) in forward; backward recomputes the reference grouped-mm path. Picks the mxfp8 kernel when ``quantization`` is MXFP8 with ``enable_grouped_gemm`` (which additionally needs ``hidden_size`` divisible by 256), otherwise the bf16 one. Requires the ``prime-kernels`` wheel, Blackwell (SM100) GPUs, ``ep=1``, ``model.impl='custom'``, MoE layers with output-weighted scores (``score_before_experts=False``), and ``moe_intermediate_size`` divisible by 128."""
quantization: QuantizationConfig | None = None
index_cache: IndexCacheConfig | None = None
@@ -256,7 +259,7 @@ class ModelConfig(BaseModelConfig):
debug: DebugModelConfig = DebugModelConfig()
"""Debugging knobs for the model and distributed training."""
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 1024
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 8192
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
@model_validator(mode="after")
@@ -387,6 +390,28 @@ SchedulerConfig: TypeAlias = Annotated[
]
def validate_scheduler(scheduler: SchedulerConfig, max_steps: int | None) -> None:
"""Check scheduler phases against max_steps so misconfigurations fail at config time."""
if isinstance(scheduler, LinearSchedulerConfig):
if scheduler.warmup_steps == 0 and scheduler.decay_steps == 0:
raise ValueError(
"Linear scheduler requires warmup_steps > 0 or decay_steps > 0 (use the constant scheduler instead)"
)
if scheduler.decay_steps > 0:
if max_steps is None:
raise ValueError("Must specify max_steps when using a linear scheduler with decay_steps > 0")
if scheduler.warmup_steps + scheduler.decay_steps > max_steps:
raise ValueError(
f"warmup_steps ({scheduler.warmup_steps}) + decay_steps ({scheduler.decay_steps}) "
f"must not exceed max_steps ({max_steps})"
)
if isinstance(scheduler, CosineSchedulerConfig):
if max_steps is None:
raise ValueError("Must specify max_steps when using a cosine scheduler")
if scheduler.warmup_steps >= max_steps:
raise ValueError(f"warmup_steps ({scheduler.warmup_steps}) must be less than max_steps ({max_steps})")
class BaseOptimizerConfig(BaseConfig):
lr: float = Field(1e-6, ge=0)
"""Peak learning rate."""
@@ -440,33 +465,13 @@ OptimizerConfig: TypeAlias = Annotated[
]
class WeightCheckpointConfig(BaseConfig):
save_sharded: bool = True
"""Save the weight checkpoint in sharded format."""
save_format: Literal["safetensors", "torch"] = "safetensors"
"""Weight checkpoint serialization format."""
save_adapter_separately: bool = False
"""Save LoRA adapters separately before merging into full model weights."""
class CheckpointConfig(BaseConfig):
output_dir: Path | None = None
"""Override directory for checkpoints and weights. If set, checkpoints and weight snapshots are written here instead of under the trainer ``output_dir`` — useful for writing large checkpoints to a separate storage volume."""
"""Override directory for checkpoints. If set, checkpoints are written here instead of under the trainer ``output_dir`` — useful for writing large checkpoints to a separate storage volume."""
interval: int | None = Field(None, ge=1)
"""Interval at which to save the training checkpoint. If None, only checkpoints at the end of training."""
weights: WeightCheckpointConfig | None = WeightCheckpointConfig()
"""Weight-checkpoint sub-configuration. If None, no HF-compatible weight checkpoints are written."""
skip_gather_master_weights: bool = False
"""Skip gathering and saving HF-compatible weight checkpoints. Useful for large models where the gather is expensive and only DCP checkpoints are needed."""
weights_only: bool = False
"""Save only weight checkpoints (no optimizer/scheduler state). Much faster and smaller than full checkpoints, but cannot resume training."""
keep_last: int | None = Field(None, ge=1)
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
@@ -547,12 +552,6 @@ class BaseWeightBroadcastConfig(BaseConfig):
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["filesystem"] = "filesystem"
save_sharded: bool = True
"""Save the weight checkpoint in sharded format."""
save_format: Literal["safetensors", "torch"] = "safetensors"
"""Weight checkpoint serialization format."""
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
host: str = "localhost"
@@ -721,14 +720,8 @@ class TrainerConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_lora_adapter_saving(self):
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
lora_enabled = self.model and self.model.lora
if not lora_enabled:
raise ValueError(
"save_adapter_separately=True requires LoRA to be enabled. "
"Set model.lora or disable save_adapter_separately."
)
def validate_scheduler_steps(self):
validate_scheduler(self.scheduler, self.max_steps)
return self
@model_validator(mode="after")
@@ -16,8 +16,8 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "qwen3_coder"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3"), "qwen3_coder"),
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
# Qwen3.5 and Qwen3-Coder use qwen3_coder — must be before the Qwen3 catch-all.
(re.compile(r"^Qwen/Qwen3\.5-"), "qwen3_coder"),
# Qwen3.5/3.6/3.8 and Qwen3-Coder use qwen3_coder — must be before the Qwen3 catch-all.
(re.compile(r"^Qwen/Qwen3\.(5|6|8)-"), "qwen3_coder"),
(re.compile(r"^Qwen/Qwen3-Coder"), "qwen3_coder"),
(re.compile(r"^Qwen/Qwen3-"), "hermes"),
]
@@ -37,7 +37,7 @@ REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
# Only Qwen3 Thinking models reason — Instruct/base models do not.
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
(re.compile(r"^Qwen/Qwen3\.5-"), "qwen3"),
(re.compile(r"^Qwen/Qwen3\.(5|6|8)-"), "qwen3"),
]
+12 -5
View File
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.3.1.dev33",
"verifiers[harbor]>=0.3.1.dev59",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -53,7 +53,7 @@ sft = "prime_rl.entrypoints.sft:main"
inference = "prime_rl.entrypoints.inference:main"
trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
evaluator = "prime_rl.entrypoints.evaluator:main"
evals = "prime_rl.entrypoints.evals:main"
env-server = "prime_rl.entrypoints.env_server:main"
[project.entry-points."vllm.general_plugins"]
@@ -86,6 +86,11 @@ gpt-oss = [
quack = [
"quack-kernels>=0.4.1",
]
# Prebuilt `prime-kernels` wheels from a release (see the `kernels` skill). Compiled for
# sm_100a; on other GPUs the package installs fine and reports its kernels unavailable.
kernels = [
"prime-kernels",
]
all = [
"prime-rl[flash-attn]",
"prime-rl[disagg]",
@@ -196,6 +201,7 @@ deep-ep = false
deep-gemm = false
nixl-cu12 = false
torchao = false
prime-kernels = false
[tool.uv.sources]
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
@@ -227,6 +233,10 @@ deep-gemm = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
prime-kernels = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
flash_attn_3 = { index = "pytorch-cu128-test" }
@@ -261,9 +271,6 @@ select = ["F", "I"]
"src/prime_rl/trainer/sft/data.py" = ["F722", "F821"]
[tool.ruff.lint.isort]
# `prime_rl` is split across two editable wheels (prime-rl + prime-rl-configs).
# Without this, ruff classifies prime_rl.configs.* as third-party because it
# doesn't live under src/.
known-first-party = ["prime_rl"]
known-third-party = ["verifiers", "renderers", "pydantic_config"]
+19
View File
@@ -35,6 +35,25 @@ When bumping a package past the workspace-wide `exclude-newer = "7 days"` window
## Optional extras
### CUDA kernels
Prebuilt wheels, pinned at a release in `[tool.uv.sources]`:
```bash
uv sync --extra kernels
```
No plain sync compiles CUDA — building from source stays an explicit, manual step (needs
`nvcc` whose CUDA major matches torch's and the `deps/prime-kernels` submodule initialized),
and overrides the wheel until the next sync:
```bash
git submodule update --init deps/prime-kernels
uv pip install --no-build-isolation -e deps/prime-kernels
```
See the `kernels` skill.
### NemotronH (Mamba SSD kernels)
```bash
+180
View File
@@ -0,0 +1,180 @@
---
name: kernels
description: How prime-rl vendors, builds, and ships CUDA kernels (the `deps/prime-kernels` submodule and the `prime-kernels` wheel). Use when adding a kernel, building it locally, calling one from training code, or publishing prebuilt wheels.
---
# CUDA kernels
CUDA kernels live in their own monorepo,
[prime-kernels](https://github.com/PrimeIntellect-ai/prime-kernels), checked out here as the
git submodule `deps/prime-kernels`, alongside prime-rl's other submodules. That repo is the
wheel root (`setup.py`, `pyproject.toml`) and `prime_kernels/` inside it is the importable
package: one folder per kernel, holding the
kernel's Python surface *and* its C++/CUDA sources under `csrc/`, all declared in the single
manifest `prime_kernels/kernels.toml`. See `deps/prime-kernels/README.md` once the submodule
is initialized.
Nothing about a kernel lives in prime-rl. prime-rl pins a prime-kernels commit, builds the
wheel from it, and installs the result — and stays a pure-Python wheel itself; never add
compiled extensions to it.
Living under `deps/` means `tool.ruff.extend-exclude = ["deps"]` in `pyproject.toml`
already covers it — prime-rl lints none of it.
## Calling a kernel from prime-rl
Kernels are compiled for exact compute capabilities and may not be built at all, so always
gate. Never import `prime_kernels.<name>` directly in training code:
```python
import prime_kernels
if prime_kernels.is_available("flash_moe"):
flash_moe = prime_kernels.load("flash_moe")
```
`prime_kernels.status()` maps every kernel to `"available"` or the reason it is not — log
it once at startup rather than failing a run halfway through. `unavailable_reason(name)` is
the same answer for one kernel (`None` when it is usable), which is what a test's skip guard
wants; `is_available` is just that call compared to `None`.
`flash_moe` is the one kernel today: fused MoE forward (bf16 + mxfp8) on Blackwell
tcgen05, reached through `model.moe_fused_kernel=true`.
What a kernel requires of its inputs — block sizes, alignments, shape constraints — belongs
to prime-kernels, which exports it: `flash_moe.BLOCK_M`, `flash_moe.MXFP8_SCALE_BLOCK`, and
`flash_moe.unsupported_shape_reason(dim, hidden_dim, mxfp8=...)`, which
`apply_fused_moe_kernel` calls once at setup so an unsupported model fails before training
rather than mid-step. Never hardcode a `128` on this side: then every requirement change is
a change in both repos.
## Building locally
`uv sync --extra kernels` installs the prebuilt wheel (see "Pinning installs at the prebuilt
wheels"); building from source is for changing kernels. It is manual by design — no `uv sync`
may compile CUDA, so the extra resolves to release wheels, never to this source tree:
```bash
git submodule update --init deps/prime-kernels
uv pip install --no-build-isolation -e deps/prime-kernels
```
Requirements: `nvcc` on `CUDA_HOME` with the **same CUDA major as torch** (torch refuses to
build extensions otherwise).
Kernels whose toolkit is unsuitable are skipped with a message and reported unavailable at
runtime — the build still succeeds. `PRIME_KERNELS=a,b` builds a subset;
`PRIME_KERNELS_REQUIRE=1` turns any skip into an error.
## Changing or adding a kernel
The work happens in the prime-kernels repo, not here. Inside `deps/prime-kernels/`:
1. Commit the sources under `prime_kernels/<name>/csrc/`.
2. Add a `[<name>]` table to `prime_kernels/kernels.toml` — `sources`, `include-dirs`,
`arch`, `cxx-std`; paths are relative to the kernel folder.
3. Write `prime_kernels/<name>/__init__.py` — `from . import _C`, then per op a wrapper
calling `torch.ops.<ns>.<op>` and a `torch.library.register_fake`. No
`torch.library.custom_op` decorator: that defines a *Python* op, and `TORCH_LIBRARY`
has already defined these C++ side — only the fake (meta) kernel is missing. A kernel
used in training also needs `torch.library.register_autograd`, since a schema carries
no backward. (`flash_moe` is forward only; prime-rl wraps it in an `autograd.Function`
of its own.)
4. Nothing else: `setup.py` and the runtime registry both read the manifest.
Rules the build assumes:
- The extension is always `prime_kernels.<name>._C`, so the C++ side defines
`PYBIND11_MODULE(_C, m)` and registers ops with `TORCH_LIBRARY*`.
- `arch` matches the device **exactly** at runtime (`10.0a` runs only on sm_100a); no PTX is
shipped to JIT from.
- Two packages registering the same `torch.ops` namespace collide. If a kernel's sources are
also installed as a standalone package (e.g. `prime_moe` from prime-flash-moe, where
`flash_moe` originally came from), uninstall it.
- Only the Python surface and the compiled `_C` ship in the wheel; `csrc/` is build input.
Then land it in prime-rl as a submodule bump.
## Bumping the pin
Kernel sources are pinned by the submodule commit, so picking up any kernel change — yours
or someone else's — is a bump:
```bash
git -C deps/prime-kernels fetch origin
git -C deps/prime-kernels log --oneline HEAD..origin/main
git -C deps/prime-kernels checkout origin/main
git add deps/prime-kernels
```
Then, in order:
- Read the diff for **host-side contract changes**, not just kernel internals. A change to
what the caller must pass (weight layout, scale packing, argument order) is silently wrong
numbers, not a build error, and prime-rl's call sites have to absorb it.
- Rebuild and re-run whatever exercises the kernel — the ABI is not checked for you. For
`flash_moe` that is `tests/unit/train/models/test_fused_moe.py`, which compares its
forward and its hand-written backward against the grouped-mm expert path; it is
`gpu`-marked and skips itself unless the kernel is available, so it only means anything
on a machine the kernel was built for.
- The bump alone ships nothing: installs resolve `prime-kernels` from a release wheel, so the
new code only reaches users once a release rebuilds the wheels and the pin below moves.
## Prebuilt wheels
[`build_kernels.yaml`](../../.github/workflows/build_kernels.yaml) builds the wheel for
x86_64 and aarch64 in the CUDA devel image (no GPU needed — nvcc cross compiles). It inits
the `deps/prime-kernels` submodule itself, runs on every bump of it, and attaches the wheels
to a release when given a `release_tag`, alongside the deep-ep/deep-gemm/torchao wheels.
Its `paths` trigger is `deps/prime-kernels` (the gitlink), **not** `deps/prime-kernels/**` —
no file under it is tracked by prime-rl, so a `**` pattern would match nothing and submodule
bumps would build no wheels.
Every release gets them: [`tag-and-release.yaml`](../../.github/workflows/tag-and-release.yaml)
calls this workflow after the tag is cut and **before** it promotes the draft, so a published
release always carries its wheels. To backfill a release that predates this, dispatch by hand:
```bash
gh workflow run build_kernels.yaml -f release_tag=vX.Y.Z -f ref=vX.Y.Z
```
The wheel version carries the ABI it was built against, e.g.
`prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl` — it imports only under
that exact torch, so the build installs the torch pinned in `uv.lock`, not the newest one.
The base version comes from `deps/prime-kernels/pyproject.toml` in the prime-kernels repo.
### Pinning installs at the prebuilt wheels
`uv sync --extra kernels` installs `prime-kernels` from the wheels named in
`[tool.uv.sources]` — the pattern deep-ep, deep-gemm and vllm already use, and the only form
the extra may take, since a sync must never compile:
```toml
[tool.uv.sources]
prime-kernels = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
```
The wheels are prime-rl release assets — the kernels live in their own repo, but they ship
with prime-rl's releases. To move the pin, the build prints both lines, ready to paste, in
its job summary. Then `uv lock`.
The pin necessarily trails by one release: a release's own assets do not exist until that
release is built, so `vX.Y.Z` can only point at wheels from an already published tag. Move it
whenever the kernels or the torch/CUDA pin change — a stale pin ships stale kernels, and a
pin whose torch no longer matches the lock fails at import, not at install.
## Gotchas
- prime-kernels' `pyproject.toml` mirrors prime-rl's own `torch>=2.9.0`; keep the two
identical, and build against the torch in `uv.lock` (`build_kernels.yaml` reads it) — the
wheel imports only under the torch it was compiled against.
- Never reintroduce `prime-kernels` as a path source: uv cannot read a source tree's metadata
without building it, so every `uv lock` would then need nvcc. A release-asset URL has static
metadata and does not.
- A fresh clone without the submodule still installs and trains — only the source build needs
it. `build_kernels.yaml` inits it and sets `PRIME_KERNELS_REQUIRE=1`, so a wheel is never
published with kernels silently skipped.
+16 -2
View File
@@ -9,7 +9,8 @@ Releases are driven by [`.github/workflows/tag-and-release.yaml`](../../.github/
1. You create a **draft GitHub Release** with the notes inline (`gh release create --draft`).
2. You open a **draft PR** that bumps `version` in `pyproject.toml`.
3. Maintainer merges. The workflow tags the commit and promotes the draft.
3. Maintainer merges. The workflow tags the commit, builds the `prime-kernels` wheels and
attaches them to the draft, then promotes it.
Release notes live on the GitHub Release, not in the repo. Prime-rl is **not** on PyPI. `.dev` tags are handled separately by `devx_tag.yaml`; `tag-and-release.yaml` ignores them.
@@ -64,6 +65,19 @@ gh pr create --draft --title "chore: release $NEW" --body "Bumps version to ${NE
Stop. Do not tag, push tags, or flip the draft to published — the workflow does that on merge.
## 5. After it publishes: move the kernel pin
The release now carries `prime_kernels-*.whl` for x86_64 and aarch64. Point installs at them
so nobody compiles CUDA, in a follow-up PR:
```bash
gh release view "$NEW" --json assets --jq '.assets[].name' # exact filenames, ABI and all
```
Update the `prime-kernels` URLs under `[tool.uv.sources]` in `pyproject.toml` to `$NEW`, then
`uv sync --all-extras` to relock. The pin always trails one release — `$NEW`'s wheels do not
exist until `$NEW` is built. See the `kernels` skill.
## Recovery
If the workflow tagged the commit but failed to promote the draft, the next main push (or `workflow_dispatch` with `tag: v{new}`) re-promotes it.
If the workflow tagged the commit but failed to promote the draft, the next main push (or `workflow_dispatch` with `tag: v{new}`) re-promotes it. A rerun rebuilds and re-uploads the kernel wheels (`--clobber`), which is harmless.
+19 -19
View File
@@ -58,7 +58,7 @@ After a restart, verify all processes are back up and progress resumed before th
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the run dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
- `{run_dir}/configs/` — resolved configs, written as JSON so explicit None settings round-trip (`rl.json` has the full picture).
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved rollout traces (see Traces below).
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved episodes (see Episodes below).
### Logs
@@ -66,7 +66,7 @@ After a restart, verify all processes are back up and progress resumed before th
{run_dir}/logs/latest/
├── trainer.log # rank 0 stdout
├── orchestrator.log # orchestrator stdout
├── evaluator.log # SFT online-eval evaluator stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evaluator.log)
├── evals.log # SFT online-eval evals stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evals.log)
├── inference.log # vLLM stdout
├── trainer/
│ ├── node_*.log # per-node (multi-node only)
@@ -82,7 +82,7 @@ Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough
Scan for problems:
```bash
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evaluator,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evals,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
```
@@ -130,7 +130,8 @@ All metrics print to the console log (and W&B when configured).
| trainer | `perf/throughput`, `perf/mfu` | tokens/s and MFU % |
| orchestrator | `time/step`, `time/save_ckpt` | phase timings |
| orchestrator | `time/wait_for_policy` | **high → trainer is bottleneck** |
| orchestrator | `dispatcher/off_policy_level/{mean,max}`, `dispatcher/inflight/{train,eval}`, `dispatcher/queued/eval` | dispatcher / async state |
| orchestrator | `dispatcher/off_policy/{mean,max}`, `dispatcher/inflight/{train,eval}`, `dispatcher/queued/eval` | dispatcher / async state |
| orchestrator | `off_policy/{mean,max}`, `off_policy/{in_flight,in_queue}/{mean,max}`, `off_policy/dropped` | per-step staleness of trained rollouts |
| env server | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
For live vLLM stats, query Prometheus directly:
@@ -140,31 +141,30 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
# vllm:num_requests_running, vllm:num_requests_waiting, vllm:gpu_cache_usage_perc (→1.0 = KV cache saturated)
```
### Traces
### Episodes
```
{run_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per rollout as it completes
{run_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per episode as it completes
{run_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
```
JSONL files of `vf.Trace` records (training tensors excluded), one line per trace — a
multi-agent env's episode contributes several lines sharing one `info.episode_id`. `all`
gets every completed rollout the moment it arrives — errored, curriculum-rejected, and never-batched
ones included — so it's crash-durable; `effective` gets the clean trainable subset that went
into the step's train batch (eval: the non-errored trainable epoch cohort; multiple eval envs
share the step file) — untrainable traces (a frozen judge's) appear only in `all`. Each record carries `run` (`{type, id, step}`; for eval, `step` is the trigger step),
`verifiers` (producing build), `agent` (model, sampling, harness, `name`, `trainable`), `ok`
(the success sentinel — `errors` alone keeps retry history even after a recovery), and
`runtime` (config + provisioned resource id, e.g. the sandbox id), plus `env_name`,
`group_id`, `episode_id`, and `policy_version` under `info`.
JSONL files of native `vf.Episode` records (training tensors excluded), one line per episode.
`all` gets every completed episode as it arrives — including trace-less failures,
curriculum-rejected work, and work that never enters a batch — so it is crash-durable.
`effective` contains the admitted clean trainable traces grouped into their original episodes
(eval: the non-errored trainable epoch cohort). Each record carries its provenance at the
episode level: `env` (`id` plus the orchestrator's `name`), full `task`, `group` (`id`),
and `run`. Training-run records discriminate train/eval work and include dispatch
step plus an optional live-policy version span. Traces retain their own task,
verifiers, agent, and runtime fields.
```bash
wc -l {run_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
jq '.rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.ok | not) | {id, env: .info.env_name, runtime}' {run_dir}/rollouts/step_*/train/all/traces.jsonl
jq '.traces[].rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.ok | not) | {id, env: .env.id, errors}' {run_dir}/rollouts/step_*/train/all/traces.jsonl
```
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the trace subtrees.
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
### Common failure modes
+47 -4
View File
@@ -1,6 +1,6 @@
---
name: start-run
description: How to launch prime-rl training runs — the `rl`, `sft`, and `inference` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
description: How to launch prime-rl training runs — the `rl`, `sft`, `inference`, and `evals` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
---
# Start a run
@@ -9,7 +9,7 @@ All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/t
## Run directories
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, weights, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, broadcasts, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
## Config system at a glance
@@ -48,8 +48,10 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
If a local env exists under `deps/prime-envs/environments/` or
`deps/verifiers/environments/` but does not import, install the env workspace
members with `uv sync --all-packages` (all) or `uv sync --package prime-rl
--package <env>` (one) — they're auto-discovered, no `pyproject.toml` edit needed.
members with `uv sync --all-extras --all-packages` (all) or `uv sync --all-extras
--package prime-rl --package <env>` (one) — they're auto-discovered, no
`pyproject.toml` edit needed. Keep `--all-extras` for training so a targeted
package sync does not prune accelerator dependencies from the environment.
## `sft` — SFT training
@@ -88,6 +90,46 @@ curl http://localhost:8000/v1/chat/completions \
- Entrypoint: `src/prime_rl/entrypoints/inference.py`
- SLURM: single-node, multi-node, and disaggregated deployments
## `evals` — multi-env evals
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
```bash
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
uv run evals @ eval.toml
```
Minimal standalone `eval.toml`:
```toml
model = "Qwen/Qwen3-4B"
[eval.client]
base_url = "http://localhost:8000/v1"
[eval.concurrency] # adaptive; same controller as [orchestrator.concurrency]
min_inflight = 8
max_inflight = 128
[[eval.source]]
num_examples = 32 # always cap eval size for smokes
group_size = 4
[eval.source.env.taskset]
id = "aime25"
[eval.source.env.agent.harness]
id = "null"
[eval.source.env.agent.runtime]
type = "subprocess"
```
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/envs/eval/{name}.log`.
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
## Summary
| Command | Purpose | Typical use |
@@ -95,6 +137,7 @@ curl http://localhost:8000/v1/chat/completions \
| `rl` | Full RL pipeline | Production RL training |
| `sft` | Supervised fine-tuning | SFT and hard-distill |
| `inference` | vLLM server | Standalone serving / debugging |
| `evals` | Multi-env evals | Standalone evals / SFT online evals |
## Key paths
+24
View File
@@ -0,0 +1,24 @@
"""Lightweight launcher for the online evals.
Defers heavy ML imports until after ``cli()`` parses CLI args, so
``evals --help`` short-circuits in ``cli()``. The actual implementation
lives in ``prime_rl.evals.evals``.
"""
import asyncio
from prime_rl.configs.evals import EvalsConfig
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Evals")
config = cli(EvalsConfig)
from prime_rl.evals.evals import run_evals
asyncio.run(run_evals(config))
if __name__ == "__main__":
main()
-24
View File
@@ -1,24 +0,0 @@
"""Lightweight launcher for the online evaluator.
Defers heavy ML imports until after ``cli()`` parses CLI args, so
``evaluator --help`` short-circuits in ``cli()``. The actual implementation
lives in ``prime_rl.orchestrator.evaluator``.
"""
import asyncio
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Evaluator")
config = cli(EvaluatorConfig)
from prime_rl.orchestrator.evaluator import run_evaluator
asyncio.run(run_evaluator(config))
if __name__ == "__main__":
main()
+78 -56
View File
@@ -1,6 +1,5 @@
import json
import os
import shutil
import signal
import subprocess
import sys
@@ -9,7 +8,7 @@ from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.configs.evals import EvalsConfig, OnlineConfig
from prime_rl.configs.orchestrator import EvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.shared import LogConfig
@@ -19,12 +18,10 @@ from prime_rl.utils.pathing import (
clean_future_steps,
create_attempt_log_dir,
format_log_message,
get_all_ckpt_steps,
get_broadcast_dir,
get_ckpt_dir,
get_config_dir,
get_log_dir,
get_step_path,
get_weights_dir,
latest_log_dir,
resolve_latest_ckpt_step,
validate_run_dir,
@@ -46,7 +43,7 @@ EVAL_SBATCH = "eval.sbatch"
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
INFERENCE_CONFIG = "inference.json"
EVALUATOR_CONFIG = "evaluator.json"
EVALS_CONFIG = "evals.json"
ENVS_DIR = "envs"
@@ -66,7 +63,7 @@ def eval_env_servers(config: SFTConfig) -> list[tuple[EvalSourceConfig, str]]:
def get_ckpt_base(config: SFTConfig) -> Path:
"""Where checkpoints and weights live: ``ckpt.output_dir`` when set, else the run dir."""
"""Where checkpoints live: ``ckpt.output_dir`` when set, else the run dir."""
return (config.ckpt.output_dir if config.ckpt else None) or config.run_dir
@@ -80,16 +77,25 @@ def resolve_resume_step(config: SFTConfig) -> int | None:
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
def build_evaluator_config(config: SFTConfig) -> EvaluatorConfig:
"""Derive the evaluator subconfig from the resolved SFT config."""
def build_evals_config(config: SFTConfig) -> EvalsConfig:
"""Derive the evals subconfig from the resolved SFT config. The launcher
spawns the env servers itself, so each source's derived address is stamped in,
marking it externally managed for the evals process."""
assert config.eval is not None
return EvaluatorConfig(
eval_config = config.eval.model_copy(deep=True)
addresses = config.eval.env_addresses
for source in eval_config.source:
source.serve.address = addresses[("eval", source.resolved_name)]
return EvalsConfig(
model=config.model.name,
eval=config.eval,
weights_dir=get_weights_dir(get_ckpt_base(config)),
eval=eval_config,
weight_broadcast=config.weight_broadcast,
online=OnlineConfig(
broadcasts_dir=get_broadcast_dir(config.run_dir),
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
),
output_dir=config.run_dir,
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
monitors=config.monitors,
)
@@ -103,7 +109,7 @@ def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None
def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: bool = False) -> None:
"""Write the inference, evaluator, and env-server configs for online evals."""
"""Write the inference, evals, and env-server configs for online evals."""
config_dir.mkdir(parents=True, exist_ok=True)
if config.inference is not None:
@@ -116,11 +122,11 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
with open(config_dir / INFERENCE_CONFIG, "w") as f:
json.dump(inference_dict, f, indent=2)
with open(config_dir / EVALUATOR_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_evaluator_config(config)), f, indent=2)
with open(config_dir / EVALS_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_evals_config(config)), f, indent=2)
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>`
# binds at the source's deterministic address, where the evaluator connects.
# binds at the source's deterministic address, where the evals process connects.
for source, address in eval_env_servers(config):
env_dir = config_dir / ENVS_DIR / "eval"
env_dir.mkdir(parents=True, exist_ok=True)
@@ -168,6 +174,11 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
ranks_filter=",".join(map(str, config.log.ranks_filter)),
prl_run_id=prl_run_id,
run_name=config.run.name,
use_nccl_broadcast=(
config.eval is not None
and config.weight_broadcast is not None
and config.weight_broadcast.type == "nccl"
),
)
script_path.parent.mkdir(parents=True, exist_ok=True)
@@ -176,7 +187,7 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Path, prl_run_id: str | None) -> None:
"""Write the SLURM script for the decoupled online-eval job (inference pool +
env servers + evaluator) to disk."""
env servers + evals) to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
@@ -199,7 +210,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
**config.env_vars,
**config.inference.env_vars,
}
evaluator_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
evals_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
script = template.render(
**config.slurm.template_vars,
@@ -214,10 +225,11 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
enable_expert_parallel=config.inference.vllm.enable_expert_parallel,
inference_env_vars=inference_env_vars,
evaluator_env_vars=evaluator_env_vars,
evals_env_vars=evals_env_vars,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
prl_run_id=prl_run_id,
run_name=config.run.name,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
)
script_path.parent.mkdir(parents=True, exist_ok=True)
@@ -226,10 +238,9 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
def sft_slurm(config: SFTConfig):
"""Run SFT training via SLURM. With online evals on a multi-node deployment, the
trainer and the eval deployment (inference pool + evaluator) are two independent
SLURM jobs: the handoff is weight checkpoints on the shared filesystem, so the
trainer job releases its allocation when training finishes while the eval job
keeps draining evals and exits after the final checkpoint."""
trainer and the eval deployment (inference pool + evals) are two independent
SLURM jobs. The trainer publishes its rank-0 hostname through the shared run
directory so the eval deployment can join its NCCL weight-broadcast group."""
assert config.slurm is not None
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
@@ -244,13 +255,13 @@ def sft_slurm(config: SFTConfig):
else {"slurm", "dry_run", "clean"}
)
if decoupled_eval:
# The trainer job only needs [eval] for the weight-checkpoint cadence; the
# The trainer job only needs [eval] for the weight-broadcast cadence; the
# inference pool lives in the eval job.
exclude = exclude | {"inference"}
write_config(config, config_path, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
# Trainer and evaluator processes log to a single shared W&B run across both jobs,
# Trainer and evals processes log to a single shared W&B run across both jobs,
# keyed by the launcher's run id.
prl_run_id: str | None = None
if decoupled_eval and config.monitors.wandb is not None:
@@ -261,8 +272,8 @@ def sft_slurm(config: SFTConfig):
logger.info(f"Wrote SLURM script to {script_path}")
# The trainer job is submitted first and the eval job depends on it having started:
# the trainer creates the shared W&B run, and the evaluator's joiner init only
# retries for a bounded window — starting the evaluator while the trainer job pends
# the trainer creates the shared W&B run, and the evals process's joiner init only
# retries for a bounded window — starting the evals process while the trainer job pends
# would crash it at wandb init.
script_paths = [script_path]
if decoupled_eval:
@@ -283,16 +294,26 @@ def sft_slurm(config: SFTConfig):
# The eval job logs at stable (non-attempt) paths under the run dir.
log_message += "\n" + format_log_message(
log_dir=get_log_dir(config.run_dir),
evaluator=True,
evals=True,
inference=True,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
num_infer_nodes=config.deployment.num_infer_nodes,
).removeprefix("Logs:\n")
if config.dry_run:
submit = "\n".join(f" sbatch {path}" for path in script_paths)
if decoupled_eval:
trainer_submit = f" TRAIN_JOB_ID=$(sbatch --parsable {script_paths[0]} | cut -d';' -f1)"
eval_submit = f" sbatch --dependency=after:$TRAIN_JOB_ID {script_paths[1]}"
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
eval_submit = (
" sbatch --dependency=after:$TRAIN_JOB_ID "
f"--export=ALL,TRAIN_JOB_ID=$TRAIN_JOB_ID {script_paths[1]}"
)
submit = "\n".join((trainer_submit, eval_submit))
else:
submit = f" sbatch {script_paths[0]}"
note = (
"\n\nSubmit the trainer job first — the evaluator joins the W&B run the trainer creates."
"\n\nSubmit the trainer job first. The eval job starts after the trainer allocation is ready."
if decoupled_eval
else ""
)
@@ -307,6 +328,8 @@ def sft_slurm(config: SFTConfig):
if submitted_job_ids:
# Hold the eval job until the trainer job has started (not finished).
cmd.append(f"--dependency=after:{submitted_job_ids[-1]}")
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
cmd.append(f"--export=ALL,TRAIN_JOB_ID={submitted_job_ids[-1]}")
cmd.append(str(path))
logger.info(f"Submitting: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True)
@@ -360,17 +383,17 @@ def sft_local(config: SFTConfig):
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
# Trainer and evaluator log to a single shared W&B run whose id ($WANDB_RUN_ID)
# Trainer and evals log to a single shared W&B run whose id ($WANDB_RUN_ID)
# equals $PRL_RUN_ID, one label per process.
wandb_shared_env: dict[str, str] = {}
if config.eval is not None:
# The trainer creates the run; the evaluator (which drains its final evals
# The trainer creates the run; the evals process (which drains its final evals
# after the trainer exits) finalizes it.
wandb_shared_env = {
"WANDB_SHARED_MODE": "1",
"WANDB_RUN_ID": os.environ["PRL_RUN_ID"],
"WANDB_SHARED_PRIMARY": "trainer",
"WANDB_SHARED_FINISHER": "evaluator",
"WANDB_SHARED_FINISHER": "evals",
"WANDB_PROGRAM": "uv run sft",
"WANDB_ARGS": json.dumps(sys.argv),
}
@@ -419,7 +442,7 @@ def sft_local(config: SFTConfig):
log_path=log_dir / "inference.log",
)
# Start one env server per eval source. The evaluator connects to each source's
# Start one env server per eval source. The evals process connects to each source's
# deterministic address, polling until the server is up.
for source, address in eval_env_servers(config):
name = source.resolved_name
@@ -432,19 +455,19 @@ def sft_local(config: SFTConfig):
)
if config.eval is not None:
logger.info("Starting evaluator process")
logger.info("Starting evals process")
start_process(
"evaluator",
["evaluator", "@", (config_dir / EVALUATOR_CONFIG).as_posix()],
"evals",
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "evaluator",
"WANDB_SHARED_LABEL": "evals",
},
log_path=log_dir / "evaluator.log",
log_path=log_dir / "evals.log",
)
from prime_rl.utils.utils import get_free_port
@@ -487,11 +510,11 @@ def sft_local(config: SFTConfig):
)
processes.append(tail_process)
# Wait for the trainer (and the evaluator, which drains its final evals after
# Wait for the trainer (and the evals process, which drains its final evals after
# the trainer's last checkpoint) while surfacing any process failure.
terminal_events = [stop_events["trainer"]]
if "evaluator" in stop_events:
terminal_events.append(stop_events["evaluator"])
if "evals" in stop_events:
terminal_events.append(stop_events["evals"])
while True:
pending = [event for event in terminal_events if not event.is_set()]
if error_queue:
@@ -527,29 +550,28 @@ def sft_local(config: SFTConfig):
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
"""Remove eval artifacts a previous run left behind: weight checkpoints and rollout
"""Remove eval artifacts a previous run left behind: weight broadcasts and rollout
trace dirs — everything on a fresh start, steps past the resume step on resume.
Without this the evaluator would replay stale checkpoints (and then skip the
Without this the evals process would replay stale broadcasts (and then skip the
re-trained ones at the same steps), and the append-only trace files would mix two
policies' rollouts under one step."""
logger = setup_logger(config.log.level or "info")
if os.environ.get("NEVER_CLEAN"):
logger.warning("NEVER_CLEAN is set - keeping stale weight checkpoints; the evaluator may replay them")
logger.warning("NEVER_CLEAN is set - keeping stale weight broadcasts; the evals process may replay them")
return
resume_step = resolve_resume_step(config)
weights_dir = get_weights_dir(get_ckpt_base(config))
stale_steps = [step for step in get_all_ckpt_steps(weights_dir) if resume_step is None or step > resume_step]
if stale_steps:
logger.info(
f"Deleting {len(stale_steps)} stale weight checkpoint(s) in {weights_dir} "
f"({','.join(map(str, stale_steps))})"
)
for step in stale_steps:
shutil.rmtree(get_step_path(weights_dir, step), ignore_errors=True)
clean_future_steps(config.run_dir, resume_step if resume_step is not None else -1)
def sft(config: SFTConfig):
# Launcher-only check: the trainer re-parses a sub-config with [inference] and
# [deployment] stripped, so the model validator cannot enforce this.
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl" and config.inference is None:
raise ValueError(
"NCCL weight broadcast requires launcher-managed inference. "
"Add an [inference] block or set weight_broadcast.type = 'filesystem'."
)
# The run identity is runtime-only, never sub-config: $PRL_RUN_ID / $PRL_RUN_NAME are
# the vehicle for runtime info between processes, and every spawned process inherits
# them. Components launched standalone have no run identity.
View File
+476
View File
@@ -0,0 +1,476 @@
"""Evals: multi-env evals against a live inference server.
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.
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
fed by the ``InferenceMetricsCollector``'s ``/metrics`` polls. Eval episodes
are version-pinned measurements, so an overload cut only blocks admission and
the in-flight pool drains through natural completions.
Env servers: sources without an explicit ``serve.address`` get an env server
spawned by the evals process at their derived address; sources with one are
externally managed (e.g. spawned by the ``sft`` launcher, which stamps the
derived addresses into this config)."""
from __future__ import annotations
import asyncio
import json
import os
import time
import uuid
from subprocess import Popen
from prime_rl import monitors
from prime_rl.configs.evals import EvalsConfig
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.types import EvalBatch, Policy
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
from prime_rl.utils.client import InferencePool, init_nccl_broadcast
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.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
from prime_rl.utils.utils import clean_exit
monkey_patch_oai_iterable_types()
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"
class Evals:
def __init__(self, config: EvalsConfig) -> None:
self.config = config
setup_logger(config.log.level, json_logging=config.log.json_logging)
intercept_vf_logging(logger="verifiers.v1", level="WARN")
mode = f"online (broadcasts_dir={config.online.broadcasts_dir})" if config.online is not None else "standalone"
get_logger().info(f"Starting evals ({mode})")
# The last weight-checkpoint step already handled (evaluated or skipped).
self.last_step = (config.online.resume_step if config.online is not None else None) or 0
self.eval_triggered_at: dict[tuple[str, int], float] = {}
self.env_server_procs: list[Popen] = []
self.dispatcher_task: asyncio.Task | None = None
async def setup(self) -> None:
config = self.config
set_default_executor()
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
wandb=config.monitors.wandb,
file=config.monitors.file,
output_dir=config.output_dir,
run_config=config,
eval_env_names=[source.resolved_name for source in config.eval.source],
overview_flavor="sft",
)
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
self.run_name = os.environ.get("PRL_RUN_NAME")
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.spawn_env_servers()
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.eval.source, config.eval.env_addresses)
await self.eval_envs.start()
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)
get_logger().success("Inference pool ready")
weight_broadcast = config.weight_broadcast
if weight_broadcast is not None and weight_broadcast.type == "nccl":
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,
)
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)
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
self.policy = Policy(version=0, model_name=config.model)
# Pessimistic per-episode token cost for the controller's starting cap,
# only used when the engine doesn't report its max context length.
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.eval.source) or 8192
self.concurrency = ConcurrencyController(config.eval.concurrency, fallback_cost=fallback_cost)
self.dispatcher = Dispatcher(
train_envs=None,
eval_envs=self.eval_envs,
train_source=None,
eval_source=self.eval_source,
policy_pool=self.pool,
policy=self.policy,
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.eval.concurrency.max_inflight,
tasks_per_minute=None,
max_off_policy_steps=0,
run_id=self.run_id,
run_name=self.run_name,
on_episode_complete=self.concurrency.record_episode,
)
# No ``on_overload``: eval episodes are measurements and are never
# cancelled — a cut only blocks admission until the pool drains.
self.concurrency.bind(
set_limit=self.dispatcher.set_limit,
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.
self.inference_metrics = InferenceMetricsCollector(
self.pool.admin_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
# hit the cap would silently sit at min_inflight forever. A pinned
# band (min_inflight = max_inflight) makes the controller inert and
# is the supported way to run against such endpoints.
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)
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); "
"pin the concurrency by setting eval.concurrency.min_inflight = max_inflight."
)
get_logger().warning(f"No engine metrics - running with concurrency pinned at {concurrency.min_inflight}")
await self.inference_metrics.start()
self.periodic_logger = PeriodicLogger(
name="Evals",
collect=self.collect_pipeline_view,
metric_keys=[
*list(self.dispatcher.gauges().keys()),
*list(self.concurrency.gauges().keys()),
*DispatcherMetrics.drain_keys(train_envs=set(), eval_envs={env.name for env in self.eval_envs}),
],
interval=config.log.interval,
wandb_enabled=wandb_enabled,
)
def spawn_env_servers(self) -> None:
"""Spawn one env server per source without an explicit ``serve.address``,
at the source's derived address."""
config = self.config
addresses = config.eval.env_addresses
config_dir = get_config_dir(config.output_dir) / "envs" / "eval"
log_dir = get_log_dir(config.output_dir) / "envs" / "eval"
for source in config.eval.source:
if source.serve.address is not None:
continue
name = source.resolved_name
address = addresses[("eval", name)]
source_dict = dump_resolved_config(source)
server_config = {
"env": source_dict["env"],
"serve": {**(source_dict.get("serve") or {}), "address": address},
"log": {"level": config.log.vf_level, "json_logging": config.log.json_logging},
}
config_dir.mkdir(parents=True, exist_ok=True)
config_path = config_dir / f"{name}.json"
config_path.write_text(json.dumps(server_config, indent=2))
log_dir.mkdir(parents=True, exist_ok=True)
log_path = log_dir / f"{name}.log"
get_logger().info(f"Starting env server {name} at {address} (logs: {log_path})")
with open(log_path, "w") as log_file:
process = Popen(
["env-server", "@", config_path.as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS},
stdout=log_file,
stderr=log_file,
)
self.env_server_procs.append(process)
async def run(self) -> None:
await self.setup()
self.dispatcher_task = asyncio.create_task(self.dispatcher.start(), name="dispatcher")
await self.periodic_logger.start()
if self.config.online is None:
await self.maybe_run_evals(step=0)
else:
await self.watch()
# The periodic logger and the collector log to the W&B run, so they
# must stop before finalize marks the run finished.
await self.periodic_logger.stop()
await self.inference_metrics.stop()
get_logger().success("Evals finished!")
async def watch(self) -> None:
"""Online mode: evaluate each eligible weight broadcast as it appears."""
config = self.config
assert config.online is not None
online = config.online
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``.
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
# 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)
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)
# 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)):
if step <= self.last_step:
continue
if step not in stable:
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]:
# 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:
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"
)
self.last_step = max(self.last_step, step)
continue
is_final = online.max_steps is not None and step >= online.max_steps
await self.maybe_run_evals(step=step, reload_weights=True, force=is_final)
if online.max_steps is not None and self.last_step >= online.max_steps:
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
evaluated."""
if newest_stable is None:
return set()
due = {
step
for interval in self.eval_source.intervals.values()
for step in range(interval, newest_stable + 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."""
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")
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 not fired:
return
now = time.perf_counter()
for env_name in fired:
self.eval_triggered_at[(env_name, step)] = now
total_rollouts = sum(
self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
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 eval_step.
while self.eval_source.next_example() 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
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=f"eval was triggered at step {step}")
await self.consume_epoch(fired)
async def consume_epoch(self, fired: list[str]) -> None:
"""Consume dispatcher episodes until every fired env's epoch finalizes,
routing them through the sink and monitors."""
# An env with no examples emits no episodes, so its epoch can never finalize.
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
while pending:
episode = await self.dispatcher.out_q.get()
step = eval_work(episode).step
await monitors.log([episode], step, "eval", "all")
eval_batch = self.eval_sink.add(episode)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
pending.discard(eval_batch.env_name)
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
if not batch.episodes:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no episodes returned, skipping log")
return
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
episodes = batch.episodes
effective = episodes.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", episodes), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
eff, full = effective.metrics, episodes.metrics
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
get_logger().success(
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
)
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
"""Pipeline view for the ``PeriodicLogger``: per-env epoch progress plus the
in-flight pool against the controller's current cap."""
disp_gauges = self.dispatcher.gauges()
disp_drain = self.dispatcher.metrics.drained(train_envs=set(), eval_envs={env.name for env in self.eval_envs})
parts = []
for env_name, _step, arrived, expected, buffered in sorted(self.eval_sink.batch_progress()):
part = f"{env_name} {arrived}/{expected} ({arrived / expected:.1%})" if expected else env_name
if buffered:
part += f" (+{buffered} buffered)"
parts.append(part)
progress_part = " | ".join(parts) if parts else "Idle"
body = (
f"{progress_part}; {self.dispatcher.inflight_eval_count} inflight episodes "
f"(cap {self.dispatcher.max_inflight}, signal {self.concurrency.signal})"
)
payload = {**disp_gauges, **disp_drain, **self.concurrency.gauges()}
return body, payload
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()
cleanup_processes(self.env_server_procs)
@clean_exit
async def run_evals(config: EvalsConfig) -> None:
evals = Evals(config)
try:
await evals.run()
# Finalize only on a clean exit — a crashed evals must not mark the run completed.
await monitors.finalize()
finally:
await evals.stop()
def main() -> None:
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
set_proc_title("Evals")
asyncio.run(run_evals(cli(EvalsConfig)))
if __name__ == "__main__":
main()
+6 -6
View File
@@ -19,12 +19,12 @@ from vllm.config import set_current_vllm_config
from vllm.logger import init_logger
from prime_rl.inference.vllm.worker.weight_transfer import update_mla_absorbed_weights
from prime_rl.trainer.rl.broadcast.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
from prime_rl.trainer.rl.broadcast.nixl.cuda_malloc_memory import (
from prime_rl.transports.weights.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
size_cuda_buffers,
use_cuda_malloc_pool,
)
from prime_rl.trainer.rl.broadcast.nixl.graph import (
from prime_rl.transports.weights.nixl.graph import (
Destination,
OperationChain,
RecordedCopy,
@@ -34,9 +34,9 @@ from prime_rl.trainer.rl.broadcast.nixl.graph import (
make_hf_lazy_weights,
plan_tensor_replay,
)
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
from prime_rl.trainer.rl.broadcast.nixl.tensor_routing import route_sharded_tensor
from prime_rl.trainer.rl.broadcast.nixl.trainer_tensor_table import TrainerTensorTable
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
from prime_rl.transports.weights.nixl.tensor_routing import route_sharded_tensor
from prime_rl.transports.weights.nixl.trainer_tensor_table import TrainerTensorTable
if TYPE_CHECKING:
from vllm.v1.worker.gpu_worker import Worker
+5 -5
View File
@@ -28,7 +28,7 @@ class FileMonitor(Monitor):
self.path.parent.mkdir(parents=True, exist_ok=True)
# Line-buffered append so a concurrently-running dashboard can tail the file.
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
self.logger.info(f"Logging metrics to {self.path} and traces to {output_dir / 'rollouts'}")
self.logger.info(f"Logging metrics to {self.path} and episodes to {output_dir / 'rollouts'}")
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
sanitized, dropped = sanitize(metrics)
@@ -41,9 +41,10 @@ class FileMonitor(Monitor):
self.file.write(json.dumps(row) + "\n")
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Append the cohort's traces to its per-step trace file. ``all`` grows one
"""Append the cohort to its per-step episode file. ``all`` grows one
episode at a time as they complete, ``effective`` one batch at a time on finalize,
so an in-progress run's traces can be inspected live."""
so an in-progress run can be inspected live. Episode-level failures are
preserved even when no trace was produced."""
def write() -> None:
path = self.output_dir / "rollouts" / f"step_{step}" / kind / subset / "traces.jsonl"
@@ -51,8 +52,7 @@ class FileMonitor(Monitor):
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
with open(path, "ab") as f:
for episode in episodes:
for trace in episode.traces:
f.write(orjson.dumps(trace.to_record(), default=str, option=opts))
f.write(orjson.dumps(episode.to_record(), default=str, option=opts))
# Record serialization is heavy pure-Python work; keep it off the event loop.
# Awaited (not fire-and-forget) so appends to one file never interleave.
+1 -1
View File
@@ -277,7 +277,7 @@ def episodes_to_parquet_bytes(episodes: list[vf.Episode], run_id: str | None, st
env_names: dict[str, str] = {}
for episode in episodes:
summary_trace = next((trace for trace in episode.traces if trace.agent.trainable), episode.traces[0])
advantages[episode.id] = summary_trace.scalar_advantage()
advantages[episode.id] = summary_trace.info.get("advantage")
env_names[episode.id] = episode.env.id
now = datetime.now(timezone.utc)
+1 -1
View File
@@ -55,7 +55,7 @@ class WandbMonitor(Monitor):
primary = label == primary_label
# The primary creates the run; the finisher writes its final state. They can
# differ when the run's creator is not its last-alive writer (e.g. the SFT
# trainer creates the run, the evaluator outlives it and finalizes).
# trainer creates the run, the evals process outlives it and finalizes).
finisher = label == os.environ.get("WANDB_SHARED_FINISHER", primary_label)
settings = wandb.Settings(
mode="shared",
+8 -17
View File
@@ -3,26 +3,19 @@
The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm
is — a bundle of sampling and the per-token training signal. This package
turns the signal half into runtime objects (the sampling half is the env's
:class:`~prime_rl.orchestrator.sampler.Sampler`):
:class:`~prime_rl.orchestrator.generation_source.GenerationSource`):
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``) — each named class owns
its scoring hooks
(``score_rollout`` / ``score_group``) and declares what it needs (loss
(``score_episode`` / ``score_group``) and declares what it needs (loss
component, a "teacher", ...). One instance per env, built by
:func:`build_algorithm`. A new credit-assignment scheme is a new named class:
subclass :class:`Algorithm`, assign advantages in the hook whose timing fits,
and register it below.
- ``base`` — the :class:`Algorithm` base class, whose non-virtual
``finalize_rollout`` / ``finalize_group`` methods the pipeline drives.
Advantages are per-token everywhere they are stored or shipped — there is no
scalar advantage in the pipeline. An algorithm assigns credit in its scoring
hook via ``Rollout.assign_advantages``: a scalar that is *broadcast* over the
rollout's completion tokens (uniform credit, the common case), or an explicit
full-length-N per-token list aligned to the concatenated sample token_ids
(0.0 off-mask).
- ``routing`` — wire-field stamping: per-token component weight streams
(rl / ce / ref_kl) and the per-token advantage stream.
- ``base`` — the :class:`Algorithm` base class. Algorithms annotate native
verifier graphs; transport samples are compiled only after admission.
- ``routing`` — graph annotation and final transport loss routing.
"""
from __future__ import annotations
@@ -37,9 +30,8 @@ from prime_rl.orchestrator.algo.max_rl import MaxRLAlgorithm
from prime_rl.orchestrator.algo.opd import OPDAlgorithm
from prime_rl.orchestrator.algo.opsd import OPSDAlgorithm
from prime_rl.orchestrator.algo.rae import RAEAlgorithm
from prime_rl.orchestrator.algo.routing import stamp_advantages, stamp_loss_routing
from prime_rl.orchestrator.algo.routing import assign_advantages, stamp_loss_routing
from prime_rl.orchestrator.algo.sft import SFTDistillAlgorithm
from prime_rl.orchestrator.types import Rollout
if TYPE_CHECKING:
from prime_rl.configs.algorithm import AlgoConfig
@@ -63,7 +55,7 @@ def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> 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
# (its sibling Sampler interprets the sampling half). Every algorithm is
# (its sibling GenerationSource interprets the sampling half). Every algorithm is
# 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().
@@ -79,10 +71,9 @@ __all__ = [
"OPDAlgorithm",
"OPSDAlgorithm",
"RAEAlgorithm",
"Rollout",
"SFTDistillAlgorithm",
"build_algorithm",
"connect_frozen_pool",
"stamp_advantages",
"assign_advantages",
"stamp_loss_routing",
]
+33 -113
View File
@@ -1,70 +1,24 @@
"""The per-env algorithm runtime: the :class:`Algorithm` base class.
Each named class in this package *is* one training algorithm, one module per
algorithm: it owns the algorithm's two scoring hooks directly —
``score_rollout`` (per arrival) and ``score_group`` (per group) — and declares
which loss component its action tokens feed (``action_loss_type``). Reading a
module top to bottom reads the algorithm; writing your own is subclassing
:class:`Algorithm` and overriding the hooks its signal needs. Shared math (group
normalization, prefill alignment) lives as plain functions in ``advantage.py``;
duplication of orchestration between similar algorithms (e.g. OPD and OPSD) is
accepted so each module stays self-contained.
The two hooks are one scope-and-timing ladder — the wider scope is unlocked by
a later barrier, so the two axes coincide. Both are ``async`` (either may do
I/O); a hook that only does advantage math never awaits:
- ``score_rollout(rollout)`` — one rollout, on arrival: rollout-local signals
(raw reward, process rewards, echo's observation weighting) *and* per-rollout
I/O against another model — an inference pool the algorithm connected in
``setup()`` (a frozen teacher) or the live policy (opsd's self-distillation),
queried with bounded concurrency. No siblings.
- ``score_group(group)`` — the cohort, on group completion: group-relative
credit (GRPO/MaxRL baselines).
How rollouts are *produced* is not the algorithm's concern: that is the env's
:class:`~prime_rl.orchestrator.sampler.Sampler`, and sample construction
(interleaving, with observation-token provenance via structural node
attribution) is pure pipeline.
The pipeline (train sink) drives each algorithm through its non-virtual
:meth:`Algorithm.finalize_rollout` / :meth:`Algorithm.finalize_group` methods
and reads the class declarations; it never branches on algorithm config fields
or model roles — liveness of a reference is the only runtime distinction.
prime-rl hosts exactly one model — the trainable policy, whose pool every
algorithm is handed (``self.policy_pool``): use it for anything that scores
against the live model (opsd's self-distillation teacher, an LLM judge, ...).
Every *frozen* model an algorithm needs is an external endpoint it *connects to*
(never launches) and owns, in :meth:`Algorithm.setup`.
"""
"""Episode-native algorithm hooks."""
from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar
import verifiers.v1 as vf
from prime_rl.configs.algorithm import ActionLossType, AlgoConfig, FrozenModelConfig
from prime_rl.orchestrator.algo.routing import stamp_advantages, stamp_loss_routing
from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.orchestrator.types import Rollout
from prime_rl.utils.client import InferencePool
async def connect_frozen_pool(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferencePool:
"""Connect a client pool to an inline frozen model and wait for it to be
ready. The endpoint is externally hosted — prime-rl connects and waits,
never launches.
When ``renderer_config`` is set, the pool's train client is the renderer
(token-in/out) client — required when the frozen model *generates* rollouts
(sft), so the rollout carries tokens. Left as plain chat-completions
otherwise (opd/opsd read teacher logprobs via prefill, where the train
client type is moot)."""
"""Connect to an externally hosted frozen model and wait for it."""
from prime_rl.utils.client import InferencePool
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
@@ -78,84 +32,50 @@ async def connect_frozen_pool(
return pool
def iter_trainable_traces(episodes: list[vf.Episode]):
"""Yield clean trainable traces that contain sampled tokens."""
for episode in episodes:
for trace in episode.traces:
if trace.has_error or not trace.agent.trainable:
continue
if any(any(node.mask) for node in trace.nodes):
yield episode, trace
class Algorithm:
"""Base class for one env's training algorithm — the runtime of the
algorithm config's per-token training signal (its sibling :class:`Sampler`
interprets the ``sampling`` half).
"""Assign training annotations directly to verifier episodes.
Everything on this class is yours to override; the pipeline drives the
compilation through the non-virtual :meth:`finalize_rollout` /
:meth:`finalize_group` methods and never calls anything else. The surface is:
- declarations — which loss component the action tokens feed
(``action_loss_type``);
- lifecycle — :meth:`setup` connects client pools to the frozen models
the algorithm declares, resolving each reference via :meth:`connect`;
- the two scoring hooks, each ``async`` and given the :class:`Rollout`
directly — read the trace, write credit via
:meth:`Rollout.assign_advantages`. They are
async so either stage may do I/O — e.g. a process-reward model or a
teacher at arrival, or a judge at group time; a hook that only does
advantage math simply never awaits.
- :meth:`score_rollout` — one rollout, on arrival: rollout-local credit,
observation ce weights, or per-token results from a model the algorithm
connected in :meth:`setup` (e.g. teacher reference logprobs). Default:
nothing.
- :meth:`score_group` — the cohort: group-relative credit. Default:
nothing — rollouts keep ``advantages=None``.
Model I/O lives in :meth:`score_rollout`: it runs at arrival, so it pays
compute on rollouts that the curriculum may later reject.
Constructed with the algorithm config it interprets plus the live policy
pool (``self.policy_pool`` — always available, never closed by the
algorithm). An algorithm that needs to tokenize (e.g. opsd's demonstration
hint) builds its own renderer in :meth:`setup` from its config; the policy's
renderer is not threaded in."""
Override :meth:`score_episode` for rollout-local work and
:meth:`score_group` for cohort-relative work. The train sink compiles the
annotated traces into transport samples only after admission.
"""
action_loss_type: ClassVar[ActionLossType] = "rl"
def __init__(self, config: AlgoConfig, policy_pool: InferencePool):
self.policy_pool = policy_pool
self.connected_pools: list[InferencePool] = [] # frozen pools connected in setup(); closed at shutdown
self.connected_pools: list[InferencePool] = []
async def setup(self) -> None:
"""Connect client pools to the algorithm's frozen models — override
and resolve each reference via :meth:`connect`. The base has nothing
to connect."""
"""Connect resources owned by the algorithm."""
async def connect(self, reference: FrozenModelConfig) -> InferencePool:
"""Connect a client pool to a frozen model endpoint and track it in
``connected_pools`` — the host closes what the algorithm opened, at
shutdown. The live policy is never connected here; opsd receives the
policy pool directly."""
"""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 score_rollout(self, rollout: Rollout) -> None:
"""Arrival phase, one rollout, before its group is complete: write
rollout-local credit (``rollout.assign_advantages``), observation ce
weights (echo), or per-token results from a model — an inference pool
connected in :meth:`setup`, or the live policy (opsd). No siblings, no
group stats."""
async def score_episode(self, episode: vf.Episode) -> None:
"""Assign rollout-local annotations to one finalized episode."""
async def score_group(self, group: list[Rollout]) -> None:
"""Group phase over the finalized cohort: write group-relative credit."""
async def score_group(self, episodes: list[vf.Episode]) -> None:
"""Assign group-relative annotations to a finalized cohort."""
async def finalize_rollout(self, rollout: Rollout) -> None:
"""Arrival phase (non-virtual): rollout-local scoring as each rollout is
tokenized."""
if rollout.samples:
await self.score_rollout(rollout)
async def finalize_episode(self, episode: vf.Episode) -> None:
"""Run rollout-local scoring when the episode has trainable traces."""
if any(True for _ in iter_trainable_traces([episode])):
await self.score_episode(episode)
async def finalize_group(self, rollouts: list[Rollout]) -> None:
"""Group phase (non-virtual): group-relative scoring, then stamp each
sample's wire fields (the advantage stream + loss routing). After this
the records are frozen — groups die at stamping."""
await self.score_group(rollouts)
for rollout in rollouts:
stamp_advantages(rollout)
for sample in rollout.samples:
stamp_loss_routing(sample, self.action_loss_type)
async def finalize_group(self, episodes: list[vf.Episode]) -> None:
"""Run group-relative scoring over the native episodes."""
await self.score_group(episodes)
+21 -16
View File
@@ -11,7 +11,6 @@ from prime_rl.utils.utils import import_object
if TYPE_CHECKING:
import verifiers.v1 as vf
from prime_rl.orchestrator.types import Rollout
from prime_rl.utils.client import InferencePool
@@ -34,13 +33,13 @@ class EchoAlgorithm(GRPOAlgorithm):
if config.filter is not None:
self.filter_fn = partial(import_object(config.filter.import_path), **config.filter.kwargs)
async def score_rollout(self, rollout: Rollout) -> None:
# Observation weighting is rollout-local; the group-relative GRPO
# baseline is inherited unchanged as ``score_group``.
self._weight_observations(rollout)
async def score_episode(self, episode: vf.Episode) -> None:
for trace in episode.traces:
if not trace.has_error and trace.agent.trainable:
self._weight_observations(trace)
def _weight_observations(self, rollout: Rollout) -> None:
"""Write each sample's ``ce_weights`` stream over the env-provided
def _weight_observations(self, trace: vf.Trace) -> None:
"""Write graph-native ``ce`` weights over the env-provided
observation tokens of later turns. Provenance is structural under v1:
within a branch, the non-sampled nodes that follow the first model
response (tool output, user feedback) are the env-provided
@@ -56,12 +55,10 @@ class EchoAlgorithm(GRPOAlgorithm):
(role tags, separators, tool-response wraps) is excluded. Nodes without
attribution (the default renderer, or relay turns with no token ids)
fall back to weighting the whole non-sampled span."""
# Same branch selection as ``trace_to_samples``, so the zip with ``rollout.samples``
# stays aligned when fork dedup drops a branch.
trainable_branches = [branch for branch, _ in iter_trainable_branches(rollout)]
filter_masks = self._filter_masks(rollout, trainable_branches) if self.filter_fn is not None else None
for sample_idx, (sample, branch) in enumerate(zip(rollout.samples, trainable_branches)):
weights = [0.0] * len(sample.token_ids)
trainable_branches = [branch for branch, _ in iter_trainable_branches(trace)]
filter_masks = self._filter_masks(trace, trainable_branches) if self.filter_fn is not None else None
for branch_idx, branch in enumerate(trainable_branches):
weights = [0.0] * len(branch.token_ids)
offset = 0
seen_response = False
for node in branch.nodes:
@@ -69,7 +66,7 @@ class EchoAlgorithm(GRPOAlgorithm):
role = node.message.role
if seen_response and not node.sampled and role in self.role_weights:
weight = self.role_weights[role]
keep_mask = filter_masks[sample_idx] if filter_masks is not None else None
keep_mask = filter_masks[branch_idx] if filter_masks is not None else None
# Per-token content granularity when the renderer attributed it; otherwise
# the whole node span (is_content empty -> fall back to current behavior).
has_content = len(node.is_content) == span
@@ -81,8 +78,16 @@ class EchoAlgorithm(GRPOAlgorithm):
if node.sampled:
seen_response = True
offset += span
if any(weights):
sample.ce_weights = weights
offset = 0
for node in branch.nodes:
end = offset + len(node.token_ids)
node_weights = weights[offset:end]
if any(node_weights):
streams = dict(node.loss_weights or {})
current = streams.get("ce", [0.0] * len(node.token_ids))
streams["ce"] = [max(old, new) for old, new in zip(current, node_weights, strict=True)]
node.loss_weights = streams
offset = end
def _filter_masks(self, trace: vf.Trace, trainable_branches: list) -> list[list[bool]]:
"""Invoke the user echo filter and validate its shape: one keep-mask
+11 -9
View File
@@ -3,12 +3,13 @@ from __future__ import annotations
from typing import TYPE_CHECKING
import torch
import verifiers.v1 as vf
from prime_rl.configs.algorithm import GRPOAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm
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.orchestrator.types import Rollout
from prime_rl.utils.client import InferencePool
@@ -21,15 +22,16 @@ class GRPOAlgorithm(Algorithm):
super().__init__(config, policy_pool)
self.length_penalty = config.length_penalty
async def score_group(self, group: list[Rollout]) -> None:
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
async def score_group(self, episodes: list[vf.Episode]) -> None:
traces = [trace for _, trace in iter_trainable_traces(episodes)]
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
length_penalty = self.length_penalty
if length_penalty is None:
advantages = rewards - rewards.mean()
else:
output = torch.tensor([rollout.num_output_tokens for rollout in group], dtype=rewards.dtype)
total = torch.tensor([rollout.num_total_tokens for rollout in group], dtype=rewards.dtype)
turns = torch.tensor([rollout.num_turns for rollout in group], dtype=rewards.dtype)
output = torch.tensor([trace.num_output_tokens for trace in traces], dtype=rewards.dtype)
total = torch.tensor([trace.num_total_tokens for trace in traces], dtype=rewards.dtype)
turns = torch.tensor([trace.num_turns for trace in traces], dtype=rewards.dtype)
input = total - output
penalty_frac = (
length_penalty.num_output_tokens_weight * (output / output.max().clamp(min=1))
@@ -39,5 +41,5 @@ class GRPOAlgorithm(Algorithm):
penalty = rewards.mean() * penalty_frac
shaped_rewards = rewards - penalty
advantages = shaped_rewards - shaped_rewards.mean()
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
rollout.assign_advantages(advantage)
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
assign_advantages(trace, advantage)
@@ -3,11 +3,13 @@ from __future__ import annotations
from collections import defaultdict
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from prime_rl.configs.algorithm import HierarchicalGRPOAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm
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.orchestrator.types import Rollout
from prime_rl.utils.client import InferencePool
@@ -28,13 +30,13 @@ class HierarchicalGRPOAlgorithm(Algorithm):
super().__init__(config, policy_pool)
self.episode_agents = set(config.episode_agents)
async def score_group(self, group: list[Rollout]) -> None:
peers: dict[tuple[str, str | None], list[Rollout]] = defaultdict(list)
for rollout in group:
episode_scoped = rollout.agent.name in self.episode_agents
key = (rollout.agent.name, rollout.episode_id if episode_scoped else None)
peers[key].append(rollout)
async def score_group(self, episodes: list[vf.Episode]) -> None:
peers: dict[tuple[str, str | None], list[vf.Trace]] = defaultdict(list)
for episode, trace in iter_trainable_traces(episodes):
episode_scoped = trace.agent.name in self.episode_agents
key = (trace.agent.name, episode.id if episode_scoped else None)
peers[key].append(trace)
for members in peers.values():
baseline = sum(rollout.reward for rollout in members) / len(members)
for rollout in members:
rollout.assign_advantages(rollout.reward - baseline)
baseline = sum(trace.reward for trace in members) / len(members)
for trace in members:
assign_advantages(trace, trace.reward - baseline)
+8 -10
View File
@@ -1,13 +1,10 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
import verifiers.v1 as vf
from prime_rl.orchestrator.algo.base import Algorithm
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
from prime_rl.orchestrator.algo.routing import assign_advantages
class MaxRLAlgorithm(Algorithm):
@@ -22,9 +19,10 @@ class MaxRLAlgorithm(Algorithm):
Assumes non-negative (canonically binary) rewards; a group with mean reward
<= 0 carries no signal and gets zero advantages."""
async def score_group(self, group: list[Rollout]) -> None:
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
async def score_group(self, episodes: list[vf.Episode]) -> None:
traces = [trace for _, trace in iter_trainable_traces(episodes)]
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
mean = rewards.mean()
advantages = torch.zeros_like(rewards) if mean <= 0 else (rewards - mean) / mean
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
rollout.assign_advantages(advantage)
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
assign_advantages(trace, advantage)
+12 -9
View File
@@ -3,12 +3,14 @@ from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from prime_rl.configs.algorithm import OPDAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
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.orchestrator.types import Rollout
from prime_rl.transport import TrainingSample
from prime_rl.utils.client import InferencePool
@@ -32,11 +34,12 @@ class OPDAlgorithm(Algorithm):
async def setup(self) -> None:
self.teacher_pool = await self.connect(self.teacher)
async def score_rollout(self, rollout: Rollout) -> None:
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"
async def score_sample(sample: TrainingSample) -> None:
sample.ref_logprobs = await pool.score(list(sample.token_ids))
await asyncio.gather(*(score_sample(sample) for sample in rollout.samples))
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))
for branch, logprobs in zip(branches, scores, strict=True):
assign_reference_logprobs(branch, logprobs)
+19 -18
View File
@@ -3,14 +3,17 @@ from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from prime_rl.configs.algorithm import OPSDAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
from prime_rl.orchestrator.algo.routing import assign_reference_logprobs
from prime_rl.orchestrator.trajectories import iter_trainable_branches
from prime_rl.orchestrator.utils import episode_env_name
if TYPE_CHECKING:
from renderers.base import Renderer
from prime_rl.orchestrator.types import Rollout
from prime_rl.transport import TrainingSample
from prime_rl.utils.client import InferencePool
@@ -50,28 +53,26 @@ class OPSDAlgorithm(Algorithm):
self.renderer = create_renderer(load_tokenizer(self.policy_pool.model_name), self.renderer_config)
def _demonstration(self, rollout: Rollout) -> str:
demonstration = rollout.info.get(self.demo_key)
def _demonstration(self, episode: vf.Episode, trace: vf.Trace) -> str:
demonstration = trace.info.get(self.demo_key)
if demonstration is None:
demonstration = getattr(rollout.task.data, self.demo_key, None)
demonstration = getattr(trace.task.data, self.demo_key, None)
if demonstration is None:
env_name = episode_env_name(episode)
raise ValueError(
f"opsd requires '{self.demo_key}' in the trace info dict or on the task "
f"(env '{rollout.env_name}', task {rollout.task.data.idx})."
f"(env '{env_name}', task {trace.task.data.idx})."
)
return demonstration
async def score_rollout(self, rollout: Rollout) -> None:
async def score_episode(self, episode: vf.Episode) -> None:
pool = self.teacher_pool
renderer = self.renderer
assert renderer is not None, "renderer not built — Algorithm.setup() must run first"
hint = self.template.format(demonstration=self._demonstration(rollout))
hint_block = renderer.render_ids([{"role": "system", "content": hint}], add_generation_prompt=False)
async def score_sample(sample: TrainingSample) -> None:
full_logprobs = await pool.score(hint_block + list(sample.token_ids))
# Drop the hint's own logprobs; the tail aligns full-length to
# sample.token_ids (demo-conditioned, the trainer's ref_kl target).
sample.ref_logprobs = full_logprobs[len(hint_block) :]
await asyncio.gather(*(score_sample(sample) for sample in rollout.samples))
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))
for branch, full_logprobs in zip(branches, scores, strict=True):
assign_reference_logprobs(branch, full_logprobs[len(hint_block) :])
+9 -7
View File
@@ -3,11 +3,13 @@ from __future__ import annotations
from collections import defaultdict
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from prime_rl.configs.algorithm import RAEAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm
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.orchestrator.types import Rollout
from prime_rl.utils.client import InferencePool
@@ -34,8 +36,8 @@ class RAEAlgorithm(Algorithm):
self.decay = config.decay
self.baselines: dict[str, float] = defaultdict(float)
async def score_group(self, group: list[Rollout]) -> None:
for rollout in group:
baseline = self.baselines[rollout.agent.name]
rollout.assign_advantages(rollout.reward - baseline)
self.baselines[rollout.agent.name] = self.decay * baseline + (1.0 - self.decay) * rollout.reward
async def score_group(self, episodes: list[vf.Episode]) -> None:
for _, trace in iter_trainable_traces(episodes):
baseline = self.baselines[trace.agent.name]
assign_advantages(trace, trace.reward - baseline)
self.baselines[trace.agent.name] = self.decay * baseline + (1.0 - self.decay) * trace.reward
+59 -49
View File
@@ -1,38 +1,71 @@
"""Wire-field stamping for the per-token streams.
The training loss is a sum of three components — ``rl`` (importance-weighted
PG + KL), ``ce`` (masked NLL), and ``ref_kl`` (reverse KL to a reference model
as the PG signal) — each normalized by its own global token count in the
trainer. The algorithm decides which component the action tokens feed
and the per-token advantages the rl component consumes; these helpers write
the component weight streams and the advantage stream onto the
``TrainingSample`` wire fields at group finalization.
"""
"""Training annotations and transport loss routing."""
from __future__ import annotations
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from prime_rl.configs.algorithm import ActionLossType
from prime_rl.transport import TrainingSample
from prime_rl.transports.rollouts import TrainingSample
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
"""Assign credit in compact sampled-token order across the trace graph."""
nodes = [node for node in trace.nodes if any(node.mask)]
for node in nodes:
if len(node.mask) != len(node.token_ids):
raise ValueError(
f"node masks must align with token ids in trace {trace.id!r}: "
f"got {len(node.mask)}, expected {len(node.token_ids)}"
)
total = sum(sum(node.mask) for node in nodes)
if isinstance(values, (int, float)):
advantages = [float(values)] * total
else:
if len(values) != total:
raise ValueError(
f"advantages must align with trace {trace.id!r}'s sampled tokens: got {len(values)}, expected {total}"
)
advantages = [float(value) for value in values]
offset = 0
for node in nodes:
end = offset + sum(node.mask)
node.advantages = advantages[offset:end]
offset = end
def assign_reference_logprobs(branch: vf.Branch, values: list[float]) -> None:
"""Project branch-aligned reference logprobs onto sampled graph nodes."""
if len(values) != len(branch.token_ids):
raise ValueError(
f"reference logprobs must align with branch tokens: got {len(values)}, expected {len(branch.token_ids)}"
)
offset = 0
for node in branch.nodes:
end = offset + len(node.token_ids)
if any(node.mask) and node.reference_logprobs is None:
node.reference_logprobs = [
float(value) for value, sampled in zip(values[offset:end], node.mask, strict=True) if sampled
]
offset = end
def scalar_advantage(trace: vf.Trace) -> float | None:
"""Mean nonzero token advantage, or zero for an assigned-zero trace."""
advantages = [value for node in trace.nodes for value in node.advantages or []]
if not advantages:
return None
nonzero = [value for value in advantages if value != 0.0]
return sum(nonzero) / len(nonzero) if nonzero else 0.0
def is_trainable(trace: vf.Trace) -> bool:
"""Whether any sampled token carries nonzero RL credit."""
return any(value != 0.0 for node in trace.nodes for value in node.advantages or [])
def stamp_loss_routing(sample: TrainingSample, action_loss_type: ActionLossType) -> None:
"""Stamp the algorithm's loss routing onto one sample's component weight
streams: action tokens (the trainable completion tokens, per the loss
mask) feed the algorithm's declared component.
``rl`` is the default and ships nothing (absent streams mean rl weight
1.0 on the loss mask — the hot path); ``ce``/``ref_kl`` weight the action
tokens into that component's stream and zero the rl stream. Streams an
algorithm wrote directly (echo's observation ce weights) are merged, not
clobbered — env-provided tokens stay out of the loss ``mask``, so the
component an algorithm weights them into is the only one that trains
them.
"""
"""Route action tokens into the algorithm's declared loss component."""
if action_loss_type == "rl":
return
@@ -49,26 +82,3 @@ def stamp_loss_routing(sample: TrainingSample, action_loss_type: ActionLossType)
else:
assert action_loss_type == "ref_kl"
sample.ref_kl_weights = action_weights
def stamp_advantages(rollout: Rollout) -> None:
"""Stamp the rollout's per-token advantage stream onto its samples' wire
fields. The stream is full-length-N — aligned to the samples' ``token_ids``
concatenated in order, 0.0 on non-trainable positions — and sliced across
them. Rollouts with no credit assigned (``advantages=None``, e.g. opd/opsd)
ship no advantage stream.
"""
advantages = rollout.advantages
if advantages is None:
return
total = sum(len(sample.token_ids) for sample in rollout.samples)
if len(advantages) != total:
raise ValueError(
f"advantage stream must align with the rollout's tokens: "
f"got {len(advantages)}, expected {total} (env '{rollout.env_name}')."
)
offset = 0
for sample in rollout.samples:
num_tokens = len(sample.token_ids)
sample.advantages = list(advantages[offset : offset + num_tokens])
offset += num_tokens
+25 -10
View File
@@ -7,9 +7,10 @@ pressure off the engines and reacts at the pipeline's own pace (AIMD):
- **Grow** the cap multiplicatively per pipeline turnover (each completion
advances the turnover by ``1/inflight``) while the engines are clear, KV
usage is below ``KV_USAGE_GROW``, and the cap binds admission.
- **Trim** above ``KV_USAGE_TRIGGER``: resize cap and pool to what the
engines hold at ``KV_USAGE_TARGET`` and cancel the excess, youngest first.
Cap moves alone cannot relieve pressure from units maturing in place.
- **Trim** above ``KV_USAGE_SOFT_CAP``: lower the cap to what the engines
hold at ``KV_USAGE_TARGET`` and let completions drain the pool (soft). If
usage still climbs past ``KV_USAGE_HARD_CAP`` — units maturing in place
outpace completions — also cancel the excess, youngest first (hard).
- **Cut** on overload: preemptions (single-shot loads) or a persistent
capacity queue (agentic loads never preempt — admission control parks
excess load in the waiting queue). Cut, cancel the excess, then freeze
@@ -46,8 +47,14 @@ BINDING_FRACTION = 0.9
KV_USAGE_GROW = 0.6
"""Grow only while every decode engine's KV usage is below this."""
KV_USAGE_TRIGGER = 0.8
"""Above this usage, trim the cap and the in-flight pool."""
KV_USAGE_SOFT_CAP = 0.8
"""Above this usage, soft-trim: lower the cap and let completions drain the
pool naturally — no work is cancelled."""
KV_USAGE_HARD_CAP = 0.9
"""Above this usage, hard-trim: in-place context growth is outpacing
completions despite the closed gate, so also cancel the pool excess before
thrash onset (a cliff, not a slope)."""
KV_USAGE_TARGET = 0.7
"""A trim resizes to inflight * target / usage — below the trigger, so pool growth has headroom before the next trim."""
@@ -271,19 +278,27 @@ class ConcurrencyController:
self.escalated = True
return
if max_usage > KV_USAGE_TRIGGER and inflight > 0 and self.trim_cooldown == 0:
if max_usage > KV_USAGE_SOFT_CAP and inflight > 0 and self.trim_cooldown == 0:
hard = max_usage > KV_USAGE_HARD_CAP
target = int(self.clamp(inflight * KV_USAGE_TARGET / max_usage))
self.resize_down(target, inflight, reason=f"kv headroom (usage {max_usage:.2f})")
self.resize_down(
target,
inflight,
reason=f"kv headroom (usage {max_usage:.2f}, {'hard' if hard else 'soft'} trim)",
cancel=hard,
)
self.trim_cooldown = KV_TRIM_COOLDOWN_POLLS
# ── internals ────────────────────────────────────────────────────────────
def resize_down(self, target: int, inflight: int, *, reason: str) -> None:
"""Lower the cap (never raise) and cancel the in-flight excess."""
def resize_down(self, target: int, inflight: int, *, reason: str, cancel: bool = True) -> None:
"""Lower the cap (never raise) and, with ``cancel``, shed the
in-flight excess; without it, admission stays blocked until the pool
drains below the new cap on its own."""
target = min(target, self.max_inflight)
self.cap = float(target)
self.apply_limit(target, reason=reason)
if self.on_overload is not None and inflight > target:
if cancel and self.on_overload is not None and inflight > target:
self.on_overload(inflight - target)
def apply_limit(self, n_max: int, *, reason: str | None) -> None:
+12 -10
View File
@@ -12,7 +12,6 @@ from prime_rl.orchestrator.curriculum.samplers import TaskSampler
if TYPE_CHECKING:
from prime_rl.configs.orchestrator import CurriculumConfig
from prime_rl.orchestrator.types import Rollout
class Curriculum:
@@ -48,11 +47,11 @@ class Curriculum:
raise TypeError(f"Unsupported admission gate config: {type(gate_config).__name__}")
self.gates[name] = gate
def on_result(self, group: list[Rollout]) -> bool:
def on_result(self, group: list[vf.Episode]) -> bool:
"""Observe every result, evaluate every gate, and combine with AND."""
if not group:
raise ValueError("Cannot report an empty rollout group")
task_keys = {rollout.task.key for rollout in group}
task_keys = {episode.task.key for episode in group}
if None in task_keys:
raise ValueError("A finalized group is missing Task.key")
if len(task_keys) != 1:
@@ -73,14 +72,17 @@ class Curriculum:
}
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
if "sampler" not in state_dict:
self.sampler.load_state_dict(state_dict)
return
expected_fields = {"sampler", "gates"}
if set(state_dict) != expected_fields:
raise ValueError(f"Curriculum checkpoint fields must be {sorted(expected_fields)}")
gate_states = state_dict["gates"]
if set(gate_states) != set(self.gates):
raise ValueError(
f"Curriculum checkpoint gates {sorted(gate_states)} do not match configured gates {sorted(self.gates)}"
)
self.sampler.load_state_dict(state_dict["sampler"])
for name, gate_state in state_dict["gates"].items():
gate = self.gates.get(name)
if gate is not None:
gate.load_state_dict(gate_state)
for name, gate in self.gates.items():
gate.load_state_dict(gate_states[name])
def metrics(self) -> dict[str, float]:
metrics = {f"sampler/{name}": float(value) for name, value in self.sampler.metrics().items()}
@@ -4,11 +4,12 @@ from __future__ import annotations
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from prime_rl.orchestrator.curriculum.gates.base import AdmissionGate
if TYPE_CHECKING:
from prime_rl.configs.orchestrator import AdvRangeGateConfig
from prime_rl.orchestrator.types import Rollout
class AdvRangeGate(AdmissionGate):
@@ -21,13 +22,15 @@ class AdvRangeGate(AdmissionGate):
def __init__(self, config: AdvRangeGateConfig) -> None:
self.config = config
def admit(self, group: list[Rollout]) -> bool:
advantages: list[float] = []
for rollout in group:
if rollout.advantages is None:
continue
trainable = [value for sample in rollout.samples for value in sample.mask]
advantages.extend(advantage for advantage, keep in zip(rollout.advantages, trainable, strict=True) if keep)
def admit(self, group: list[vf.Episode]) -> bool:
advantages = [
advantage
for episode in group
for trace in episode.traces
if not trace.has_error and trace.agent.trainable
for node in trace.nodes
for advantage in node.advantages or []
]
if not advantages:
return True
return not all(self.config.reject_min <= advantage <= self.config.reject_max for advantage in advantages)
@@ -2,16 +2,15 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from typing import Any
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
import verifiers.v1 as vf
class AdmissionGate:
"""Base class for user-authored training-sample admission policies."""
def admit(self, group: list[Rollout]) -> bool:
def admit(self, group: list[vf.Episode]) -> bool:
"""Return whether a finalized group should enter the training batch."""
return True
@@ -4,13 +4,10 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Iterator
from typing import TYPE_CHECKING, Any
from typing import Any
import verifiers.v1 as vf
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
class TaskSampler(Iterator[vf.Task], ABC):
"""Base class for user-authored task selection policies."""
@@ -20,7 +17,7 @@ class TaskSampler(Iterator[vf.Task], ABC):
"""Choose the next task."""
raise NotImplementedError
def observe(self, group: list[Rollout]) -> None:
def observe(self, group: list[vf.Episode]) -> None:
"""Update sampling state from a finalized group."""
def state_dict(self) -> dict[str, Any]:
@@ -13,7 +13,6 @@ from prime_rl.orchestrator.curriculum.samplers.base import TaskSampler
if TYPE_CHECKING:
from prime_rl.configs.orchestrator import DifficultyPoolSamplerConfig
from prime_rl.orchestrator.types import Rollout
class DifficultyPoolSampler(TaskSampler):
@@ -64,14 +63,19 @@ class DifficultyPoolSampler(TaskSampler):
raise RuntimeError("DifficultyPoolSampler has no tasks in a pool with positive weight")
return self.rng.choices(self.tasks, weights=weights, k=1)[0]
def observe(self, group: list[Rollout]) -> None:
rewards = [rollout.reward for rollout in group if not rollout.has_error and rollout.agent.trainable]
def observe(self, group: list[vf.Episode]) -> None:
rewards = [
trace.reward
for episode in group
for trace in episode.traces
if not trace.has_error and trace.agent.trainable
]
if not rewards:
return
task_key = group[0].task.key
if task_key is None:
task = group[0].task
if task.key is None:
raise ValueError("A finalized group is missing Task.key")
self.task_rewards[task_key] = sum(rewards) / len(rewards)
self.task_rewards[task.key] = sum(rewards) / len(rewards)
def state_dict(self) -> dict[str, Any]:
return {
+195 -192
View File
@@ -7,28 +7,27 @@
once.
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
- Emit-everything invariant: every dispatched episode eventually reaches
``out_q`` exactly once, as a ``list[Rollout]``. Failures
(env error, empty trajectory, task exception, off-policy cancel) carry
``trace.last_error`` set; sinks decide drop / partial-train policy.
``out_q`` exactly once — as a native episode, or covered by its group's
single ``Cancellation`` message when the group is dropped. Failures
remain episode errors; sinks decide drop / partial-train policy.
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
schedule next. Transitions are level-triggered (driven by the eval
source's emptiness), so in-flight episodes of the opposite kind drain
naturally on either side of an eval boundary.
- ``on_version_pending`` (called by the watcher before the engines pause for
the weight update) bumps ``off_policy_steps`` on in-flight train episodes and
drops groups past ``max_off_policy_steps``.
Eval rollouts are measurements for the policy version they started with,
so they are allowed to finish even if training advances. Train rollouts
sampled from a frozen model never age — their sampler doesn't change
with policy updates.
Cancellations surface as synthetic ``Cancelled`` markers so the sink's
count-to-``group_size`` finalization still fires.
the weight update) drops train groups already past ``max_off_policy_steps`` — a
compute-saving early cancel; the sink's queue sweep is what guarantees the
bound. Eval episodes are measurements for the policy version they started
with, so they are allowed to finish even if training advances. Train
episodes sampled from a frozen model never go stale — their generation
source doesn't change with policy updates.
"""
from __future__ import annotations
import asyncio
import time
import traceback
import uuid
from collections import defaultdict
from collections.abc import Callable
@@ -43,12 +42,15 @@ from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.train_source import TrainSource
from prime_rl.orchestrator.types import (
Cancellation,
CancelReason,
GroupState,
InflightEpisode,
Policy,
Rollout,
RolloutKind,
Progress,
WorkKind,
)
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
@@ -118,49 +120,59 @@ class DispatcherMetrics:
return keys
def error_trace_task(group: GroupState | None) -> vf.TraceTask:
"""Preserve task identity on a synthetic error trace."""
if group is None:
return vf.TraceTask(type="Task", data=vf.TaskData(idx=-1, prompt=None))
def _trace_task(task: vf.Task) -> vf.TraceTask:
return vf.TraceTask(
type=type(group.task).__name__,
data=vf.TaskData(idx=group.task.data.idx, prompt=None),
key=group.task.key,
hash=group.task.hash,
type=type(task).__name__,
data=task.data,
key=task.key,
hash=task.hash,
)
def _validate_episode_task(episode: vf.WireEpisode, task: vf.Task) -> None:
expected = (task.key, task.hash)
actual = (episode.task.key, episode.task.hash)
if actual != expected:
raise ValueError(f"Episode task provenance {actual} does not match dispatched task {expected}")
class Dispatcher:
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules
rollouts under shared capacity, and emits ``Rollout``\\ s to
``out_q``. The watcher drives ``on_version_pending`` for off-policy
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules episodes
under shared capacity, and emits native verifier episodes to ``out_q``.
The watcher drives ``on_version_pending`` for staleness
cancellation; the orchestrator triggers eval epochs."""
def __init__(
self,
*,
train_envs: TrainEnvs,
train_envs: TrainEnvs | None,
eval_envs: EvalEnvs | None,
train_source: TrainSource,
train_source: TrainSource | None,
eval_source: EvalSource | None,
policy_pool: InferencePool,
policy: Policy,
progress: Progress | None,
initial_max_inflight: int,
max_inflight_ceiling: int | None,
tasks_per_minute: float | None,
max_off_policy_steps: int,
run_id: str,
run_name: str | None,
on_episode_complete: Callable[[str, str, int, float], None] | None = None,
) -> None:
self.policy = policy
self.progress = progress
self.train_envs = train_envs
self.eval_envs = eval_envs
# Train rollouts go to the env sampler's pool; eval always
# Train rollouts go to the env's generation source; eval always
# evaluates the policy.
self.policy_pool = policy_pool
self.train_source = train_source
self.eval_source = eval_source
self.max_off_policy_steps = max_off_policy_steps
self.run_id = run_id
self.run_name = run_name
# ``(env_name, kind, total_tokens, duration_s)`` per completed episode
self.on_episode_complete = on_episode_complete
@@ -181,7 +193,7 @@ class Dispatcher:
self.admission_window_s = 5.0
self.admission_window_start = time.monotonic()
self.admissions_in_window = 0
self.min_burst = max((env.config.group_size for env in train_envs), default=8)
self.min_burst = max((env.config.group_size for env in train_envs or ()), default=8)
self.inflight: dict[asyncio.Task, InflightEpisode] = {}
self.groups: dict[uuid.UUID, GroupState] = {}
@@ -189,9 +201,9 @@ class Dispatcher:
# Bounded so the dispatcher backpressures on a slow sink (unbounded
# when no hard ceiling is configured — the dynamic cap still bounds
# in-flight work). One entry per episode — the sinks count episodes,
# never loose traces.
# never loose traces — plus one ``Cancellation`` per dropped group.
maxsize = max(8, max_inflight_ceiling) if max_inflight_ceiling is not None else 0
self.out_q: asyncio.Queue[list[Rollout]] = asyncio.Queue(maxsize=maxsize)
self.out_q: asyncio.Queue[vf.WireEpisode | Cancellation] = asyncio.Queue(maxsize=maxsize)
self.mode: DispatcherMode = DispatcherMode.PREFER_TRAIN
# Set by the orchestrator after the final train step; pipeline then
@@ -208,13 +220,14 @@ class Dispatcher:
self.stopped = asyncio.Event()
self.task: asyncio.Task | None = None
def _train_pool_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
def _train_generation_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
"""``(pool, model_name, is_live)`` for *train* rollouts of this env —
the env sampler's pool. (Eval always uses the policy.)"""
sampler = self.train_envs.get(env_name).sampler
if sampler.samples_from_live_policy:
return sampler.pool, self.policy.model_name, True
return sampler.pool, sampler.pool.model_name, False
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
@property
def inflight_train_count(self) -> int:
@@ -256,9 +269,9 @@ class Dispatcher:
if shed >= n:
break
# Count only live cancellations toward the excess: drop_group's
# return includes never-dispatched markers, which free no permits
# return includes never-dispatched episodes, which free no permits
live = sum(1 for meta in self.inflight.values() if meta.group_id == group_id)
await self.drop_group(group_id)
await self.drop_group(group_id, reason="overload")
shed += live
if shed:
get_logger().warning(f"Cancelled {shed} youngest in-flight episodes after overload cut")
@@ -273,8 +286,8 @@ class Dispatcher:
return burst_cap - self.admissions_in_window
@property
def inflight_by_env(self) -> dict[tuple[RolloutKind, str], int]:
counts: dict[tuple[RolloutKind, str], int] = defaultdict(int)
def inflight_by_env(self) -> dict[tuple[WorkKind, str], int]:
counts: dict[tuple[WorkKind, str], int] = defaultdict(int)
for meta in self.inflight.values():
counts[(meta.kind, meta.env_name)] += 1
return dict(counts)
@@ -290,7 +303,7 @@ class Dispatcher:
(``next_fresh_group``), but its ``group_size`` rollouts dispatch one at a time across
``fill_inflight`` passes — so the queue can be empty while a group is still mid-schedule."""
return bool(self.eval_source) or any(
g.kind == "eval" and g.rollouts_to_schedule > 0 for g in self.groups.values()
g.kind == "eval" and g.episodes_to_schedule > 0 for g in self.groups.values()
)
@property
@@ -304,15 +317,17 @@ class Dispatcher:
triggered eval drain naturally."""
self.train_scheduling_disabled = True
@property
def max_off_policy_level(self) -> int:
steps = [m.off_policy_steps for m in self.inflight.values() if m.kind == "train"]
return max(steps) if steps else 0
@property
def mean_off_policy_level(self) -> float:
steps = [m.off_policy_steps for m in self.inflight.values() if m.kind == "train"]
return sum(steps) / len(steps) if steps else 0.0
def inflight_staleness(self) -> list[int]:
"""Current staleness of each in-flight live-sourced train episode: the
version the batch being collected trains on (v{step-1}) minus the
episode's dispatch version."""
if self.train_envs is None or self.progress is None:
return []
return [
(self.progress.step - 1) - meta.policy_version
for meta in self.inflight.values()
if meta.kind == "train" and self.train_envs.get(meta.env_name).generation_source.uses_live_policy
]
# ── lifecycle ──────────────────────────────────────────────────────────
@@ -337,7 +352,7 @@ class Dispatcher:
timeout=0.5, # wake periodically to re-check fill (mode flips)
)
for task in done:
await self.handle_completed_rollout(task)
await self.handle_completed_episode(task)
except asyncio.CancelledError:
return
@@ -349,31 +364,32 @@ class Dispatcher:
self.task = None
async def on_version_pending(self, step: int) -> None:
"""Bump off-policy counters and drop groups past
``max_off_policy_steps`` (drop_group emits ``Cancelled`` markers so
the sink still finalizes the partial group). Eval rollouts are not
aged because they are tied to their start-time policy version.
"""Drop train groups past ``max_off_policy_steps``: a group dispatched at
v{k} ships at earliest in the batch currently collecting, at staleness
``(progress.step - 1) - k`` — beyond the bound it can never train, so
cut it before more inference sinks in. This is a compute saver; the
sink's queue sweep is what guarantees no stale episode ships. Eval
groups never go stale (they are tied to their start-time policy
version), nor do frozen-sourced train groups (their generation source
doesn't change with policy updates).
Runs *before* the inference engines are paused for the weight update so
the resulting aborts are processed while the engine is still stepping —
otherwise the orphaned KV transfers crash the decode engine on resume
(see ``WeightWatcher.apply_policy_update``)."""
stale_groups: set[uuid.UUID] = set()
if self.train_envs is None or self.progress is None:
return
min_version = min_fresh_version(self.progress.step, self.max_off_policy_steps)
stale_groups = [
gid
for gid, group in self.groups.items()
if group.kind == "train"
and self.train_envs.get(group.env_name).generation_source.uses_live_policy
and group.policy_version_at_start < min_version
]
cancelled = 0
for meta in self.inflight.values():
if meta.kind != "train":
continue
# Frozen-sourced rollouts never go stale — their sampler doesn't
# change with policy updates.
if not self.train_envs.get(meta.env_name).sampler.samples_from_live_policy:
continue
meta.off_policy_steps += 1
if meta.off_policy_steps > self.max_off_policy_steps:
stale_groups.add(meta.group_id)
for gid in stale_groups:
removed = await self.drop_group(gid)
cancelled += removed
cancelled += await self.drop_group(gid, reason="stale")
if cancelled:
get_logger().warning(
@@ -421,7 +437,7 @@ class Dispatcher:
get_logger().info(f"Switching dispatcher mode to prefer {prefer} episodes because {reason}")
self.mode = new_mode
async def try_schedule(self, kind: RolloutKind) -> bool:
async def try_schedule(self, kind: WorkKind) -> bool:
"""Schedule one rollout of ``kind``: prefer continuing an existing
group (keeps prefix-cache hits); otherwise open a fresh group from
the corresponding source. Returns False if nothing could be
@@ -433,21 +449,22 @@ class Dispatcher:
return False
for gid, group in list(self.groups.items()):
if group.kind != kind or group.rollouts_to_schedule <= 0:
if group.kind != kind or group.episodes_to_schedule <= 0:
continue
return await self.schedule_group_rollout(gid, group)
return await self.schedule_group_episode(gid, group)
fresh = self.next_fresh_group(kind, envs)
if fresh is None:
return False
gid = uuid.uuid4()
self.groups[gid] = fresh
return await self.schedule_group_rollout(gid, fresh)
return await self.schedule_group_episode(gid, fresh)
def next_fresh_group(self, kind: RolloutKind, envs) -> GroupState | None:
def next_fresh_group(self, kind: WorkKind, envs) -> GroupState | None:
"""Pop the next example from the corresponding source and wrap it in
a ``GroupState``. Returns ``None`` if the source is empty."""
if kind == "train":
assert self.train_source is not None
source = self.train_source
else:
assert self.eval_source is not None
@@ -464,20 +481,20 @@ class Dispatcher:
kind=kind,
env_name=env_name,
task=example["task"],
rollouts_to_schedule=group_size,
target_rollouts=group_size,
episodes_to_schedule=group_size,
target_episodes=group_size,
eval_step=eval_step,
policy_version_at_start=self.policy.version,
)
async def schedule_group_rollout(self, group_id: uuid.UUID, group: GroupState) -> bool:
async def schedule_group_episode(self, group_id: uuid.UUID, group: GroupState) -> bool:
"""Dispatch one ``run`` task for this group.
Returns False only if we couldn't even schedule one rollout (no clients
ready, no permits). Returns True after issuing one task — the caller
loops to keep scheduling.
"""
# Train rollouts use the env sampler's pool via the
# Train rollouts use the env's generation source via the
# renderer/token train client. Eval always evaluates the policy and
# goes through the eval client (chat-completions) so eval scores stay
# comparable.
@@ -485,7 +502,7 @@ class Dispatcher:
pool, model_name = self.policy_pool, self.policy.model_name
live_sourced = True
else:
pool, model_name, live_sourced = self._train_pool_for(group.env_name)
pool, 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
@@ -503,7 +520,7 @@ class Dispatcher:
else:
cache_salt = None
group.rollouts_to_schedule -= 1
group.episodes_to_schedule -= 1
await self.acquire()
self.admissions_in_window += 1
task = asyncio.create_task(
@@ -519,13 +536,23 @@ class Dispatcher:
kind=group.kind,
env_name=group.env_name,
group_id=group_id,
task=group.task,
policy_version=group.policy_version_at_start,
step=self._work_step(group.kind, group.eval_step),
client_config=client,
eval_step=group.eval_step,
started_at=time.monotonic(),
)
return True
def _work_step(self, kind: WorkKind, eval_step: int | None) -> int:
if kind == "eval":
assert eval_step is not None
return eval_step
if self.progress is None:
raise RuntimeError("Train dispatch requires progress state")
return self.progress.step
async def acquire(self) -> None:
"""Reserve one permit + rate-limit it. Caller must precheck
``available_permits >= 1``; this is not a blocking acquire."""
@@ -541,13 +568,8 @@ class Dispatcher:
if refund_admission:
self.admissions_in_window = max(0, self.admissions_in_window - 1)
async def handle_completed_rollout(self, task: asyncio.Task) -> None:
"""Emit every dispatched episode exactly once to ``out_q``. Task
exceptions synthesize an error-marker episode so the sink's
count-to-``group_size`` finalization still triggers. Cancelled tasks
(popped by ``drop_group``) raise ``CancelledError`` and are discarded —
``drop_group`` already emitted their markers.
"""
async def handle_completed_episode(self, task: asyncio.Task) -> None:
"""Emit every dispatched episode exactly once to ``out_q``."""
meta = self.inflight.pop(task, None)
if meta is None:
return # already handled by drop_group / cancel_inflight_episodes
@@ -556,76 +578,97 @@ class Dispatcher:
is_synth_exception = False
try:
result = task.result()
rollouts: list[Rollout] = result if isinstance(result, list) else [result]
if not rollouts:
raise RuntimeError("env run returned an empty episode (no traces)")
episode: vf.WireEpisode = task.result()
except asyncio.CancelledError:
return
except Exception as exc:
get_logger().warning(f"Rollout task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
rollouts = [
Rollout(
task=error_trace_task(group),
agent=vf.AgentInfo(config=vf.AgentConfig()),
)
]
for r in rollouts:
r.record_error(exc)
get_logger().warning(f"Episode task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
episode = vf.WireEpisode(
env=vf.EnvInfo(id=meta.env_name),
task=_trace_task(meta.task),
ok=False,
errors=[
vf.Error(
type=type(exc).__name__,
message=str(exc),
traceback="".join(traceback.format_exception(exc)),
)
],
)
is_synth_exception = True
for r in rollouts:
if not r.has_error and r.num_turns == 0:
if not episode.traces and episode.ok:
episode.ok = False
episode.errors.append(vf.Error(type="EmptyEpisode", message="Episode returned with no traces"))
for trace in episode.traces:
if not trace.has_error and trace.num_turns == 0:
# Empty trajectory: promote to an explicit error so the sink
# treats it like any other failure (``has_error`` reads ``ok``)
r.errors.append(vf.Error(type="EmptyTrajectory", message="Rollout returned with no trajectory steps"))
r.ok = False
trace.errors.append(vf.Error(type="EmptyTrajectory", message="Trace returned with no trajectory steps"))
trace.ok = False
episode.ok = False
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
if r.has_error:
if trace.has_error:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if not is_synth_exception and r.last_error is not None:
if not is_synth_exception and trace.last_error is not None:
get_logger().warning(
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — {r.last_error.type}: {r.last_error.message}"
f"Trace failed in group {meta.group_id} ({meta.env_name}) — "
f"{trace.last_error.type}: {trace.last_error.message}"
)
if not episode.ok and not episode.traces:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if not is_synth_exception and self.on_episode_complete is not None and meta.started_at > 0:
total_tokens = sum(r.num_total_tokens for r in rollouts)
self.on_episode_complete(meta.env_name, meta.kind, total_tokens, time.monotonic() - meta.started_at)
await self.emit_episode(meta, group, rollouts)
self.on_episode_complete(
meta.env_name, meta.kind, episode.num_total_tokens, time.monotonic() - meta.started_at
)
await self.emit_episode(meta, group, episode)
async def emit_episode(self, meta: InflightEpisode, group: GroupState | None, rollouts: list[Rollout]) -> None:
"""Stamp prime-rl metadata onto one completed episode and put it on
``out_q``. Pops the group from ``self.groups`` once every owed episode
has been emitted."""
async def emit_episode(
self,
meta: InflightEpisode,
group: GroupState | None,
episode: vf.WireEpisode,
) -> None:
"""Stamp one completed episode with its dispatch provenance and emit it."""
_validate_episode_task(episode, meta.task)
eval_step = meta.eval_step
policy_version = meta.policy_version
if group is not None:
eval_step = group.eval_step
policy_version = group.policy_version_at_start
group.emitted += 1
if group.emitted >= group.target_rollouts:
if group.emitted >= group.target_episodes:
self.groups.pop(meta.group_id, None)
for rollout in rollouts:
rollout.kind = meta.kind
rollout.env_name = meta.env_name
rollout.group_id = meta.group_id
rollout.policy_version = policy_version
rollout.off_policy_steps = meta.off_policy_steps
if meta.kind == "eval":
assert eval_step is not None, "eval rollout missing eval_step"
rollout.eval_step = eval_step
await self.out_q.put(rollouts)
if meta.kind == "eval":
assert eval_step is not None, "eval episode missing eval_step"
episode.env.name = meta.env_name
episode.group = vf.GroupInfo(id=str(meta.group_id))
live_policy = meta.kind == "eval"
if meta.kind == "train":
assert self.train_envs is not None
live_policy = self.train_envs.get(meta.env_name).generation_source.uses_live_policy
policy = vf.PolicySpan(start=policy_version, end=self.policy.version) if live_policy else None
work: vf.WorkInfo = (
vf.EvalWorkInfo(step=meta.step, policy=policy)
if meta.kind == "eval"
else vf.TrainWorkInfo(step=meta.step, policy=policy)
)
run = vf.TrainRunInfo(id=self.run_id, name=self.run_name, work=work)
episode.record_run(run)
await self.out_q.put(episode)
async def drop_group(self, group_id: uuid.UUID) -> int:
"""Cancel remaining in-flight tasks for this group and emit a
``Cancelled`` marker for every rollout it still owes the sink
(both in-flight and not-yet-scheduled). Returns the count for
off-policy metrics."""
async def drop_group(self, group_id: uuid.UUID, *, reason: CancelReason) -> int:
"""Cancel this group's remaining in-flight tasks and emit one
``Cancellation`` covering every episode it still owes the sink (both
in-flight and never-dispatched), so count-to-``group_size``
finalization still fires. Returns the owed count for metrics."""
group = self.groups.pop(group_id, None)
# Sync claim phase: pop matching tasks from ``self.inflight`` and
# release their permits in one non-yielding sweep. After this loop
# the dropped tasks are no longer reachable from ``self.inflight``,
# so ``handle_completed_rollout``'s existing None-guard makes the
# so ``handle_completed_episode``'s existing None-guard makes the
# subsequent async emit phase race-free.
claimed: list[tuple[asyncio.Task, InflightEpisode]] = []
for task, meta in list(self.inflight.items()):
@@ -635,68 +678,27 @@ class Dispatcher:
self.release()
claimed.append((task, meta))
tasks_to_cancel = [task for task, _ in claimed]
inflight_cancelled = len(claimed)
last_meta: InflightEpisode | None = claimed[-1][1] if claimed else None
for _, meta in claimed:
trace = Rollout(
task=error_trace_task(group),
agent=vf.AgentInfo(config=vf.AgentConfig()),
ok=False,
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
stop_condition="error",
)
await self.emit_episode(meta, group, [trace])
# The group may have rollouts that were never dispatched
# (``rollouts_to_schedule > 0``). Emit markers for those too so the
# sink hits ``target_rollouts``
#
# ``last_meta`` can be ``None`` if the only inflight task for this
# group completed naturally between ``on_version_pending``'s snapshot
# and us reaching it — synthesize a stand-in from the group state
unscheduled_cancelled = 0
if group is not None and group.rollouts_to_schedule > 0:
fallback_meta = last_meta or InflightEpisode(
kind=group.kind,
env_name=group.env_name,
group_id=group_id,
policy_version=group.policy_version_at_start,
eval_step=group.eval_step,
)
unscheduled_cancelled = group.rollouts_to_schedule
for _ in range(unscheduled_cancelled):
trace = Rollout(
task=error_trace_task(group),
agent=vf.AgentInfo(config=vf.AgentConfig()),
ok=False,
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
stop_condition="error",
)
await self.emit_episode(fallback_meta, group, [trace])
unscheduled_cancelled = group.episodes_to_schedule if group is not None else 0
cancelled = inflight_cancelled + unscheduled_cancelled
if cancelled > 0:
meta_for_log = last_meta or (
InflightEpisode(
kind=group.kind,
env_name=group.env_name,
group_id=group_id,
policy_version=group.policy_version_at_start if group else 0,
eval_step=group.eval_step,
)
if group is not None
else None
)
if meta_for_log is not None:
self.metrics.record_cancellation(kind=meta_for_log.kind, env_name=meta_for_log.env_name, n=cancelled)
get_logger().debug(
f"drain {meta_for_log.kind} | group={str(group_id)[:8]} env={meta_for_log.env_name} | "
f"cancelled={cancelled} (inflight={inflight_cancelled} unscheduled={unscheduled_cancelled})"
)
if tasks_to_cancel:
await safe_cancel_all(tasks_to_cancel)
if cancelled > 0:
# ``group`` can be ``None`` only if every episode was already
# emitted — then nothing is in flight or unscheduled, so kind/env
# always resolve from the group or a claimed meta.
kind = group.kind if group is not None else claimed[-1][1].kind
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"cancelled={cancelled} (inflight={inflight_cancelled} unscheduled={unscheduled_cancelled})"
)
await self.out_q.put(
Cancellation(kind=kind, env_name=env_name, group_id=str(group_id), count=cancelled, reason=reason)
)
if claimed:
await safe_cancel_all([task for task, _ in claimed])
return cancelled
async def cancel_inflight_episodes(self) -> None:
@@ -737,11 +739,12 @@ class Dispatcher:
def gauges(self) -> dict[str, float]:
"""Instantaneous, read-only gauges sampled by the periodic logger."""
staleness = self.inflight_staleness()
return {
"dispatcher/inflight/train": float(self.inflight_train_count),
"dispatcher/inflight/eval": float(self.inflight_eval_count),
"dispatcher/queued/eval": float(self.queued_eval_examples),
"dispatcher/mode": float(self.mode == DispatcherMode.PREFER_EVAL),
"dispatcher/off_policy_level/max": float(self.max_off_policy_level),
"dispatcher/off_policy_level/mean": self.mean_off_policy_level,
"dispatcher/off_policy/max": float(max(staleness, default=0)),
"dispatcher/off_policy/mean": sum(staleness) / len(staleness) if staleness else 0.0,
}
+24 -31
View File
@@ -29,15 +29,9 @@ 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.sampler import Sampler
from prime_rl.orchestrator.types import Rollout
from prime_rl.orchestrator.generation_source import GenerationSource
from prime_rl.utils.logger import get_logger
# Every wire trace validates into this type. WireTaskData (extra="allow") keeps the env's task
# fields without importing the env package — the orchestrator never reads them typed (only
# task.idx + task.model_dump).
ROLLOUT_TYPE = Rollout[vf.WireTaskData]
# 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
# before serving.
@@ -80,11 +74,11 @@ class Env:
await self.env_client.wait_for_server_startup(timeout=ENV_SERVER_STARTUP_TIMEOUT)
taskset = vf.load_taskset(self.config.env.taskset)
if type(taskset).INFINITE:
self.tasks = iter(taskset.load())
self.tasks = iter(taskset)
self.num_tasks = None
else:
# Materialize off the event loop — load() may pull a dataset.
materialized = await asyncio.to_thread(lambda: list(taskset.load()))
# Materialize off the event loop — iterating may pull a dataset.
materialized = await asyncio.to_thread(lambda: list(taskset))
self.tasks = iter(materialized)
self.num_tasks = len(materialized)
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
@@ -102,40 +96,39 @@ class Env:
model_name: str,
cache_salt: str | None,
task_data: dict,
) -> list[Rollout]:
"""Run one episode; return its typed Traces. A zero-trace episode raises (the
dispatcher synthesizes the error marker); a not-``ok`` episode marks its clean
traces failed so partial episodes never train."""
) -> vf.WireEpisode:
"""Run and return one typed episode. A failed multi-trace episode marks
its otherwise-clean traces failed so partial episodes never train."""
episode = await self.env_client.run(
task_data=task_data,
client=client,
model=model_name,
sampling=self._sampling(cache_salt),
)
if not episode.traces:
error = episode.last_error
detail = f"{error.type}: {error.message}" if error is not None else "no traces and no error recorded"
raise RuntimeError(f"episode failed before any trace was produced — {detail}")
rollouts = [ROLLOUT_TYPE.model_construct(**dict(wire)) for wire in episode.traces]
for rollout in rollouts:
rollout.episode_id = episode.id
if not episode.ok and rollout.ok:
for trace in episode.traces:
if not episode.ok and trace.ok:
error = episode.last_error or vf.Error(
type="EpisodeFailed", message="A sibling trace in this episode failed"
)
rollout.errors = [*rollout.errors, error]
rollout.ok = False
return rollouts
trace.errors = [*trace.errors, error]
trace.ok = False
return episode
class TrainEnv(Env):
config: TrainSourceConfig
def __init__(self, config: TrainSourceConfig, address: str, sampler: Sampler, algorithm: Algorithm):
def __init__(
self,
config: TrainSourceConfig,
address: str,
generation_source: GenerationSource,
algorithm: Algorithm,
):
super().__init__(config, address)
self.sampler = sampler
self.generation_source = generation_source
self.algorithm = algorithm
self.sampling_args = sampler.sampling_args(config.sampling.to_sampling_args())
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
class EvalEnv(Env):
@@ -188,8 +181,8 @@ class Envs(Generic[EnvT]):
class TrainEnvs(Envs[TrainEnv]):
"""Collection of training environments, each paired with its rollout
:class:`Sampler` and runtime :class:`Algorithm`, built from the env's
"""Collection of training environments, each paired with its
:class:`GenerationSource` and runtime :class:`Algorithm`, built from the env's
resolved algorithm config."""
def __init__(
@@ -206,7 +199,7 @@ class TrainEnvs(Envs[TrainEnv]):
env = TrainEnv(
config,
addresses[("train", config.resolved_name)],
Sampler(config.algo.sampling, policy_pool, renderer_config),
GenerationSource(config.algo.sampling, policy_pool, renderer_config),
build_algorithm(config.algo, policy_pool),
)
self._envs[env.name] = env
+45 -78
View File
@@ -1,52 +1,36 @@
"""EvalSink: three-level rollout sink for eval epochs.
Same shape as ``TrainSink``, but no tokenization, advantages, or admission:
1. ``process_rollout`` — no-op.
2. ``process_group`` — at ``group_size`` episodes, move the rollouts
(errored ones included) into the ``(env, eval_step)`` bucket.
3. ``process_batch`` — at ``num_examples × group_size`` episodes, return an
``EvalBatch`` with the full returned cohort (metrics are computed downstream).
``add()`` takes one episode (``list[Rollout]``) and returns ``EvalBatch | None``;
all accounting counts episodes, never loose traces.
"""
"""Evaluation-side episode, group, and epoch assembly."""
from __future__ import annotations
import uuid
from collections import defaultdict
import verifiers.v1 as vf
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.metrics import EvalRollouts
from prime_rl.orchestrator.types import EvalBatch, Rollout
from prime_rl.orchestrator.metrics import EvalEpisodes
from prime_rl.orchestrator.types import EvalBatch
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, eval_work
from prime_rl.utils.logger import get_logger
class EvalSink:
"""Constructed only when eval is configured."""
"""Collect completed evaluation episodes into per-environment epochs."""
def __init__(self, *, eval_envs: EvalEnvs) -> None:
self.eval_envs = eval_envs
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
# Episodes arrived per group / per batch bucket — the finalization counts.
self.pending_group_episodes: dict[uuid.UUID, int] = defaultdict(int)
self.pending_batches: dict[tuple[str, int], list[Rollout]] = defaultdict(list)
self.pending_batch_episodes: dict[tuple[str, int], int] = defaultdict(int)
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
self.pending_batches: dict[tuple[str, int], list[vf.Episode]] = defaultdict(list)
def add(self, episode: list[Rollout]) -> EvalBatch | None:
"""Process one episode arrival; finalize the group on the ``group_size``-th
episode and the per-env epoch on the ``num_examples × group_size``-th."""
env_name = episode[0].env_name
group_id = episode[0].group_id
for rollout in episode:
self.process_rollout(rollout)
bkey = (env_name, episode[0].eval_step)
self.pending_groups[group_id].extend(episode)
self.pending_group_episodes[group_id] += 1
if self.pending_group_episodes[group_id] >= self.group_size_for(env_name):
def add(self, episode: vf.Episode) -> EvalBatch | None:
env_name = episode_env_name(episode)
group_id = episode_group_id(episode)
eval_step = eval_work(episode).step
bkey = (env_name, eval_step)
group = self.pending_groups[group_id]
group.append(episode)
if len(group) >= self.group_size_for(env_name):
self.process_group(group_id)
if self.pending_batch_episodes[bkey] >= self.batch_size_for(env_name):
if len(self.pending_batches[bkey]) >= self.batch_size_for(env_name):
return self.process_batch(bkey)
return None
@@ -54,24 +38,19 @@ class EvalSink:
return self.eval_envs.get(env_name).config.group_size
def batch_size_for(self, env_name: str) -> int:
"""``num_examples × group_size`` — total episodes expected for one
epoch of ``env_name``."""
env = self.eval_envs.get(env_name)
return len(env.examples) * env.config.group_size
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
"""One entry per accumulating ``(env, eval_step)`` batch:
``(env_name, eval_step, batch_count, expected, buffered)``.
``batch_count`` is finalized-group episodes in ``pending_batches``;
``buffered`` is partial-group episode arrivals."""
batch_counts: dict[tuple[str, int], int] = dict(self.pending_batch_episodes)
batch_counts = {key: len(runs) for key, runs in self.pending_batches.items()}
buffered: dict[tuple[str, int], int] = {}
for group_id, rollouts in self.pending_groups.items():
if not rollouts:
for group in self.pending_groups.values():
if not group:
continue
env_name = rollouts[0].env_name
bkey = (env_name, rollouts[0].eval_step)
buffered[bkey] = buffered.get(bkey, 0) + self.pending_group_episodes.get(group_id, 0)
episode = group[0]
eval_step = eval_work(episode).step
key = (episode_env_name(episode), eval_step)
buffered[key] = buffered.get(key, 0) + len(group)
return [
(
env_name,
@@ -80,47 +59,35 @@ class EvalSink:
self.batch_size_for(env_name),
buffered.get((env_name, eval_step), 0),
)
for (env_name, eval_step) in set(batch_counts) | set(buffered)
for env_name, eval_step in set(batch_counts) | set(buffered)
]
# ── level 1: per-rollout (no-op for eval) ─────────────────────────────
def process_rollout(self, rollout: Rollout) -> None:
"""No-op. Eval rollouts don't need trainer-bound tokenization; the
method exists to keep the three-level structure uniform with
``TrainSink``.
"""
return None
# ── level 2: per-group (move into batch bucket) ───────────────────────
def process_group(self, group_id: uuid.UUID) -> None:
def process_group(self, group_id: str) -> None:
group = self.pending_groups.pop(group_id, [])
episodes = self.pending_group_episodes.pop(group_id, 0)
if not group:
return
env_name = group[0].env_name
task_idx = group[0].task.data.idx
eval_step = group[0].eval_step
bucket = self.pending_batches[(env_name, eval_step)]
bucket.extend(group)
self.pending_batch_episodes[(env_name, eval_step)] += episodes
episode = group[0]
env_name = episode_env_name(episode)
eval_step = eval_work(episode).step
self.pending_batches[(env_name, eval_step)].extend(group)
survivors = [r for r in group if not r.has_error]
num_errored = len(group) - len(survivors)
rewards = [r.reward for r in survivors]
traces = [trace for episode in group for trace in episode.traces]
survivors = [trace for trace in traces if not trace.has_error]
num_errored = len(traces) - len(survivors) + sum(not episode.ok for episode in group if not episode.traces)
rewards = [trace.reward for trace in survivors]
avg_reward = sum(rewards) / len(rewards) if rewards else 0.0
task_idx = next((trace.task.data.idx for trace in traces), None)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} eval_step={eval_step} | "
f"rollouts={len(group)} (errored={num_errored}) | reward={avg_reward:.4f}"
f"Finished group | env={env_name} task_idx={task_idx} "
f"eval_step={eval_step} | episodes={len(group)} traces={len(traces)} "
f"(errored={num_errored}) | reward={avg_reward:.4f}"
)
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
"""Pop the finished ``(env, eval_step)`` epoch and return the ``EvalBatch`` with its full
returned cohort (errored rollouts included — the ``all`` set). Metrics are computed
downstream via ``EvalBatch.rollouts.metrics`` over the all/effective subsets, so the sink
does no aggregation."""
env_name, step = key
rollouts = self.pending_batches.pop(key, [])
self.pending_batch_episodes.pop(key, None)
return EvalBatch(env_name=env_name, step=step, rollouts=EvalRollouts(rollouts))
episodes = self.pending_batches.pop(key, [])
return EvalBatch(
env_name=env_name,
step=step,
episodes=EvalEpisodes(episodes, group_size=self.group_size_for(env_name)),
)
+1 -1
View File
@@ -46,7 +46,7 @@ class EvalSource:
def trigger(self, step: int, *, force: bool = False) -> list[str]:
"""Fire eligible envs for ``step`` and return their names. On resume
``first_trigger`` is False, so the startup/base eval doesn't re-run.
``force`` fires every env regardless of interval (e.g. the evaluator's
``force`` fires every env regardless of interval (e.g. the evals process's
final-checkpoint eval)."""
is_first, self.first_trigger = self.first_trigger, False
if is_first and self.eval_config.skip_first_step:
-320
View File
@@ -1,320 +0,0 @@
"""Online evaluator: disk-checkpoint-driven evals against a live inference server.
The trainer writes HF weight checkpoints to ``weights/step_{n}`` (``STABLE``
marker on completion) — that is its signal that a new policy is ready. The
evaluator watches the directory, tells the inference server to reload each
eligible checkpoint from disk (``/update_weights``, no NCCL rendezvous), and
runs the configured evals against the updated weights, sequentially per
checkpoint so every epoch measures exactly one policy version.
Reuses the orchestrator's eval components — ``EvalEnvs`` / ``EvalSource`` /
``EvalSink`` / ``EvalRollouts`` — and logs metrics and episodes through the same
monitors (``eval/{env}/...`` metrics, episode traces via the file monitor).
"""
from __future__ import annotations
import asyncio
import os
import time
import uuid
import verifiers.v1 as vf
from prime_rl import monitors
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.orchestrator.envs import EvalEnv, EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.types import EvalBatch, Rollout
from prime_rl.orchestrator.utils import group_episodes, intercept_vf_logging, set_default_executor
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_step_path
from prime_rl.utils.utils import clean_exit
monkey_patch_oai_iterable_types()
monkey_patch_chat_completion_logprobs()
# How often to re-scan the weights directory for new checkpoints.
POLL_INTERVAL_S = 2.0
class Evaluator:
def __init__(self, config: EvaluatorConfig) -> None:
self.config = config
setup_logger(config.log.level, json_logging=config.log.json_logging)
intercept_vf_logging(logger="verifiers.v1", level="WARN")
get_logger().info(f"Starting evaluator (weights_dir={config.weights_dir})")
# The last weight-checkpoint step already handled (evaluated or skipped).
self.last_step = config.resume_step or 0
self.eval_triggered_at: dict[tuple[str, int], float] = {}
async def setup(self) -> None:
config = self.config
set_default_executor()
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
wandb=config.monitors.wandb,
file=config.monitors.file,
output_dir=config.output_dir,
run_config=config,
eval_env_names=[source.resolved_name for source in config.eval.source],
overview_flavor="sft",
)
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
self.run_name = os.environ.get("PRL_RUN_NAME")
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)
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.eval.source, config.eval.env_addresses)
await self.eval_envs.start()
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)
get_logger().success("Inference pool ready")
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=config.resume_step is not None)
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
async def run(self) -> None:
await self.setup()
config = self.config
if config.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``.
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). Requires the resume step's weights on disk. The final checkpoint
# force-fires every env, exactly like the watch loop below.
is_final = config.max_steps is not None and config.resume_step >= config.max_steps
await self.maybe_run_evals(step=config.resume_step, reload_weights=True, force=is_final)
get_logger().info(f"Watching {config.weights_dir} for new weight checkpoints (max_steps={config.max_steps})")
while True:
assert config.weights_dir is not None # resolved by the config validator
steps = get_all_ckpt_steps(config.weights_dir)
stable = {step: (get_step_path(config.weights_dir, step) / "STABLE").exists() for step in steps}
newest_stable = max((step for step in steps if stable[step]), default=None)
# Also walk eval-due steps that are no longer on disk: checkpoint cleaning
# (ckpt.keep_last / keep_interval) 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)):
if step <= self.last_step:
continue
if step not in stable:
get_logger().warning(
f"Weight checkpoint for eval step {step} was deleted before it could be "
"evaluated (checkpoint cleaning outpaced the evaluator) - skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
if not stable[step]:
# The trainer writes checkpoints 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:
break # still being written — later steps can't be ready either
get_logger().warning(
f"Weight checkpoint step {step} has no STABLE marker but newer stable "
"checkpoints exist - treating it as abandoned and skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
is_final = config.max_steps is not None and step >= config.max_steps
await self.maybe_run_evals(step=step, reload_weights=True, force=is_final)
if config.max_steps is not None and self.last_step >= config.max_steps:
break
await asyncio.sleep(POLL_INTERVAL_S)
get_logger().success("Evaluator finished!")
def deleted_due_steps(self, steps: list[int], newest_stable: int | None) -> set[int]:
"""Eval-due steps up to the newest stable checkpoint that are missing from the
weights dir — the trainer wrote them (it saves at every due step), so their
absence means checkpoint cleaning removed them before they were evaluated."""
if newest_stable is None:
return set()
due = {
step
for interval in self.eval_source.intervals.values()
for step in range(interval, newest_stable + 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."""
assert self.config.weights_dir is not None # resolved by the config validator
weight_dir = get_step_path(self.config.weights_dir, step)
if reload_weights and not (weight_dir / "STABLE").exists():
get_logger().warning(f"No stable weight checkpoint for step {step} ({weight_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 not fired:
return
now = time.perf_counter()
for env_name in fired:
self.eval_triggered_at[(env_name, step)] = now
total_rollouts = sum(
self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
for env_name in fired
)
if reload_weights:
get_logger().info(f"Updating inference weights to checkpoint step {step} ({weight_dir})")
try:
await self.pool.update_weights(weight_dir, 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 eval_step.
while self.eval_source.next_example() is not None:
pass
get_logger().error(f"Failed to update inference weights to step {step} - skipping evals: {exc!r}")
return
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
await self.run_evals(step)
async def run_evals(self, step: int) -> None:
"""Drain the eval queue for one step under bounded concurrency, routing
finished episodes through the sink and finalizing each env's epoch."""
semaphore = asyncio.Semaphore(self.config.eval.max_inflight_episodes)
tasks: list[asyncio.Task] = []
while (example := self.eval_source.next_example()) is not None:
env = self.eval_envs.get(example["env_name"])
group_id = uuid.uuid4()
for _ in range(env.config.group_size):
tasks.append(asyncio.create_task(self.run_episode(env, example, group_id, step, semaphore)))
for future in asyncio.as_completed(tasks):
episode = await future
run = vf.EvalRunInfo(id=self.run_id, name=self.run_name, step=step)
for rollout in episode:
rollout.record_run(
run,
env_name=rollout.env_name,
group_id=str(rollout.group_id),
episode_id=rollout.episode_id,
policy_version=rollout.policy_version,
)
await monitors.log(group_episodes(episode), step, "eval", "all")
eval_batch = self.eval_sink.add(episode)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
async def run_episode(
self,
env: EvalEnv,
example: dict,
group_id: uuid.UUID,
step: int,
semaphore: asyncio.Semaphore,
) -> list[Rollout]:
"""Run one episode against the env server; failures synthesize an
error-marker rollout so the sink's count-based finalization still fires."""
async with semaphore:
try:
rollouts = await env.run(
client=self.pool.eval_client,
model_name=self.pool.model_name,
cache_salt=str(step),
task_data=example["task"].data.model_dump(mode="json"),
)
except Exception as exc:
get_logger().warning(f"Rollout task failed in group {group_id} ({env.name}): {exc!r}")
rollout = Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=example["task"].data.idx, prompt=None)),
agent=vf.AgentInfo(config=vf.AgentConfig()),
)
rollout.record_error(exc)
rollouts = [rollout]
for rollout in rollouts:
if not rollout.has_error and rollout.num_turns == 0:
rollout.errors.append(
vf.Error(type="EmptyTrajectory", message="Rollout returned with no trajectory steps")
)
rollout.ok = False
get_logger().warning(f"Empty trajectory in group {group_id} ({env.name})")
rollout.kind = "eval"
rollout.env_name = env.name
rollout.group_id = group_id
# For SFT-driven evals the policy version *is* the checkpoint step.
rollout.policy_version = step
rollout.eval_step = step
return rollouts
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
if not batch.rollouts:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
return
await monitors.log(group_episodes(batch.rollouts.effective.rollouts), batch.step, "eval", "effective")
rollouts = batch.rollouts
effective = rollouts.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", rollouts), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
eff, full = effective.metrics, rollouts.metrics
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
get_logger().success(
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
)
async def stop(self) -> None:
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
pool = getattr(self, "pool", None)
if pool is not None:
await pool.stop()
@clean_exit
async def run_evaluator(config: EvaluatorConfig) -> None:
evaluator = Evaluator(config)
try:
await evaluator.run()
# Finalize only on a clean exit — a crashed evaluator must not mark the run completed.
await monitors.finalize()
finally:
await evaluator.stop()
def main() -> None:
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
set_proc_title("Evaluator")
asyncio.run(run_evaluator(cli(EvaluatorConfig)))
if __name__ == "__main__":
main()
@@ -1,12 +1,4 @@
"""How an env's train rollouts are produced — the sample strategy.
The algorithm (``algo/``) consumes finalized rollouts and compiles them into
per-token loss-component weights; the sampler owns where those rollouts come
from. Today that is one question — which model generates them — and its
consequences (sampling logprobs, prefix-cache salting, and off-policy
staleness are all liveness questions about the source). Future sampling
strategies (replay buffers, branching) extend here, not the algorithm.
"""
"""Resolve the model source used to generate an env's train episodes."""
from __future__ import annotations
@@ -21,8 +13,8 @@ if TYPE_CHECKING:
from prime_rl.utils.client import InferencePool
class Sampler:
"""One env's rollout source.
class GenerationSource:
"""One env's generation model and inference pool.
``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
@@ -40,20 +32,20 @@ class Sampler:
self.connected_pools: list[InferencePool] = [] # client pools connected in setup(); closed at shutdown
async def setup(self) -> None:
"""Connect a client pool to a frozen sampling source and wait for
"""Connect a client pool 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)
@property
def samples_from_live_policy(self) -> bool:
def uses_live_policy(self) -> bool:
return self.config.source == "policy"
def sampling_args(self, args: dict) -> dict:
"""Source-specific sampling-arg overrides. Sampling logprobs are only
needed for importance ratios on policy-sampled tokens — frozen
endpoints may reject the knob."""
if not self.samples_from_live_policy:
if not self.uses_live_policy:
args.pop("logprobs", None)
return args
@@ -307,6 +307,22 @@ class InferenceMetricsCollector:
self.task = asyncio.create_task(poll_loop())
async def probe(self, attempts: int = 3, interval: float = 2.0) -> bool:
"""Scrape once, outside the poll loop, and report whether any engine
answered with metrics. External API endpoints (no vLLM ``/metrics``)
fail every attempt immediately; the retries only cover a real engine
racing its first exposition."""
for attempt in range(attempts):
if attempt > 0:
await asyncio.sleep(interval)
try:
await self.collect_and_log()
except Exception as e:
get_logger().warning(f"Inference metrics probe failed: {e!r}")
if self.previous:
return True
return False
async def collect_and_log(self):
now = time.monotonic()
+301 -230
View File
@@ -1,38 +1,53 @@
"""Train and eval rollout metrics.
A rollout container (``TrainRollouts`` / ``EvalRollouts``) owns the rollout list and exposes
``.effective`` (the clean subset, as the same container type) and ``.metrics`` (``TrainMetrics`` /
``EvalMetrics``). The metrics object exposes each distributional / rate metric as a ``Stat`` — so
``rollouts.metrics.num_input_tokens.mean()`` works — and assembles the full
``{prefix}/{subset}/<metric>/<stat>`` wandb dict via ``.to_wandb(...)``.
The wandb layout mirrors the episode/trace hierarchy, one aggregation per level:
- ``{prefix}/{subset}/<metric>/<stat>`` — episode level, one value per episode summing its traces
(matching ``vf.Episode``'s aggregates). Only the count metrics live here.
- ``{prefix}/{subset}/<agent>/<metric>/<stat>`` — agent level, one value per trace, grouped by agent
name (``vf.Episode.by_agent``) so agents never mix into one distribution. Everything trace-scoped
lives here: reward, rates, timing, custom metrics, the pipeline verdicts, the eval scores.
A single-agent env has one trace per episode, so the count metrics coincide across levels.
No I/O, no pandas — plain Python over the ``vf.Trace`` properties each rollout exposes.
"""
"""Episode-native train and evaluation metrics."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Iterator, Literal
from collections.abc import Callable, Iterator
from dataclasses import dataclass
from typing import Any, Literal
from prime_rl.orchestrator.utils import compute_pass_metrics
import verifiers.v1 as vf
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
from prime_rl.orchestrator.algo.routing import is_trainable, scalar_advantage
from prime_rl.orchestrator.utils import compute_pass_metrics, episode_env_name, episode_group_id
Subset = Literal["all", "effective"]
@dataclass(frozen=True)
class TraceRecord:
"""A trace joined with its episode and training selection state.
``cancelled`` marks episodes the pipeline voided (stale drop) — a
selection verdict disjoint from trace errors."""
episode: vf.Episode
trace: vf.Trace
sampled: bool
admitted: bool
cancelled: bool
def _records(
episodes: list[vf.Episode],
sampled_trace_ids: set[str],
admitted: set[str],
cancelled: set[str],
) -> list[TraceRecord]:
return [
TraceRecord(
episode=episode,
trace=trace,
sampled=trace.id in sampled_trace_ids,
admitted=episode.id in admitted,
cancelled=episode.id in cancelled,
)
for episode in episodes
for trace in episode.traces
]
class Stat:
"""A distribution of per-rollout values with mean/max/min and p10/p90 accessors."""
"""A distribution with mean, extrema, and percentile accessors."""
def __init__(self, values: list[float]) -> None:
self.values = values
@@ -47,14 +62,13 @@ class Stat:
return float(min(self.values)) if self.values else 0.0
def percentile(self, q: float) -> float:
"""Linear-interpolated ``q``-th percentile (numpy's default method); 0.0 if empty."""
if not self.values:
return 0.0
s = sorted(self.values)
rank = q / 100 * (len(s) - 1)
lo = int(rank)
hi = min(lo + 1, len(s) - 1)
return float(s[lo] + (s[hi] - s[lo]) * (rank - lo))
values = sorted(self.values)
rank = q / 100 * (len(values) - 1)
low = int(rank)
high = min(low + 1, len(values) - 1)
return float(values[low] + (values[high] - values[low]) * (rank - low))
def p10(self) -> float:
return self.percentile(10)
@@ -63,7 +77,6 @@ class Stat:
return self.percentile(90)
def to_dict(self, prefix: str) -> dict[str, float]:
"""``{prefix}/mean,max,min,p10,p90``; ``{}`` for an empty distribution."""
if not self.values:
return {}
return {
@@ -76,11 +89,12 @@ class Stat:
class StatGroup:
"""A nested group of named ``Stat``s. ``to_dict`` emits ``{prefix}/<name>/<stat>`` for each
distribution and ``group[name]`` returns one; subclasses supply the names via ``stats()``."""
def __init__(self, records: list[TraceRecord]) -> None:
self.records = records
def __init__(self, rollouts: list[Rollout]) -> None:
self.rollouts = rollouts
@property
def traces(self) -> list[vf.Trace]:
return [record.trace for record in self.records]
def stats(self) -> dict[str, Stat]:
raise NotImplementedError
@@ -96,41 +110,35 @@ class StatGroup:
class TimingMetrics(StatGroup):
"""Per-phase rollout durations, nested so ``metrics.timing.setup.mean()`` reads naturally.
``total`` is the per-rollout sum across all phases."""
PHASES = ("setup", "agent", "finalize", "scoring")
@property
def setup(self) -> Stat:
return Stat([r.timing.setup.duration for r in self.rollouts])
return Stat([trace.timing.setup.duration for trace in self.traces])
@property
def agent(self) -> Stat:
return Stat([r.timing.agent.duration for r in self.rollouts])
return Stat([trace.timing.agent.duration for trace in self.traces])
@property
def agent_model(self) -> Stat:
"""The share of the agent phase spent inside model calls (inference)."""
return Stat([r.timing.agent.model.duration for r in self.rollouts])
return Stat([trace.timing.agent.model.duration for trace in self.traces])
@property
def agent_harness(self) -> Stat:
"""The share of the agent phase spent outside model calls (harness, tools,
user simulation)."""
return Stat([r.timing.agent.harness.duration for r in self.rollouts])
return Stat([trace.timing.agent.harness.duration for trace in self.traces])
@property
def finalize(self) -> Stat:
return Stat([r.timing.finalize.duration for r in self.rollouts])
return Stat([trace.timing.finalize.duration for trace in self.traces])
@property
def scoring(self) -> Stat:
return Stat([r.timing.scoring.duration for r in self.rollouts])
return Stat([trace.timing.scoring.duration for trace in self.traces])
@property
def total(self) -> Stat:
return Stat([sum(getattr(r.timing, p).duration for p in self.PHASES) for r in self.rollouts])
return Stat([sum(getattr(trace.timing, phase).duration for phase in self.PHASES) for trace in self.traces])
def stats(self) -> dict[str, Stat]:
return {
@@ -142,26 +150,24 @@ class TimingMetrics(StatGroup):
class CustomMetrics(StatGroup):
"""Per-key ``Stat``s over a dynamic per-rollout dict attribute (env ``@metric``s or reward
components), each over the rollouts that carry the key. Scoring seeds every expected key
with ``None`` before invoking it, so a ``None`` value means the signal never produced a
score and counts as 0.0 — the ``effective`` subset excludes errored rollouts and gives the
clean means. ``value`` extracts the float from each scored entry (rewards are ``vf.Reward``
records; metrics are plain floats)."""
def __init__(self, rollouts: list[Rollout], attr: str, value: Callable[[Any], float] = float) -> None:
super().__init__(rollouts)
def __init__(
self,
records: list[TraceRecord],
attr: str,
value: Callable[[Any], float] = float,
) -> None:
super().__init__(records)
self.attr = attr
self.value = value
def stats(self) -> dict[str, Stat]:
names = sorted({name for r in self.rollouts for name in getattr(r, self.attr)})
names = sorted({name for trace in self.traces for name in getattr(trace, self.attr)})
return {
name: Stat(
[
self.value(scores[name]) if scores[name] is not None else 0.0
for r in self.rollouts
if name in (scores := getattr(r, self.attr))
for trace in self.traces
if name in (scores := getattr(trace, self.attr))
]
)
for name in names
@@ -169,78 +175,73 @@ class CustomMetrics(StatGroup):
class TraceMetrics(StatGroup):
"""Trace-level metrics for one agent, every one of them flat over that agent's traces: one
sample is one trace, so a fan-out (n same-agent traces in one episode, e.g. n solvers) simply
contributes n samples. Weighing whole episodes against each other is the episode level's job;
inside a seat the trace is the unit, which is also what the advantage computation samples."""
DISTRIBUTIONS = ("reward", "num_total_tokens", "num_input_tokens", "num_output_tokens", "num_turns", "num_branches")
DISTRIBUTIONS = (
"reward",
"num_total_tokens",
"num_input_tokens",
"num_output_tokens",
"num_turns",
"num_branches",
)
RATES = ("is_truncated", "is_completed")
def stats(self) -> dict[str, Stat]:
return {
name: Stat([float(getattr(r, name)) for r in self.rollouts]) for name in (*self.DISTRIBUTIONS, *self.RATES)
name: Stat([float(getattr(trace, name)) for trace in self.traces])
for name in (*self.DISTRIBUTIONS, *self.RATES)
}
@property
def timing(self) -> TimingMetrics:
return TimingMetrics(self.rollouts)
return TimingMetrics(self.records)
@property
def metrics(self) -> CustomMetrics:
"""Env custom ``@metric`` outputs, keyed by name."""
return CustomMetrics(self.rollouts, "metrics")
return CustomMetrics(self.records, "metrics")
@property
def rewards(self) -> CustomMetrics:
"""Per-component reward breakdown, keyed by name (each entry's weighted ``value``,
summed into the scalar ``reward``)."""
return CustomMetrics(self.rollouts, "rewards", value=lambda reward: reward.value)
return CustomMetrics(self.records, "rewards", value=lambda reward: reward.value)
@property
def has_error(self) -> Stat:
return Stat([float(r.has_error) for r in self.rollouts])
return Stat([float(trace.has_error) for trace in self.traces])
@property
def cancelled(self) -> Stat:
"""Pipeline cancellations (stale drop) — disjoint from errors."""
return Stat([float(record.cancelled) for record in self.records])
def stop_conditions(self) -> dict[str, float]:
"""``generation_truncated`` over the agent's traces, then each recorded
``stop_condition``'s rate over the traces that recorded one."""
out = {
"generation_truncated": sum(
1 for r in self.rollouts if r.is_truncated and r.stop_condition != "prompt_too_long"
trace.is_truncated and trace.stop_condition != "prompt_too_long" for trace in self.traces
)
/ len(self.rollouts)
/ len(self.traces)
}
conditions = [r.stop_condition for r in self.rollouts if r.stop_condition is not None]
conditions = [trace.stop_condition for trace in self.traces if trace.stop_condition is not None]
for condition in sorted(set(conditions)):
out[condition] = conditions.count(condition) / len(conditions)
return out
def error_types(self) -> dict[str, int]:
"""Count of errored traces by error type (the trace's last error — e.g. ``Cancelled``,
``ProviderError``)."""
types = [r.last_error.type for r in self.rollouts if r.has_error and r.last_error is not None]
return {t: types.count(t) for t in sorted(set(types))}
types = [trace.last_error.type for trace in self.traces if trace.has_error and trace.last_error is not None]
return {error_type: types.count(error_type) for error_type in sorted(set(types))}
def solve_rates(self) -> dict[str, float]:
"""Per-group solve rates over the agent's traces, assuming binary 0/1 rewards (unspecified
for other reward ranges): ``solved_none`` (the group earned no reward), ``solved_all``
(every trace scored 1.0), and ``solved_some`` (the mixed remainder — the GRPO-signal
groups)."""
groups: dict = {}
for r in self.rollouts:
groups.setdefault(r.group_id, []).append(r)
n_groups = len(groups)
solved_none = sum(1 for g in groups.values() if sum(r.reward for r in g) == 0)
solved_all = sum(1 for g in groups.values() if all(r.reward == 1.0 for r in g))
for record in self.records:
groups.setdefault(episode_group_id(record.episode), []).append(record.trace)
num_groups = len(groups)
solved_none = sum(sum(trace.reward for trace in group) == 0 for group in groups.values())
solved_all = sum(all(trace.reward == 1.0 for trace in group) for group in groups.values())
return {
"solved_none": solved_none / n_groups,
"solved_all": solved_all / n_groups,
"solved_some": 1 - (solved_none + solved_all) / n_groups,
"solved_none": solved_none / num_groups,
"solved_all": solved_all / num_groups,
"solved_some": 1 - (solved_none + solved_all) / num_groups,
}
def to_dict(self, prefix: str, *, subset: Subset) -> dict[str, float]:
"""Full ``<stat>`` fan-out for the distributions; ``/mean`` only for the 0/1 rates.
Errors live only on the ``all`` subset (``effective`` drops them by construction)."""
stats = self.stats()
out: dict[str, float] = {}
for name in self.DISTRIBUTIONS:
@@ -252,211 +253,281 @@ class TraceMetrics(StatGroup):
out |= self.rewards.to_dict(f"{prefix}/rewards")
if subset == "all":
out[f"{prefix}/has_error/mean"] = self.has_error.mean()
out |= {f"{prefix}/error/{t}": float(count) for t, count in self.error_types().items()}
out |= {f"{prefix}/stop_condition/{k}": v for k, v in self.stop_conditions().items()}
out |= {f"{prefix}/{k}": v for k, v in self.solve_rates().items()}
out[f"{prefix}/cancelled/mean"] = self.cancelled.mean()
out |= {f"{prefix}/error/{key}": float(value) for key, value in self.error_types().items()}
out |= {f"{prefix}/{key}": value for key, value in self.solve_rates().items()}
out |= {f"{prefix}/stop_condition/{key}": value for key, value in self.stop_conditions().items()}
return out
class EpisodeMetrics:
"""Metrics shared by train and eval over a rollout list. The count metrics (tokens/turns/
branches) are episode-level — one value per episode, summing its traces — and are the only
per-metric keys ``to_wandb`` emits at the env level; every trace-level metric is emitted per
agent via ``by_agent()``. The boolean ``Stat`` properties (0/1 distributions, ``.mean()`` is
the rate) serve the console log lines. ``TrainMetrics`` / ``EvalMetrics`` extend ``to_wandb``
with the train pipeline rates and the eval scores."""
def __init__(self, rollouts: list[Rollout]) -> None:
self.rollouts = rollouts
def episodes(self) -> list[list[Rollout]]:
"""The subset's rollouts grouped into their episodes. A rollout without an
``episode_id`` (synthesized error markers) is its own episode."""
grouped: dict[str, list[Rollout]] = {}
for r in self.rollouts:
grouped.setdefault(r.episode_id or r.id, []).append(r)
return list(grouped.values())
def __init__(
self,
episodes: list[vf.Episode],
records: list[TraceRecord],
cancelled: set[str] | None = None,
) -> None:
self.episodes = episodes
self.records = records
self.cancelled_ids = cancelled if cancelled is not None else set()
def by_agent(self) -> dict[str, TraceMetrics]:
"""Per-agent metric views (``vf.Episode.by_agent`` over the subset's rollouts)."""
per_agent: dict[str, list[Rollout]] = {}
for r in self.rollouts:
per_agent.setdefault(r.agent.name, []).append(r)
return {name: TraceMetrics(rollouts) for name, rollouts in sorted(per_agent.items())}
per_agent: dict[str, list[TraceRecord]] = {}
for record in self.records:
per_agent.setdefault(record.trace.agent.name, []).append(record)
return {name: TraceMetrics(records) for name, records in sorted(per_agent.items())}
def _episode_stat(self, attr: str) -> Stat:
by_episode = {id(episode): 0.0 for episode in self.episodes}
for record in self.records:
by_episode[id(record.episode)] += float(getattr(record.trace, attr))
return Stat(list(by_episode.values()))
# Episode-level count metrics: one value per episode, summing its traces — the same
# aggregation as ``vf.Episode.num_turns`` / ``num_*_tokens``.
@property
def num_total_tokens(self) -> Stat:
return Stat([float(sum(r.num_total_tokens for r in episode)) for episode in self.episodes()])
return self._episode_stat("num_total_tokens")
@property
def num_input_tokens(self) -> Stat:
return Stat([float(sum(r.num_input_tokens for r in episode)) for episode in self.episodes()])
return self._episode_stat("num_input_tokens")
@property
def num_output_tokens(self) -> Stat:
return Stat([float(sum(r.num_output_tokens for r in episode)) for episode in self.episodes()])
return self._episode_stat("num_output_tokens")
@property
def num_turns(self) -> Stat:
return Stat([float(sum(r.num_turns for r in episode)) for episode in self.episodes()])
return self._episode_stat("num_turns")
@property
def num_branches(self) -> Stat:
return Stat([float(sum(r.num_branches for r in episode)) for episode in self.episodes()])
return self._episode_stat("num_branches")
# Boolean rate metrics for the console log lines (0/1 distributions — ``.mean()`` is the
# rate); to_wandb emits their per-agent counterparts instead.
@property
def is_truncated(self) -> Stat:
return Stat([float(r.is_truncated) for r in self.rollouts])
return Stat([float(record.trace.is_truncated) for record in self.records])
@property
def has_error(self) -> Stat:
return Stat([float(r.has_error) for r in self.rollouts])
return Stat(
[float(not episode.ok or any(trace.has_error for trace in episode.traces)) for episode in self.episodes]
)
@property
def cancelled(self) -> Stat:
"""Per-episode pipeline-cancellation rate — same denominator as
``has_error``. Read from the id-set, not the trace records, so
trace-less episodes (synthetic error episodes inside a voided group)
still count."""
return Stat([float(episode.id in self.cancelled_ids) for episode in self.episodes])
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
"""The common metric dict for one ``{prefix}/{subset}`` slice. Empty input → ``{}``."""
if not self.rollouts:
if not self.episodes:
return {}
p = f"{prefix}/{subset}"
metric_prefix = f"{prefix}/{subset}"
out: dict[str, float] = {}
out |= self.num_total_tokens.to_dict(f"{p}/num_total_tokens")
out |= self.num_input_tokens.to_dict(f"{p}/num_input_tokens")
out |= self.num_output_tokens.to_dict(f"{p}/num_output_tokens")
out |= self.num_turns.to_dict(f"{p}/num_turns")
out |= self.num_branches.to_dict(f"{p}/num_branches")
for agent, agent_metrics in self.by_agent().items():
out |= agent_metrics.to_dict(f"{p}/{agent}", subset=subset)
for name in ("num_total_tokens", "num_input_tokens", "num_output_tokens", "num_turns", "num_branches"):
out |= getattr(self, name).to_dict(f"{metric_prefix}/{name}")
if subset == "all":
out[f"{metric_prefix}/has_error/mean"] = self.has_error.mean()
out[f"{metric_prefix}/cancelled/mean"] = self.cancelled.mean()
for agent, metrics in self.by_agent().items():
out |= metrics.to_dict(f"{metric_prefix}/{agent}", subset=subset)
return out
class TrainMetrics(EpisodeMetrics):
"""Common metrics plus per-agent pipeline rates. ``reward`` (flat over all traces)
serves the console log lines; the wandb reward stats are per-agent."""
@property
def reward(self) -> Stat:
return Stat([float(r.reward) for r in self.rollouts])
return Stat([float(record.trace.reward) for record in self.records])
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
out = super().to_wandb(prefix=prefix, subset=subset)
# Pipeline verdicts are per-trace, so they read per agent like the rest.
for agent, traces in self.by_agent().items():
p = f"{prefix}/{subset}/{agent}"
rollouts = traces.rollouts
out[f"{p}/is_trainable/mean"] = sum(float(r.is_trainable) for r in rollouts) / len(rollouts)
out[f"{p}/is_admitted/mean"] = sum(float(r.is_admitted) for r in rollouts) / len(rollouts)
metric_prefix = f"{prefix}/{subset}/{agent}"
out[f"{metric_prefix}/is_trainable/mean"] = sum(
float(is_trainable(record.trace)) for record in traces.records
) / len(traces.records)
out[f"{metric_prefix}/is_admitted/mean"] = sum(float(record.admitted) for record in traces.records) / len(
traces.records
)
return out
def pass_at_k(rollouts: list[Rollout]) -> dict[str, float]:
"""pass@k / pass^k averaged over examples; ``{}`` for non-binary rewards."""
rewards = [r.reward for r in rollouts]
def pass_at_k(records: list[TraceRecord]) -> dict[str, float]:
rewards = [record.trace.reward for record in records]
if not set(rewards).issubset({0.0, 1.0}):
return {}
by_example: dict = {}
for r in rollouts:
by_example.setdefault(r.group_id, []).append(r.reward)
per_example = [compute_pass_metrics(rs) for rs in by_example.values()]
keys = sorted({k for d in per_example for k in d})
return {k: sum(d[k] for d in per_example if k in d) / sum(1 for d in per_example if k in d) for k in keys}
for record in records:
by_example.setdefault(episode_group_id(record.episode), []).append(record.trace.reward)
per_example = [compute_pass_metrics(group) for group in by_example.values()]
keys = sorted({key for result in per_example for key in result})
return {
key: sum(result[key] for result in per_example if key in result) / sum(key in result for result in per_example)
for key in keys
}
class EvalMetrics(EpisodeMetrics):
"""Common metrics plus the per-agent ``avg@<group_size>`` score and (on the effective subset,
for binary-reward tasks) pass@k / pass^k. Both score an agent's own traces, so they live in its
subtree like every other trace-level metric. ``group_size`` (the ``avg@k`` k, the run's rollouts
per example) is supplied by the container so the ``all`` and ``effective`` subsets — and every
agent — share one stable key."""
def __init__(self, rollouts: list[Rollout], group_size: int) -> None:
super().__init__(rollouts)
def __init__(self, episodes: list[vf.Episode], records: list[TraceRecord], group_size: int) -> None:
super().__init__(episodes, records)
self.group_size = group_size
@property
def reward(self) -> Stat:
return Stat([float(r.reward) for r in self.rollouts])
return Stat([float(record.trace.reward) for record in self.records])
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
out = super().to_wandb(prefix=prefix, subset=subset)
for agent, traces in self.by_agent().items():
p = f"{prefix}/{subset}/{agent}"
out[f"{p}/avg@{self.group_size}"] = traces.stats()["reward"].mean()
metric_prefix = f"{prefix}/{subset}/{agent}"
out[f"{metric_prefix}/avg@{self.group_size}"] = traces.stats()["reward"].mean()
if subset == "effective":
out |= {f"{p}/{k}": v for k, v in pass_at_k(traces.rollouts).items()}
out |= {f"{metric_prefix}/{key}": value for key, value in pass_at_k(traces.records).items()}
return out
class TrainRollouts:
"""A list of train rollouts (everything that came back, including rejected,
errored and untrainable traces). ``effective`` is the clean trainable subset;
``metrics`` builds ``TrainMetrics`` over them."""
def __init__(self, rollouts: list[Rollout] | None = None) -> None:
self.rollouts = rollouts if rollouts is not None else []
def append(self, rollout: Rollout) -> None:
self.rollouts.append(rollout)
def __len__(self) -> int:
return len(self.rollouts)
def __iter__(self) -> Iterator[Rollout]:
return iter(self.rollouts)
class EpisodeCollection:
def __init__(
self,
episodes: list[vf.Episode] | None = None,
sampled_trace_ids: set[str] | None = None,
admitted: set[str] | None = None,
cancelled: set[str] | None = None,
predicate: Callable[[TraceRecord], bool] | None = None,
) -> None:
self.episodes = episodes if episodes is not None else []
self.sampled_trace_ids = sampled_trace_ids if sampled_trace_ids is not None else set()
self.admitted = admitted if admitted is not None else {episode.id for episode in self.episodes}
self.cancelled = cancelled if cancelled is not None else set()
self._predicate = predicate
@property
def effective(self) -> TrainRollouts:
return TrainRollouts([r for r in self.rollouts if r.is_admitted and not r.has_error and r.agent.trainable])
def records(self) -> list[TraceRecord]:
records = _records(self.episodes, self.sampled_trace_ids, self.admitted, self.cancelled)
if self._predicate is None:
return records
return [record for record in records if self._predicate(record)]
def by_env(self) -> dict[str, TrainRollouts]:
grouped: dict[str, list[Rollout]] = {}
for r in self.rollouts:
grouped.setdefault(r.env_name, []).append(r)
return {env: TrainRollouts(rs) for env, rs in grouped.items()}
@property
def selected_episodes(self) -> list[vf.Episode]:
if self._predicate is None:
return self.episodes
selected = {id(record.episode) for record in self.records}
return [episode for episode in self.episodes if id(episode) in selected]
@property
def num_traces(self) -> int:
return len(self.records)
@property
def num_total_tokens(self) -> int:
return sum(record.trace.num_total_tokens for record in self.records)
@property
def vf_episodes(self) -> list[vf.Episode]:
if self._predicate is None:
return self.selected_episodes
by_episode: dict[int, list[vf.Trace]] = {}
for record in self.records:
trace = record.trace
advantage = scalar_advantage(trace)
if advantage is not None:
trace = trace.model_copy(update={"info": {**trace.info, "advantage": advantage}})
by_episode.setdefault(id(record.episode), []).append(trace)
return [
episode.model_copy(update={"traces": by_episode[id(episode)]})
for episode in self.selected_episodes
if id(episode) in by_episode
]
def append(
self,
episode: vf.Episode,
*,
sampled_trace_ids: set[str] | None = None,
admitted: bool = True,
cancelled: bool = False,
) -> None:
self.episodes.append(episode)
self.sampled_trace_ids.update(sampled_trace_ids or set())
if admitted:
self.admitted.add(episode.id)
if cancelled:
self.cancelled.add(episode.id)
def extend(
self,
episodes: list[vf.Episode],
*,
sampled_trace_ids: set[str] | None = None,
admitted: bool = True,
cancelled: bool = False,
) -> None:
self.episodes.extend(episodes)
self.sampled_trace_ids.update(sampled_trace_ids or set())
if admitted:
self.admitted.update(episode.id for episode in episodes)
if cancelled:
self.cancelled.update(episode.id for episode in episodes)
def __len__(self) -> int:
return len(self.selected_episodes)
def __iter__(self) -> Iterator[vf.Episode]:
return iter(self.selected_episodes)
class TrainEpisodes(EpisodeCollection):
@property
def effective(self) -> TrainEpisodes:
return TrainEpisodes(
self.episodes,
self.sampled_trace_ids,
self.admitted,
self.cancelled,
predicate=lambda record: (
record.admitted
and record.sampled
and not record.cancelled
and not record.trace.has_error
and record.trace.agent.trainable
),
)
def by_env(self) -> dict[str, TrainEpisodes]:
grouped: dict[str, list[vf.Episode]] = {}
for episode in self.selected_episodes:
grouped.setdefault(episode_env_name(episode), []).append(episode)
return {
env_name: TrainEpisodes(episodes, self.sampled_trace_ids, self.admitted, self.cancelled, self._predicate)
for env_name, episodes in grouped.items()
}
@property
def metrics(self) -> TrainMetrics:
return TrainMetrics(self.rollouts)
return TrainMetrics(self.selected_episodes, self.records, self.cancelled)
class EvalRollouts:
"""A list of eval rollouts (errored + untrainable included). ``effective`` is the
non-errored trainable subset (a view).
``group_size`` (rollouts per example, the ``avg@k`` k) is derived from the full epoch and carried
onto ``effective`` so both subsets share one stable key; ``metrics`` builds ``EvalMetrics``."""
def __init__(self, rollouts: list[Rollout] | None = None, group_size: int | None = None) -> None:
self.rollouts = rollouts if rollouts is not None else []
self._group_size = group_size
def __len__(self) -> int:
return len(self.rollouts)
def __iter__(self) -> Iterator[Rollout]:
return iter(self.rollouts)
class EvalEpisodes(EpisodeCollection):
def __init__(
self,
episodes: list[vf.Episode],
group_size: int,
predicate: Callable[[TraceRecord], bool] | None = None,
) -> None:
super().__init__(episodes, predicate=predicate)
self.group_size = group_size
@property
def group_size(self) -> int:
"""The largest group in trainable (policy) traces — equals the configured group size
whenever one example kept all its rollouts; untrainable traces don't count, so a
multi-agent episode doesn't inflate ``k``. A subview carries its parent's value so
``avg@k`` doesn't drift across subsets."""
if self._group_size is not None:
return self._group_size
counts: dict = {}
for r in self.rollouts:
if r.agent.trainable:
counts[r.group_id] = counts.get(r.group_id, 0) + 1
return max(counts.values(), default=0)
@property
def effective(self) -> EvalRollouts:
return EvalRollouts(
[r for r in self.rollouts if not r.has_error and r.agent.trainable], group_size=self.group_size
def effective(self) -> EvalEpisodes:
return EvalEpisodes(
self.episodes,
self.group_size,
predicate=lambda record: not record.trace.has_error and record.trace.agent.trainable,
)
@property
def metrics(self) -> EvalMetrics:
return EvalMetrics(self.rollouts, self.group_size)
return EvalMetrics(self.selected_episodes, self.records, self.group_size)
+185 -107
View File
@@ -3,14 +3,12 @@
``Orchestrator`` owns the shared state (policy, progress, ckpt, monitor)
and drives the pipeline. Components are single-purpose:
- ``Dispatcher`` schedules rollouts; emits ``Rollout`` (train/eval
discriminated by ``kind``) on its queue.
- ``TrainSink`` ingests train rollouts (tokenize → advantages → admission)
- ``Dispatcher`` schedules environment runs and emits completed episodes.
- ``TrainSink`` ingests train rollouts (score → admission → sample compilation)
and returns a ``TrainBatch`` when the threshold is met.
- ``EvalSink`` ingests eval rollouts and returns an ``EvalBatch`` (the full
returned cohort) on epoch completion.
- ``TrainRollouts`` / ``EvalRollouts`` carry the rollouts and build the per-step W&B metrics
(``batch.rollouts.metrics`` / ``.effective.metrics``).
- ``TrainEpisodes`` / ``EvalEpisodes`` preserve episode boundaries and build per-step metrics.
- ``WeightWatcher`` advances ``Policy`` and notifies observers.
- ``PeriodicLogger`` polls the components on a shared interval for the
``_timestamp``-axis pipeline log.
@@ -37,11 +35,12 @@ if TYPE_CHECKING:
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.orchestrator.ckpt import CheckpointManager
from prime_rl.transport.base import MicroBatchSender
from prime_rl.transports.rollouts.base import MicroBatchSender
from prime_rl.utils.client import InferencePool
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.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
@@ -49,6 +48,7 @@ from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.metrics import TrainEpisodes
from prime_rl.orchestrator.packing import BatchPacker
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
@@ -58,15 +58,17 @@ from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.train_sink import TrainSink
from prime_rl.orchestrator.train_source import TrainSource
from prime_rl.orchestrator.types import (
Cancellation,
EvalBatch,
Policy,
Progress,
Rollout,
TrainBatch,
)
from prime_rl.orchestrator.utils import (
episode_group_id,
episode_staleness,
eval_work,
get_weight_dir,
group_episodes,
intercept_vf_logging,
set_default_executor,
setup_policy_inference_pool,
@@ -74,8 +76,8 @@ from prime_rl.orchestrator.utils import (
)
from prime_rl.orchestrator.watcher import WeightWatcher
from prime_rl.trainer.model import setup_tokenizer
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
from prime_rl.transport import setup_micro_batch_sender
from prime_rl.transports.rollouts import setup_micro_batch_sender
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
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
@@ -269,10 +271,10 @@ class Orchestrator:
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")
# Build + ready pools for each env's frozen sampling source and the
# Build + ready pools for each env's frozen generation source and the
# algorithm's frozen reference model
await asyncio.gather(
*(env.sampler.setup() for env in self.train_envs),
*(env.generation_source.setup() for env in self.train_envs),
*(env.algorithm.setup() for env in self.train_envs),
)
@@ -382,10 +384,13 @@ class Orchestrator:
eval_source=self.eval_source,
policy_pool=self.policy_inference,
policy=self.policy,
progress=self.progress,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
tasks_per_minute=config.tasks_per_minute,
max_off_policy_steps=config.max_off_policy_steps,
run_id=self.run_id,
run_name=self.run_name,
on_episode_complete=self.concurrency.record_episode,
)
self.concurrency.bind(
@@ -408,10 +413,12 @@ class Orchestrator:
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,
on_result=self.train_source.on_result,
)
self.eval_sink = EvalSink(eval_envs=self.eval_envs) if self.eval_envs is not None else None
self.watcher = WeightWatcher(
config,
@@ -484,6 +491,7 @@ class Orchestrator:
clean_exit = False
try:
await self.main_loop()
await self.wait_for_final_broadcast()
clean_exit = True
finally:
elapsed = format_time(time.perf_counter() - start_time)
@@ -512,42 +520,76 @@ class Orchestrator:
get_logger().warning("Orchestrator cleanup complete (forced).")
trim_process_memory()
async def wait_for_final_broadcast(self) -> None:
"""Stay alive for the trainer's last in-memory broadcast (v{max_steps-1};
nothing samples from v{max_steps}, so it is never sent). An in-memory
broadcast is a blocking collective — tearing down the watcher before
the rendezvous would strand the trainer inside it."""
config = self.config
if config.weight_broadcast.type not in ("nccl", "nixl") or config.max_steps is None:
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")
async def wait() -> None:
while self.policy.version < final_version:
self.version_advanced.clear()
if self.policy.version >= final_version:
return
# A dead watcher can never deliver the broadcast — fail out
# instead of idling until the timeout.
self._raise_if_component_stopped()
try:
await asyncio.wait_for(self.version_advanced.wait(), timeout=5)
except asyncio.TimeoutError:
pass
try:
await asyncio.wait_for(wait(), timeout=config.weight_broadcast.timeout)
except asyncio.TimeoutError:
get_logger().warning(
f"Trainer did not broadcast v{final_version} within {config.weight_broadcast.timeout}s — "
"shutting down anyway"
)
async def main_loop(self) -> None:
"""Consume episodes (``list[Rollout]``) from the dispatcher and route them
to the train / eval sink. Both sinks return a finalized batch (or
``None``) from ``add()``; we just dispatch on the result."""
"""Consume completed episodes and group ``Cancellation``\\ s from the
dispatcher and route them to the train / eval sink. The sinks return a
finalized batch (or ``None``); we just dispatch on the result."""
while not self.stopped.is_set():
self._raise_if_component_stopped()
if self.draining and self.dispatcher.is_idle:
get_logger().info("Pipeline drained, exiting main loop")
self.stopped.set()
break
try:
episode: list[Rollout] = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
item = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
except asyncio.TimeoutError:
self._raise_if_component_stopped()
continue
if isinstance(item, Cancellation):
assert item.kind == "train" # eval groups are never dropped
train_batch = await self.train_sink.cancel(item)
if train_batch is not None and not self.draining and not self.stopped.is_set():
await self.finalize_train_batch(train_batch)
continue
episode = item
# Every completed rollout — errored, rejected, or never batched — lands in the
# ``all`` trace file the moment it arrives, so it survives crashes and drains.
# Train rollouts belong to the batch window currently collecting (``progress.step``),
# eval rollouts to the step whose eval triggered them.
kind = episode[0].kind
step = episode[0].eval_step if kind == "eval" else self.progress.step
assert step is not None
run: vf.RunInfo = (
vf.EvalRunInfo(id=self.run_id, name=self.run_name, step=step)
if kind == "eval"
else vf.TrainRunInfo(id=self.run_id, name=self.run_name, step=step)
)
for rollout in episode:
rollout.record_run(
run,
env_name=rollout.env_name,
group_id=str(rollout.group_id),
episode_id=rollout.episode_id,
policy_version=rollout.policy_version,
)
await monitors.log(group_episodes(episode), step, kind, "all")
if episode.run is None:
raise ValueError("Dispatched episode is missing run identity")
if not isinstance(episode.run, vf.TrainRunInfo):
raise ValueError("Orchestrated episode is missing training-run provenance")
kind = episode.run.work.type
step = episode.run.work.step if kind == "eval" else self.progress.step
await monitors.log([episode], step, kind, "all")
if kind == "eval":
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
@@ -562,6 +604,18 @@ class Orchestrator:
if train_batch is not None and not self.draining and not self.stopped.is_set():
await self.finalize_train_batch(train_batch)
def _raise_if_component_stopped(self) -> None:
"""Propagate unexpected background-component termination to the run."""
for task in self.component_tasks:
if not task.done():
continue
if task.cancelled():
raise RuntimeError(f"{task.get_name()} stopped unexpectedly")
error = task.exception()
if error is not None:
raise error
raise RuntimeError(f"{task.get_name()} exited unexpectedly")
async def finalize_train_batch(self, batch: TrainBatch) -> None:
"""Ship one ``TrainBatch`` out to the trainer and handle the I/O
side-effects (ckpt, monitors.log, reference scoring, sender.send,
@@ -577,20 +631,16 @@ class Orchestrator:
step_time = (now - self.last_batch_at) if self.last_batch_at is not None else 0.0
self.last_batch_at = now
# A resume can start past the end (checkpoint written at the final
# step, or a lowered ``max_steps``): never ship beyond the budget.
if config.max_steps is not None and step > config.max_steps:
self.draining = True
self.dispatcher.disable_train_scheduling()
n_cancelled = await self.dispatcher.cancel_inflight_train_episodes()
get_logger().info(
f"Draining pipeline (cancelled {n_cancelled} in-flight train episode(s); "
f"any in-flight evals will complete)"
)
await self.start_draining(f"Step {step} exceeds max_steps={config.max_steps}")
return
if not batch.samples:
self.consecutive_empty_batches += 1
get_logger().warning(
f"Step {step}: empty train batch after {len(batch.rollouts)} finalized rollouts "
f"Step {step}: empty train batch after {len(batch.episodes)} finalized episodes "
f"(consecutive empty batches: "
f"{self.consecutive_empty_batches}/{MAX_CONSECUTIVE_EMPTY_BATCHES})"
)
@@ -601,20 +651,20 @@ class Orchestrator:
)
return
self.consecutive_empty_batches = 0
effective = batch.rollouts.effective
n_trainable = sum(1 for r in effective if r.is_trainable)
if effective and n_trainable / len(effective) <= 0.1:
effective = batch.cohort.effective
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
if effective.num_traces and n_trainable / effective.num_traces <= 0.1:
get_logger().warning(
f"Only {n_trainable}/{len(effective)} effective rollouts are trainable "
f"({n_trainable / len(effective):.1%}) — consider reviewing task difficulty"
f"Only {n_trainable}/{effective.num_traces} effective traces are trainable "
f"({n_trainable / effective.num_traces:.1%}) — consider reviewing task difficulty"
)
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
# Without this, fast envs fill batches from buffered rollouts, the
# orchestrator finishes early, and its teardown strands the trainer inside
# an in-memory broadcast handshake that needs the live weight watcher.
# Always satisfiable: the trainer skips only the final TARGET_LAG+1
# in-memory broadcasts.
# Without this, fast envs fill batches from buffered rollouts and the
# orchestrator races arbitrarily far ahead of the trainer. Always
# satisfiable: the trainer broadcasts every version except v{max_steps},
# and ``wait_for_final_broadcast`` keeps the watcher alive through the
# last rendezvous after the pipeline drains.
required_version = step - 1 - TARGET_LAG
if self.policy.version < required_version:
get_logger().info(
@@ -629,18 +679,9 @@ class Orchestrator:
await self.version_advanced.wait()
self.wait_for_policy_time += time.perf_counter() - hold_start
# Stamp each rollout's true staleness: batch ``step`` trains on policy
# v{step-1}, so a rollout generated from v{k} is (step-1)-k versions
# off-policy — queue time included, unlike the dispatcher's in-flight
# counter, which only sees weight updates during generation. Frozen-
# sourced rollouts stay 0 (their sampler doesn't follow the policy).
for r in batch.rollouts:
if self.train_envs.get(r.env_name).sampler.samples_from_live_policy:
r.off_policy_steps = (step - 1) - r.policy_version
# The effective (clean, trained-on) subset is logged at ship time; the full arrival
# window already streamed into the ``all`` cohort on arrival.
await monitors.log(group_episodes(effective.rollouts), step, "train", "effective")
await monitors.log(effective.vf_episodes, step, "train", "effective")
pack_start_time = time.perf_counter()
micro_batch_grid = await asyncio.to_thread(self.packer.pack, batch.samples)
@@ -652,10 +693,10 @@ class Orchestrator:
save_ckpt_time = await self.maybe_save_ckpt(step)
trim_process_memory()
# Rollout metrics over the {agg,<env>} × {all,effective} matrix. ``batch.rollouts`` is the
# full arrival window (errored + rejected included); ``.effective`` is the clean subset.
# Episode metrics over the {agg,<env>} × {all,effective} matrix. ``all`` is the
# full arrival window; ``effective`` is the exact shipped cohort.
metrics: dict[str, float] = {}
for subset, pool in (("all", batch.rollouts), ("effective", effective)):
for subset, pool in (("all", batch.episodes), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
for env_name, env_pool in pool.by_env().items():
metrics |= env_pool.metrics.to_wandb(prefix=f"train/{env_name}", subset=subset)
@@ -664,11 +705,11 @@ class Orchestrator:
# objects). ``num_tokens`` is over the full arrival window; the input/output breakdown is over
# the effective (shipped) subset, summing the same ``vf.Trace`` token properties the metric
# matrix reports.
num_tokens = sum(r.num_total_tokens for r in batch.rollouts)
num_input = sum(r.num_input_tokens for r in effective)
num_output = sum(r.num_output_tokens for r in effective)
num_rollouts = len(batch.rollouts)
num_unique_examples = len({r.group_id for r in batch.rollouts})
num_tokens = batch.episodes.num_total_tokens
num_input = sum(record.trace.num_input_tokens for record in effective.records)
num_output = sum(record.trace.num_output_tokens for record in effective.records)
num_rollouts = batch.episodes.num_traces
num_unique_examples = len({episode_group_id(episode) for episode in batch.episodes})
metrics |= {
"progress/tokens": num_tokens,
"progress/input_tokens": num_input,
@@ -684,8 +725,24 @@ class Orchestrator:
"time/wait_for_policy": self.wait_for_policy_time,
"step": step,
}
for env_name, env_pool in batch.rollouts.by_env().items():
metrics[f"batch/{env_name}"] = len(env_pool) / len(batch.rollouts)
# Staleness of the shipped cohort, decomposed into its in-flight and
# in-queue shares; ``dropped`` counts queued traces the sink voided
# since the last ship.
staleness = [episode_staleness(episode, step) for episode in effective]
if staleness:
totals, in_flight, in_queue = (list(values) for values in zip(*staleness))
metrics |= {
"off_policy/mean": sum(totals) / len(totals),
"off_policy/max": float(max(totals)),
"off_policy/in_flight/mean": sum(in_flight) / len(in_flight),
"off_policy/in_flight/max": float(max(in_flight)),
"off_policy/in_queue/mean": sum(in_queue) / len(in_queue),
"off_policy/in_queue/max": float(max(in_queue)),
}
metrics["off_policy/dropped"] = float(self.train_sink.stale_drops)
self.train_sink.stale_drops = 0
for env_name, env_pool in batch.episodes.by_env().items():
metrics[f"batch/{env_name}"] = env_pool.num_traces / batch.episodes.num_traces
metrics |= self.train_source.metrics()
await monitors.log(metrics, step=step)
self.wait_for_policy_time = 0.0
@@ -700,8 +757,25 @@ class Orchestrator:
self.log_train_batch(batch, step=step, step_time=step_time)
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 —
# and with a tight ``max_off_policy_steps`` it never fills at all (the
# versions it would need are never broadcast).
if config.max_steps is not None and step >= config.max_steps:
await self.start_draining("Shipped the final batch")
trim_process_memory()
async def start_draining(self, reason: str) -> None:
"""Stop scheduling train work and let the pipeline empty; triggered
eval epochs still run to completion."""
self.draining = True
self.dispatcher.disable_train_scheduling()
n_cancelled = await self.dispatcher.cancel_inflight_train_episodes()
get_logger().info(
f"{reason} — draining pipeline (cancelled {n_cancelled} in-flight "
f"train episode(s); any in-flight evals will complete)"
)
def maybe_trigger_eval(self, step: int) -> None:
"""Fire eligible eval epochs and flip to ``PREFER_EVAL`` if anything
fires. No-op when eval is not configured."""
@@ -787,66 +861,77 @@ class Orchestrator:
def log_train_batch(self, batch: TrainBatch, *, step: int, step_time: float) -> None:
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
``Error`` is the sink-level rate (errored arrivals / total arrivals, over the full window);
the quality metrics are over the effective (clean, trained-on) subset, as is ``Trainable``."""
rollouts = batch.rollouts
effective = rollouts.effective
Every quality metric (Reward, Trainable, Turns, Branches, Max Off-Policy, Truncation) is
computed over exactly the traces shipped to the trainer this step (``batch.cohort``).
``Error``, ``Cancelled``, and ``Ratio`` are rates over the step's full arrival window —
over the shipped set they are 0/0/share-of-shipped by construction, so the window is the
only scope where they carry signal (and they stay disjoint: a cancellation is a pipeline
decision, not a rollout failure)."""
episodes = batch.episodes
effective = batch.cohort.effective
eff = effective.metrics
n_generated = len(rollouts)
n_effective = len(effective)
n_trainable = sum(1 for r in effective if r.is_trainable)
n_generated = episodes.num_traces
n_effective = effective.num_traces
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
trainable_rate = (n_trainable / n_effective) if n_effective else 0.0
max_off_policy = max((r.off_policy_steps for r in effective), default=0)
max_off_policy_steps = max((episode_staleness(episode, step)[0] for episode in effective), default=0)
head = (
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
f"Trainable {n_trainable}/{n_effective} ({trainable_rate:.1%}) | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max_off_policy} | "
f"Error {rollouts.metrics.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
f"Max Off-Policy {max_off_policy_steps} | "
f"Error {episodes.metrics.has_error.mean():.1%} | Cancelled {episodes.metrics.cancelled.mean():.1%} | "
f"Truncation {eff.is_truncated.mean():.1%}"
)
if len(self.train_envs) <= 1:
get_logger().success(head)
return
by_env = rollouts.by_env()
name_width = max((len(n) for n in by_env), default=0)
window_by_env = episodes.by_env()
shipped_by_env = effective.by_env()
env_names = sorted(set(window_by_env) | set(shipped_by_env))
name_width = max((len(name) for name in env_names), default=0)
lines = [head]
for env_name in sorted(by_env):
pool = by_env[env_name]
env_eff_pool = pool.effective
for env_name in env_names:
pool = window_by_env.get(env_name, TrainEpisodes())
env_eff_pool = shipped_by_env.get(env_name, TrainEpisodes())
env_eff = env_eff_pool.metrics
ratio = (len(pool) / n_generated) if n_generated else 0.0
ratio = (pool.num_traces / n_generated) if n_generated else 0.0
lines.append(
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_eff.reward.mean():.4f} | "
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max((r.off_policy_steps for r in env_eff_pool), default=0)} | "
f"Error {pool.metrics.has_error.mean():.1%} | Truncation {env_eff.is_truncated.mean():.1%}"
f"Max Off-Policy {max((episode_staleness(episode, step)[0] for episode in env_eff_pool), default=0)} | "
f"Error {pool.metrics.has_error.mean():.1%} | Cancelled {pool.metrics.cancelled.mean():.1%} | "
f"Truncation {env_eff.is_truncated.mean():.1%}"
)
get_logger().success("\n\t\t ".join(lines))
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors."""
if not batch.rollouts:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
if not batch.episodes:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no episodes returned, skipping log")
return
# The non-errored subset is logged on epoch completion (multiple eval envs share the
# step's trace file — each epoch appends its cohort once, and every record carries
# ``env_name``); the full returned cohort already streamed into ``all`` on arrival.
await monitors.log(group_episodes(batch.rollouts.effective.rollouts), batch.step, "eval", "effective")
policy_versions = {r.policy_version for r in batch.rollouts}
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
policy_spans = [eval_work(episode).policy for episode in batch.episodes]
if any(span is None for span in policy_spans):
raise ValueError(f"Eval {batch.env_name} step {batch.step} is missing policy provenance")
policy_versions = {span.start for span in policy_spans if span is not None}
policy_version = min(policy_versions)
if len(policy_versions) > 1:
get_logger().warning(
f"Eval {batch.env_name} step {batch.step} had mixed policy versions: {sorted(policy_versions)}"
)
# Rollout metrics over {all,effective} (eval batches are per-env, so no `agg` axis).
# Episode metrics over {all,effective} (eval batches are per-env, so no `agg` axis).
# ``effective`` = non-errored; pass@k / pass^k only over the effective set.
rollouts = batch.rollouts
effective = rollouts.effective
episodes = batch.episodes
effective = episodes.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", rollouts), ("effective", effective)):
for subset, pool in (("all", episodes), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
metrics[f"eval/{batch.env_name}/policy_version"] = float(policy_version)
metrics["step"] = float(batch.step)
@@ -854,7 +939,7 @@ class Orchestrator:
# Success line — quality metrics over the effective set, error rate over the full returned
# cohort. ``Stat.mean()`` is 0.0 for an empty set.
eff, full = effective.metrics, rollouts.metrics
eff, full = effective.metrics, episodes.metrics
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
get_logger().success(
@@ -890,16 +975,9 @@ class Orchestrator:
are 1-indexed while policy versions stay 0-indexed, so the shipped-batch
count is ``progress.step - 1``."""
lead = (self.progress.step - 1) - self.policy.version
# The trainer skips the final in-memory weight broadcasts, so policy.version never
# reaches the last step. Let the final batch through instead of waiting for it.
building_final_batch_without_update = (
self.config.weight_broadcast.type in ("nccl", "nixl")
and self.config.max_steps is not None
and self.progress.step >= self.config.max_steps - 1
)
gate = self.dispatcher.dispatch_allowed
was_set = gate.is_set()
if lead > TARGET_LAG and not building_final_batch_without_update:
if lead > TARGET_LAG:
if was_set:
get_logger().info(
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
@@ -953,7 +1031,7 @@ class Orchestrator:
await self.policy_inference.stop()
if self.train_envs is not None:
for env in self.train_envs:
for pool in (*env.sampler.connected_pools, *env.algorithm.connected_pools):
for pool in (*env.generation_source.connected_pools, *env.algorithm.connected_pools):
await pool.stop()
task = asyncio.create_task(teardown())
+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.transport.types import MicroBatch, TrainingSample
from prime_rl.transports.rollouts.types import MicroBatch, TrainingSample
from prime_rl.utils.logger import get_logger
+253 -197
View File
@@ -1,59 +1,40 @@
"""TrainSink: three-level rollout sink for the training side.
"""Training-side episode, group, and batch assembly.
1. ``process_rollout`` — eager per-rollout tokenization (overlaps with
dispatcher producing more rollouts), then the env algorithm's
``finalize_rollout`` (rollout-local scoring + any reference I/O). Errored
and untrainable rollouts skip this.
2. ``process_group`` — removes errored rollouts, hands the trainable
survivors to the env algorithm's ``finalize_group`` (advantages +
per-sample wire stamping), then asks the source curriculum whether the
result should train.
3. ``process_batch`` — assembles the trainer-bound ``TrainingSample`` list
and optionally removes zero-advantage RL payload.
``add()`` takes one episode (``list[Rollout]``) and returns
``TrainBatch | None``; group accounting counts episodes, never loose traces.
I/O concerns (ship to trainer, monitors.log) live on the
orchestrator.
"""
``add()`` takes one completed episode and ``cancel()`` a dropped group's
``Cancellation``; both return ``TrainBatch | None``. Before every readiness
check the sink sweeps ``pending_batch`` for traces past ``max_off_policy_steps`` —
this sweep, not the dispatcher's in-flight cancel, is what guarantees nothing
stale ships."""
from __future__ import annotations
import asyncio
import uuid
from collections import defaultdict
from collections.abc import Callable
from collections.abc import Callable, Iterable
import verifiers.v1 as vf
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.algo.base import iter_trainable_traces
from prime_rl.orchestrator.algo.routing import stamp_loss_routing
from prime_rl.orchestrator.envs import TrainEnvs
from prime_rl.orchestrator.metrics import TrainRollouts
from prime_rl.orchestrator.metrics import TrainEpisodes
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.orchestrator.types import Rollout, TrainBatch
from prime_rl.transport import TrainingSample
from prime_rl.orchestrator.types import Cancellation, 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.utils.logger import get_logger
MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS = 10
def payload_tokens(rollout: Rollout) -> int:
"""Token cost of the rollout's trainer-bound payload — the samples built by
``process_rollout``. This is what actually ships: forked traces can drop
branches with no trainable tokens, so ``Trace.num_total_tokens`` (which sums
over all branches) may overcount. For linear traces the two agree.
Zero-payload rollouts (no trainable samples at all) fall back to the trace
total so they still advance token batching — a degenerate all-zero-payload
stream then ships empty batches and trips the orchestrator's
consecutive-empty-batch abort instead of stalling the readiness check."""
return sum(len(sample.token_ids) for sample in rollout.samples) or rollout.num_total_tokens
def payload_tokens(samples: list[TrainingSample], trace: vf.Trace | None = None) -> int:
"""Token cost of one trainer-bound trace."""
return sum(len(sample.token_ids) for sample in samples) or (trace.num_total_tokens if trace is not None else 0)
def _prune_zero_advantages(sample: TrainingSample) -> bool:
"""Remove zero-advantage tokens from the RL component.
Return whether the sample still carries any RL, CE, or reference-KL
component and therefore needs to be shipped.
"""
"""Remove zero-advantage tokens from the RL component."""
if sample.advantages is None:
return True
@@ -81,7 +62,7 @@ def _prune_zero_advantages(sample: TrainingSample) -> bool:
class TrainSink:
"""Three-level train sink. Constructed once, fed via ``add(rollout)``."""
"""Score native episodes, admit groups, then compile trainer payloads."""
def __init__(
self,
@@ -90,9 +71,10 @@ 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,
on_result: Callable[[list[Rollout]], bool] | None = None,
on_result: Callable[[list[vf.Episode]], bool] | None = None,
) -> None:
assert (batch_size is None) != (token_batch_size is None), (
"Exactly one of batch_size / token_batch_size must be set"
@@ -101,177 +83,240 @@ class TrainSink:
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
self.on_result = on_result
# Observation window for the next shipped batch: rollouts of groups
# finalized since the last ship (errored + rejected + admitted).
# In-progress groups stay out until they finalize.
self.pending_rollouts: TrainRollouts = TrainRollouts()
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
# isn't unique — the same task can be re-sampled while an
# earlier group is still in flight
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
# Episodes arrived per group — the finalization count (an episode may
# add several traces to ``pending_groups`` but counts once here).
self.pending_group_episodes: dict[uuid.UUID, int] = defaultdict(int)
self.pending_batch: list[Rollout] = []
# Running payload-token total of ``pending_batch`` (token-batched
# runs), kept in sync on append/pop so the readiness check never
# re-sums per arrival.
self.pending_tokens: int = 0
# Finalized work since the most recent positive contribution, measured
# in the active batch unit.
self.zero_output_units: int = 0
self.reported_zero_output_windows: int = 0
self.pending_episodes = TrainEpisodes()
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
# A dropped group's terminal marker; its ``count`` fills in for the
# episodes the group will never deliver.
self.pending_group_cancellations: dict[str, Cancellation] = {}
self.pending_batch: dict[str, list[TrainingSample]] = {}
self.episode_by_trace: dict[str, vf.Episode] = {}
self.pending_tokens = 0
# Queued traces voided by the staleness sweep since the last ship;
# read and reset by the orchestrator's per-step metrics.
self.stale_drops = 0
# Step of the last full staleness sweep — queued traces only age when
# ``progress.step`` advances, so one full sweep per step suffices.
self._swept_step = 0
self.zero_output_units = 0
self.reported_zero_output_windows = 0
def group_size_for(self, env_name: str) -> int:
return self.train_envs.get(env_name).config.group_size
def batch_progress(self) -> tuple[int, int, str]:
"""``(current, target, unit)`` for the train batch — counts only
``pending_batch`` (survivors of finalized groups, queued for the
trainer), so it's an honest 0→target fill. Partial-group arrivals are
reported separately by ``buffered_count()``."""
if self.batch_size is not None:
return len(self.pending_batch), self.batch_size, "rollouts"
return len(self.pending_batch), self.batch_size, "traces"
assert self.token_batch_size is not None
return self.pending_tokens, self.token_batch_size, "tokens"
def buffered_count(self) -> int:
"""Episodes that have arrived but sit in not-yet-complete groups —
buffered in the sink ahead of the batch."""
return sum(self.pending_group_episodes.values())
return sum(len(group) for group in self.pending_groups.values())
def pending_batch_by_env(self) -> dict[str, int]:
"""Per-env breakdown of ``batch_progress()`` (``pending_batch`` only);
values sum to the aggregate."""
counts: dict[str, int] = defaultdict(int)
for r in self.pending_batch:
counts[r.env_name] += 1
for trace_id in self.pending_batch:
episode = self.episode_by_trace[trace_id]
counts[episode_env_name(episode)] += 1
return dict(counts)
async def add(self, episode: list[Rollout]) -> TrainBatch | None:
"""Process one episode arrival; finalize the group on the
``group_size``-th episode; return a ``TrainBatch`` if the finalization
pushed (or left) the batch over its threshold. Arrivals into
still-incomplete groups never ship a batch."""
group_id = episode[0].group_id
env_name = episode[0].env_name
for rollout in episode:
await self.process_rollout(rollout)
self.pending_groups[group_id].extend(episode)
self.pending_group_episodes[group_id] += 1
if self.pending_group_episodes[group_id] < self.group_size_for(env_name):
async def add(self, episode: vf.Episode) -> TrainBatch | None:
"""Process one completed episode and return a batch when ready."""
await self.process_episode(episode)
group_id = episode_group_id(episode)
env_name = episode_env_name(episode)
self.pending_groups[group_id].append(episode)
if not self._group_complete(group_id, env_name):
return None
await self.process_group(group_id)
# ``pending_batch`` only grows on group finalization, so readiness is
# only re-checked here — the window of a shipped batch then always
# contains at least the group that finalized it.
return self._maybe_batch()
async def cancel(self, cancellation: Cancellation) -> TrainBatch | None:
"""Process a dropped group's terminal marker: its ``count`` completes
the group's episode accounting so finalization still fires. A
``stale`` drop also voids the group's already-arrived episodes in
``process_group`` — they share the group's dispatch version, so they
are equally stale."""
self.pending_group_cancellations[cancellation.group_id] = cancellation
if not self._group_complete(cancellation.group_id, cancellation.env_name):
return None
await self.process_group(cancellation.group_id)
return self._maybe_batch()
def _group_complete(self, group_id: str, env_name: str) -> bool:
cancellation = self.pending_group_cancellations.get(group_id)
cancelled = cancellation.count if cancellation is not None else 0
return len(self.pending_groups[group_id]) + cancelled >= self.group_size_for(env_name)
def _maybe_batch(self) -> TrainBatch | None:
"""Sweep stale queued traces, then cut a batch if the survivors still
meet the threshold."""
self._drop_stale()
ready = (
len(self.pending_batch) >= self.batch_size
if self.batch_size is not None
else self.pending_tokens >= (self.token_batch_size or 0)
)
if ready:
return self.process_batch()
return None
return self.process_batch() if ready else None
async def process_rollout(self, rollout: Rollout) -> None:
"""Build training samples from the rollout's Trace (one per branch), walking the
message graph. Training is renderer-only across all modes (RL/OPD student, SFT teacher),
so every node already carries its tokens. Errored rollouts are dropped at the group
level, so skip them here; untrainable traces never become training data."""
if rollout.has_error or not rollout.agent.trainable:
def _drop_stale(self, trace_ids: Iterable[str] | None = None) -> None:
"""Void queued traces past ``max_off_policy_steps``. The batch being
collected is ``progress.step`` and trains policy v{step-1}, so a
queued trace generated from v{k} would ship at staleness
``(step-1) - k``. This sweep is the hard guarantee on trained
staleness; the dispatcher's in-flight cancel only saves compute.
Queued traces only age when ``progress.step`` advances, so the full
sweep runs once per step; ``trace_ids`` scopes the check to a freshly
inserted group, whose traces may already be stale on arrival.
Frozen-sourced episodes (no policy span) never go stale.
A swept trace whose window already shipped is visible only in
``stale_drops`` — its episode was reported with that window, and
re-observing it would double-count its stats."""
if trace_ids is None:
if self._swept_step == self.progress.step:
return
self._swept_step = self.progress.step
trace_ids = list(self.pending_batch)
min_version = min_fresh_version(self.progress.step, self.config.max_off_policy_steps)
if min_version <= 0:
return
samples = await asyncio.to_thread(
trace_to_samples,
rollout,
env_name=rollout.env_name,
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
)
rollout.samples = samples or []
# Arrival phase: rollout-local scoring (raw reward, echo observation
# weighting, opd/opsd reference logprobs) runs as soon as the rollout is
# tokenized — before its group is complete.
await self.train_envs.get(rollout.env_name).algorithm.finalize_rollout(rollout)
async def process_group(self, group_id: uuid.UUID) -> None:
"""Finalize one group, ask its curriculum for admission, and queue it."""
group = self.pending_groups.pop(group_id, [])
self.pending_group_episodes.pop(group_id, None)
if not group:
return
# Window membership follows group finalization, not arrival: a rollout
# only becomes observable (metrics / persistence) once its whole group
# is finalized, so a batch's window never claims rollouts of a group
# that ships later. Dropped groups still land here — they were observed.
for r in group:
self.pending_rollouts.append(r)
env_name = group[0].env_name
task_idx = group[0].task.data.idx
survivors = [r for r in group if not r.has_error]
num_errored = len(group) - len(survivors)
env = self.train_envs.get(env_name)
# Untrainable traces carry no samples and must not skew the group baseline.
survivors = [r for r in survivors if r.agent.trainable]
if not survivors:
self._admit(group)
self._record_zero_output(group)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"rollouts={len(group)} (errored={num_errored}) | dropped: no trainable survivors"
)
return
# Advantages + per-sample wire stamping (advantage stream, loss
# routing) are the algorithm's job (finalize_group); the sink only
# owns the grouping mechanics.
await env.algorithm.finalize_group(survivors)
# The env has a single sampling temperature; fan it out per token
# (context tokens are masked out, so their temperature is don't-care).
temperature = env.sampling_args["temperature"]
for r in survivors:
for sample in r.samples:
sample.temperatures = [temperature] * len(sample.token_ids)
if not self._admit(group):
self._record_zero_output(group)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"rollouts={len(group)} (errored={num_errored}) | rejected by curriculum"
)
return
for r in survivors:
self.pending_batch.append(r)
dropped = 0
for trace_id in trace_ids:
episode = self.episode_by_trace[trace_id]
policy = train_work(episode).policy
if policy is None or policy.start >= min_version:
continue
samples = self.pending_batch.pop(trace_id)
if self.token_batch_size is not None:
self.pending_tokens += payload_tokens(r)
self.pending_tokens -= payload_tokens(samples, self._trace(trace_id))
del self.episode_by_trace[trace_id]
self.pending_episodes.cancelled.add(episode.id)
dropped += 1
if dropped:
self.stale_drops += dropped
get_logger().warning(
f"Dropped {dropped} queued traces past max_off_policy_steps={self.config.max_off_policy_steps}. "
"Consider increasing it to avoid this."
)
async def process_episode(self, episode: vf.Episode) -> None:
"""Run rollout-local algorithm work on one native episode."""
env_name = episode_env_name(episode)
await self.train_envs.get(env_name).algorithm.finalize_episode(episode)
async def process_group(self, group_id: str) -> None:
group = self.pending_groups.pop(group_id, [])
cancellation = self.pending_group_cancellations.pop(group_id, None)
if not group and cancellation is None:
return
env_name = episode_env_name(group[0]) if group else cancellation.env_name
env = self.train_envs.get(env_name)
traces = [trace for episode in group for trace in episode.traces]
task_idx = next((trace.task.data.idx for trace in traces), None)
num_errored = sum(trace.has_error for trace in traces) + sum(
not episode.ok for episode in group if not episode.traces
)
n_owed = len(group) + (cancellation.count if cancellation is not None else 0)
# A stale drop voids the whole group: every member shares the dispatch
# version, so the arrived episodes are exactly as stale as the
# cancelled tail. Stale groups bypass the curriculum — a pipeline
# decision is not a task result.
if cancellation is not None and cancellation.reason == "stale":
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)"
)
return
survivors = [trace for _, trace in iter_trainable_traces(group)]
if survivors:
await env.algorithm.finalize_group(group)
admitted = self._admit(group) if group else False
if not survivors or not admitted:
self.pending_episodes.extend(group, admitted=admitted)
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}"
)
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,
)
for sample in samples:
sample.temperatures = [temperature] * len(sample.token_ids)
stamp_loss_routing(sample, env.algorithm.action_loss_type)
if samples:
samples_by_trace[trace.id] = samples
self.pending_episodes.extend(group, sampled_trace_ids=set(samples_by_trace), admitted=True)
if not samples_by_trace:
self._record_zero_output(group, survivors, n_owed)
return
self.pending_batch.update(samples_by_trace)
for episode in group:
for trace in episode.traces:
if trace.id in samples_by_trace:
self.episode_by_trace[trace.id] = episode
if self.token_batch_size is not None:
self.pending_tokens += sum(
payload_tokens(samples, self._trace(trace_id)) for trace_id, samples in samples_by_trace.items()
)
self._drop_stale(samples_by_trace)
# A group's traces share one dispatch version, so the insertion sweep
# voids all or none of them. A fully-voided group shipped nothing —
# advance the zero-output budget instead of resetting it, or a stalled
# trainer plus a tight bound could void groups forever without ever
# tripping the abort.
if not any(trace_id in self.pending_batch for trace_id in samples_by_trace):
self._record_zero_output(group, [], n_owed)
return
self.zero_output_units = 0
self.reported_zero_output_windows = 0
rewards = [r.reward for r in survivors]
avg_reward = sum(rewards) / len(rewards) if rewards else 0.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"rollouts={len(group)} (errored={num_errored}) | reward={avg_reward:.4f}"
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reward={avg_reward:.4f}"
)
def _admit(self, group: list[Rollout]) -> bool:
admitted = self.on_result(group) if self.on_result is not None else True
for rollout in group:
rollout.is_admitted = admitted
return admitted
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)
def _record_zero_output(self, group: list[Rollout]) -> None:
def _admit(self, group: list[vf.Episode]) -> bool:
return self.on_result(group) if self.on_result is not None else True
def _record_zero_output(self, group: list[vf.Episode], survivors: list[vf.Trace], n_owed: int) -> None:
"""``n_owed`` counts the group's full episode budget (arrived +
cancelled), so dropped groups advance the zero-output budget at the
same rate as fully-delivered ones."""
if self.batch_size is not None:
self.zero_output_units += len(group)
returned_traces = sum(len(episode.traces) for episode in group)
self.zero_output_units += len(survivors) or returned_traces or n_owed
else:
payload = sum(payload_tokens(rollout) for rollout in group)
self.zero_output_units += payload or self.config.seq_len * len(group)
survivor_tokens = sum(trace.num_total_tokens for trace in survivors)
episode_tokens = sum(episode.num_total_tokens for episode in group)
self.zero_output_units += survivor_tokens or episode_tokens or self.config.seq_len * n_owed
self._check_zero_output_budget()
def _check_zero_output_budget(self) -> None:
@@ -289,42 +334,53 @@ class TrainSink:
if windows >= MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS:
raise RuntimeError(
f"{windows} consecutive zero-output batch equivalents — "
"check the curriculum admission policy and task difficulty."
"check the curriculum admission policy, task difficulty, and staleness drops."
)
def process_batch(self) -> TrainBatch:
"""Pop a cohort off ``pending_batch`` (by rollout count when
``batch_size`` is set, by token count when ``token_batch_size`` is
set), and assemble the trainer-bound ``TrainingSample`` list. Overflow
stays for the next batch."""
items = list(self.pending_batch.items())
if self.batch_size is not None:
cohort = self.pending_batch[: self.batch_size]
self.pending_batch = self.pending_batch[self.batch_size :]
selected = items[: self.batch_size]
else:
assert self.token_batch_size is not None
cut = 0
running = 0
for i, r in enumerate(self.pending_batch):
running += payload_tokens(r)
cut = i + 1
for index, (trace_id, samples) in enumerate(items):
running += payload_tokens(samples, self._trace(trace_id))
cut = index + 1
if running >= self.token_batch_size:
break
cohort = self.pending_batch[:cut]
self.pending_batch = self.pending_batch[cut:]
selected = items[:cut]
self.pending_tokens -= running
if self.config.train.filter_zero_advantages:
for rollout in cohort:
rollout.samples = [sample for sample in rollout.samples if _prune_zero_advantages(sample)]
samples: list[TrainingSample] = [sample for rollout in cohort for sample in rollout.samples]
selected_by_trace = dict(selected)
selected_ids = set(selected_by_trace)
for trace_id in selected_ids:
del self.pending_batch[trace_id]
# ``rollouts`` is the observation window — every rollout of every group finalized since the
# last ship (errored + rejected + admitted) — while ``samples`` is the shipped cohort's
# trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive the clean subset +
# metric views on demand. Reset the window only when the batch actually ships (non-empty
# samples) — an empty batch is dropped unlogged by the orchestrator, so keep accumulating its
# finalized groups (and any overflow) into the next shipped batch's window.
rollouts = self.pending_rollouts
if self.config.train.filter_zero_advantages:
selected_by_trace = {
trace_id: [sample for sample in samples if _prune_zero_advantages(sample)]
for trace_id, samples in selected
}
selected_by_trace = {trace_id: samples for trace_id, samples in selected_by_trace.items() if samples}
samples = [sample for trace_samples in selected_by_trace.values() for sample in trace_samples]
shipped_ids = set(selected_by_trace)
traces_by_episode: dict[int, list[vf.Trace]] = defaultdict(list)
selected_episodes: dict[int, vf.Episode] = {}
for trace_id in selected_ids:
episode = self.episode_by_trace.pop(trace_id)
if trace_id in shipped_ids:
selected_episodes[id(episode)] = episode
traces_by_episode[id(episode)].extend(trace for trace in episode.traces if trace.id == trace_id)
cohort_episodes = [
episode.model_copy(update={"traces": traces_by_episode[id(episode)]})
for episode in selected_episodes.values()
]
cohort = TrainEpisodes(cohort_episodes, sampled_trace_ids=shipped_ids)
episodes = self.pending_episodes
if samples:
self.pending_rollouts = TrainRollouts()
return TrainBatch(rollouts=rollouts, samples=samples)
self.pending_episodes = TrainEpisodes()
return TrainBatch(episodes=episodes, cohort=cohort, samples=samples)
+17 -10
View File
@@ -4,13 +4,13 @@ from __future__ import annotations
import random
from collections import defaultdict
from typing import TYPE_CHECKING, Any
from typing import Any
import verifiers.v1 as vf
from prime_rl.orchestrator.curriculum import Curriculum
from prime_rl.orchestrator.envs import TrainEnvs
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
from prime_rl.orchestrator.utils import episode_env_name
class TrainSource:
@@ -41,11 +41,11 @@ class TrainSource:
"task": next(self.curricula[env_name].sampler),
}
def on_result(self, group: list[Rollout]) -> bool:
def on_result(self, group: list[vf.Episode]) -> bool:
"""Report a finalized group and return whether it should train."""
if not group:
raise ValueError("Cannot report an empty rollout group")
env_name = group[0].env_name
env_name = episode_env_name(group[0])
admitted = self.curricula[env_name].on_result(group)
if not isinstance(admitted, bool):
raise TypeError(f"Curriculum.on_result() must return bool, got {type(admitted).__name__}")
@@ -73,8 +73,15 @@ class TrainSource:
}
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
expected_fields = {"rng", "envs"}
if set(state_dict) != expected_fields:
raise ValueError(f"Train-source checkpoint fields must be {sorted(expected_fields)}")
env_states = state_dict["envs"]
if set(env_states) != set(self.curricula):
raise ValueError(
f"Train-source checkpoint envs {sorted(env_states)} do not match configured envs "
f"{sorted(self.curricula)}"
)
self.rng.setstate(state_dict["rng"])
for name, curriculum_state in state_dict["envs"].items():
curriculum = self.curricula.get(name)
if curriculum is not None:
curriculum.load_state_dict(curriculum_state)
for name, curriculum in self.curricula.items():
curriculum.load_state_dict(env_states[name])
+28 -3
View File
@@ -20,8 +20,8 @@ from collections.abc import Iterator
import numpy as np
import verifiers.v1 as vf
from prime_rl.transport import TrainingSample
from prime_rl.transport.types import EncodedTensor, RoutedExperts
from prime_rl.transports.rollouts import TrainingSample
from prime_rl.transports.rollouts.types import EncodedTensor, RoutedExperts
from prime_rl.utils.logger import get_logger
@@ -89,6 +89,25 @@ def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[b
yield branch, mask
def _loss_weights(branch: vf.Branch, name: str, trained_nodes: set[int]) -> list[float] | None:
"""Flatten one graph-native loss stream, training each shared node once."""
weights: list[float] = []
for node in branch.nodes:
node_weights = (node.loss_weights or {}).get(name)
if node_weights is None or id(node) in trained_nodes:
weights.extend([0.0] * len(node.token_ids))
continue
if len(node_weights) != len(node.token_ids):
raise ValueError(
f"loss weight stream {name!r} must align with node token_ids: "
f"got {len(node_weights)}, expected {len(node.token_ids)}"
)
weights.extend(node_weights)
if any(node_weights):
trained_nodes.add(id(node))
return weights if any(weights) else None
def trace_to_samples(
trace: vf.Trace,
*,
@@ -100,13 +119,14 @@ def trace_to_samples(
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
`branch.sampled_mask` / `branch.logprobs`), so a sample carries it directly: `mask` marks
the trainable (model-sampled) tokens, the context tokens between completions stay masked
out. Errored rollouts are dropped upstream (`TrainSink.process_rollout`), so no error
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.
"""
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
@@ -123,9 +143,14 @@ def trace_to_samples(
logprobs=branch.logprobs,
temperatures=[], # filled by TrainSink.process_group
env_name=env_name,
ref_logprobs=branch.reference_logprobs,
mm_kwargs=mm_kwargs,
mm_token_type_ids=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"]),
ref_kl_weights=_loss_weights(branch, "ref_kl", trained_loss_nodes["ref_kl"]),
advantages=branch.advantages,
)
)
if not samples:
+33 -89
View File
@@ -1,19 +1,17 @@
"""Shared dataclasses for the orchestrator. Data carriers only; no behavior."""
"""Shared orchestrator data carriers."""
from __future__ import annotations
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING, Generic, Literal, Protocol
from typing import TYPE_CHECKING, Literal, Protocol
import verifiers.v1 as vf
from pydantic import ConfigDict, Field
from verifiers.v1.task import DataT
from prime_rl.transport import TrainingSample
from prime_rl.transports.rollouts import TrainingSample
if TYPE_CHECKING:
from prime_rl.orchestrator.metrics import EvalRollouts, TrainRollouts
from prime_rl.orchestrator.metrics import EvalEpisodes, TrainEpisodes
@dataclass
@@ -35,20 +33,36 @@ class Progress:
total_problems: int = 0
RolloutKind = Literal["train", "eval"]
WorkKind = Literal["train", "eval"]
CancelReason = Literal["stale", "overload"]
@dataclass
class Cancellation:
"""Terminal marker for a dropped group: one message covering every episode
the group still owed the sink (in-flight and never-dispatched), so
count-to-``group_size`` finalization still fires. ``reason`` distinguishes
pipeline decisions (staleness, overload cut) from episode errors."""
kind: WorkKind
env_name: str
group_id: str
count: int
reason: CancelReason
@dataclass
class InflightEpisode:
"""Per-task scheduling state in the dispatcher; one entry per in-flight
``run`` task."""
"""Scheduling state for one in-flight environment run."""
kind: RolloutKind
kind: WorkKind
env_name: str
group_id: uuid.UUID
task: vf.Task
policy_version: int
step: int
client_config: vf.ClientConfig | None = None
off_policy_steps: int = 0
eval_step: int | None = None
started_at: float = 0.0
"""``time.monotonic()`` at dispatch; feeds episode-duration estimates."""
@@ -59,105 +73,35 @@ class GroupState:
"""Per-group dispatcher state: what's left to schedule + the pinned
client (for prefix-cache hits)."""
kind: RolloutKind
kind: WorkKind
env_name: str
task: vf.Task
"""The group's task — its data is shipped on every dispatch."""
rollouts_to_schedule: int
target_rollouts: int
episodes_to_schedule: int
target_episodes: int
emitted: int = 0
eval_step: int | None = None
pinned_client: vf.ClientConfig | None = None
policy_version_at_start: int = 0
class Rollout(vf.Trace[DataT], Generic[DataT]):
"""A completed rollout: the env's typed ``vf.Trace`` *is* the rollout — prime-rl's
orchestration metadata lives on it directly (set by the dispatcher once the rollout
returns), so there's no wrapper. Train vs eval is the ``kind`` discriminator. All metadata
fields are ``exclude=True``, so dumping a Rollout yields a plain trace on the wire; the
orchestrator mirrors them onto the trace's own fields via ``vf.Trace.record_run`` (``kind`` as
``run.type``, the run id, the step, and ``env_name``/``group_id``/``policy_version`` into
``info``) when a rollout arrives, so the on-disk records stay fully placeable.
It is also the single currency the scoring hooks receive: a hook reads the trace
directly (``rollout.reward``, ``rollout.nodes``, ``rollout.num_turns``) and writes
credit through :meth:`assign_advantages` (scalar broadcast or per-token), which
spreads over the samples' trainable (mask-True) tokens."""
model_config = ConfigDict(arbitrary_types_allowed=True) # ``samples`` holds msgspec structs
kind: RolloutKind = Field(default="train", exclude=True)
env_name: str = Field(default="", exclude=True)
group_id: uuid.UUID = Field(default_factory=uuid.uuid4, exclude=True)
# Links the traces of one episode; stamped into ``info`` on arrival so
# saved records keep their grouping.
episode_id: str = Field(default="", exclude=True)
policy_version: int = Field(default=0, exclude=True)
off_policy_steps: int = Field(default=0, exclude=True)
samples: list[TrainingSample] = Field(default_factory=list, exclude=True)
# Per-token rl advantage stream, full-length-N (= len(token_ids)) per
# sample, concatenated across the rollout's samples in order; 0.0 on
# non-trainable positions. None means no credit was assigned.
advantages: list[float] | None = Field(default=None, exclude=True)
is_admitted: bool = Field(default=True, exclude=True)
eval_step: int | None = Field(default=None, exclude=True)
def assign_advantages(self, values: float | list[float]) -> None:
"""Write the rl advantage stream: a scalar broadcast over the
rollout's trainable (mask-True) tokens (0.0 elsewhere), or a per-token
list already aligned full-length to the samples' concatenated
``token_ids``. A rollout never assigned ships no advantage stream."""
total = sum(len(sample.token_ids) for sample in self.samples)
if isinstance(values, (int, float)):
self.advantages = [
float(values) if trainable else 0.0 for sample in self.samples for trainable in sample.mask
]
return
if len(values) != total:
raise ValueError(
f"per-token advantages must align with the rollout's tokens: "
f"got {len(values)}, expected {total} (env '{self.env_name}')."
)
self.advantages = [float(v) for v in values]
def scalar_advantage(self) -> float | None:
"""Scalar view of the per-token advantage stream for monitoring: the
mean over assigned (non-zero) positions — exact for the uniform GRPO
case, 0.0 for a zero-advantage group, None when no credit was assigned."""
if not self.advantages:
return None
nonzero = [a for a in self.advantages if a != 0.0]
return sum(nonzero) / len(nonzero) if nonzero else 0.0
@property
def is_trainable(self) -> bool:
"""Whether the rollout carries a training signal — a nonzero advantage on some token. A
uniform-reward GRPO group (all-zero advantages) or an unscored rollout has no gradient."""
return bool(self.advantages) and any(a != 0.0 for a in self.advantages)
@dataclass
class TrainBatch:
"""``rollouts`` is the observation window since the last ship — every rollout of every group
finalized in that span (errored + rejected included; rollouts of still-incomplete groups wait
for a later window). Its ``.effective`` / ``.metrics`` views drive logging. ``samples`` is the
trainer-bound payload from the admitted cohort — an empty list means nothing
ships, which would stall the trainer. Trainable counts derive from ``rollouts.effective``
(``r.is_trainable``) and token totals from ``samples``, so neither is carried as a field."""
"""Observation and shipped-cohort reports plus the trainer payload."""
rollouts: TrainRollouts
episodes: TrainEpisodes
cohort: TrainEpisodes
samples: list[TrainingSample]
@dataclass
class EvalBatch:
"""One env's eval epoch. ``rollouts`` is the full returned cohort (errored included); its
"""One env's eval epoch. ``episodes`` is the full returned cohort (errored included); its
``.effective`` / ``.metrics`` views drive logging."""
env_name: str
step: int
rollouts: EvalRollouts
episodes: EvalEpisodes
class VersionObserver(Protocol):
+50 -22
View File
@@ -6,10 +6,9 @@ import math
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
import verifiers.v1 as vf
from verifiers.v1.episode import EnvInfo
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.utils.client import InferencePool
@@ -20,8 +19,55 @@ from prime_rl.utils.utils import (
get_step_path,
)
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
def episode_env_name(episode: vf.Episode[Any, Any, Any]) -> str:
name = episode.env.name
if name is None:
raise ValueError("Orchestrated episode is missing its environment name")
return name
def episode_group_id(episode: vf.Episode[Any, Any, Any]) -> str:
group = episode.group
if group is None:
raise ValueError("Orchestrated episode is missing its rollout group")
return group.id
def train_work(episode: vf.Episode[Any, Any, Any]) -> vf.TrainWorkInfo:
run = episode.run
if not isinstance(run, vf.TrainRunInfo) or not isinstance(run.work, vf.TrainWorkInfo):
raise ValueError("Train episode is missing training-work provenance")
return run.work
def eval_work(episode: vf.Episode[Any, Any, Any]) -> vf.EvalWorkInfo:
run = episode.run
if not isinstance(run, vf.TrainRunInfo) or not isinstance(run.work, vf.EvalWorkInfo):
raise ValueError("Eval episode is missing evaluation-work provenance")
return run.work
def min_fresh_version(step: int, max_off_policy_steps: int) -> int:
"""Oldest dispatch version whose episodes may still train in batch
``step`` — anything older would ship past ``max_off_policy_steps``."""
return (step - 1) - max_off_policy_steps
def episode_staleness(episode: vf.Episode[Any, Any, Any], training_step: int) -> tuple[int, int, int]:
"""``(total, in_flight, in_queue)`` staleness of one train episode when
consumed by batch ``training_step``: the version the batch trains on
(v{step-1}) minus the version that generated the episode. ``in_flight``
is the span's share (weight updates during generation); ``in_queue`` is
time spent buffered between completion and ship. Frozen-sourced episodes
(no policy span) are never stale."""
policy = train_work(episode).policy
if policy is None:
return 0, 0, 0
total = max(0, (training_step - 1) - policy.start)
in_flight = min(total, max(0, policy.end - policy.start))
in_queue = total - in_flight
return total, in_flight, in_queue
async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
@@ -54,24 +100,6 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
return renderer, inference_pool
def group_episodes(rollouts: "list[Rollout]") -> list[vf.Episode]:
"""Regroup rollouts into their episodes. The dispatcher unwraps every
``vf.Episode`` into its traces on arrival; ``episode_id`` links them back
together (a rollout without one forms a single-trace episode)."""
groups: dict[str, list] = {}
for rollout in rollouts:
groups.setdefault(rollout.episode_id or rollout.id, []).append(rollout)
return [
vf.Episode(
id=episode_id,
env=EnvInfo(id=group[0].env_name),
traces=group,
ok=all(trace.ok for trace in group),
)
for episode_id, group in groups.items()
]
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
"""Intercepts verifiers logging and routes through prime-rl logger with optional prefix."""
vf_logger = logging.getLogger(logger)
+5 -4
View File
@@ -1,5 +1,5 @@
"""WeightWatcher: polls the broadcast dir, advances ``Policy``, notifies
observers (dispatcher → off-policy cancel). Standalone async task; the
observers (dispatcher → staleness cancel). Standalone async task; the
orchestrator's barrier bounds the in-flight lead."""
from __future__ import annotations
@@ -11,7 +11,7 @@ from modelexpress import p2p_pb2
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.types import Policy, VersionObserver
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
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
@@ -77,7 +77,8 @@ class WeightWatcher:
def compute_next_ckpt_step(self) -> int:
"""Return the next policy version exposed by the configured transport."""
if self.model_express is not None:
if self.config.max_steps is not None and self.ckpt_step >= self.config.max_steps - 2:
# 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.
@@ -116,7 +117,7 @@ class WeightWatcher:
self.ckpt_step = next_step
self.policy.version = next_step
# Drain off-policy rollouts BEFORE pausing the inference engines.
# Drain stale rollouts BEFORE pausing the inference engines.
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
# ``_reqs_not_processed``), which is only propagated to the workers
# while the engine is stepping. If we drain after resume instead,
@@ -42,15 +42,15 @@ ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
{% if prl_run_id %}
# Trainer and evaluator (separate SLURM job) log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evaluator (which
# Trainer and evals (separate SLURM job) log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
# outlives the trainer) finalizes it.
export PRL_RUN_ID={{ prl_run_id }}
export PRL_RUN_NAME={{ run_name }}
export WANDB_RUN_ID=$PRL_RUN_ID
export WANDB_SHARED_MODE=1
export WANDB_SHARED_PRIMARY=trainer
export WANDB_SHARED_FINISHER=evaluator
export WANDB_SHARED_FINISHER=evals
export WANDB_SHARED_LABEL=trainer
export WANDB_PROGRAM="uv run sft"
{% endif %}
@@ -62,6 +62,11 @@ export MASTER_ADDR="${HOSTNAMES[0]}"
export MASTER_PORT=29500
echo "MASTER_ADDR=${MASTER_ADDR}"
echo "MASTER_PORT=${MASTER_PORT}"
{% if use_nccl_broadcast %}
# The eval job has a separate allocation. Publish the trainer's NCCL host through
# the shared run directory under this job ID.
printf '%s\n' "$MASTER_ADDR" > "$OUTPUT_DIR/.sft_nccl_host_$SLURM_JOB_ID"
{% endif %}
# Install environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
@@ -155,5 +160,8 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
--local-ranks-filter={{ ranks_filter }} \
-m prime_rl.trainer.sft.train \
@ $CONFIG_PATH \
{%- if use_nccl_broadcast %}
--weight-broadcast.host 0.0.0.0 \
{%- endif %}
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
LAUNCH_SH
@@ -22,10 +22,9 @@
#SBATCH --error={{ output_dir }}/eval_job_%j.log
# Online-eval job for a decoupled SFT run: the inference pool (one vLLM engine per
# DP rank behind a single router) plus the evaluator and its env servers. The trainer
# runs in a separate SLURM job and hands weights over via checkpoints on the shared
# filesystem, so this job outlives the trainer and exits after evaluating the final
# checkpoint (max_steps).
# DP rank behind a single router) plus the evals process and its env servers. The trainer
# runs in a separate SLURM job. This job exits after evaluating the final weight
# broadcast (max_steps).
# Exit immediately on any failed command so a crash anywhere releases the
# allocation instead of leaving zombie processes holding nodes.
@@ -50,27 +49,35 @@ export OUTPUT_DIR={{ output_dir }}
mkdir -p $OUTPUT_DIR/logs/inference
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
# A clean evaluator exit cannot trip srun --kill-on-bad-exit (which only propagates
# A clean evals exit cannot trip srun --kill-on-bad-exit (which only propagates
# failures), so node 0 publishes completion through this job-scoped sentinel and the
# other nodes watch for it to release their engines. Stale sentinels from other job
# IDs are inert, so only this job's own path needs clearing.
export EVAL_DONE=$OUTPUT_DIR/.eval_done_$SLURM_JOB_ID
rm -f "$EVAL_DONE"
{% if prl_run_id %}
# Trainer (separate SLURM job) and evaluator log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evaluator (which
# Trainer (separate SLURM job) and evals log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
# outlives the trainer) finalizes it.
export PRL_RUN_ID={{ prl_run_id }}
export PRL_RUN_NAME={{ run_name }}
export WANDB_RUN_ID=$PRL_RUN_ID
export WANDB_SHARED_MODE=1
export WANDB_SHARED_PRIMARY=trainer
export WANDB_SHARED_FINISHER=evaluator
export WANDB_SHARED_FINISHER=evals
export WANDB_PROGRAM="uv run sft"
{% endif %}
# Networking
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
export HOSTNAMES_STR="${HOSTNAMES[*]}"
{% if use_nccl_broadcast %}
: "${TRAIN_JOB_ID:?TRAIN_JOB_ID is required for NCCL weight broadcast}"
TRAIN_HOST_FILE="$OUTPUT_DIR/.sft_nccl_host_$TRAIN_JOB_ID"
until [ -s "$TRAIN_HOST_FILE" ]; do sleep 1; done
export TRAIN_HOST=$(<"$TRAIN_HOST_FILE")
rm -f "$TRAIN_HOST_FILE"
echo "TRAIN_HOST=${TRAIN_HOST}"
{% endif %}
# Single global router on node 0 fronts every per-rank endpoint; admin ops
# (pause/update_weights/resume) bypass it and hit each rank directly.
@@ -139,7 +146,7 @@ CLEANUP_SH
# Run the eval deployment
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a crashed engine/router/evaluator terminates the SLURM job instead
# tasks so a crashed engine/router/evals terminates the SLURM job instead
# of leaving the surviving ranks holding nodes.
#
# The body goes to bash on stdin through a quoted heredoc instead of a
@@ -204,9 +211,9 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
{%- if eval_env_names %}
# One env server per eval source next to the evaluator, which connects to each
# One env server per eval source next to the evals process, which connects to each
# source at its deterministic loopback address (so this node), polling until
# they are up - the servers and the evaluator start in parallel.
# they are up - the servers and the evals process start in parallel.
{%- for name in eval_env_names %}
mkdir -p $OUTPUT_DIR/logs/envs/eval
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.json \
@@ -214,30 +221,33 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
{%- endfor %}
{%- endif %}
# The evaluator watches the trainer's weights dir on the shared filesystem and
# drives the pool: data plane through the router, admin ops per rank.
{%- for key, value in evaluator_env_vars.items() %}
# The evals process watches trainer broadcast markers and drives the pool:
# data plane through the router, admin ops per rank.
{%- for key, value in evals_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
WANDB_SHARED_LABEL=evaluator uv run evaluator \
@ $CONFIG_DIR/evaluator.json \
WANDB_SHARED_LABEL=evals uv run evals \
@ $CONFIG_DIR/evals.json \
--eval.client.base-url $INFER_URLS \
--eval.client.admin-base-url $ADMIN_URLS \
2>&1 | tee $OUTPUT_DIR/logs/evaluator.log &
EVALUATOR_PID=$!
{%- if use_nccl_broadcast %}
--weight-broadcast.host $TRAIN_HOST \
{%- endif %}
2>&1 | tee $OUTPUT_DIR/logs/evals.log &
EVALS_PID=$!
else
# Watch for the completion sentinel so this node's wait below returns when
# the evaluator (on node 0) finishes cleanly.
# the evals process (on node 0) finishes cleanly.
( until [ -f "$EVAL_DONE" ]; do sleep 10; done ) &
fi
# Wait for the first background job to exit and propagate its exit code. This
# turns background process crashes (engines, router, env servers, evaluator)
# turns background process crashes (engines, router, env servers, evals)
# into task failures that --kill-on-bad-exit=1 can broadcast to the other nodes
# so the whole job tears down instead of leaving zombies holding the allocation.
wait -n -p FINISHED_PID
EXIT_CODE=$?
if [ "${FINISHED_PID:-}" = "${EVALUATOR_PID:-none}" ]; then
if [ "${FINISHED_PID:-}" = "${EVALS_PID:-none}" ]; then
# Publish completion so the sentinel watchers on the other nodes release too
# (a zero exit here never trips --kill-on-bad-exit).
touch "$EVAL_DONE"
+1 -1
View File
@@ -6,7 +6,7 @@ from typing import Any
import numpy as np
from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
from prime_rl.transports.rollouts.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
+6 -239
View File
@@ -2,37 +2,27 @@ import bisect
import gc
import shutil
import time
import warnings
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
import torch
from torch import Tensor, nn
from torch import nn
from torch.distributed.checkpoint.state_dict import get_state_dict, set_model_state_dict, set_state_dict
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
from torch.distributed.checkpoint.state_dict_saver import save as dcp_save
from torch.distributed.checkpoint.stateful import Stateful
from torch.distributed.tensor import DTensor
from torch.nn import Module
from torch.optim.lr_scheduler import LRScheduler
from torch.optim.optimizer import Optimizer
from torchdata.stateful_dataloader import StatefulDataLoader
from transformers.processing_utils import ProcessorMixin
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.configs.shared import ResumeConfig
from prime_rl.configs.trainer import CheckpointConfig, LoRAConfig, WeightCheckpointConfig
from prime_rl.trainer.lora import get_lora_state, has_lora_layers, save_lora_config
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.configs.trainer import CheckpointConfig
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
from prime_rl.trainer.weights import (
gather_weights_on_master,
save_state_dict,
)
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path, get_weights_dir
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path
@dataclass
@@ -174,12 +164,6 @@ class CheckpointManager:
"""Get the path to write the trainer checkpoint for a given step."""
return get_step_path(self.ckpt_dir, step) / "trainer"
def mark_stable(self, step: int) -> None:
"""Write STABLE file to indicate checkpoint is complete (for eval to safely read)."""
if self.world.is_master:
step_path = get_step_path(self.ckpt_dir, step)
(step_path / "STABLE").touch()
def save_to_path(
self,
path: Path,
@@ -322,229 +306,12 @@ class CheckpointManager:
self.ckpt_steps = [step for step in self.ckpt_steps if step in steps_to_keep]
class WeightCheckpointManager:
"""Utility class to save HF-compatible weight checkpoints."""
def __init__(
self,
output_dir: Path,
config: WeightCheckpointConfig,
lora_config: LoRAConfig | None = None,
save_async: bool = False,
keep_last: int | None = None,
keep_interval: int | None = None,
resume: ResumeConfig | None = None,
):
self.weights_dir = get_weights_dir(output_dir)
self.config = config
self.lora_config = lora_config
self.logger = get_logger()
self.world = get_world()
if self.world.is_master:
all_steps = get_all_ckpt_steps(self.weights_dir)
if resume is not None and resume.step is not None:
self.ckpt_steps = [s for s in all_steps if s <= resume.step]
else:
self.ckpt_steps = all_steps
else:
self.ckpt_steps = []
self.keep_last = keep_last
self.keep_interval = keep_interval
def get_step_path(self, step: int) -> Path:
"""Get the path to write the weight checkpoint for a given step."""
return get_step_path(self.weights_dir, step)
def mark_stable(self, step: int) -> None:
"""Write STABLE file to indicate weight checkpoint is complete."""
if self.world.is_master:
step_path = self.get_step_path(step)
(step_path / "STABLE").touch()
def get_run_adapter_state_dict(self) -> dict[str, Tensor]:
lora_state_dict = {
f"base_model.model.{key}": (value.full_tensor() if isinstance(value, DTensor) else value).to(
"cpu", non_blocking=False
)
for key, value in get_lora_state().adapter_state_dict().items()
}
if not lora_state_dict:
raise ValueError("The LoRA state dict is empty. Something went wrong.")
return lora_state_dict
def save_to_path(
self,
path: Path,
state_dict: dict[str, Tensor],
lora_state_dict: dict[str, Tensor] | None,
model,
tokenizer: PreTrainedTokenizer,
processor: ProcessorMixin | None = None,
):
"""Save HF-compatible weight checkpoint to a given path."""
if self.world.is_master:
path.mkdir(parents=True, exist_ok=True)
start_time = time.perf_counter()
self.logger.debug(f"Saving weight checkpoint to {path}")
# Suppress torch.distributed warnings during checkpoint saving
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.distributed")
warnings.filterwarnings("ignore", category=UserWarning, module="torch.distributed.*")
# Save weights
save_state_dict(state_dict, path, self.config.save_format, self.config.save_sharded)
# Save model config, generation arguments and tokenizer
model.config.save_pretrained(path)
if model.generation_config:
# training sets use_cache=False which can conflict with
# cache_implementation — save with use_cache=True without
# mutating the model's config
from copy import deepcopy
gen_config = deepcopy(model.generation_config)
gen_config.use_cache = True
gen_config.save_pretrained(path)
# Processor first: it saves its own (unmodified) tokenizer, which the
# configured tokenizer (pad token, custom chat template) must override.
if processor is not None:
processor.save_pretrained(path)
tokenizer.save_pretrained(path)
if lora_state_dict is not None:
adapter_path = path / "lora_adapters"
adapter_path.mkdir(parents=True, exist_ok=True)
save_state_dict(
lora_state_dict, adapter_path, self.config.save_format, save_sharded=False, adapter=True
)
if self.lora_config:
save_lora_config(
model,
adapter_path,
rank=self.lora_config.rank,
alpha=self.lora_config.alpha,
dropout=self.lora_config.dropout,
)
self.logger.debug(f"Saved weight checkpoint to {path} in {time.perf_counter() - start_time:.2f} seconds")
def save(
self,
step: int,
model: nn.Module,
tokenizer: PreTrainedTokenizer,
processor: ProcessorMixin | None = None,
):
"""Save a HF-compatible weight-only checkpoint for a given step."""
step_path = self.get_step_path(step)
# Master-only mkdir + barrier: concurrent mkdir from every rank can
# re-raise FileExistsError on a parallel FS (EEXIST + stale is_dir()).
if self.world.is_master:
step_path.mkdir(parents=True, exist_ok=True)
torch.distributed.barrier()
# Gather all weights on master rank
self.logger.debug("Gathering weights on master rank for weight checkpoint")
start_time = time.perf_counter()
state_dict = gather_weights_on_master(model, self.world.is_master, dtype=torch.bfloat16)
self.logger.debug(f"Gathered weights on master rank in {time.perf_counter() - start_time:.2f} seconds")
# Remove tied weight keys to match original model format
if getattr(model.config, "tie_word_embeddings", False):
for key in getattr(model, "_tied_weights_keys", []):
state_dict.pop(key, None)
if has_lora_layers(model) and self.config.save_adapter_separately:
self.logger.debug("Getting run adapter state dict for weight checkpoint")
start_time = time.perf_counter()
lora_state_dict = self.get_run_adapter_state_dict()
self.logger.debug(f"Got run adapter state dict in {time.perf_counter() - start_time:.2f} seconds")
else:
lora_state_dict = None
# Convert to HF hub format if needed
if isinstance(model, PreTrainedModelPrimeRL) and model.is_prime_state_dict(state_dict):
self.logger.debug("Converting PrimeRL format to HF format for weight checkpoint")
start_time = time.perf_counter()
model.convert_to_hf(state_dict)
self.logger.debug(
f"Converted PrimeRL format to HF format in {time.perf_counter() - start_time:.2f} seconds"
)
else:
from transformers.core_model_loading import revert_weight_conversion
self.logger.debug("Reverting transformers internal format to HF hub format for weight checkpoint")
start_time = time.perf_counter()
state_dict = revert_weight_conversion(model, state_dict)
self.logger.debug(f"Reverted to HF hub format in {time.perf_counter() - start_time:.2f} seconds")
# Save weight checkpoint on master rank
self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer, processor)
self.mark_stable(step)
bisect.insort(self.ckpt_steps, step)
def maybe_clean(self) -> None:
"""Deletes past checkpoints based on keep_last and keep_interval policies. No-op if both are None."""
if self.keep_last is None and self.keep_interval is None:
return
# Get all the checkpoint steps to delete
assert list(self.ckpt_steps) == sorted(self.ckpt_steps)
# Determine which steps to keep
steps_to_keep = set()
# Always keep the newest weight checkpoint — it is the current policy. With
# keep_interval-only cleaning, a freshly saved non-aligned final checkpoint would
# otherwise be deleted immediately, and the online evaluator would wait for the
# max_steps checkpoint forever.
if self.ckpt_steps:
steps_to_keep.add(self.ckpt_steps[-1])
# Keep the most recent keep_last steps
if self.keep_last is not None:
steps_to_keep.update(self.ckpt_steps[-self.keep_last :])
# Keep steps at keep_interval intervals
if self.keep_interval is not None:
for step in self.ckpt_steps:
if step % self.keep_interval == 0:
steps_to_keep.add(step)
# Delete steps not in steps_to_keep (only master rank deletes to avoid race condition)
ckpt_steps_to_delete = [step for step in self.ckpt_steps if step not in steps_to_keep]
if self.world.is_master:
for ckpt_step in ckpt_steps_to_delete:
ckpt_path = self.get_step_path(ckpt_step)
if ckpt_path.exists():
self.logger.debug(f"Removing past checkpoint for step {ckpt_step} ({ckpt_path})")
_try_rmtree(ckpt_path, self.logger)
# Update checkpoint steps
self.ckpt_steps = [step for step in self.ckpt_steps if step in steps_to_keep]
def setup_ckpt_managers(
def setup_ckpt_manager(
output_dir: Path,
ckpt_config: CheckpointConfig | None,
lora_config: LoRAConfig | None = None,
resume: ResumeConfig | None = None,
) -> tuple[CheckpointManager, WeightCheckpointManager | None]:
) -> CheckpointManager:
"""The checkpoint manager always exists: ``resume`` decides whether it loads,
``ckpt`` whether it saves (a resume without ``ckpt`` loads but saves nothing)."""
ckpt_output_dir = (ckpt_config.output_dir if ckpt_config else None) or output_dir
ckpt_manager = CheckpointManager(ckpt_output_dir, ckpt_config or CheckpointConfig(), resume)
if ckpt_config and ckpt_config.weights and not ckpt_config.skip_gather_master_weights:
weight_ckpt_manager = WeightCheckpointManager(
ckpt_output_dir,
ckpt_config.weights,
lora_config=lora_config,
keep_last=ckpt_config.keep_last,
keep_interval=ckpt_config.keep_interval,
resume=resume,
)
else:
weight_ckpt_manager = None
return ckpt_manager, weight_ckpt_manager
return CheckpointManager(ckpt_output_dir, ckpt_config or CheckpointConfig(), resume)

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