Compare commits

...
38 Commits
Author SHA1 Message Date
samsjaandGitHub fb31b51e84 fix: disable dynamo on Ulysses all-to-all to prevent FSDP×compile NCCL deadlock (#3195)
When torch.compile is used with Ulysses context parallelism and FSDP,
the all-to-all collectives are traced into the compiled backward graph
while FSDP's reduce-scatter hooks fire eagerly via the autograd engine.
The compiler may reorder the all-to-all backward differently across
ranks, causing rank 0 to wait on reduce_scatter while rank 1 waits on
all_to_all — a classic collective ordering mismatch that deadlocks NCCL
after the 1-hour watchdog timeout (PR #3186, job 1578).

Wrapping _all_to_all_seq_to_head and _all_to_all_head_to_seq with
torch._dynamo.disable forces a graph break around the collectives so
they execute eagerly in the autograd engine, restoring a single
consistent backward ordering between the two collective systems.
2026-08-05 21:43:25 -07:00
samsjaandGitHub 33b7d19cb1 Revert "chore: release v0.8.0 (#3207)" (#3208)
This reverts commit 56a9402953.
2026-08-05 20:53:32 -07:00
samsjaandGitHub 56a9402953 chore: release v0.8.0 (#3207) 2026-08-05 20:42:26 -07:00
0c0b92f99c chore: remove padded vLLM input scrub (#3203)
The scrub from #2506 was a temporary mitigation for NaN logits caused by
stale padded decode inputs poisoning CUDA-graph replay. The root cause is
fixed in the pinned vLLM 0.26.0: the non-contiguous logits bug in the
native Triton top-k/top-p kernel (vllm-project/vllm#42739) is included,
and _preprocess now zeros the padded positions tail natively.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 15:53:27 -07:00
samsjaandGitHub 84ce4d6677 fix: add eval.retrigger_on_resume to re-fire evals at checkpoint step on resume (#3123)
On resume, the orchestrator defaults to assuming a clean exit where all
evals already completed. When a run crashes mid-eval, the user can set
eval.retrigger_on_resume=True to re-trigger interval-aligned evals
at the checkpoint step instead of the next interval boundary.

No changes to EvalSource — the existing first_trigger = not is_resumed
already skips the base eval on resume and just checks step % interval,
so passing resume_step to trigger() is sufficient.
2026-08-05 15:49:32 -07:00
01e959596a feat: auto-resolve parsers for Laguna, gpt-oss, and Trinity (#3201)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 15:06:50 -07:00
HubertandGitHub 738eb5016a fix(nemotron-h): use fla causal_conv1d for packed Mamba conv (#3192)
Both NemotronH Mamba paths built their packed-document metadata with a
`cu_seqlens.tolist()` and a Python loop over documents, once per Mamba
layer. On Super that is 40 host-device syncs per forward (80 with
activation recompute): each one blocks the Python thread until the CUDA
stream drains, so the CPU never runs ahead and, under context
parallelism, every rank re-synchronizes to its slowest CP partner at
every layer instead of absorbing jitter in queue depth.

Replace the per-document conv loop and the hand-built seq_idx with
fla's Triton `causal_conv1d` and `prepare_sequence_ids`, matching the
call shape already used for Qwen3.5 GDN in `trainer/model.py` and
`qwen3_5_moe`. Both fla helpers derive boundaries from `cu_seqlens`
directly and are `@tensor_cache`d by argument identity, so the 40
layers of a forward share one build.

fla is already a required dependency and its Triton backend needs no
arch-specific CUDA compilation, which was the stated reason for
avoiding a fused conv here.
2026-08-04 20:41:49 -07:00
06eb91d7c8 fix: accept seq_lens contract kwargs in GlmMoeDsaModel.forward (#3197)
* fix: accept seq_lens contract kwargs in GlmMoeDsaModel.forward

The fused LM head wrapper forwards seq_lens/seq_lens_are_pre_shard to the
inner model, but only GlmMoeDsaForCausalLM accepted them.

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

* review: drop inline comment above seq_lens kwargs

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 20:21:03 -07:00
327f378e07 feat!: standalone env servers (#3162)
* feat!: remove env-server sidecaring, launcher spawns at deterministic addresses

The orchestrator never spawns env servers anymore — it always connects to
each source's serve.address and polls until the server is up. Addresses
are assigned deterministically at config validation (tcp://127.0.0.1:5000+
across train then eval sources), so the launcher (local rl + multinode
sbatch template) spawns the servers in parallel with the orchestrator and
both sides agree on where each server lives from the config alone.

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

* chore: docstring + test tidy

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

* refactor!: derive env-server addresses, require address on env-server config

Addresses are wiring, not intent — like the transport blocks, they are no
longer configurable on sources. The orchestrator derives each server's
address from the source's position in the config; the env-server entrypoint
takes a required address the launcher writes per source.

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

* refactor: env-server config mirrors verifiers' serve CLI, per-run base port

EnvServerConfig composes vf's env/serve/legacy blocks verbatim, so an
env-server TOML reads like a vf serve config. orchestrator.env_server_base_port
offsets the derived port range, giving concurrent runs on one host (e.g.
multi-run orchestrators) each their own 1:1 env server.

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

* feat(configs): multi-env debug config (2 reverse-text train sources + eval)

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

* feat: rename env server entrypoint to `env` (keep `env-server` alias), env_server_addresses -> env_addresses

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

* chore: env/ prefix for env server stop-event keys

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

* refactor: rename env server naming to env throughout

EnvServerConfig -> configs/env.py:EnvConfig, source-level EnvConfig -> SourceConfig,
entrypoint moves to entrypoints/env.py, env_server_base_port -> env_base_port,
proctitle PRIME-RL::Env

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

* docs: trim env entrypoint row

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

* feat: drop the verifiers serve CLI, adopt vf.ServeConfig

Bumps deps/verifiers to PrimeIntellect-ai/verifiers#2237 (serve CLI removed,
ServingConfig renamed ServeConfig); prl's source-level ServingConfig follows suit

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

* docs: drop the removed serve CLI reference from EnvConfig

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

* chore: pin verifiers to main (serve CLI removal merged)

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

* ci: slim install imports configs.env

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

* revert: keep env-server naming, validate env identity on EnvServerConfig

The env console script shadows coreutils env in activated shells — back to
env-server as the sole entrypoint (still at entrypoints/, orchestrator source
class stays EnvConfig as on main). EnvServerConfig regains the identity
validation the nested source config used to provide (missing env, mixed v0/v1)

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

* fix(slurm): remove apostrophe from env-server launch comment

The multi-node srun body is one single-quoted bash -c string, so the
apostrophe in "source's" closed it early: every rendered sbatch failed to
parse with a syntax error near unexpected token '(' and the job died before
any component started. Reword the comment and note the constraint.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 16:48:48 -07:00
4aeca13870 chore: scope the jaxtyping lint ignores so F821 runs everywhere else (#3194)
* chore: scope the jaxtyping lint ignores so F821 runs everywhere else

F821 (undefined name) was disabled repo-wide for jaxtyping's shape
strings, so ruff could not report a missing import anywhere in prime-rl —
and style CI runs only ruff. Four modules actually use those annotations;
the ignore now names them.

The fifth file the rule fired on was not jaxtyping: rotary_emb annotated
a config it never imported, so the name resolved to nothing. Imported.

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

* chore: trim the ignore comment

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 15:50:49 -07:00
minh hoangandGitHub 8ab86036b2 fix(ci): allow branch/commit refs in ghcr image build (#3126)
* fix(ci): allow branch/commit refs in ghcr image build

The `ref` input already advertises "Branch, tag, or commit to build",
but Resolve image vars rejected anything that wasn't main, v*, or *.dev*,
so dispatching a build off a feature branch failed.

Drop the allowlist (the ref is checked out — hence existence-validated —
before this step) and name non-tag builds with `git describe` so a
branch build tags as e.g. v0.7.1.dev55-3-gfea5aadcf-<branch>, carrying
the nearest release + commit distance + short sha and never colliding
with a clean release tag. Exact-tag refs still build under the tag
verbatim, and the commit-<sha> tag is kept since the platform pins it.

* ci: restrict manual image builds to maintain/admin

workflow_dispatch already requires write access, but that includes any
write-level collaborator. Add an authorize job that gates the build on
the dispatcher having maintain or admin (via the collaborator permission
API). Automated in-repo dispatches run as github-actions[bot] and are
allowed so devx_tag dev-image builds and the release build keep working.
prepare now needs authorize, gating the whole build + manifest chain.

* ci: gate only manual dispatches in authorize job

The authorize job ran for every trigger, including on:release. Scope the
permission check to workflow_dispatch (manual builds) so release/other
events pass through. Guard the step (not the job) so a skip still leaves
prepare's `needs: authorize` satisfied.
2026-08-04 12:46:29 -07:00
f0bc8f1fab fix: standalone inference at dp=1 EP (template) + poolside_v1 tool-call regex (#3184)
* fix: port dp=1 EP dense-style launch to standalone inference template

Same bug as #3094, same fix: the multi-node branch of inference.sbatch.j2
still passed external-LB DP args (data_parallel_rank/address) at dp=1
(e.g. tp=8 on 8-GPU nodes), which vLLM >=0.24 rejects with
'data_parallel_external_lb can only be set when data_parallel_size > 1'.

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

* fix: accept poolside_v1 tool calls without newline after function name

Laguna S 2.1 emits <tool_call>name<arg_key>... with no newline; the
non-streaming func_detail_regex required one, so every tool call failed
detail parsing and leaked verbatim into content (finish_reason=stop).
Upstream vLLM >=0.25 accepts both forms; patch only the regex via the
shared vLLM plugin.

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

* Revert "fix: accept poolside_v1 tool calls without newline after function name"

This reverts commit b054923274aecb39f82671b2f9eae22ef0590fb9.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 09:16:46 -07:00
756f217f22 fix: bump vf + fix lock (#3187)
* fix: relock uv.lock after research-environments bump

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

* fix: bump verifiers to 0.2.2.dev76 and rename ServingConfig to ServeConfig

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 18:34:18 -07:00
78cef2844f chore: bump research-environments to latest main (#3185)
Bump the deps/research-environments submodule pin 21a284618 -> f9c43a74 (latest
main), which includes research-environments #744 fixing senior_swe_bench_v1's stale
verifiers.v1.clients.config import (moved to verifiers.v1.configs.client) so
senior-swe-bench-v1 resolves against latest verifiers.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 17:26:39 -07:00
ef42886edc feat(orchestrator): multi-agent native metrics (#3165)
* feat(orchestrator): episode- and agent-level rollout metrics

Adapt to verifiers#2187 (Episode derived aggregates): episode.last_error
rename, submodule bump. Mirror the episode/trace hierarchy in the wandb
layout: count metrics read at the episode level (per-episode sums), and
a new {scope}/{subset}/<agent>/<metric>/<stat> level reports trace-level
metrics per agent, averaging in-episode fan-outs first.

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

* chore: bump verifiers to vf#2187 head, episode wording cleanups

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

* refactor(orchestrator): RolloutMetrics -> EpisodeMetrics, AgentMetrics -> TraceMetrics

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

* feat(orchestrator)!: trace-level metrics are agent-only, timing generation span renamed agent

Env level now carries only episode-level facts (count sums, pipeline
rates, eval scores); reward, truncation, errors, stop conditions, timing,
custom metrics and solve rates move under {scope}/{subset}/<agent>/.
Adapts to the vf span rename (Timing.agent, AgentSpan, split_agent_time)
and re-pins deps/verifiers. Overview reward/error/truncation panels match
the per-agent keys by regex.

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

* feat(configs): agentic-judge reverse-text debug config

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

* chore(configs): deterministic two-call judge policy for the agentic-judge debug config

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

* chore: bump verifiers to vf#2187 head

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

* chore: bump verifiers to vf#2187 head (main merged)

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

* chore: bump verifiers pin

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

* chore: bump verifiers pin

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

* chore: re-pin verifiers to the vf#2187 merge commit

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

* chore: bump verifiers and research-environments to latest main

verifiers f646beb37 -> f6e420b99 (0.2.2.dev66, 17 commits) and
research-environments 6a2dee6fc -> ccb375ce5 (main + the scicode-v1
pin relax from research-environments#740).

Adaptations to the verifiers changes:
- Episode.error is now Episode.errors + a last_error property (vf#2187)
- verifiers.v1.loaders / verifiers.v1.push moved into
  verifiers.v1.utils.{loaders,platform} (vf#2204)
- verifiers floors bumped to 0.2.2.dev66 (root and prime-rl-configs)

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

* chore: bump research-environments to latest main

ccb375ce5 -> 9a57c713c: research-environments#740 refreshed on current
main, picking up the ViRL39K v1 taskset (RE#689) and the taskset prompt
config fixes (RE#742). verifiers main is unchanged since f6e420b99.

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

* chore: bump verifiers to 0.2.2.dev73 (per-rollout clients)

f6e420b99 -> 576506d66 (7 commits). vf#2218 builds one client per
rollout with a process-wide elastic renderer pool: TrainClientConfig
drops pool_size for a multiplex knob, and the config module moved from
clients.config to configs.client. The orchestrator config follows suit
(pool_size -> multiplex, None = client default). Floors to dev73.

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

* chore!: pin research-environments to the scicode merge commit, drop orchestrator.multiplex

deps/research-environments -> 21a284618 (research-environments#740 on
main). The orchestrator-level renderer knob (pool_size, briefly
multiplex) is removed instead of renamed: clients resolve inside env-
server workers, whose concurrency is already bounded per env by
serve.pool.multiplex (default 128, below the client-side renderer
default of 256), so each worker warms one renderer and the elastic pool
grows on demand.

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

* feat(orchestrator)!: pipeline verdicts and eval scores are per-agent too

is_trainable / is_filtered / filters and avg@k / pass@k all score a
single trace, so they read per agent like every other trace-level
metric instead of pooling an episode's seats.

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

* chore: drop the agentic-judge debug config from this PR

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

* docs: spell out the per-agent metric level in the monitor-run skill

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

* docs: eval's overview score is the per-agent avg@k

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

* fix(orchestrator): agent-level rates are flat over traces

is_truncated / is_completed rode the per-episode mean path with the
distributions, so an uneven fan-out — what the effective subset leaves
whenever a sibling errors — reweighted them away from the plain
fraction their siblings and the docs promise.

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

* refactor(orchestrator)!: agent-level metrics are flat over traces

One aggregation per level: the episode level sums an episode's traces,
the agent level takes each trace as a sample. Reward, avg@k and the
per-agent counts had been collapsing each episode's fan-out to a mean
first, which left them the odd ones out among the seat's own metrics and
made avg@k's k — a trace count — disagree with what it averaged.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 16:04:14 -07:00
ed05a1418d fix: count unscored reward components as zero in rollout metrics (#3182)
* fix(metrics): count unscored reward components as zero

Verifiers now seeds expected reward/metric names with None when scoring
starts, so a scoring failure leaves seeded-unscored entries instead of an
empty dict. CustomMetrics counts unscored rewards as 0.0 (matching the
scalar reward, which sums them as 0) and keeps averaging metrics over the
rollouts that scored them, so all-subset per-key reward means no longer
collapse onto effective when scoring errors occur.

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

* chore: bump verifiers submodule

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

* chore: bump verifiers submodule

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

* fix(metrics): count unscored metrics as zero too

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

* chore: bump verifiers to main

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 15:25:25 -07:00
1ef8f1a843 chore: bump verifiers and research-environments to latest main (#3172)
* chore: bump verifiers and research-environments to latest main

verifiers f646beb37 -> f6e420b99 (0.2.2.dev66, 17 commits) and
research-environments 6a2dee6fc -> ccb375ce5 (main + the scicode-v1
pin relax from research-environments#740).

Adaptations to the verifiers changes:
- Episode.error is now Episode.errors + a last_error property (vf#2187)
- verifiers.v1.loaders / verifiers.v1.push moved into
  verifiers.v1.utils.{loaders,platform} (vf#2204)
- verifiers floors bumped to 0.2.2.dev66 (root and prime-rl-configs)

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

* chore: bump research-environments to latest main

ccb375ce5 -> 9a57c713c: research-environments#740 refreshed on current
main, picking up the ViRL39K v1 taskset (RE#689) and the taskset prompt
config fixes (RE#742). verifiers main is unchanged since f6e420b99.

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

* chore: bump verifiers to 0.2.2.dev73 (per-rollout clients)

f6e420b99 -> 576506d66 (7 commits). vf#2218 builds one client per
rollout with a process-wide elastic renderer pool: TrainClientConfig
drops pool_size for a multiplex knob, and the config module moved from
clients.config to configs.client. The orchestrator config follows suit
(pool_size -> multiplex, None = client default). Floors to dev73.

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

* chore!: pin research-environments to the scicode merge commit, drop orchestrator.multiplex

deps/research-environments -> 21a284618 (research-environments#740 on
main). The orchestrator-level renderer knob (pool_size, briefly
multiplex) is removed instead of renamed: clients resolve inside env-
server workers, whose concurrency is already bounded per env by
serve.pool.multiplex (default 128, below the client-side renderer
default of 256), so each worker warms one renderer and the elastic pool
grows on demand.

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

* fix(orchestrator): read the agent timing span

vf#2187 renamed Timing.generation to Timing.agent (GenerationSpan ->
AgentSpan); the timing metrics group crashed every RL run's first
to_wandb. Metric keys follow (timing/agent, timing/agent/{model,
harness}). The unit fixture missed it because mk() duck-types Trace;
its namespace now mirrors the real field names.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 13:43:28 -07:00
e229a286f2 fix: checkpoint and resume the orchestrator train data position (#3164)
* fix(orchestrator): checkpoint and resume the train data position

Shuffle each finite env's task table with seed=epoch (1-indexed) so the
permutation is reproducible, snapshot per-env {epoch, cursor} into
Progress.data_positions at checkpoint time, and restore + log the
position on resume.

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

* fix(orchestrator): track and fast-forward infinite taskset cursors on resume

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

* chore(orchestrator): drop old-checkpoint load compat

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

* refactor(orchestrator): make the data position first-class checkpoint state

TrainSource is a torch Stateful (state_dict/load_state_dict) saved under
its own train_source key next to progress, mirroring the SFT dataloader.

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

* docs: simplify orchestrator checkpoint table row

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

* refactor(orchestrator): simplify TrainSource surface

Hardcode the env-choice seed, drop the torch Stateful base (nothing
consumes the protocol), log the restored position from ckpt.load, and
rename _shuffled to _shuffle.

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

* feat(orchestrator): make the cross-env dispatch sequence reproducible

Advance the env-choice RNG exactly once per dispatched example - a draw
whose permit cost doesn't fit is held (head-of-line) instead of redrawn -
and checkpoint the RNG state and pending draw with the per-env positions.

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

* fix(orchestrator): save the interval checkpoint on the event loop

state_dict() on a to_thread worker raced the dispatcher mutating
TrainSource; the payload is tiny, so snapshot and write synchronously.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 11:31:56 -07:00
2ffe374e02 fix(trainer): add B300/GB200/GB300 peak FLOPS for MFU (#3168)
B300 device names fell through to the A100 fallback (312 TFLOPS),
inflating reported MFU ~7x. Add dense BF16 peaks per NVIDIA datasheets:
GB200/GB300 superchips at 2.5 PFLOPS, HGX B200/B300 at 2.25 PFLOPS.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-01 21:51:18 +02:00
bbb90a1b41 chore(configs): expand inline TOML tables to sections (#3167)
Every checked-in config, example, and doc snippet now uses [section]
headers instead of key = { ... } inline tables. Purely stylistic: all
48 rewritten TOML files parse identically to their previous versions.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 15:24:35 -07:00
Matej SirovatkaandGitHub 9f0d41e23d chore(inference): bump vLLM to 0.26.0 (#3166) 2026-07-30 21:57:55 +02:00
e0638c7eb6 chore: adapt to the verifiers trace record cleanups (#3157)
* rename training environments to sources

* fix CPU test config fixtures

* rename evaluation environments to sources

* chore(orchestrator)!: rename max_inflight_rollouts to max_inflight_episodes

A dispatcher permit has always bought one episode, not one rollout: for a v1
env one `run` request is one episode (however many agents play it), and a
legacy group-scoring call reserves one permit per bridged v0 rollout, each of
which is its own single-agent episode. Name the knob what it counts.

`max_inflight_rollouts` still parses as an alias, as `rollouts_per_example`
does for `group_size`.

* feat(orchestrator)!: compose the verifiers env, serve and legacy blocks

verifiers split `EnvServerConfig` into three blocks, so an env entry composes
them instead of inheriting one class:

    [[orchestrator.train.source]]
    env    = { taskset = { id = "..." } }   # what runs
    serve  = { pool = { ... }, address, max_concurrent }   # how it's hosted
    legacy = { id, args }                   # a classic v0 env instead

`serve.pool` sizes the spawned server (was `pool`), `serve.address` points at an
external one (was `address`), and `serve.max_concurrent` bounds one worker's
episodes in flight — usually left unset, since `max_inflight_episodes` is the
run's bound. Each moved key raises with a pointer home, including the
`num_workers` shorthand the old validator migrated silently.

BREAKING: `pool` / `address` / `num_workers` on an env entry move under `serve`,
and a v0 env's `id` / `args` / `extra_env_kwargs` move under `legacy`.

TEMPORARY: `deps/verifiers` points at the `feat/one-agent-per-episode` branch
(PrimeIntellect-ai/verifiers#2157) so the two sides can be run together; re-pin
to a merged `main` commit before this lands.

* fix the source-config readers the compose commit missed

The Prime monitor still built its run-registration payload from `env.id`, which
the composed entry doesn't have — `AttributeError` at registration whenever
Prime monitoring is on. It reads `env_id` now, the property that spans both the
v1 and the v0 shape.

The packer's fixture still used the bare `id` shorthand, so its three runs were
rejected at config parse and skipped by `discover_runs`. Full CPU unit suite:
416 passed.

Re-pins `deps/verifiers` to the branch tip of verifiers#2157, which fixes the
same class of stale access on that side (`config.legacy.id`). Still a branch
commit — re-pin to a merged `main` before this lands.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* spell the env annotation out instead of vf.EnvField

verifiers dropped the `EnvField` alias, which was only ever
`SerializeAsAny[EnvConfig]` under a name that collided with `env_field()`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* declare the env default with the factory verifiers exports

`vf.env_field()` is gone: it only wrapped `Field(default_factory=...)`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* inline the legacy helpers, use the config class as the default

Follows verifiers dropping the three `configs/legacy.py` helpers and the
`single_agent_env_config` factory: `is_legacy` and `env_id` are one-liners here,
the mixed-run refusal is spelled out in `validate_env`, and the `env` default is
`vf.SingleAgentEnvConfig()`. `env.max_concurrent` now works as an alias for
`env.max_concurrent_agents`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* drop the serving-key pointers here too

The same call as verifiers a0ebc408: `num_workers` / `pool` / `address` on a source
entry now fail as an ordinary `extra_forbidden` instead of naming their new home.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* bump verifiers: no max_concurrent alias on the env block

`env.max_concurrent` used to bound a served worker's agent runs across episodes, so
accepting it as `max_concurrent_agents` multiplied it by the episodes in flight. It
errors now, like every other moved key. 416 unit tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* bump verifiers to 0.2.2.dev43 (merged main)

deps/verifiers d0bb0ffe5 -> fcb48822e, which is the squash-merge of the composed
env/serve/legacy config blocks (#2157) plus everything else since the last bump:
Harbor 0.20.0 (#2161), runtime-blamed box failures (#2156), standalone MCP clients
pinned to v1 (#2155), and the v1 test/E2E split (#2127).

Lock: harbor 0.14.0 -> 0.20.0, which drops claude-agent-sdk and datasets from its
own deps and adds filelock/platformdirs, so those move with it.

Replaces the temporary branch pin this PR carried.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix: spawn the env server again, and let a pip-only install resolve verifiers

Two CI failures from the compose commit.

The orchestrator stopped spawning env servers. It decides spawn-vs-connect by
`address is None`, and prime-rl's own field defaulted to None; `vf.ServingConfig`
defaults to `tcp://127.0.0.1:5000`, so every env looked external and the run waited
120s for a server nobody started. It now asks whether the address was *pinned*
(`model_fields_set`), so an unset `[serve]` spawns on a free port as before, and
pinning any address — including verifiers' own default — connects.

The slim `prime-rl-configs` wheel is installed from /tmp with no workspace context,
so `verifiers` resolves from PyPI, where `>=0.2.1` picks stable 0.2.1 — no
`SingleAgentEnvConfig`. Floor is `>=0.2.2.dev43` now, a pre-release specifier so the
dev release is eligible.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore: adapt to the verifiers trace record cleanups

Companion to PrimeIntellect-ai/verifiers#2172: record_* mutators, required
agent seat and RunInfo.id, last_error, and agent.name/.trainable reads.

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

* chore: re-pin verifiers to merged main (f646beb37)

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

---------

Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 10:34:53 -07:00
halleriteandGitHub 0b583306eb feat(orchestrator): hierarchical GRPO for proposer-solver envs (#3138) 2026-07-30 15:31:13 +02:00
halleriteandGitHub d612e23c1d chore(configs)!: remove every config shim (#3156) 2026-07-30 01:50:01 +02:00
halleriteandGitHub d135ed4c90 feat(orchestrator)!: rename env collections to sources, compose the verifiers config blocks (#3150) 2026-07-30 01:41:54 +02:00
1fd2d732c2 fix: read overview quality metrics from effective subset (#3159)
* fix: read overview quality metrics from effective subset

The all subset counts errored rollouts as zeros for num_branches,
num_turns, num_total_tokens, and is_truncated, which skews the
distributions and makes the panels uninterpretable. Point the wandb
overview panels and the eval success line at the effective subset;
has_error stays on all since effective drops errors by construction.

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

* fix: reword zero-skew rationale, drop subset guidance from skill

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-29 16:36:13 -07:00
6a9969e61a chore: bump renderers to 0.1.9.dev9 (#3158)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-29 16:06:49 -07:00
1385e0722c fix: compute trainable rate over effective rollouts (#3152)
* fix(orchestrator): compute trainable rate over effective rollouts

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

* chore: drop comment

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-07-28 23:52:21 -07:00
e2ad3beaaa feat(monitor): effective reward/score in wandb overview (#3153)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 23:40:39 -07:00
9551e20fa8 chore: single global router in front of engines for all deployments (#3105)
* chore: single global router in front of engines for all deployments

Every deployment shape now runs one client-facing router on server.port
with engines behind it on backend_port: local single-node runs spawn a
vllm-router in the inference entrypoint, and the SLURM templates collapse
per-replica routers into a single global router on inference node 0.
router/backend_port move to InferenceConfig top level; router = "None"
runs a bare engine (used for per-rank SLURM engine processes).

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

* fix: finish single-node router integration

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-07-29 05:17:43 +02:00
6df90dc0aa feat: default rollout transport to zmq and inject host for multi-node (#3149)
* feat(config): shared [rollout_transport] propagated to trainer + orchestrator

Add rollout_transport as a shared RLConfig field (mirroring weight_broadcast /
ckpt / wandb), propagated to trainer.rollout_transport and
orchestrator.rollout_transport via propagate_shared_fields. A single
[rollout_transport] block configures both sub-configs.

auto_setup_rollout_transport (like auto_setup_weight_broadcast) resolves the
shared field from the sub-configs so the launcher's ZMQ host-injection gate is
correct whether transport is set via the shared block or directly on
trainer/orchestrator.rollout_transport (the documented fallback), and rejects
mismatched sub-config transports.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(launcher): inject rollout_transport.host for multi-node zmq transport

ZMQ rollout transport binds/connects a single rollout_transport.host (default
localhost). On multi-node trainer deployments the training-batch PUSH/PULL and
micro-batch PUB/SUB span nodes, so data ranks on non-head nodes connect to their
own localhost and hang at step 0. The launcher already injects
weight_broadcast.host=$MASTER_ADDR for nccl but had no equivalent for
rollout_transport.

When config.rollout_transport resolves to zmq, inject --rollout_transport.host
$MASTER_ADDR into the trainer torchrun and the orchestrator (mirrors the existing
weight_broadcast.host injection). Filesystem transport is unaffected.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(config): default rollout transport to zmq

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-29 04:43:50 +02:00
8372c37a15 fix: plot overview time panels on relative wall time (#3148)
* fix(monitor): plot overview time panels on relative wall time

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

* chore: drop view_signature docstring

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-07-28 15:21:05 -07:00
15f5355f5f chore: bump verifiers + research-environments to latest main (#3147)
- deps/verifiers -> d0bb0ffe5 (network-policy alignment #2124, Codex MCP tools
  #2140, Ruff 0.16 / ty tooling, and everything since the last bump)
- deps/research-environments -> 6a2dee6fc (judges/swe agentic-judge setups #720,
  MMMU-Pro / CharXiv tasksets, wideseek verifiers-pin fix #731)
- uv.lock relocked (adds charxiv-v1, mmmu-pro-v1; bfcl-v3-v1 0.2.0 -> 0.3.0)

No code changes needed: the runtime-on-agent config addressing and Reward-record
metrics landed with the earlier bump (#3137).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 12:50:01 -07:00
JannikStandGitHub d1bfcbc636 chore(ci): enable nightly FFT cron (#3142) 2026-07-28 13:06:46 +02:00
f50ec5c4c8 feat(orchestrator): RAE — role-conditioned advantage estimation for self-play envs (SPIRAL) (#3136)
* feat(orchestrator): RAE — SPIRAL's role-conditioned advantage estimation for self-play envs

Add the `rae` algorithm (SPIRAL, arXiv:2506.24119): each trainable agent
keeps an EMA baseline of its own rewards, and every trace's advantage is
its reward minus its agent's pre-update baseline. Group-relative baselines
mis-credit multi-agent self-play — in a zero-sum game the group mean is ~0
whatever the policy does, and centering both agents against it turns any
structural asymmetry (first-mover edge) into permanent credit. Baselines
are keyed per (env, agent) — the paper's per (game, role) — and any
group_size works, including 1.

configs/debug/algo/rae.toml runs shared-policy Kuhn poker self-play
(kuhn-poker-v1, both agents late-bound to the run's model).

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

* chore(tests): drop RAE unit tests

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-27 19:34:50 +02:00
9b944591c4 chore: bump verifiers to latest main; adopt runtime-on-agent, Reward records, textarena player (#3137)
* chore: bump verifiers to latest main; adopt runtime-on-agent, Reward records, textarena player

deps/verifiers b13ba60da → 295a06505 (+12: interleaving agents + kuhn-poker-v1,
runtime moves from the harness onto the agent (#2106), trace rewards become
Reward{score, weight} records (#2119), wordle-v1 rides the rewritten
TextArenaEnv, pluggable harness skills, agentic-judge grading knobs).

Adoption:
- every `env.<agent>.harness = { ..., runtime = ... }` config line splits into
  `harness = { ... }` + `env.<agent>.runtime = ...` (configs/, examples/, docs/,
  skills/)
- wordle configs address the textarena seat as `env.player`
- reward metrics read the weighted `Reward.value` (CustomMetrics gains a value
  extractor); unit-test trace builders record `vf.Reward(score=...)`
- uv.lock re-locked for verifiers 0.2.2.dev29

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

* fix(tests): adopt Reward records in prime-monitor rollout builder

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-27 18:26:18 +02:00
JannikStandGitHub 3b22dd951c fix(nightly-fft): restore auto-resolve latest v*.dev* when no image_tag input (#3134)
* fix(nightly-fft): restore auto-resolve latest v*.dev* when no image_tag input

The nightly's whole point is to catch regressions on tip-of-main, so a
plain 'gh workflow run "Nightly FFT"' must dispatch against the newest
built v*.dev* by default. #3133 removed that fallback and made no-input
dispatches emit an empty tag, which falls through to the platform's
default 'main' alias — currently baked ~50 commits stale — so the run
crashes on validation.

Restores the original behavior: no input → auto-resolve latest dev.
Explicit image_tag input still overrides (from #3132). Dispatch step
always passes --image-tag since the tag is always populated now.

* fix(ci): guard dev-tag resolver against pipefail

GitHub Actions runs the shell under `bash -eo pipefail` by default.
Two failure modes:
- `grep -E ...` returns 1 when no v*.dev* tags exist yet
- `head -n 10` closes the pipe after 10 lines, SIGPIPE-ing `sort`

Either aborts the step before the explicit no-candidates guard runs.
Wrap the pipeline in set +o pipefail / set -o pipefail.
2026-07-24 10:10:26 +02:00
JannikStandGitHub 13770289ef fix(nightly-fft): don't force --image-tag when no dispatch input (#3133)
* fix(nightly-fft): pin image_tag to commit-c505e07a1 in each config

The default 'main' image the platform validator ships is baked ~50
commits behind tip and predates cb74ae2be (which added the env.
wrapper on train.env entries). It rejects env.taskset with
'train.env[0].env — Extra inputs are not permitted' and doesn't know
the 'prime-qwen3' renderer name, so every nightly orchestrator
crash-loops on validation.

- Pin top-level image_tag = 'commit-c505e07a1' in each nightly-fft
  toml. c505e07a1 is post-cb74ae2be and accepts the current v1 shape.
- Workflow: when no dispatch input is set, emit an empty tag and skip
  --image-tag on prime train so the toml pin wins. Explicit
  workflow_dispatch image_tag still overrides.
- Drop this pin once v0.7.1+ (with the v1 schema) is released and the
  backend default resolves to it.

* revert: drop image_tag pin from nightly-fft configs

Keep the workflow change (only pass --image-tag when explicit input);
rely on prime-cli's built-in fallback: --image-tag > toml image_tag >
backend default. No commit-hash pin baked into the checked-in configs.
2026-07-24 06:59:43 +02:00
131 changed files with 3283 additions and 1739 deletions
+50 -13
View File
@@ -34,8 +34,42 @@ concurrency:
cancel-in-progress: false
jobs:
authorize:
name: Authorize dispatcher
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Require maintain or admin
# Gate MANUAL dispatches only; other events (e.g. release) are
# already privileged and pass through. Guard the step, not the job —
# a skipped job would skip `prepare` via `needs: authorize`.
if: github.event_name == 'workflow_dispatch'
env:
GH_TOKEN: ${{ github.token }}
ACTOR: ${{ github.triggering_actor }}
REPO: ${{ github.repository }}
run: |
# Restricted to repo members with maintain or admin. Automated
# in-repo dispatches (devx_tag dev-image builds, the release build)
# run as github-actions[bot] via GITHUB_TOKEN — allow those through.
if [ "$ACTOR" = "github-actions[bot]" ]; then
echo "Dispatcher is repo automation ($ACTOR); allowed."
exit 0
fi
role=$(gh api "repos/${REPO}/collaborators/${ACTOR}/permission" --jq '.role_name' 2>/dev/null || true)
echo "Dispatcher $ACTOR has repo role: ${role:-<none>}"
case "$role" in
admin|maintain)
echo "Authorized." ;;
*)
echo "::error::$ACTOR (role: ${role:-none}) is not allowed to trigger image builds; requires maintain or admin." >&2
exit 1 ;;
esac
prepare:
name: Prepare build
needs: authorize
runs-on: ubuntu-latest
permissions:
contents: read
@@ -81,27 +115,30 @@ jobs:
INPUT_TAG: ${{ env.BUILD_TAG }}
PLATFORMS: ${{ env.BUILD_PLATFORMS }}
run: |
case "$INPUT_REF" in
main|v[0-9]*|*.dev[0-9]*) ;;
*)
echo "ref '${INPUT_REF}' not allowed for ghcr publish (must be main, v*, or *.dev*)" >&2
exit 1
;;
esac
if [ -n "$INPUT_TAG" ] && [ "$INPUT_TAG" != "$INPUT_REF" ] && [ "$INPUT_REF" != "main" ]; then
echo "custom 'tag' that differs from 'ref' is only allowed when ref=main; got ref='${INPUT_REF}' tag='${INPUT_TAG}'" >&2
exit 1
fi
raw_tag="$INPUT_TAG"
if [ -z "$raw_tag" ]; then
raw_tag="$INPUT_REF"
sanitize() {
echo "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//' | cut -c1-50
}
# A ref that is exactly a git tag builds under that tag verbatim;
# any other ref (branch / arbitrary commit) is prefixed with
# `git describe` so the tag carries the nearest release, commit
# distance and short sha (e.g. v0.7.0-42-g1a2b3c4d5-fix-my-branch)
# and can't collide with a clean release tag.
if [ -n "$INPUT_TAG" ]; then
tag=$(sanitize "$INPUT_TAG")
elif tag=$(git describe --tags --exact-match 2>/dev/null); then
:
else
tag="$(git describe --tags --always)-$(sanitize "$INPUT_REF")"
fi
tag=$(echo "$raw_tag" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | cut -c1-50 | sed 's/^-//;s/-$//')
if [ -z "$tag" ]; then
echo "Could not derive a valid image tag from '${raw_tag}'." >&2
echo "Could not derive a valid image tag from ref='${INPUT_REF}' tag='${INPUT_TAG}'." >&2
exit 1
fi
+16 -8
View File
@@ -13,9 +13,9 @@ on:
required: false
default: ""
# Scheduled run at 3AM PST (11AM UTC) — disabled for now, enable once dry-run passes
# schedule:
# - cron: "0 11 * * *"
# Scheduled run at 3AM PST (11AM UTC)
schedule:
- cron: "0 11 * * *"
permissions:
contents: read
@@ -113,16 +113,24 @@ jobs:
exit 0
fi
# The GHCR versions API can list a tag before its manifest is
# actually pullable (build in-flight, or manifest step didn't
# finish). So: pull the top N candidate tags, then verify each
# with a manifest HEAD via the anonymous registry token flow;
# take the newest one that resolves.
# No dispatch input: auto-resolve the newest v*.dev* tag on
# GHCR (the point of a nightly is to catch regressions on
# tip-of-main). The GHCR versions API can list a tag before
# its manifest is actually pullable (build in-flight, or
# manifest step didn't finish), so pull the top N candidates
# and verify each with a manifest HEAD via the anonymous
# registry token flow; take the newest one that resolves.
# Disable pipefail locally: `grep` may exit 1 on no matches
# (empty tag list) and `head` may SIGPIPE `sort` after
# reading its 10 lines. Both would abort the step before the
# explicit no-candidates guard below runs.
set +o pipefail
candidates=$(gh api --paginate \
"/orgs/primeintellect-ai/packages/container/prime-rl/versions" \
--jq '.[].metadata.container.tags[]' \
| grep -E '^v[0-9]+\.[0-9]+\.[0-9]+\.dev[0-9]+$' \
| sort -Vru | head -n 10)
set -o pipefail
if [ -z "$candidates" ]; then
echo "No v*.dev* tag listed on GHCR." >&2
exit 1
+3 -2
View File
@@ -8,8 +8,9 @@ Configurations for running prime-rl.
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
- **`ci/`** — integration and nightly configs used by CI.
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
(per-algorithm smokes) and `fake/` (fake-data trainer/SFT smokes). Not guaranteed
functional or up to date.
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
(two reverse-text train sources + one eval source, one env server per source). Not
guaranteed functional or up to date.
```bash
uv run rl @ configs/basic/<env>/rl.toml
+15 -3
View File
@@ -32,10 +32,22 @@ group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 768
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[ckpt] # Checkpoint at the end of training
+12 -3
View File
@@ -19,10 +19,19 @@ batch_size = 128
group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "math-env-v1"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[trainer.model]
seq_len = 16384
+10 -3
View File
@@ -22,10 +22,17 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
+10 -3
View File
@@ -40,10 +40,17 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "wiki-search-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[ckpt] # Checkpoint at the end of training
+10 -3
View File
@@ -21,10 +21,17 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 128
group_size = 8
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "wordle-v1"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
+18 -3
View File
@@ -22,10 +22,25 @@ group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 384
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, task = { similarity_power = 4, power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
min_turns = 2
max_turns = 2
min_names_per_turn = 1
max_names_per_turn = 3
[orchestrator.train.source.env.taskset.task]
similarity_power = 4
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
@@ -26,10 +26,17 @@ name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
enable_lora = true
@@ -25,10 +25,17 @@ name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
enable_lora = true
@@ -25,10 +25,17 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
gpu_memory_utilization = 0.7
@@ -0,0 +1,10 @@
# Env server for the multi-run RL integration test: one per orchestrator, each bound at
# its run's base port (the test passes --serve.address).
[env.taskset]
id = "reverse-text-v1"
[env.agent.harness]
id = "null"
[env.agent.runtime]
type = "subprocess"
@@ -14,10 +14,17 @@ lr = 3e-5
[train.sampling]
max_completion_tokens = 128
[[train.env]]
[[train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[train.source.env.taskset]
id = "reverse-text-v1"
[train.source.env.agent.harness]
id = "null"
[train.source.env.agent.runtime]
type = "subprocess"
[ckpt]
interval = 10
@@ -37,10 +37,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -49,10 +56,17 @@ num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -43,10 +43,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -55,10 +62,17 @@ num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -23,10 +23,17 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
+10 -3
View File
@@ -22,10 +22,17 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
+15 -3
View File
@@ -18,10 +18,22 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 768
+22 -6
View File
@@ -18,20 +18,36 @@ batch_size = 512
group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "math-env-v1"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "aime2024"
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer]
[trainer.model]
+10 -3
View File
@@ -18,10 +18,17 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
batch_size = 128
group_size = 16
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 128
+10 -3
View File
@@ -23,10 +23,17 @@ oversampling_factor = 2.0
type = "zero_advantage"
enforce = true
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "wiki-search-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
+10 -3
View File
@@ -18,10 +18,17 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "wordle-v1"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
@@ -20,10 +20,18 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "color-codeword"
env.taskset = { id = "color-codeword-v1", images_per_turn = 1 }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "color-codeword-v1"
images_per_turn = 1
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[trainer]
+15 -3
View File
@@ -24,10 +24,22 @@ type = "echo"
[orchestrator.algo.roles.user]
alpha = 0.1
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
+20 -6
View File
@@ -21,10 +21,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -33,10 +40,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
+20 -6
View File
@@ -21,10 +21,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -33,10 +40,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
+32 -11
View File
@@ -31,20 +31,34 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text-grpo"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text-opd"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.env.algo]
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.source.algo]
type = "opd"
[orchestrator.train.env.algo.teacher]
[orchestrator.train.source.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
@@ -55,10 +69,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
+20 -6
View File
@@ -33,10 +33,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -45,10 +52,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
+20 -6
View File
@@ -33,10 +33,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -45,10 +52,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 1e-4
+73
View File
@@ -0,0 +1,73 @@
max_steps = 20
seq_len = 4096
[model]
name = "Qwen/Qwen3-0.6B"
[wandb]
project = "algorithms-debug"
name = "debug-rae"
[orchestrator]
batch_size = 32
group_size = 1
[orchestrator.algo]
type = "rae"
[orchestrator.renderer]
name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.source]]
name = "kuhn-poker"
[orchestrator.train.source.env.taskset]
id = "kuhn-poker-v1"
[orchestrator.train.source.env.player0.harness]
id = "null"
[orchestrator.train.source.env.player0.runtime]
type = "subprocess"
[orchestrator.train.source.env.player1.harness]
id = "null"
[orchestrator.train.source.env.player1.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 512
[[orchestrator.eval.source]]
name = "kuhn-poker"
[orchestrator.eval.source.env.taskset]
id = "kuhn-poker-v1"
[orchestrator.eval.source.env.player0.harness]
id = "null"
[orchestrator.eval.source.env.player0.runtime]
type = "subprocess"
[orchestrator.eval.source.env.player1.harness]
id = "null"
[orchestrator.eval.source.env.player1.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
+20 -6
View File
@@ -29,10 +29,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -41,10 +48,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
+20 -6
View File
@@ -38,10 +38,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -50,10 +57,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
+20 -6
View File
@@ -38,10 +38,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -50,10 +57,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 1e-4
+67
View File
@@ -0,0 +1,67 @@
# Minimal multi-env debug run: two reverse-text train sources + one eval source.
# The launcher spawns one env server per source at its derived address
# (tcp://127.0.0.1:5000-5002); the orchestrator connects to each.
max_steps = 10
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.renderer]
name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text-a"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text-b"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 5
num_examples = 64
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
gpu_memory_utilization = 0.5
+1 -1
+1 -1
+132 -12
View File
@@ -17,6 +17,8 @@ This page covers the math and the configurable algorithmic components: the algor
- [Custom Loss](#custom-loss)
- [Advantage](#advantage)
- [Default Advantage](#default-advantage)
- [Hierarchical GRPO](#hierarchical-grpo)
- [Self-Play Advantage (RAE)](#self-play-advantage-rae)
- [Authoring an Algorithm](#authoring-an-algorithm)
- [Reference Scoring](#reference-scoring)
- [Filters](#filters)
@@ -67,6 +69,8 @@ type = "grpo" # the default
|---|---|---|---|
| `grpo` | policy | `rl` on actions | Standard group-relative RL. |
| `max_rl` | policy | `rl` on actions | MaxRL ([arXiv:2602.02710](https://arxiv.org/abs/2602.02710)): GRPO's centered reward normalized by the group **mean** instead of the standard deviation — the gradient is unbiased for the order-`group_size` truncation of the maximum-likelihood objective, upweighting hard examples like `1/p`. |
| `rae` | policy | `rl` on actions | RAE (SPIRAL, [arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): reward minus a per-agent EMA baseline of that agent's own rewards — the estimator for multi-agent self-play envs, where the group mean would mix the agents' opposite reward scales. See [Self-Play Advantage](#self-play-advantage-rae). |
| `hierarchical_grpo` | policy | `rl` on actions | GRPO for proposer-solver envs. Solvers are compared only with attempts on the same proposed problem; proposers are compared with the other proposals in the group. See [Hierarchical GRPO](#hierarchical-grpo). |
| `opd` | policy | `ref_kl` on actions | On-policy distillation ([Thinking Machines](https://thinkingmachines.ai/blog/on-policy-distillation/)): the policy samples, per-token reverse KL against a reference model as the gradient signal. Needs a `teacher`. |
| `sft` | *(the teacher)* | `ce` on actions | Hard distillation: a frozen model generates rollouts, the policy trains with CE on its tokens. Needs a frozen `sampling.source` (the teacher it samples from). |
| `opsd` | policy | `ref_kl` on actions | SDFT ([arXiv:2601.19897](https://arxiv.org/abs/2601.19897)): the model is its own reference, conditioned on an expert demonstration. The teacher *is* the live policy (the paper's setting, no extra deployment) — no model to configure. |
@@ -96,7 +100,9 @@ Echo also takes an optional user-supplied token filter that narrows the role sel
```toml
[orchestrator.algo.filter]
import_path = "my_module.drop_warnings"
kwargs = { patterns = ["WARNING"] }
[orchestrator.algo.filter.kwargs]
patterns = ["WARNING"]
```
```python
@@ -116,17 +122,33 @@ Both components resolve per environment. Each env inherits `[orchestrator.algo]`
[orchestrator.algo]
type = "grpo"
[[orchestrator.train.env]]
name = "math"
taskset = { id = "math-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
# inherits the top-level grpo
[[orchestrator.train.source]]
name = "math" # inherits the top-level grpo
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "math-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "terminal"
taskset = { id = "terminal-v1" }
harness = { id = "bash", runtime = { type = "subprocess" } }
algo = { type = "echo" } # this env runs its own algorithm
[orchestrator.train.source.env.taskset]
id = "terminal-v1"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
# this env runs its own algorithm
[orchestrator.train.source.algo]
type = "echo"
```
### The Algorithm Classes
@@ -138,6 +160,8 @@ At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_r
| `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) |
| `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 |
| `sft` | `SFTDistillAlgorithm` | `score_group`: group-norm credit (feeds filters) |
@@ -174,7 +198,7 @@ $$
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
$$
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the group-relative algorithms (`grpo`, `max_rl`, and `echo`'s action tokens).
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
@@ -245,7 +269,9 @@ Wire it up:
[trainer.loss]
type = "custom"
import_path = "my_module.ppo_clip_loss"
kwargs = { clip_eps = 0.2 }
[trainer.loss.kwargs]
clip_eps = 0.2
```
The dataclasses:
@@ -276,6 +302,8 @@ The per-token training signal is set by `algo.type` and the [algorithm](#the-alg
|---|---|---|
| `grpo` | `rl` | Group-norm: reward minus per-group baseline, optional length penalty. |
| `max_rl` | `rl` | Mean-normalized group credit (maximum-likelihood RL). |
| `rae` | `rl` | Reward minus a per-agent EMA baseline (SPIRAL's role-conditioned advantage estimation) — for multi-agent self-play envs. |
| `hierarchical_grpo` | `rl` | GRPO for proposer-solver envs: solvers are compared within one proposed problem, while proposers are compared across proposals. |
| `echo` | `rl` + `ce` | Group-norm on action tokens, plus weighted CE on env-provided tokens selected by message role (each role's `alpha` is its ECHO λ), optionally narrowed by a user filter. |
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream; `group_size` only fans out sampling. |
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream. |
@@ -297,6 +325,98 @@ type = "grpo"
type = "linear"
```
### Hierarchical GRPO
GRPO gives each rollout its reward minus the average reward of comparable rollouts. In an ordinary single-agent group, every rollout answers the same task, so one group average is enough.
A proposer-solver env is different. Starting from one source task, it produces several proposed problems, then runs several solver attempts on each problem:
```text
one source task
├── proposed problem A
│ ├── proposer trace
│ ├── solver attempt 1
│ └── solver attempt 2
└── proposed problem B
├── proposer trace
├── solver attempt 1
└── solver attempt 2
```
The solver attempts for A should not be compared with the solver attempts for B: the two problems may have very different difficulty. Proposer and solver rewards should not be compared either: they measure different jobs.
`hierarchical_grpo` therefore chooses the average separately for each role:
| Trace | Compared with | Why |
|---|---|---|
| Solver | Other solver attempts on the same proposed problem | They attempted the same problem. |
| Proposer | Other proposer traces in the group | They started from the same source task and proposed alternatives. |
For example, if three solvers receive rewards `[1, 1, 0]` on one proposed problem, their average is `2/3` and their advantages are `[1/3, 1/3, -2/3]`. Solver rewards from other proposed problems do not affect those values. The proposers are scored separately according to how useful their problems were for the solvers, then compared with the other proposers in the group.
Configure which roles are compared within a single proposed problem with `episode_agents`. For `proposer-solver-v1`, that role is `solver`:
```toml
[orchestrator.algo]
type = "hierarchical_grpo"
episode_agents = ["solver"]
[[orchestrator.train.source]]
name = "proposer-solver"
group_size = 4 # proposed problems per source task
env.n = 4 # solver attempts per proposed problem
[orchestrator.train.source.env.taskset]
id = "proposer-solver-v1"
[orchestrator.train.source.env.proposer.harness]
id = "null"
[orchestrator.train.source.env.proposer.runtime]
type = "subprocess"
[orchestrator.train.source.env.solver.harness]
id = "null"
[orchestrator.train.source.env.solver.runtime]
type = "subprocess"
```
`group_size` controls how many problems are proposed from each source task. `env.n` controls how many solvers attempt each proposed problem. If a comparison contains only one trace—for example, a solver when `env.n = 1`—its advantage is zero and the zero-advantage filter removes it.
This algorithm is accepted only for proposer-solver envs. Use the env's `train_proposer` and `train_solver` settings if you want to train only one role.
### Self-Play Advantage (RAE)
Group-relative baselines assume the group is exchangeable attempts by one agent. A multi-agent self-play env breaks that: one episode yields one trace per agent, all trainable, and in a zero-sum game the rewards sum to ~0 whatever the policy does — the group mean carries no information, and centering against it converts any structural asymmetry (a first-mover edge) into permanent credit for one agent.
`rae` implements SPIRAL's role-conditioned advantage estimation ([arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): each agent keeps an exponential-moving-average baseline of its own rewards, and every trace's advantage is its reward minus its agent's baseline — measured against the *pre-update* baseline (the unbiased order), then folded in at `decay` (SPIRAL's α, default 0.95). The algorithm instance is per-env, so baselines are keyed per (env, agent) — the paper's per (game, role). Advantages are not normalized, and `group_size` is free (RAE needs no sibling rollouts; `group_size = 1` is fine). Baselines live in orchestrator memory and re-warm from 0 over ~`1/(1 − decay)` traces per agent after a restart.
```toml
[orchestrator.algo]
type = "rae"
decay = 0.95
[[orchestrator.train.source]]
name = "kuhn-poker"
[orchestrator.train.source.env.taskset]
id = "kuhn-poker-v1"
[orchestrator.train.source.env.player0.harness]
id = "null"
[orchestrator.train.source.env.player0.runtime]
type = "subprocess"
[orchestrator.train.source.env.player1.harness]
id = "null"
[orchestrator.train.source.env.player1.runtime]
type = "subprocess"
```
Both of `kuhn-poker-v1`'s agents late-bind to the run's own model — shared-policy self-play against a continuously improving opponent. Pin one agent to a frozen endpoint (`env.player1.model = ...`) for asymmetric play; its traces are marked untrainable by the env and never reach the advantage computation. A single-agent env under `rae` degrades to REINFORCE with an EMA baseline.
### Authoring an Algorithm
+44 -18
View File
@@ -17,7 +17,7 @@ Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeInt
- [Optional Sub-Configs](#optional-sub-configs)
- [None](#none)
- [Discriminated Unions](#discriminated-unions)
- [Environments](#environments-orchestratortrainenv)
- [Environments](#environments)
- [Environment Variables](#environment-variables)
- [Examples](#examples)
@@ -55,7 +55,7 @@ CLI flags mirror the TOML tree using dots:
> Field names are snake_case in TOML (`max_model_len`) and kebab-case on the CLI (`--max-model-len`).
> Renamed fields keep their old name as a validation alias — e.g. `rollouts_per_example` is still accepted in TOML and CLI after being renamed to `group_size`. Mixing the two names across sources is safe.
> A renamed field keeps no alias for its old name: the old spelling fails as an unknown key rather than being silently translated.
## Inspecting and Validating
@@ -93,20 +93,23 @@ uv run rl @ rl.toml --trainer.model.lora.target-modules '["q_proj", "k_proj", "v
target_modules = ["q_proj", "k_proj", "v_proj"]
```
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables (e.g. environments), see [Environments](#environments-orchestratortrainenv).
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables, see [Environments](#environments).
### Dicts
CLI takes a JSON literal. TOML uses a table or inline-table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
CLI takes a JSON literal. TOML uses a table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
```bash
uv run rl @ rl.toml --orchestrator.train.env.0.args \
uv run rl @ rl.toml --orchestrator.train.source.0.args \
'{"dataset_name": "openai/gsm8k", "dataset_subset": "main"}'
```
```toml
[[orchestrator.train.env]]
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
[[orchestrator.train.source]]
[orchestrator.train.source.args]
dataset_name = "openai/gsm8k"
dataset_subset = "main"
```
### Optional Sub-Configs
@@ -142,27 +145,50 @@ mu = 0.95
Omit `type` to keep the default variant.
### Environments (`[[orchestrator.train.env]]`)
### Environments
Training environments are an array of tables — set one per env, optionally with sampling weights:
Training and evaluation sources are arrays of tables. Set one source per environment; training sources can optionally carry sampling weights:
```toml
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "gsm8k"
env.taskset = { id = "gsm8k-v1", split = "train" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
ratio = 3 # 75% of batches
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "gsm8k-v1"
split = "train"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
ratio = 1 # default — 25% of batches
[[orchestrator.eval.env]]
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.eval.source]]
name = "gsm8k-eval"
env.taskset = { id = "gsm8k-v1", split = "test" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "gsm8k-v1"
split = "test"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
```
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
+29 -15
View File
@@ -30,7 +30,9 @@ We support 3 distinct deployment shapes:
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `backend_port`, and a `[...deployment.router]` block, etc.
Every deployment shape has the same client-facing layout: a single global router listens on `inference.server.port` and fronts all vLLM engines, which listen on `inference.backend_port` (+ rank offset). Clients always talk to one URL, regardless of how many engines run behind it.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape and topology knobs such as `num_nodes` and `num_replicas`.
```toml
[inference.deployment]
@@ -56,6 +58,8 @@ The single-node deployment is the default deployment shape. It runs the inferenc
type = "single_node"
```
The launcher starts a `vllm-router` on `inference.server.port` (default `8000`) fronting the vLLM engine on `inference.backend_port` (default `8100`). Clients connect to the router URL; admin operations (weight updates, health checks) bypass the router and hit the engine port directly — the RL entrypoint wires `orchestrator.model.client.admin_base_url` accordingly.
This deployment shape runs the inference server on a single node, if configured with NVLink enabled, it allows you more freedom in terms of parallelism configurations.
```toml
@@ -102,7 +106,7 @@ tp = 2
dp = 4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a router instance running on the same node as the 1st replica — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[...deployment.router]` block. You can read more about the supported routing options in the [router](#router) section.
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a single global router running on the first inference node, fronting the per-rank endpoints of all replicas — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[inference.router]` block. You can read more about the supported routing options in the [router](#router) section.
### Wide-EP
@@ -160,25 +164,31 @@ num_train_nodes = 4
num_infer_replicas = 3
```
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes and start 3 separate router instances.
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes, fronted by the single global router.
## Router
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
Every deployment fronts its vLLM engines with a single global router — it listens on `inference.server.port` and is the one URL clients connect to. The backend is configured via a discriminated `[inference.router]` block (`type = "vllm-router" | "llm-d"`):
```toml
[inference.deployment.router] # or [deployment.router] for the standalone inference entrypoint
[inference.router] # or [router] for the standalone inference entrypoint
type = "llm-d" # "vllm-router" (default) or "llm-d"
# llm-d-only knobs (all optional):
scorers = { "prefix-cache-scorer" = 3.0, "active-request-scorer" = 2.0 } # base, applied to every profile
prefill_scorer_overrides = { "queue-scorer" = 2.0, "kv-cache-utilization-scorer" = 2.0 } # merged onto the P/D prefill profile
decode_scorer_overrides = {} # merged onto the P/D decode profile
non_cached_tokens = 16 # below this many non-cached prompt tokens, skip remote prefill (P/D)
non_cached_tokens = 16 # llm-d only: below this many non-cached prompt tokens, skip remote prefill (P/D)
# llm-d only: base scorer weights, applied to every profile
[inference.router.scorers]
"prefix-cache-scorer" = 3.0
"active-request-scorer" = 2.0
# llm-d only: merged onto the P/D prefill profile (decode_scorer_overrides for decode)
[inference.router.prefill_scorer_overrides]
"queue-scorer" = 2.0
"kv-cache-utilization-scorer" = 2.0
```
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy. Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`. The only backend supported for single-node (local) deployments.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy (multi-node / disaggregated SLURM deployments only). Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
Both backends support the 2 most important things:
- Request routing - KV cache re-use and balanced routing
@@ -251,8 +261,12 @@ For configuring various knobs with environment variables, we enable you to confi
[inference.deployment]
type = "disaggregated"
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip"}
[inference.deployment.prefill_env_vars]
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
[inference.deployment.decode_env_vars]
"VLLM_DEEP_GEMM_WARMUP" = "skip"
```
These are role-specific and layer on top of [`env_vars`](configuration.md#environment-variables) shared by all inference processes regardless of role.
@@ -279,6 +293,6 @@ enable_router_replay = true # this will also auto-set the inference.enable_retur
enable_return_routed_experts = true
```
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend increasing `orchestrator.*.env.num_workers` to allow for more parallelization on the verifiers side.
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
+1 -1
View File
@@ -12,7 +12,7 @@ A `prime-rl` RL run is three cooperating processes:
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses ZMQ, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap the rollout link to the local filesystem (`rollout_transport.type = "filesystem"`) if you want rollouts persisted to disk. See [Scaling](scaling.md) for the deployment options.
## Installation
+1 -1
View File
@@ -231,7 +231,7 @@ Full multi-node configs ship under [`examples/advanced/`](https://github.com/Pri
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), and the launcher prints one URL per node. Front the URLs with a router or point clients at any of them.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
### Custom Templates
+13 -12
View File
@@ -36,7 +36,8 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer + inference. |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at the source's derived `serve.address`); only needed when running the orchestrator standalone. |
## RL Trainer
@@ -59,9 +60,9 @@ 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.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.env]]` | Training environments. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Environments](configuration.md#environments-orchestratortrainenv). |
| `[[orchestrator.eval.env]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
| `[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). |
**Monitoring:**
@@ -89,6 +90,8 @@ The RL entrypoint supports several training algorithms, switched via `[orchestra
|---|---|---|
| `grpo` (default) | None | Standard group-relative RL |
| `max_rl` | None | [MaxRL](https://arxiv.org/abs/2602.02710): GRPO with mean-normalized advantages (maximum-likelihood RL) |
| `rae` | None | [SPIRAL](https://arxiv.org/abs/2506.24119)'s role-conditioned advantage estimation: reward minus a per-agent EMA baseline, for multi-agent self-play envs (e.g. `kuhn-poker-v1`) |
| `hierarchical_grpo` | None | GRPO for proposer-solver envs: compare solvers only with attempts on the same proposed problem, and compare proposers with the other proposals in the group |
| `opd` | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): the policy generates rollouts, the trainer minimizes per-token reverse KL to a reference model |
| `sft` | Required, any OpenAI-compatible endpoint | Hard-distill: a frozen model generates rollouts, the policy trains on its tokens |
| `opsd` | None — the live policy is its own reference (no deployment) | [SDFT](https://arxiv.org/abs/2601.19897): the model is its own reference conditioned on expert demonstrations |
@@ -215,7 +218,7 @@ Checkpointing is split across processes because the orchestrator and trainer can
| Process | What's saved | Where |
|---|---|---|
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<output_dir>/checkpoints/step_N/trainer/` |
| Orchestrator | Step counter, total tokens / samples / problems | `<output_dir>/checkpoints/step_N/orchestrator/` |
| Orchestrator | Progress, per-env data state | `<output_dir>/checkpoints/step_N/orchestrator/` |
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
| Trainer (HF weights) | HF-compatible weight snapshot for serving | `<output_dir>/weights/step_N/` |
@@ -256,7 +259,7 @@ For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write t
### Log Files
The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The full layout (single-node runs skip the `node_*.log` and `router_*.log` files):
The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
```
<output_dir>/logs/
@@ -268,20 +271,18 @@ The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The f
│ └── torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log # per-rank
├── inference/
│ ├── node_*.log # per-node inference stdout (multi-node only)
│ └── router_*.log # vllm-router per replica (multi-node only)
└── envs/{train,eval}/<env_name>/
├── env_server.log
└── env_worker_<id>.log
│ └── router.log # the single global router (multi-node only)
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
```
Env worker logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
```bash
tail -F <output_dir>/logs/{trainer,orchestrator,inference}.log
tail -F <output_dir>/logs/trainer/node_*.log # multi-node only
tail -F <output_dir>/logs/inference/router_*.log # multi-node only
tail -F <output_dir>/logs/inference/router.log # multi-node only
```
### Console Output
+54 -17
View File
@@ -71,7 +71,7 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
max_inflight_episodes = 512
[orchestrator.renderer]
name = "glm-4.5"
@@ -93,14 +93,25 @@ num_turns_weight = 0.0
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
# entry wholesale (keep `name`/`question_field`/`choices` in sync with the taskset defaults —
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "openseeker"
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
[orchestrator.train.env.env.taskset]
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "openseeker-v1"
[[orchestrator.train.env.env.taskset.task.judges]]
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
@@ -108,21 +119,32 @@ question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.env.env.taskset.task.judges]]
# [[orchestrator.train.source.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "redsearcher"
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
[orchestrator.train.env.env.taskset]
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
[[orchestrator.train.env.env.taskset.task.judges]]
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
@@ -130,7 +152,7 @@ question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.env.env.taskset.task.judges]]
# [[orchestrator.train.source.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
@@ -142,18 +164,33 @@ choices = ["A", "B"]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "browsecomp"
num_examples = 500 # full set is 1266; cap eval at 500
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.env.env.taskset]
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-search"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "browsecomp-v1"
task = { judge = { model = "Qwen/Qwen3-235B-A22B-Instruct-2507" } }
[orchestrator.eval.source.env.taskset.task.judge]
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.eval.env.env.taskset.task.judges]]
# [[orchestrator.eval.source.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
+32 -8
View File
@@ -82,7 +82,7 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
max_inflight_episodes = 512
[orchestrator.algo]
type = "grpo"
@@ -97,10 +97,21 @@ num_turns_weight = 0.1
name = "glm-4.5"
thinking_retention = "all"
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
[orchestrator.train.source.env.taskset]
id = "scaleswe-v1"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-swe"]
[orchestrator.prime_monitor]
@@ -109,11 +120,24 @@ env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-swe"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
# --- Inference ---
+49 -18
View File
@@ -72,7 +72,7 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
max_inflight_episodes = 512
[orchestrator.renderer]
name = "glm-4.5"
@@ -91,22 +91,31 @@ num_turns_weight = 0.1
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "tmax"
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
[orchestrator.train.env.env.taskset]
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-terminal"]
[orchestrator.train.source.env.taskset]
id = "tmax-v1"
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
# [[orchestrator.train.env.env.taskset.judges]]
# [[orchestrator.train.source.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.train.env.env.taskset.judges]]
# [[orchestrator.train.source.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
@@ -118,45 +127,67 @@ id = "tmax-v1"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swebench-verified"
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.env.env.taskset]
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-terminal"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
# [[orchestrator.eval.env.env.taskset.judges]]
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.eval.env.env.taskset.judges]]
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "terminal-bench-2"
group_size = 4 # avg@4
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.env.env.taskset]
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-terminal"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "terminal-bench-2-v1"
# [[orchestrator.eval.env.env.taskset.judges]]
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.eval.env.env.taskset.judges]]
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
+22 -6
View File
@@ -35,16 +35,32 @@ prefill_nodes_per_replica = 2
num_prefill_replicas = 4
decode_nodes_per_replica = 8
num_decode_replicas = 1
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
[deployment.router]
[deployment.prefill_env_vars]
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
[deployment.decode_env_vars]
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
[router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 }
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 }
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 }
non_cached_tokens = 128
[router.scorers]
"prefix-cache-scorer" = 3.0
[router.prefill_scorer_overrides]
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[router.decode_scorer_overrides]
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[slurm]
job_name = "glm5.2-16node-llmd"
partition = "all"
+44 -13
View File
@@ -28,23 +28,44 @@ prefill_nodes_per_replica = 2
num_prefill_replicas = 4
decode_nodes_per_replica = 8
num_decode_replicas = 1
# skip warmup for faster start in cost of some jit overhead early
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
[inference.deployment.prefill_env_vars]
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
[inference.deployment.decode_env_vars]
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
# gives the most KV cache while keeping decent throughput, KV cache increase comes in from lower deep-ep LL static buffers
prefill_vllm_overrides = {"enable_dbo"=true}
decode_vllm_overrides = {"max_num_batched_tokens"=96, "max_num_seqs"=96}
[inference.deployment.prefill_vllm_overrides]
"enable_dbo" = true
[inference.deployment.router]
[inference.deployment.decode_vllm_overrides]
"max_num_batched_tokens" = 96
"max_num_seqs" = 96
[inference.router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 } # need some prefix-cache routing, however due to shared mooncake pool do low prio
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 } # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 } # decode doesn't really create queue, it fills in KV cache fast, give 4.0
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[slurm]
job_name = "glm5-llmd"
partition = "all" # FILL IN: set to your cluster's partition
@@ -81,7 +102,7 @@ weight_decay = 0.0
[orchestrator]
batch_size = 256
group_size = 16
max_inflight_rollouts = 2048
max_inflight_episodes = 2048
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
[orchestrator.model]
@@ -93,13 +114,23 @@ clear_thinking = false
[orchestrator.train.sampling]
temperature = 1.0
extra_body = {chat_template_kwargs = {clear_thinking = false}}
[orchestrator.train.sampling.extra_body.chat_template_kwargs]
clear_thinking = false
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "r2e"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "rlm", runtime = { type = "prime", labels = ["glm5-llmd"] } }
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["glm5-llmd"]
[inference]
enable_expert_parallel = true
+11 -3
View File
@@ -71,10 +71,18 @@ name = "zai-org/GLM-5-FP8"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] } }
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
labels = ["glm5-pd-disag", "swe-bench-verified"]
[[orchestrator.post_batch_filters]]
type = "gibberish"
+78 -21
View File
@@ -47,35 +47,77 @@ weight_decay = 0.01
batch_size = 2048
oversampling_factor = 2
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "swe"
ratio = 0.3
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe"] } }
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["intellect-3.1", "swe"]
[[orchestrator.train.source]]
name = "deepdive"
ratio = 0.2
env.taskset = { id = "deepdive-v1" }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] } }
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "deepdive-v1"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["intellect-3.1", "deepdive"]
[[orchestrator.train.source]]
name = "math"
ratio = 0.3
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "i3_math_v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "logic"
ratio = 0.2
env.taskset = { id = "i3_logic_v1", filter = { max = 0.874 } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "i3_logic_v1"
[orchestrator.train.source.env.taskset.filter]
max = 0.874
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "code"
ratio = 0.2
env.taskset = { id = "i3_code_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "i3_code_v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
@@ -84,15 +126,30 @@ enforce = true
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] } }
[[orchestrator.eval.env]]
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
labels = ["intellect-3.1", "swe-bench-verified"]
[[orchestrator.eval.source]]
name = "aime2025"
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "aime25-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[inference.parallel]
tp = 8
+22 -6
View File
@@ -49,18 +49,34 @@ oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "swe"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe"] } }
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["minimax-swe", "swe"]
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] } }
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
labels = ["minimax-swe", "swe-bench-verified"]
[inference.parallel]
tp = 8
+32 -8
View File
@@ -66,7 +66,7 @@ type = "adamw"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 1536
max_inflight_episodes = 1536
[orchestrator.algo]
type = "grpo"
@@ -81,21 +81,45 @@ num_turns_weight = 0.1
name = "nemotron-3"
truncate_history_thinking = false
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
[orchestrator.train.source.env.taskset]
id = "scaleswe-v1"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["nemotron-3-super-swe"]
[orchestrator.prime_monitor]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["nemotron-3-super-swe"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[inference]
enable_expert_parallel = true
+21 -7
View File
@@ -48,18 +48,32 @@ max_off_policy_steps = 8
[orchestrator.train.sampling]
max_completion_tokens = 32768
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "math"
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "i3_math_v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "aime2025"
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "aime25-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[inference.parallel]
tp = 8
tp = 8
+23 -7
View File
@@ -46,18 +46,34 @@ batch_size = 512
oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "swe"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] } }
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["qwen30b-swe", "swe"]
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] } }
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
labels = ["qwen30b-swe", "swe-bench-verified"]
[inference.parallel]
tp = 8
tp = 8
+14 -3
View File
@@ -35,9 +35,20 @@ batch_size = 512
group_size = 16
max_off_policy_steps = 32
[[orchestrator.train.env]]
env.taskset = { id = "general-agent-v1", task = { tools = { colocated = true } }, min_tier = 1 }
env.agent.harness = { id = "null", runtime = { type = "modal" } }
[[orchestrator.train.source]]
[orchestrator.train.source.env.taskset]
id = "general-agent-v1"
min_tier = 1
[orchestrator.train.source.env.taskset.task.tools]
colocated = true
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "modal"
[inference]
gpu_memory_utilization = 0.85
+15 -3
View File
@@ -31,9 +31,21 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 768
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference] # Default inference config
+22 -6
View File
@@ -16,20 +16,36 @@ batch_size = 512
group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "math-env-v1"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "aime2024"
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.model]
seq_len = 16384
+10 -3
View File
@@ -15,10 +15,17 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
+3 -2
View File
@@ -133,10 +133,11 @@ uv run eval wiki-search-v1 --harness.id null \
The V1 taskset fixes the question bank and searchable corpus. You can replace its reference judge in `rl.toml`:
```toml
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wiki-search"
taskset = { id = "wiki-search-v1", task = { judges = [{ id = "reference", model = "openai/gpt-5.4-nano" }] } }
harness = { id = "null", runtime = { type = "subprocess" } }
harness = { id = "null" }
runtime = { type = "subprocess" }
```
## Notes
+10 -3
View File
@@ -44,10 +44,17 @@ max_completion_tokens = 512
type = "zero_advantage"
enforce = true
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "wiki-search-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[ckpt] # Checkpoint at the end of training
+10 -3
View File
@@ -18,10 +18,17 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "wordle-v1"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
+10 -3
View File
@@ -13,10 +13,17 @@ name = "reverse-text"
[train.sampling]
max_completion_tokens = 128
[[train.env]]
[[train.source]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[train.source.env.taskset]
id = "reverse-text-v1"
[train.source.env.agent.harness]
id = "null"
[train.source.env.agent.runtime]
type = "subprocess"
[renderer]
name = "prime-qwen3"
+2 -2
View File
@@ -7,10 +7,10 @@ requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.4.2",
"renderers>=0.1.8",
"renderers>=0.1.9.dev10",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.2.1",
"verifiers>=0.2.2.dev76",
]
[build-system]
@@ -35,6 +35,7 @@ executes them.
from typing import Annotated, Any, ClassVar, Literal, TypeAlias
import verifiers.v1 as vf
from pydantic import Field, model_validator
from renderers import AutoRendererConfig, RendererConfig
@@ -188,6 +189,13 @@ class BaseAlgoConfig(BaseConfig):
)
return self
def validate_env(self, env_config: vf.EnvConfig) -> None:
"""Raise if this algorithm cannot run on the env it is configured for,
given that env's resolved config. Most algorithms read only the rollouts
and their rewards, so they run on any env and the base does nothing;
override where the credit assignment encodes an env's episode structure.
Called once per train env after algorithm inheritance resolves."""
class GRPOAlgoConfig(BaseAlgoConfig):
type: Literal["grpo"] = "grpo"
@@ -232,6 +240,60 @@ class MaxRLAlgoConfig(BaseAlgoConfig):
action_loss_type: ClassVar[ActionLossType] = "rl"
class RAEAlgoConfig(BaseAlgoConfig):
type: Literal["rae"] = "rae"
"""RAE — role-conditioned advantage estimation (SPIRAL,
https://arxiv.org/abs/2506.24119): scalar advantage = reward minus a
per-agent EMA baseline of that agent's own rewards, consumed by the ``rl``
loss component. The advantage estimator for multi-agent self-play envs
(``kuhn-poker-v1`` and friends): in a zero-sum game the group mean is ~0
whatever the policy does, so a group-relative baseline mixes the agents'
opposite reward scales — a structural first-mover edge would read as
permanent credit. Per-agent baselines measure each agent against its own
expected reward instead. Works with any ``group_size`` (including 1)."""
action_loss_type: ClassVar[ActionLossType] = "rl"
decay: float = Field(0.95, ge=0.0, lt=1.0)
"""EMA decay of the per-agent baselines (SPIRAL's α): after a trace is
scored, its agent's baseline moves as ``baseline ← decay · baseline +
(1 − decay) · reward``. Baselines start at 0 and live in orchestrator
memory — a restart re-warms them over ~1/(1 − decay) traces per agent."""
class HierarchicalGRPOAlgoConfig(BaseAlgoConfig):
type: Literal["hierarchical_grpo"] = "hierarchical_grpo"
"""GRPO for proposer-solver envs.
Agents in ``episode_agents`` are compared with same-role attempts on the
same proposed problem. Other agents are compared with the same role across
proposals generated from one source task. This keeps rewards from different
problems and different roles out of the same average."""
action_loss_type: ClassVar[ActionLossType] = "rl"
episode_agents: list[str] = Field(min_length=1)
"""Roles compared within one proposed problem. Use ``["solver"]`` for
``proposer-solver-v1``."""
def validate_env(self, env_config: vf.EnvConfig) -> None:
"""Require the proposer-solver structure used by the comparisons."""
try:
from proposer_solver_v1 import ProposerSolverEnvConfig
except ImportError as e:
raise ValueError(
"algorithm 'hierarchical_grpo' requires a proposer-solver env, but the "
"proposer-solver-v1 package is not installed (`uv sync --all-packages`)."
) from e
if not isinstance(env_config, ProposerSolverEnvConfig):
raise ValueError(
f"algorithm 'hierarchical_grpo' needs a proposer-solver env, but this env resolved to "
f"{type(env_config).__name__}. It compares solver attempts on the same proposed "
"problem and proposers across proposals. Use 'grpo' for a flat env or 'rae' for "
"multi-agent self-play."
)
class OPDAlgoConfig(BaseAlgoConfig):
type: Literal["opd"] = "opd"
"""On-policy distillation: the per-token signal is the reverse KL to
@@ -305,7 +367,14 @@ class SFTAlgoConfig(BaseAlgoConfig):
AlgoConfig: TypeAlias = Annotated[
GRPOAlgoConfig | EchoAlgoConfig | MaxRLAlgoConfig | OPDAlgoConfig | OPSDAlgoConfig | SFTAlgoConfig,
GRPOAlgoConfig
| EchoAlgoConfig
| MaxRLAlgoConfig
| RAEAlgoConfig
| HierarchicalGRPOAlgoConfig
| OPDAlgoConfig
| OPSDAlgoConfig
| SFTAlgoConfig,
Field(discriminator="type"),
]
"""The training algorithm: sampling plus the per-token training signal (credit
@@ -314,6 +383,8 @@ its class defaults are the vetted setting.
- ``grpo`` — policy group sampling, group-relative advantage, RL loss (the default).
- ``max_rl`` — GRPO with mean-normalized advantages (maximum-likelihood RL).
- ``rae`` — reward minus a per-agent EMA baseline (SPIRAL), for multi-agent self-play envs.
- ``hierarchical_grpo`` — GRPO for proposer-solver envs: solvers are compared within one proposed problem and proposers across proposals. Needs ``episode_agents``.
- ``opd`` — on-policy distillation: policy samples, per-token reverse KL against a reference model. Needs ``teacher``.
- ``opsd`` — SDFT: policy samples, demo-conditioned reverse KL against the live policy (the teacher is the policy itself).
- ``sft`` — a frozen model samples, the policy trains with CE on its tokens. Needs a frozen ``sampling.source``.
@@ -1,14 +1,66 @@
from pathlib import Path
from prime_rl.configs.orchestrator import EnvConfig
import verifiers.v1 as vf
from pydantic import SerializeAsAny, model_validator
from prime_rl.configs.shared import LogConfig
from prime_rl.utils.config import BaseConfig
class EnvServerConfig(BaseConfig):
env: EnvConfig
"""``uv run env-server``: what to serve (``[env]``, or ``[legacy]`` for a classic v0
env) and how it's hosted (``[serve]``). The ``rl`` launcher writes one of these per
train/eval source, with ``serve.address`` set to the source's derived address."""
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
"""The environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
serve: vf.ServeConfig = vf.ServeConfig()
"""How it's served: the worker pool, the bind address, each worker's episode bound."""
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
"""A classic (v0) environment to serve through the bridge instead of ``env``."""
log: LogConfig = LogConfig()
output_dir: Path = Path("outputs")
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
@model_validator(mode="before")
@classmethod
def _resolve_env(cls, data):
"""Narrow ``env`` to the selected env's config class."""
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
@property
def is_legacy(self) -> bool:
"""Whether this serves the v0 bridge: a legacy id and no v1 taskset."""
return self.legacy.id is not None and not self.env.taskset.id
@property
def env_id(self) -> str:
"""The served env's identifier: the v1 env's, else the v0 env id."""
return self.env.env_id or self.legacy.id or ""
@model_validator(mode="after")
def validate_env(self):
# A v0 id next to any v1 env identity leaves one of the two going nowhere, and
# which one depends on `is_legacy`: a taskset makes it False, so the v0 env never
# loads; a bare `env.id` leaves it True, so the v0 env runs under the v1 name.
if self.legacy.id is not None and self.env.env_id:
if self.env.taskset.id:
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with "
f"the v1 taskset {self.env.taskset.id!r}. Pairing a reusable env with a taskset "
f"is env.id = {self.legacy.id!r}; to run the v0 env instead, drop the taskset."
)
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with the "
f"v1 env.id {self.env.id!r}: the v0 env is what would run, stamped with the v1 "
"env's name. Keep whichever one you meant to run."
)
if not self.env_id:
raise ValueError(
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or legacy = { id = "<id>" } (v0)'
)
return self
@@ -190,9 +190,6 @@ class VllmRouterConfig(BaseConfig):
type: Literal["vllm-router"] = "vllm-router"
port: int = 8000
"""Port the router listens on — becomes the client-facing router URL."""
policy: str = "consistent_hash"
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
@@ -202,9 +199,6 @@ class LlmdRouterConfig(BaseConfig):
type: Literal["llm-d"] = "llm-d"
port: int = 8000
"""Port the Envoy gateway listens on — becomes the client-facing router URL."""
scorers: dict[str, float] = {
"prefix-cache-scorer": 3.0,
"active-request-scorer": 2.0,
@@ -254,12 +248,6 @@ class BaseInferenceDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
"""GPUs per node."""
backend_port: int = 8100
"""Port for the per-rank vLLM backend instances."""
router: RouterConfig = VllmRouterConfig()
"""Router fronting the per-rank endpoints."""
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
type: Literal["single_node"] = "single_node"
@@ -331,6 +319,12 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
class InferenceConfig(BaseConfig):
server: ServerConfig = ServerConfig()
router: RouterConfig | None = Field(default_factory=VllmRouterConfig)
"""Router fronting the engine(s). Every deployment runs a single global router as the client-facing endpoint on ``server.port``, with the engines listening on ``backend_port``. Set to ``None`` to run a bare engine on ``server.port`` without a router (the SLURM launchers do this for per-rank engine processes; the sbatch script starts the router)."""
backend_port: int = 8100
"""Port for the vLLM engine(s) behind the router. Defaults to ``server.port + 100``. Multi-node deployments start one engine per local DP rank at ``backend_port + rank``."""
model: ModelConfig = Field(default_factory=ModelConfig)
parallel: ParallelConfig = ParallelConfig()
@@ -438,8 +432,7 @@ class InferenceConfig(BaseConfig):
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
router = getattr(self.deployment, "router", None)
if router is not None and router.type == "llm-d" and self.enable_return_routed_experts:
if self.router is not None and self.router.type == "llm-d" and self.enable_return_routed_experts:
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(enable_return_routed_experts): it breaks P/D and is unverified for multi-node. "
@@ -447,6 +440,21 @@ class InferenceConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_router_deployment(self):
"""The llm-d router (EPP + Envoy) is launched by the SLURM templates only; multi-node deployments need a router to front the per-rank engines."""
if self.router is not None and self.router.type == "llm-d" and self.deployment.type == "single_node":
raise ValueError("The llm-d router backend requires a multi-node or disaggregated SLURM deployment.")
if self.router is None and self.deployment.type in ("multi_node", "disaggregated"):
raise ValueError("Multi-node / disaggregated deployments require a router fronting the per-rank engines.")
return self
@model_validator(mode="after")
def auto_setup_backend_port(self):
if self.router is not None and "backend_port" not in self.model_fields_set:
self.backend_port = self.server.port + 100
return self
@model_validator(mode="after")
def auto_setup_kv_cache_offload(self):
if self.kv_cache_offload is not None:
@@ -1,10 +1,10 @@
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
import verifiers.v1 as vf
from pydantic import AliasChoices, Field, model_validator
from pydantic import Field, SerializeAsAny, model_validator
from renderers import AutoRendererConfig, RendererConfig
from verifiers.v1.configs.serve import PoolConfig
from prime_rl.configs.algorithm import (
AlgoConfig,
@@ -15,12 +15,12 @@ from prime_rl.configs.shared import (
ClientConfig,
EnvVars,
FileMonitorConfig,
FileSystemTransportConfig,
HeartbeatConfig,
LogConfig,
PrimeMonitorConfig,
TransportConfig,
WandbWithExtrasConfig,
ZMQTransportConfig,
)
from prime_rl.configs.trainer import TokenizerConfig
from prime_rl.utils.config import BaseConfig
@@ -54,9 +54,7 @@ class TrainSamplingConfig(BaseConfig):
temperature: float = Field(1.0, ge=0, le=2.0)
"""Sampling temperature."""
max_completion_tokens: int | None = Field(
None, validation_alias=AliasChoices("max_completion_tokens", "max_tokens")
)
max_completion_tokens: int | None = None
"""Maximum output tokens per turn. If None, generates until max context length or EOS."""
# Strictly speaking, extra_body is not a sampling parameter, but it is the
@@ -79,18 +77,6 @@ class TrainSamplingConfig(BaseConfig):
return args
@model_validator(mode="before")
@classmethod
def _deprecate_max_tokens(cls, data: Any) -> Any:
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
warnings.warn(
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
return data
class EvalSamplingConfig(BaseConfig):
temperature: float | None = Field(None, ge=0, le=2.0)
@@ -105,9 +91,7 @@ class EvalSamplingConfig(BaseConfig):
min_p: float | None = Field(None, ge=0)
"""Min-p sampling threshold. None defers to the inference server default."""
max_completion_tokens: int | None = Field(
None, validation_alias=AliasChoices("max_completion_tokens", "max_tokens")
)
max_completion_tokens: int | None = None
"""Maximum output tokens per turn. None defers to the inference server default."""
reasoning_effort: Literal["minimal", "low", "medium", "high"] | None = None
@@ -138,40 +122,57 @@ class EvalSamplingConfig(BaseConfig):
return args
@model_validator(mode="before")
@classmethod
def _deprecate_max_tokens(cls, data: Any) -> Any:
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
warnings.warn(
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
return data
class ServeConfig(BaseConfig):
"""The subset of verifiers' ``ServeConfig`` a source configures — the worker pool
and the per-worker bound. The launcher materializes it into the env server's full
``[serve]`` block, filling in the source's derived address
(``OrchestratorConfig.env_addresses``)."""
pool: PoolConfig = Field(default_factory=vf.ElasticPoolConfig)
"""Worker-pool sizing. ``elastic`` (default) starts at one worker and scales up on
demand; ``static`` pre-spawns a fixed ``num_workers``."""
max_concurrent: int | None = Field(None, ge=1)
"""Episodes in flight per worker (None = unbounded; the dispatcher's
``max_inflight_episodes`` is the run's bound)."""
class EnvConfig(vf.EnvServerConfig):
class EnvConfig(BaseConfig):
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
runs, ``serve`` — how it's hosted, ``legacy`` — a classic v0 env instead) plus this
orchestrator's own per-env knobs."""
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
"""The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
serve: ServeConfig = ServeConfig()
"""How this source's env server is sized. Consumed by the launcher (which writes each source's env-server config), not by the orchestrator — the orchestrator only connects."""
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
"""A classic (v0) environment to run through the bridge instead of ``env``."""
name: str | None = None
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
address: str | None = None
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically. The ``pool`` sizes the spawned server."""
ratio: float = Field(1.0, gt=0)
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
@model_validator(mode="before")
@classmethod
def _migrate_num_workers(cls, data):
"""Back-compat: the removed ``num_workers`` maps onto ``pool`` — an int becomes a
fixed ``static`` pool, ``"auto"`` falls through to the default ``elastic`` pool. An
explicit ``pool`` always wins."""
if isinstance(data, dict) and "num_workers" in data:
num_workers = data.pop("num_workers")
if "pool" not in data and num_workers != "auto":
data["pool"] = {"type": "static", "num_workers": num_workers}
return data
def _resolve_env(cls, data):
"""Narrow ``env`` to the selected env's config class."""
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
@property
def is_legacy(self) -> bool:
"""A classic (v0) env run through the bridge: a legacy id and no v1 taskset."""
return self.legacy.id is not None and not self.env.taskset.id
@property
def env_id(self) -> str:
"""The env's identifier: the v1 env's, else the v0 env id."""
return self.env.env_id or self.legacy.id or ""
@property
def resolved_name(self) -> str:
@@ -179,9 +180,24 @@ class EnvConfig(vf.EnvServerConfig):
@model_validator(mode="after")
def validate_env(self):
# A v0 id next to any v1 env identity leaves one of the two going nowhere, and
# which one depends on `is_legacy`: a taskset makes it False, so the v0 env never
# loads; a bare `env.id` leaves it True, so the v0 env runs under the v1 name.
if self.legacy.id is not None and self.env.env_id:
if self.env.taskset.id:
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with "
f"the v1 taskset {self.env.taskset.id!r}. Pairing a reusable env with a taskset "
f"is env.id = {self.legacy.id!r}; to run the v0 env instead, drop the taskset."
)
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with the "
f"v1 env.id {self.env.id!r}: the v0 env is what would run, stamped with the v1 "
"env's name. Keep whichever one you meant to run."
)
if not self.env_id:
raise ValueError(
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or id = "<id>" (v0/legacy)'
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or legacy = { id = "<id>" } (v0)'
)
if self.resolved_name == "agg":
raise ValueError(
@@ -192,25 +208,25 @@ class EnvConfig(vf.EnvServerConfig):
@model_validator(mode="after")
def resolve_legacy_env_kwargs(self):
"""For a v0/legacy env, surface the v1 knobs the legacy bridge applies via
``extra_env_kwargs`` (``env.set_kwargs(...)``): the per-rollout wall-clock timeout and
the multi-turn completion-token budget, read off ``env.agent``. (``max_seq_len`` is
added per train run in ``OrchestratorConfig.resolve_env_config``, which knows
``seq_len``.)"""
``legacy.extra_env_kwargs`` (``env.set_kwargs(...)``): the per-rollout wall-clock
timeout and the multi-turn completion-token budget, read off ``env.agent``.
(``max_seq_len`` is added per train run in ``OrchestratorConfig.resolve_env_config``,
which knows ``seq_len``.)"""
if self.is_legacy:
agent = getattr(self.env, "agent", None)
if agent is not None:
if agent.timeout.rollout is not None:
self.extra_env_kwargs["timeout_seconds"] = agent.timeout.rollout
self.legacy.extra_env_kwargs["timeout_seconds"] = agent.timeout.rollout
if agent.max_output_tokens is not None:
self.extra_env_kwargs["max_total_completion_tokens"] = agent.max_output_tokens
self.legacy.extra_env_kwargs["max_total_completion_tokens"] = agent.max_output_tokens
return self
class TrainEnvConfig(EnvConfig):
class TrainSourceConfig(EnvConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
group_size: int = Field(1, ge=1)
"""Rollouts generated per example for GRPO group-relative advantages.
Inherits from ``orchestrator.group_size`` when unset."""
@@ -220,14 +236,14 @@ class TrainEnvConfig(EnvConfig):
this env its own algorithm."""
class EvalEnvConfig(EnvConfig):
class EvalSourceConfig(EnvConfig):
sampling: EvalSamplingConfig = EvalSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
num_examples: int = -1
"""Eval examples to sample from the dataset. ``-1`` uses all available examples."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
group_size: int = Field(1, ge=1)
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8)."""
interval: int = Field(100, ge=1)
@@ -235,8 +251,8 @@ class EvalEnvConfig(EnvConfig):
class TrainConfig(BaseConfig):
env: list[TrainEnvConfig] = Field(default_factory=list)
"""Training environments."""
source: list[TrainSourceConfig] = Field(default_factory=list)
"""Training sources."""
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
@@ -246,7 +262,7 @@ class TrainConfig(BaseConfig):
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
is configured per env, defaulting to elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.env:
for env in self.source:
if "sampling" not in env.model_fields_set:
env.sampling = TrainSamplingConfig(**group_sampling)
else:
@@ -256,7 +272,7 @@ class TrainConfig(BaseConfig):
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [env.resolved_name for env in self.env]
env_names = [env.resolved_name for env in self.source]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(
@@ -266,8 +282,8 @@ class TrainConfig(BaseConfig):
class EvalConfig(BaseConfig):
env: list[EvalEnvConfig] = Field(default_factory=list)
"""Evaluation environments."""
source: list[EvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources."""
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
"""Shared eval sampling configuration; can differ from training sampling."""
@@ -275,7 +291,7 @@ class EvalConfig(BaseConfig):
num_examples: int = -1
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
group_size: int = Field(1, ge=1)
"""Default rollouts per example. Can be overridden per env."""
interval: int = Field(100, ge=1)
@@ -285,38 +301,43 @@ class EvalConfig(BaseConfig):
"""If True, skip the startup eval that otherwise runs before any
train rollouts."""
retrigger_on_resume: bool = False
"""If True, re-trigger evals at the checkpoint step on resume (e.g. after a
crash that left in-flight evals unfinished). By default, assumes a clean
exit where all evals already completed."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.env:
if "sampling" not in env.model_fields_set:
env.sampling = EvalSamplingConfig(**group_sampling)
for source in self.source:
if "sampling" not in source.model_fields_set:
source.sampling = EvalSamplingConfig(**group_sampling)
else:
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
env.sampling = EvalSamplingConfig(**merged)
if "num_examples" not in env.model_fields_set:
env.num_examples = self.num_examples
if "group_size" not in env.model_fields_set:
env.group_size = self.group_size
if "interval" not in env.model_fields_set:
env.interval = self.interval
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
source.sampling = EvalSamplingConfig(**merged)
if "num_examples" not in source.model_fields_set:
source.num_examples = self.num_examples
if "group_size" not in source.model_fields_set:
source.group_size = self.group_size
if "interval" not in source.model_fields_set:
source.interval = self.interval
return self
@model_validator(mode="after")
def validate_non_empty_envs(self):
if not self.env:
def validate_non_empty_sources(self):
if not self.source:
raise ValueError(
"EvalConfig must define at least one env. Either drop the "
"EvalConfig must define at least one source. Either drop the "
"[orchestrator.eval] block entirely (to disable eval) or "
"add a [[orchestrator.eval.env]] block."
"add a [[orchestrator.eval.source]] block."
)
return self
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [env.resolved_name for env in self.env]
env_names = [source.resolved_name for source in self.source]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(
@@ -437,7 +458,7 @@ class OrchestratorConfig(BaseConfig):
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
assignment and loss routing, fused — its ``type`` names the algorithm).
Defaults to ``grpo``. Override per env via ``[[orchestrator.train.env]]``'s
Defaults to ``grpo``. Override per source via ``[[orchestrator.train.source]]``'s
``algo``."""
model: ModelConfig = ModelConfig()
@@ -456,11 +477,6 @@ class OrchestratorConfig(BaseConfig):
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. RL/OPD roll out through the renderer
client; SFT uses it to backfill tokens for its chat-completions teacher."""
pool_size: int | None = Field(None, ge=1)
"""Number of renderer slots shared across concurrent rollouts. Bump
for long multi-turn prompts where client-side jinja tokenization
serializes."""
optim: OptimizerConfig = OptimizerConfig()
"""Per-run optimizer configuration for multi-run training."""
@@ -509,7 +525,7 @@ class OrchestratorConfig(BaseConfig):
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
"""Transport used to receive updated weights from the trainer."""
rollout_transport: TransportConfig = FileSystemTransportConfig()
rollout_transport: TransportConfig = ZMQTransportConfig()
"""Transport used to ship rollouts from orchestrator to trainer."""
output_dir: Path = Path("outputs/run_default")
@@ -518,6 +534,9 @@ class OrchestratorConfig(BaseConfig):
tasks_per_minute: int | None = Field(None, ge=1)
"""Rate limit per environment worker, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. With multiple workers, the effective total rate is ``workers × this value``. None disables rate limiting."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the source at position ``i`` (train, then eval) is served at ``tcp://127.0.0.1:<base + i>``. Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
batch_size: int | None = Field(None, ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
@@ -525,12 +544,12 @@ class OrchestratorConfig(BaseConfig):
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
oversampling_factor: float | None = Field(None, gt=0)
"""Rollout-mode batching only. Multiplier used to derive ``max_inflight_rollouts`` from ``batch_size`` when ``max_inflight_rollouts`` is unset. Values below 1.0 intentionally cap in-flight rollout capacity below ``batch_size``."""
"""Rollout-mode batching only. Multiplier used to derive ``max_inflight_episodes`` from ``batch_size`` when ``max_inflight_episodes`` is unset. Values below 1.0 intentionally cap in-flight episode capacity below ``batch_size``."""
max_inflight_rollouts: int | None = Field(None, ge=1)
"""Maximum number of rollouts kept in-flight. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
max_inflight_episodes: int | None = Field(None, ge=1)
"""Maximum number of episodes kept in-flight — one episode is one agent run at a time, whatever the env's agents are. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
group_size: int = Field(1, ge=1)
"""Output sequences returned per example during training."""
seq_len: int = 2048
@@ -552,33 +571,6 @@ class OrchestratorConfig(BaseConfig):
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
@model_validator(mode="before")
@classmethod
def _env_to_train(cls, data: Any) -> Any:
"""Allow [[env]] and [sampling] as shorthand for [train] with [[train.env]] and [train.sampling]."""
if not isinstance(data, dict):
return data
if "env" in data or "sampling" in data:
train = data.setdefault("train", {})
if isinstance(train, dict):
if "env" in data:
warnings.warn(
"'[[orchestrator.env]]' is deprecated, use '[[orchestrator.train.env]]' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
train.setdefault("env", data.pop("env"))
if "sampling" in data:
warnings.warn(
"'[orchestrator.sampling]' is deprecated, use '[orchestrator.train.sampling]' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
train.setdefault("sampling", data.pop("sampling"))
return data
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
@@ -617,31 +609,23 @@ class OrchestratorConfig(BaseConfig):
def inherit_env_algorithms(self):
"""Envs without their own algorithm inherit the top-level one.
Declared before any validator that reads ``algo``."""
for env_cfg in self.train.env:
for env_cfg in self.train.source:
if env_cfg.algo is None:
env_cfg.algo = self.algo.model_copy(deep=True)
return self
@model_validator(mode="after")
def validate_env_algorithms(self):
"""Let each algorithm reject environments it cannot score correctly."""
for env_cfg in self.train.source:
assert env_cfg.algo is not None # resolved by inherit_env_algorithms
env_cfg.algo.validate_env(env_cfg.env)
return self
@property
def any_policy_sourced(self) -> bool:
"""True when at least one train env samples rollouts from the live policy."""
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.env)
@model_validator(mode="after")
def validate_pool_size(self):
"""``pool_size`` sizes the renderer-client pool for policy-sourced
sampling. Reject it when that path never runs — no train env samples
from the policy — so callers don't silently pass it and wonder why
it's ignored."""
if self.pool_size is None:
return self
if not self.any_policy_sourced:
raise ValueError(
f"orchestrator.pool_size={self.pool_size!r} is set but no train env samples "
"from the policy — the renderer-client sampling pool never runs (the renderer "
"is still used for client-side tokenization). Remove pool_size."
)
return self
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.source)
@model_validator(mode="after")
def validate_renderer_auto_resolves(self):
@@ -691,29 +675,29 @@ class OrchestratorConfig(BaseConfig):
if has_token_batch:
if self.oversampling_factor is not None:
raise ValueError("oversampling_factor can only be set when batch_size is set")
if self.max_inflight_rollouts is None:
raise ValueError("max_inflight_rollouts must be set when token_batch_size is set")
if self.max_inflight_episodes is None:
raise ValueError("max_inflight_episodes must be set when token_batch_size is set")
else:
assert self.batch_size is not None
if self.batch_size % self.group_size != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
resolved_max_inflight_rollouts = max(
resolved_max_inflight_episodes = max(
self.group_size,
int(self.batch_size * oversampling_factor),
)
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
expected_max_inflight_rollouts = resolved_max_inflight_rollouts
if self.max_inflight_rollouts != expected_max_inflight_rollouts:
raise ValueError("max_inflight_rollouts conflicts with oversampling_factor * batch_size")
if self.max_inflight_rollouts is None:
self.max_inflight_rollouts = resolved_max_inflight_rollouts
if self.max_inflight_episodes is not None and self.oversampling_factor is not None:
expected_max_inflight_episodes = resolved_max_inflight_episodes
if self.max_inflight_episodes != expected_max_inflight_episodes:
raise ValueError("max_inflight_episodes conflicts with oversampling_factor * batch_size")
if self.max_inflight_episodes is None:
self.max_inflight_episodes = resolved_max_inflight_episodes
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.group_size:
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
if self.max_inflight_episodes is not None and self.max_inflight_episodes < self.group_size:
raise ValueError("max_inflight_episodes must be at least the number of rollouts per example")
# Propagate the top-level ``group_size`` into each train env that didn't set its own.
for env_cfg in self.train.env:
for env_cfg in self.train.source:
if "group_size" not in env_cfg.model_fields_set:
env_cfg.group_size = self.group_size
@@ -736,7 +720,7 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_config(self):
"""Set vLLM sampling defaults + legacy env kwargs on each train env from top-level fields."""
for env in self.train.env:
for env in self.train.source:
# Policy-sourced rollouts hit our vLLM server; frozen-sourced
# rollouts may hit external OAI endpoints that reject these knobs.
assert env.algo is not None
@@ -746,6 +730,27 @@ class OrchestratorConfig(BaseConfig):
env.sampling.extra_body.setdefault("return_token_ids", True)
if env.is_legacy:
# v0 env: cap per-turn response tokens to the training budget (the legacy
# bridge applies extra_env_kwargs via env.set_kwargs).
env.extra_env_kwargs["max_seq_len"] = self.seq_len
# bridge applies legacy.extra_env_kwargs via env.set_kwargs).
env.legacy.extra_env_kwargs["max_seq_len"] = self.seq_len
return self
@property
def env_sources(self) -> list[tuple[str, EnvConfig]]:
"""Every ``(split, source)`` this run pulls from, train first then eval — the
order that fixes each source's deterministic env-server port."""
sources: list[tuple[str, EnvConfig]] = [("train", source) for source in self.train.source]
if self.eval is not None:
sources += [("eval", source) for source in self.eval.source]
return sources
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each source's env server lives, keyed by ``(split, resolved_name)``:
``tcp://127.0.0.1:<port>`` with ports from ``env_server_base_port`` in
``env_sources`` order. The launcher binds env servers at exactly these addresses
and the orchestrator connects to them, so both sides agree from the config
alone."""
return {
(split, source.resolved_name): f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, (split, source) in enumerate(self.env_sources)
}
@@ -22,6 +22,7 @@ from prime_rl.configs.shared import (
EnvVars,
FileMonitorConfig,
SlurmConfig,
TransportConfig,
VLMConfig,
)
from prime_rl.configs.trainer import (
@@ -260,6 +261,8 @@ class RLConfig(BaseConfig):
weight_broadcast: SharedWeightBroadcastConfig | None = None
rollout_transport: TransportConfig | None = None
bench: bool = False
"""Benchmark mode. Sets trainer and orchestrator to benchmark mode and, when set, suffixes the W&B project with ``-bench``."""
@@ -419,6 +422,28 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def auto_setup_rollout_transport(self):
"""Resolve the shared ``rollout_transport`` from the sub-configs so the launcher can
gate multi-node ZMQ host injection on it (mirrors ``auto_setup_weight_broadcast``).
``rollout_transport`` may be set either as the shared block (propagated down to both
sub-configs by ``propagate_shared_fields``) or directly on
``trainer.rollout_transport`` / ``orchestrator.rollout_transport`` (the documented
fallback). Either way the shared field must reflect the resolved per-component
transport, otherwise the launcher would leave ZMQ trainers connecting to localhost.
"""
if self.trainer.rollout_transport.type != self.orchestrator.rollout_transport.type:
raise ValueError(
"trainer.rollout_transport.type "
f"({self.trainer.rollout_transport.type!r}) != orchestrator.rollout_transport.type "
f"({self.orchestrator.rollout_transport.type!r}); set the shared [rollout_transport] "
"block or make both sub-configs the same type."
)
if self.rollout_transport is None:
self.rollout_transport = self.trainer.rollout_transport
return self
@model_validator(mode="after")
def validate_eplb_requires_quantized_weight_transfer(self):
if self.inference is None or not self.inference.enable_eplb:
@@ -529,7 +554,7 @@ class RLConfig(BaseConfig):
(after InferenceConfig's own validators, which therefore miss it).
"""
if self.inference is not None and self.inference.enable_return_routed_experts:
router = getattr(self.inference.deployment, "router", None)
router = self.inference.router
if router is not None and router.type == "llm-d":
raise ValueError(
"The llm-d router backend does not support routed-expert return "
@@ -539,6 +564,12 @@ class RLConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_multi_node_requires_router(self):
if self.deployment.type == "multi_node" and self.inference is not None and self.inference.router is None:
raise ValueError("Multi-node deployments require inference.router to front the per-rank engines.")
return self
@model_validator(mode="after")
def validate_router_replay_without_kv_offload(self):
if (
@@ -707,27 +738,27 @@ class RLConfig(BaseConfig):
def auto_setup_inference_client(self):
"""Auto-configure the orchestrator policy client from the inference server config.
Direct single-node runs expose all local DP ranks behind one base URL,
so pin logical clients with ``X-data-parallel-rank``. Multi-node SLURM
runs expose a vllm-router URL instead; the router balances across
per-rank backend URLs and forwards request headers, so the orchestrator
must not inject a DP-rank header there. When no train env samples from
the policy (e.g. sft_distill), also set base_url — policy-sourced
algorithms rely on the ClientConfig default (``["http://localhost:8000/v1"]``)
which already matches the auto-launched policy vLLM at inference.server.port = 8000.
When no train env samples from the policy (e.g. sft_distill), set
base_url. Policy-sourced algorithms rely on the ClientConfig default
(``["http://localhost:8000/v1"]``), which already matches the
auto-launched policy router at inference.server.port = 8000.
"""
if self.inference is None:
return self
client = self.orchestrator.model.client
if "dp_rank_count" not in client.model_fields_set:
if self.deployment.type == "multi_node":
client.dp_rank_count = 1
else:
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
if not self.orchestrator.any_policy_sourced and "base_url" not in client.model_fields_set:
host = self.inference.server.host or "localhost"
port = self.inference.server.port
client.base_url = [f"http://{host}:{port}/v1"]
if (
self.deployment.type == "single_node"
and self.inference.router is not None
and "admin_base_url" not in client.model_fields_set
):
# Admin ops (pause/update_weights/resume) must bypass the router and hit
# the engine directly; multi-node runs get ADMIN_URLS from the sbatch.
host = self.inference.server.host or "localhost"
client.admin_base_url = [f"http://{host}:{self.inference.backend_port}/v1"]
return self
@model_validator(mode="after")
@@ -141,9 +141,6 @@ class ClientConfig(BaseConfig):
skip_model_check: bool = False
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
dp_rank_count: int = Field(1, ge=1)
"""Number of data-parallel ranks behind each base URL. When > 1, each URL is expanded into ``dp_rank_count`` logical clients pinned via the ``X-data-parallel-rank`` header, so every request within a rollout hits the same DP engine and reuses KV cache. Auto-set from the inference config when using the RL entrypoint."""
admin_base_url: list[str] | None = None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in disaggregated P/D deployments where the router must not handle admin traffic."""
@@ -8,12 +8,12 @@ from prime_rl.configs.shared import (
BaseModelConfig,
EnvVars,
FileMonitorConfig,
FileSystemTransportConfig,
HeartbeatConfig,
MetricsServerConfig,
TrainerLogConfig,
TransportConfig,
WandbConfig,
ZMQTransportConfig,
)
from prime_rl.utils.config import BaseConfig
@@ -582,7 +582,7 @@ class TrainerConfig(BaseConfig):
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
"""Transport used to broadcast updated weights from trainer to inference."""
rollout_transport: TransportConfig = FileSystemTransportConfig()
rollout_transport: TransportConfig = ZMQTransportConfig()
"""Transport used to ship rollouts from orchestrator to trainer."""
log: TrainerLogConfig = TrainerLogConfig()
@@ -2,12 +2,17 @@ import re
# (regex, parser_name) — first match wins.
TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
# Trinity-Large-Thinking uses the Qwen3-Coder tool format; the rest of the family is Hermes.
(re.compile(r"^arcee-ai/Trinity-Large-Thinking"), "qwen3_coder"),
(re.compile(r"^arcee-ai/Trinity-"), "hermes"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.2"), "deepseek_v32"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.1"), "deepseek_v31"),
(re.compile(r"^zai-org/GLM-4\.5"), "glm45"),
(re.compile(r"^zai-org/GLM-4\.7"), "glm47"),
(re.compile(r"^zai-org/GLM-5"), "glm47"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2"),
(re.compile(r"^openai/gpt-oss"), "openai"),
(re.compile(r"^poolside/Laguna"), "poolside_v1"),
(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"),
@@ -18,9 +23,13 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
]
REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
# Trinity-Large-Preview doesn't reason; the Thinking/Mini/Nano variants do.
(re.compile(r"^arcee-ai/Trinity-(Large-Thinking|Mini|Nano)"), "deepseek_r1"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.[12]"), "deepseek_r1"),
(re.compile(r"^zai-org/GLM-"), "glm45"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
# openai/gpt-oss has no entry here — vLLM's harmony serving path splits reasoning natively.
(re.compile(r"^poolside/Laguna"), "poolside_v1"),
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
@@ -126,6 +126,9 @@ def propagate_shared_fields(data: Any) -> Any:
"inference.model.chat_template",
)
# [rollout_transport] → both sub-configs (host is launcher-injected for zmq multi-node).
propagate("rollout_transport", "trainer.rollout_transport", "orchestrator.rollout_transport")
# Top-level scalars.
propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps")
propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len")
+13 -6
View File
@@ -18,7 +18,7 @@ dependencies = [
"torchaudio",
"torchdata>=0.11.0",
"transformers==5.6.2",
"vllm>=0.24.0",
"vllm>=0.26.0",
"mooncake-transfer-engine>=0.3.10.post2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.2.1",
"verifiers[harbor]>=0.2.2.dev76",
"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"
env-server = "prime_rl.orchestrator.env_server.env_server:main"
env-server = "prime_rl.entrypoints.env_server:main"
[project.entry-points."vllm.general_plugins"]
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
@@ -200,8 +200,8 @@ vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
@@ -235,7 +235,14 @@ explicit = true
[tool.ruff.lint]
select = ["F", "I"]
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
# jaxtyping writes shapes as string annotations (`Int[Tensor, "batch seq"]`), which ruff reads as
# forward references and reports as syntax errors / undefined names.
[tool.ruff.lint.per-file-ignores]
"src/prime_rl/trainer/model.py" = ["F722", "F821"]
"src/prime_rl/trainer/rl/data.py" = ["F722", "F821"]
"src/prime_rl/trainer/rl/loss.py" = ["F722", "F821"]
"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).
+28 -6
View File
@@ -30,10 +30,12 @@ uv run rl @ rl.toml --dry-run --output-dir /tmp/x # write resolved TOML to /tmp/
## Validators
Incompatible combinations (e.g. CP requires flash attention) must raise in a `model_validator` at resolve time, not at runtime. When renaming a field, emit a deprecation warning with a migration hint — never silently drop.
Incompatible combinations (e.g. CP requires flash attention) must raise in a `model_validator` at resolve time, not at runtime. When renaming a field, remove the old spelling: no `validation_alias`, no auto-translating `mode="before"` validator. The old key then fails as an unknown key, which is the signal. An alias that stays forever is worse than a break — it never gets retired, and a key whose *meaning* changed silently misconfigures the run.
## Special syntax
**No inline tables** — checked-in configs use `[section]` headers, never `key = { ... }`. Expand `env.taskset = { id = "..." }` to a full-path header (`[orchestrator.train.source.env.taskset]` — subtable headers after a `[[...]]` entry attach to that entry).
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--model.max-model-len None`.
@@ -41,19 +43,39 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
**Lists** — TOML uses array of tables; later config files replace lists wholesale, so overlays must include the full desired list:
```toml
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.eval.source]]
name = "reverse-text-eval"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
split = "test"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
```
CLI: `--orchestrator.train.env.0.env.taskset.id reverse-text-v1`.
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text-v1` or `--orchestrator.eval.source.0.env.taskset.id reverse-text-v1`.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--vllm-extra '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-env override: `[orchestrator.train.env.algo] type = "opd"` (the env assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
+1 -1
View File
@@ -57,7 +57,7 @@ Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
### llm-d router backend
Multi-node / disaggregated deployments can route through the upstream llm-d Endpoint Picker instead of `vllm-router` (set `[...deployment.router] type = "llm-d"`). It needs three native binaries — install once:
Multi-node / disaggregated deployments can route through the upstream llm-d Endpoint Picker instead of `vllm-router` (set `[inference.router] type = "llm-d"`). It needs three native binaries — install once:
```bash
bash scripts/install_llmd.sh # builds epp + pd-sidecar from a pinned llm-d-router commit (vendored Go), fetches envoy
+22 -14
View File
@@ -72,7 +72,7 @@ After a restart, verify all processes are back up and progress resumed before th
│ └── torchrun/ # per-rank stdout/stderr
├── inference/
│ ├── node_*.log # per-node (multi-node only)
│ └── router_0.log # vllm-router per replica (multi-node only)
│ └── router.log # the single global router (multi-node only; single-node logs it in inference.log)
└── envs/{train,eval}/{env_name}.log # one log file per env
```
@@ -89,17 +89,25 @@ grep -E "WARNING|ERROR" {output_dir}/logs/envs/{train,eval}/*.log
All metrics print to the console log (and W&B when configured).
**Progress** — orchestrator log. Rollout metrics are keyed `{scope}/{subset}/<metric>/<stat>`: `scope` is `train/agg` (all train envs) or `train/<env>` (`eval/<env>` for eval); `subset` is `all` (every rollout) or `effective` (post-filter).
**Progress** — orchestrator log. Rollout metrics mirror the episode/trace hierarchy, at two levels:
- `{scope}/{subset}/<metric>/<stat>` — episode-level facts only: the token/turn/branch counts, summed over an episode's traces.
- `{scope}/{subset}/<agent>/<metric>/<stat>` — every trace-level metric (reward, truncation, errors, timing, env metrics, filter verdicts, eval scores), keyed by agent name so seats never mix. Flat over that agent's traces: one sample is one trace, so an in-episode fan-out like n solvers contributes n samples.
`scope` is `train/agg` (all train envs) or `train/<env>` (`eval/<env>` for eval); `subset` is `all` (every rollout) or `effective` (post-filter). Single-agent envs have one agent — usually `agent` — and one trace per episode, so both levels agree; multi-agent envs name each seat (`proposer`, `solver`, `judge`, …).
| Metric | Description |
|--------|-------------|
| `train/agg/all/reward/mean` | mean training reward (per env: `train/<env>/all/reward/mean`) |
| `train/agg/all/num_total_tokens/mean` | avg tokens per rollout (also `num_input_tokens`, `num_output_tokens`) |
| `train/agg/all/num_turns/mean` | avg turns per rollout (multi-turn only) |
| `train/agg/all/is_truncated/mean` | fraction truncated |
| `train/agg/all/has_error/mean` | fraction errored (per-type under `train/agg/all/error/<type>`; also `dispatcher/errored/{train,eval}`) |
| `train/<env>/all/metrics/<name>/mean` | env-specific metrics (e.g. pass rate) |
| `eval/<env>/all/{avg@k,pass@k}` | eval scores when configured |
| `train/agg/effective/<agent>/reward/mean` | mean training reward for that agent (per env: `train/<env>/effective/<agent>/reward/mean`) |
| `train/agg/effective/num_total_tokens/mean` | avg tokens per episode, summed over its agents (also `num_input_tokens`, `num_output_tokens`) |
| `train/agg/effective/num_turns/mean` | avg turns per episode, summed over its agents |
| `train/<env>/effective/<agent>/num_turns/mean` | avg turns for that agent alone (also token counts, `num_branches`) |
| `train/agg/effective/<agent>/is_truncated/mean` | fraction of that agent's rollouts truncated |
| `train/agg/all/<agent>/has_error/mean` | fraction of that agent's rollouts errored (per-type under `train/agg/all/<agent>/error/<type>`; also `dispatcher/errored/{train,eval}`) |
| `train/agg/all/<agent>/is_trainable/mean` | fraction carrying a training signal — 0.0 for a frozen seat like a judge (also `is_filtered`, `filters/<name>`) |
| `train/<env>/effective/<agent>/metrics/<name>/mean` | env-specific metrics for that agent (e.g. pass rate) |
| `train/<env>/effective/<agent>/timing/agent/model/mean` | model vs harness share of that agent's phase |
| `eval/<env>/effective/<agent>/{avg@k,pass@k}` | eval scores for that agent, when configured |
**Stability** — trainer log:
@@ -126,7 +134,7 @@ All metrics print to the console log (and W&B when configured).
For live vLLM stats, query Prometheus directly:
```bash
curl -s http://localhost:8000/metrics | grep -E "num_requests|gpu_cache_usage"
curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage" # engine port (8000 is the router)
# vllm:num_requests_running, vllm:num_requests_waiting, vllm:gpu_cache_usage_perc (→1.0 = KV cache saturated)
```
@@ -154,7 +162,7 @@ jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.ok | not) | {id, env: .info.env_name, runtime}' {output_dir}/rollouts/step_*/train/all/traces.jsonl
```
The binary batches consumed by the trainer still live at `{output_dir}/rollouts/step_N/train_rollouts.bin`, 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 `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
### Common failure modes
@@ -172,9 +180,9 @@ All processes use `setproctitle` so they're visible in `ps`/`htop`/`pstree`:
```
PRIME-RL::Launcher
├── PRIME-RL::Inference (vLLM server, GPU 0)
├── PRIME-RL::Orchestrator (CPU-only)
│ └── Verifiers::EnvServer (ZMQ env server per environment)
│ └── Verifiers::EnvWorker0..N
├── PRIME-RL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
│ └── Verifiers::EnvWorker0..N
├── PRIME-RL::Orchestrator (CPU-only; connects to each env server)
├── torchrun
│ └── PRIME-RL::Trainer (GPU 1+)
└── tail trainer.log
+1 -1
View File
@@ -57,7 +57,7 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
## `inference` — vLLM server
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly.
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly.
```bash
uv run inference --model.name Qwen/Qwen3-0.6B
@@ -12,28 +12,26 @@ from prime_rl.utils.utils import clean_exit
@clean_exit
def run_server(config: EnvServerConfig):
env = config.env
address = env.address or "tcp://127.0.0.1:5000"
# The env's ``pool`` (static or elastic) sizes the server; a v0/legacy env runs through
# ``serve.pool`` (static or elastic) sizes the server; a v0/legacy env runs through
# the bridge, a v1 env is a native env block — both speak the same serve protocol,
# so the orchestrator is agnostic. serve_env applies the logging setup in this process
# and in every spawned worker.
server_kwargs = (
{"env_id": env.env_id, "env_args": env.args, "extra_env_kwargs": env.extra_env_kwargs}
if env.is_legacy
else {"config_data": env_config_data(env.env)}
{"env_id": config.env_id, "env_args": config.legacy.args, "extra_env_kwargs": config.legacy.extra_env_kwargs}
if config.is_legacy
else {"config_data": env_config_data(config.env), "max_concurrent": config.serve.max_concurrent}
)
serve_env(
**pool_serve_kwargs(env.pool),
legacy=env.is_legacy,
address=address,
**pool_serve_kwargs(config.serve.pool),
legacy=config.is_legacy,
address=config.serve.address,
log_setup=partial(setup_env_server_logging, config.log.level, config.log.json_logging),
**server_kwargs,
)
def main():
"""Main entry-point for env-server. Run using `uv run env-server`"""
"""Main entry-point for the env server. Run using `uv run env-server`"""
set_proc_title("EnvServer")
run_server(cli(EnvServerConfig))
+78 -16
View File
@@ -1,8 +1,10 @@
import json
import os
import signal
import subprocess
import sys
from pathlib import Path
from threading import Event, Thread
from typing import Any
import tomli_w
@@ -11,7 +13,12 @@ from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli, to_toml_dict
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, DEFAULT_INFERENCE_ENV_VARS, set_proc_title
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
cleanup_processes,
set_proc_title,
)
INFERENCE_TOML = "inference.toml"
INFERENCE_SBATCH = "inference.sbatch"
@@ -28,12 +35,21 @@ def vllm_overrides_fragment(overrides: dict[str, Any]) -> str:
return ", " + json.dumps(overrides)[1:-1].replace('"', '\\"')
def write_config(config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None) -> Path:
"""Write resolved config to disk."""
def write_config(
config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None, engine_only: bool = False
) -> Path:
"""Write resolved config to disk.
With ``engine_only``, the router is nulled so per-rank processes run bare
engines — the sbatch script starts the single global router.
"""
output_dir.mkdir(parents=True, exist_ok=True)
config_path = output_dir / INFERENCE_TOML
toml_dict = to_toml_dict(config, exclude=exclude)
if engine_only:
toml_dict["router"] = "None"
with open(config_path, "wb") as f:
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
tomli_w.dump(toml_dict, f)
return config_path
@@ -61,6 +77,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
dp_per_node=dp_per_node,
num_nodes=getattr(config.deployment, "num_nodes", 1),
port=config.server.port,
router=config.router,
router_port=config.server.port,
is_disaggregated=is_disaggregated,
kv_offload=offload is not None,
kv_offload_mooncake=is_mooncake,
@@ -82,7 +100,6 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
num_decode_replicas=config.deployment.num_decode_replicas,
prefill_port=config.deployment.prefill_port,
decode_port=config.deployment.decode_port,
router=config.deployment.router,
data_parallel_rpc_port=config.data_parallel_rpc_port,
use_deep_gemm=config.use_deep_gemm,
prefill_env_vars=config.deployment.prefill_env_vars,
@@ -92,8 +109,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
)
elif is_multi_node:
template_vars.update(
router=config.deployment.router,
backend_port=config.deployment.backend_port,
backend_port=config.backend_port,
data_parallel_rpc_port=config.data_parallel_rpc_port,
enable_expert_parallel=config.enable_expert_parallel,
infer_nodes_per_replica=config.deployment.num_nodes,
@@ -112,12 +128,9 @@ def inference_slurm(config: InferenceConfig):
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
config_dir = get_config_dir(config.output_dir)
exclude = (
{"deployment", "slurm", "dry_run"}
if config.deployment.type in ("multi_node", "disaggregated")
else {"slurm", "dry_run"}
)
config_path = write_config(config, config_dir, exclude=exclude)
is_multi_node = config.deployment.type in ("multi_node", "disaggregated")
exclude = {"deployment", "slurm", "dry_run"} if is_multi_node else {"slurm", "dry_run"}
config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node)
logger.info(f"Wrote config to {config_path}")
script_path = config.output_dir / INFERENCE_SBATCH
@@ -141,8 +154,35 @@ def inference_slurm(config: InferenceConfig):
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
def start_router(config: InferenceConfig) -> subprocess.Popen:
"""Start the vllm-router on ``server.port``, fronting the local engine at ``backend_port``."""
assert config.router is not None and config.router.type == "vllm-router"
host = config.server.host
worker_host = "localhost" if host in (None, "0.0.0.0") else host
cmd = [
"vllm-router",
"--policy",
config.router.policy,
"--host",
host or "0.0.0.0",
"--port",
str(config.server.port),
"--worker-urls",
f"http://{worker_host}:{config.backend_port}",
"--intra-node-data-parallel-size",
str(config.data_parallel_size_local or config.parallel.dp),
"--request-id-headers",
"x-session-id",
"--worker-startup-timeout-secs",
"4200",
"--prometheus-port",
str(config.server.port + 21000),
]
return subprocess.Popen(cmd)
def inference_local(config: InferenceConfig):
"""Run inference locally."""
"""Run inference locally: a router on ``server.port`` fronting the engine on ``backend_port``."""
from prime_rl.inference.server import setup_vllm_env
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
@@ -153,7 +193,6 @@ def inference_local(config: InferenceConfig):
host = config.server.host or "0.0.0.0"
port = config.server.port
logger.info(f"Starting inference on http://{host}:{port}/v1\n")
# Apply the inference env (defaults + [inference.env_vars]) in-process so a standalone
# `uv run inference` gets the same environment the rl/SLURM launchers inject into the
@@ -162,9 +201,32 @@ def inference_local(config: InferenceConfig):
setup_vllm_env(config)
router_process: subprocess.Popen | None = None
router_stopping = Event()
if config.router is not None:
logger.info(f"Starting router on http://{host}:{port}/v1 (engine on port {config.backend_port})\n")
router_process = start_router(config)
# The router owns the client-facing port; the engine moves behind it.
config.server.port = config.backend_port
def watch_router():
router_process.wait()
if not router_stopping.is_set():
logger.error(f"Router exited with code {router_process.returncode} - shutting down")
os.kill(os.getpid(), signal.SIGTERM)
Thread(target=watch_router, daemon=True).start()
else:
logger.info(f"Starting inference on http://{host}:{port}/v1\n")
from prime_rl.inference.vllm.server import server # pyright: ignore
server(config, vllm_extra=config.vllm_extra)
try:
server(config, vllm_extra=config.vllm_extra)
finally:
if router_process is not None:
router_stopping.set()
cleanup_processes([router_process])
def inference(config: InferenceConfig):
+95 -12
View File
@@ -8,12 +8,14 @@ import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from urllib.parse import urlparse
import pynvml
import tomli_w
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.inference import vllm_overrides_fragment
from prime_rl.utils.config import cli, to_toml_dict
@@ -43,6 +45,17 @@ TRAINER_TOML = "trainer.toml"
ORCHESTRATOR_TOML = "orchestrator.toml"
INFERENCE_TOML = "inference.toml"
ENVS_DIR = "envs"
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig, str]]:
"""``(split, source, address)`` for every train/eval source. The launcher runs one
env server per source at its deterministic address; the orchestrator connects there."""
addresses = config.orchestrator.env_addresses
return [
(split, source, addresses[(split, source.resolved_name)]) for split, source in config.orchestrator.env_sources
]
def get_physical_gpu_ids() -> list[int]:
"""Return physical GPU IDs visible to the launcher."""
@@ -73,8 +86,28 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
if config.inference is not None:
# Exclude launcher-only fields that are not needed by the vLLM server
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
inference_dict = to_toml_dict(config.inference, exclude=exclude_inference)
if config.deployment.type == "multi_node":
# Per-rank processes run bare engines; the sbatch starts the single global router.
inference_dict["router"] = "None"
with open(output_dir / INFERENCE_TOML, "wb") as f:
tomli_w.dump(to_toml_dict(config.inference, exclude=exclude_inference), f)
tomli_w.dump(inference_dict, f)
# One EnvServerConfig TOML per source: `env-server @ <path>` binds at the source's
# deterministic address, where the orchestrator connects. The source's env/serve/legacy
# blocks carry over; its other knobs (sampling, algo, name, ...) are orchestrator-side.
for split, source, address in env_servers(config):
env_dir = output_dir / ENVS_DIR / split
env_dir.mkdir(parents=True, exist_ok=True)
source_dict = to_toml_dict(source)
env_server_dict = {
"env": source_dict["env"],
"serve": {**source_dict.get("serve", {}), "address": address},
"legacy": source_dict.get("legacy", {}),
"log": {"level": config.orchestrator.log.vf_level, "json_logging": config.orchestrator.log.json_logging},
}
with open(env_dir / f"{source.resolved_name}.toml", "wb") as f:
tomli_w.dump(env_server_dict, f)
def rl_local(config: RLConfig):
@@ -127,8 +160,6 @@ def rl_local(config: RLConfig):
# Validate client port matches inference server port
if config.inference is not None and not config.orchestrator.model.client.is_elastic:
from urllib.parse import urlparse
base_url = config.orchestrator.model.client.base_url[0]
parsed = urlparse(base_url)
client_port = parsed.port
@@ -201,9 +232,9 @@ def rl_local(config: RLConfig):
)
frozen_endpoints: list[str] = []
for env in config.orchestrator.train.env:
for env in config.orchestrator.train.source:
algo = env.algo
assert algo is not None, "TrainEnvConfig.algo must be resolved before launch (inherit_env_algorithms)"
assert algo is not None, "TrainSourceConfig.algo must be resolved before launch (inherit_env_algorithms)"
for ref in (algo.sampling.source, getattr(algo, "teacher", None)):
if isinstance(ref, FrozenModelConfig):
frozen_endpoints.append(f"{ref.name} ({', '.join(ref.base_url)})")
@@ -215,6 +246,41 @@ def rl_local(config: RLConfig):
"otherwise rollouts will hang."
)
# Start one env server per source. The orchestrator connects to each source's
# deterministic address, polling until the server is up, so the servers and the
# orchestrator start in parallel.
for split, source, address in env_servers(config):
name = source.resolved_name
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.toml").as_posix()]
logger.info(f"Starting {split} env server {name} at {address}")
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
env_server_log.parent.mkdir(parents=True, exist_ok=True)
with open(env_server_log, "w") as log_file:
env_server_process = Popen(
env_server_cmd,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**config.env_vars,
**config.orchestrator.env_vars,
},
stdout=log_file,
stderr=log_file,
)
processes.append(env_server_process)
# Start monitoring thread
stop_event = Event()
stop_events[f"env/{split}/{name}"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(env_server_process, stop_event, error_queue, f"{split} env server {name}"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_TOML).as_posix()]
logger.info("Starting orchestrator process")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
@@ -387,6 +453,11 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
else {}
)
# Env servers launch next to the orchestrator, one per train/eval source.
sources = config.orchestrator.env_sources
train_env_names = [source.resolved_name for split, source in sources if split == "train"]
eval_env_names = [source.resolved_name for split, source in sources if split == "eval"]
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
@@ -414,7 +485,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
num_prefill_replicas=infer_deploy.num_prefill_replicas,
num_decode_replicas=infer_deploy.num_decode_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router=infer_deploy.router,
router=config.inference.router,
router_port=config.inference.server.port,
prefill_port=infer_deploy.prefill_port,
decode_port=infer_deploy.decode_port,
inference_tp=config.inference.parallel.tp,
@@ -430,8 +502,11 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
**mooncake_vars,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
)
else:
script = template.render(
@@ -445,20 +520,24 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
num_infer_replicas=config.deployment.num_infer_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
router=config.inference.router if config.inference else VllmRouterConfig(),
router_port=config.inference.server.port if config.inference else 8000,
infer_nodes_per_replica=config.deployment.infer_nodes_per_replica,
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
backend_port=config.inference.backend_port if config.inference else 8100,
inference_tp=config.inference.parallel.tp if config.inference else 1,
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
dp_per_node=(config.deployment.gpus_per_node // config.inference.parallel.tp) if config.inference else 1,
**mooncake_vars,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
trainer_env_vars=trainer_env_vars,
orchestrator_env_vars=orchestrator_env_vars,
inference_env_vars=inference_env_vars,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
@@ -479,8 +558,10 @@ def rl_slurm(config: RLConfig):
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean_output_dir"})
logger.info(f"Wrote config to {config_dir / RL_TOML}")
train_env_names = [env.resolved_name for env in config.orchestrator.train.env]
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
train_env_names = [env.resolved_name for env in config.orchestrator.train.source]
eval_env_names = (
[source.resolved_name for source in config.orchestrator.eval.source] if config.orchestrator.eval else []
)
log_message = format_log_message(
log_dir=log_dir,
@@ -494,8 +575,10 @@ def rl_slurm(config: RLConfig):
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
train_env_names = [env.resolved_name for env in config.orchestrator.train.env]
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
train_env_names = [env.resolved_name for env in config.orchestrator.train.source]
eval_env_names = (
[source.resolved_name for source in config.orchestrator.eval.source] if config.orchestrator.eval else []
)
has_infer = config.deployment.infer_nodes_per_replica > 0
log_message = format_log_message(
-3
View File
@@ -1,7 +1,5 @@
import torch
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
def apply_shared_vllm_patches():
"""vLLM general plugin: prime-rl patches that must run in every vLLM process.
@@ -16,7 +14,6 @@ def apply_shared_vllm_patches():
monkey_patch_nano_v3_reasoning_parser()
monkey_patch_qwen3_coder_param_newline_trim()
monkey_patch_minimax_m2_think_end_passthrough()
monkey_patch_vllm_padded_input_scrub()
monkey_patch_return_routed_experts_with_nixl_connector()
monkey_patch_kv_xfer_finished_tolerate_freed()
monkey_patch_online_fp8_parameter_cast()
+4 -8
View File
@@ -10,14 +10,10 @@ def setup_vllm_env(config: InferenceConfig):
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
# Force the V1 GPU model runner. vLLM 0.24.0 routes Llama/Mistral/Qwen3 plus MoE archs
# (DeepseekV2, Qwen2Moe, GraniteMoe; the 0.23 MoE/quantized guard was removed) to the
# V2 runner, which has no `_preprocess` hook for our padded-input scrub (see
# inference/vllm/padded_input_scrub.py) and doesn't zero the padded decode tail
# itself; that stale tail poisons CUDA-graph replay as NaN logits (reproduced on
# Nemotron-Nano SWE, PR #2506; upstream fix vllm#42779 is still unmerged). V1 keeps
# the scrub effective for every model and is also required for routed-experts capture
# (the NIXL PD path rejects V2). setdefault so it stays overridable.
# Force the V1 GPU model runner. vLLM routes Llama/Mistral/Qwen3 plus MoE archs
# (DeepseekV2, Qwen2Moe, GraniteMoe) to the V2 runner by default, but V2 doesn't
# support routed-experts capture (the NIXL PD path rejects it). setdefault so it
# stays overridable.
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
@@ -1,88 +0,0 @@
from __future__ import annotations
import logging
import threading
from collections.abc import Sequence
from typing import Any
logger = logging.getLogger(__name__)
_INSTALL_LOCK = threading.Lock()
_INSTALLED = False
def monkey_patch_vllm_padded_input_scrub() -> None:
"""Zero vLLM's padded model inputs before graph replay.
vLLM pads decode batches up to CUDA graph capture sizes. Some kernels read
model-input tensors past the scheduled-token prefix, so stale values in the
padded tail can affect replayed decode graphs. Keep this shim until the
vLLM-side fix is available in the pinned runtime.
Remove this patch once https://github.com/vllm-project/vllm/pull/42779 is
included in the vLLM release we pin/use.
"""
global _INSTALLED
with _INSTALL_LOCK:
if _INSTALLED:
return
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
if getattr(GPUModelRunner, "_prime_rl_padded_input_scrub", False):
_INSTALLED = True
return
original_preprocess = GPUModelRunner._preprocess
def _patched_preprocess(
self: Any,
scheduler_output: Any,
num_input_tokens: int,
intermediate_tensors: Any | None = None,
) -> tuple[Any, ...]:
result = original_preprocess(
self,
scheduler_output,
num_input_tokens,
intermediate_tensors,
)
num_scheduled_tokens = int(scheduler_output.total_num_scheduled_tokens)
_zero_padded_model_inputs(
result,
num_scheduled_tokens,
int(num_input_tokens),
)
return result
GPUModelRunner._preprocess = _patched_preprocess
GPUModelRunner._prime_rl_padded_input_scrub = True
_INSTALLED = True
logger.warning("Enabled vLLM padded model-input scrub.")
def _zero_padded_model_inputs(
preprocess_result: Sequence[Any],
num_scheduled_tokens: int,
num_input_tokens: int,
) -> None:
"""Zero the model-input tail beyond scheduled tokens in-place."""
if num_input_tokens <= num_scheduled_tokens:
return
input_ids = preprocess_result[0]
inputs_embeds = preprocess_result[1]
positions = preprocess_result[2]
pad_slice = slice(num_scheduled_tokens, num_input_tokens)
if input_ids is not None:
input_ids[pad_slice].zero_()
if inputs_embeds is not None:
inputs_embeds[pad_slice].zero_()
if positions is not None:
if positions.ndim == 1:
positions[pad_slice].zero_()
else:
positions[..., pad_slice].zero_()
-4
View File
@@ -25,7 +25,6 @@ from prime_rl.inference.patches import (
monkey_patch_nano_v3_reasoning_parser,
monkey_patch_strip_routed_experts_from_chat,
monkey_patch_tokenize_params_validation,
monkey_patch_vllm_padded_input_scrub,
)
# NOTE: Fix harmony stop token propagation for GPT-OSS models
@@ -37,9 +36,6 @@ monkey_patch_tokenize_params_validation()
# NOTE: Register Nano V3 reasoning parser so configs can use
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
monkey_patch_nano_v3_reasoning_parser()
# NOTE: Optional mitigation for vLLM padded decode inputs until the native fix
# is available in our pinned runtime.
monkey_patch_vllm_padded_input_scrub()
# NOTE: routed_experts are consumed only via the serialized /generate path (router
# replay). The chat-completions path encodes them as a base64 np.save string the PD
# router cannot merge, which fails eval rollouts (they use chat completions). Strip
@@ -1,7 +1,7 @@
"""Prime-RL extensions to vLLM's `/inference/v1/generate` handler.
vLLM 0.22 ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.serve.disagg.serving.ServingTokens`` that already covers
vLLM ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
priority, ``data_parallel_rank`` header routing and server-side ``max_tokens``
defaulting. We subclass it for the bits still missing from the upstream handler:
@@ -37,12 +37,12 @@ from vllm.entrypoints.openai.engine.protocol import (
RequestResponseMetadata,
UsageInfo,
)
from vllm.entrypoints.serve.disagg.protocol import (
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateRequest,
GenerateResponse,
GenerateResponseChoice,
)
from vllm.entrypoints.serve.disagg.serving import ServingTokens
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
from vllm.entrypoints.serve.utils.api_utils import get_max_tokens
from vllm.outputs import RequestOutput
from vllm.sampling_params import RequestOutputKind, SamplingParams
@@ -176,7 +176,7 @@ class PrimeRlServingTokens(ServingTokens):
request: GenerateRequest,
raw_request: Request | None = None,
) -> PrimeRlGenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
# Mirrors upstream ``ServingTokens.serve_tokens`` (vllm 0.22). Diffs:
# Mirrors upstream ``ServingTokens.serve_tokens``. Diffs:
# (a) inject ``data_parallel_rank`` from the inbound header into
# ``engine_client.generate``; (b) default ``sampling_params.max_tokens``
# to ``max_model_len - prompt_len`` when the caller didn't set it; and
@@ -200,10 +200,11 @@ class PrimeRlServingTokens(ServingTokens):
# Build the engine input — features-aware (MM) or text-only fallback.
# Identical to upstream so we keep tracking it.
if features := request.features:
from vllm.entrypoints.serve.disagg.mm_serde import decode_mm_kwargs_item
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import decode_mm_kwargs_item
from vllm.inputs import mm_input
from vllm.multimodal.inputs import (
MultiModalKwargsItem,
MultiModalKwargsItems,
PlaceholderRange,
)
@@ -220,13 +221,13 @@ class PrimeRlServingTokens(ServingTokens):
mm_kwargs[modality] = [None] * len(hashes)
engine_input = mm_input(
prompt_token_ids=request.token_ids,
mm_kwargs=mm_kwargs, # type: ignore[arg-type]
mm_kwargs=MultiModalKwargsItems(mm_kwargs),
mm_hashes=features.mm_hashes,
mm_placeholders=mm_placeholders,
cache_salt=request.cache_salt,
)
else:
(engine_input,) = await self.openai_serving_render.preprocess_completion(
(engine_input,) = await self.online_renderer.preprocess_completion(
request,
prompt_input=request.token_ids,
prompt_embeds=None,
+9 -2
View File
@@ -5,8 +5,9 @@ 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`):
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``opd``,
``opsd``, ``sft``) — each named class owns its scoring hooks
- 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
component, a "teacher", ...). One instance per env, built by
:func:`build_algorithm`. A new credit-assignment scheme is a new named class:
@@ -31,9 +32,11 @@ from typing import TYPE_CHECKING
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_pool
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
from prime_rl.orchestrator.algo.hierarchical_grpo import HierarchicalGRPOAlgorithm
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.sft import SFTDistillAlgorithm
from prime_rl.orchestrator.types import Rollout
@@ -48,6 +51,8 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
"grpo": GRPOAlgorithm,
"echo": EchoAlgorithm,
"max_rl": MaxRLAlgorithm,
"rae": RAEAlgorithm,
"hierarchical_grpo": HierarchicalGRPOAlgorithm,
"opd": OPDAlgorithm,
"opsd": OPSDAlgorithm,
"sft": SFTDistillAlgorithm,
@@ -69,9 +74,11 @@ __all__ = [
"Algorithm",
"EchoAlgorithm",
"GRPOAlgorithm",
"HierarchicalGRPOAlgorithm",
"MaxRLAlgorithm",
"OPDAlgorithm",
"OPSDAlgorithm",
"RAEAlgorithm",
"Rollout",
"SFTDistillAlgorithm",
"build_algorithm",
@@ -0,0 +1,40 @@
from __future__ import annotations
from collections import defaultdict
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import HierarchicalGRPOAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
from prime_rl.utils.client import InferencePool
class HierarchicalGRPOAlgorithm(Algorithm):
"""GRPO for proposer-solver envs.
Solver rewards are compared only with other attempts on the same proposed
problem. Proposer rewards are compared with the other proposals generated
from the same source task. Keeping those comparisons separate avoids
treating different problem difficulties or different agent roles as
interchangeable.
``episode_agents`` lists the roles, normally ``solver``, that are compared
within one episode. Other roles are compared across the full rollout group.
A comparison group with one trace produces zero advantage."""
def __init__(self, config: HierarchicalGRPOAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
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)
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)
+41
View File
@@ -0,0 +1,41 @@
from __future__ import annotations
from collections import defaultdict
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import RAEAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
from prime_rl.utils.client import InferencePool
class RAEAlgorithm(Algorithm):
"""Role-conditioned advantage estimation (SPIRAL, arXiv:2506.24119):
credit = reward minus a per-agent EMA baseline of that agent's rewards.
The advantage estimator for multi-agent self-play envs (kuhn-poker-v1 and
friends): in a zero-sum game the group mean is ~0 whatever the policy does,
and centering all agents against it mixes their opposite reward scales — a
structural first-mover edge would read as permanent credit for one agent.
A per-agent baseline tracks each agent's own expected reward instead, so
credit measures improvement over that agent's usual result. The instance is
per-env, so baselines are keyed per (env, agent) — the paper's per
(game, role). A single-agent env degrades to REINFORCE with an EMA baseline.
Each trace is scored against the baseline *before* its reward updates it
(the reference implementation's unbiased order). Baselines start at 0 and
live in orchestrator memory: a restart re-warms them over ~1/(1 − decay)
traces per agent."""
def __init__(self, config: RAEAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
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
+17 -5
View File
@@ -1,4 +1,5 @@
"""Checkpoint manager for ``Progress``. Layout:
"""Checkpoint manager for the orchestrator state (``Progress`` counters +
``TrainSource`` data position). Layout:
``<output_dir>/checkpoints/step_N/orchestrator/progress.pt``."""
from __future__ import annotations
@@ -13,6 +14,7 @@ from pathlib import Path
import torch
from prime_rl.configs.orchestrator import CheckpointConfig
from prime_rl.orchestrator.train_source import TrainSource
from prime_rl.orchestrator.types import Progress
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_ckpt_dir, get_step_path
@@ -26,7 +28,7 @@ class CheckpointManager:
def get_ckpt_path(self, step: int) -> Path:
return get_step_path(self.ckpt_dir, step) / "orchestrator"
def save(self, progress: Progress, step: int) -> None:
def save(self, progress: Progress, train_source: TrainSource, step: int) -> None:
ckpt_path = self.get_ckpt_path(step)
ckpt_path.mkdir(parents=True, exist_ok=True)
start = time.perf_counter()
@@ -35,7 +37,7 @@ class CheckpointManager:
fd, tmp_name = tempfile.mkstemp(dir=ckpt_path, prefix="progress.pt.", suffix=".tmp")
try:
with os.fdopen(fd, "wb") as f:
torch.save({"progress": progress}, f)
torch.save({"progress": progress, "train_source": train_source.state_dict()}, f)
os.replace(tmp_name, ckpt_path / "progress.pt")
except BaseException:
with contextlib.suppress(OSError):
@@ -45,7 +47,7 @@ class CheckpointManager:
f"Orchestrator checkpoint saved to {ckpt_path} in {format_time(time.perf_counter() - start)}"
)
def load(self, progress: Progress, step: int) -> None:
def load(self, progress: Progress, train_source: TrainSource, step: int) -> None:
ckpt_path = self.get_ckpt_path(step)
state_file = ckpt_path / "progress.pt"
if not state_file.exists():
@@ -53,7 +55,7 @@ class CheckpointManager:
get_logger().debug(f"Loading checkpoint from {state_file}")
start = time.perf_counter()
if self.config.skip_progress:
get_logger().info("Skipping progress loading from checkpoint")
get_logger().info("Skipping progress and data position loading from checkpoint")
else:
with open(state_file, "rb") as f:
state = torch.load(f, weights_only=False)
@@ -61,6 +63,16 @@ class CheckpointManager:
for key, value in asdict(saved).items():
if hasattr(progress, key):
setattr(progress, key, value)
train_source.load_state_dict(state["train_source"])
for name, position in state["train_source"]["envs"].items():
if name not in train_source.base_rows:
continue
rows = train_source.base_rows[name]
num_tasks = len(rows) if rows is not None else "infinite"
get_logger().info(
f"Resumed data position for env {name} - epoch={position['epoch']}, "
f"cursor={position['cursor']}/{num_tasks}"
)
get_logger().debug(f"Orchestrator checkpoint loaded in {format_time(time.perf_counter() - start)}")
+19 -12
View File
@@ -1,12 +1,14 @@
"""RolloutDispatcher: schedules rollouts under a shared permit counter.
- Capacity (``max_inflight_rollouts``) is shared across train + eval.
A group-scoring task that runs N rollouts in one call reserves N permits.
- Capacity (``max_inflight_episodes``) is shared across train + eval. One permit is
one episode: for a v1 env one ``run`` request, and a group-scoring task that runs
N rollouts in one call reserves N permits (each bridged v0 rollout is its own
single-agent episode).
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
- Emit-everything invariant: every dispatched env-rollout eventually reaches
``out_q`` exactly once, as one episode (a ``list[Rollout]``). Failures
- 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.error`` set; sinks decide drop / partial-train policy.
``trace.last_error`` set; 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 rollouts of the opposite kind drain
@@ -129,7 +131,7 @@ class RolloutDispatcher:
eval_source: EvalSource | None,
policy_pool: InferencePool,
policy: Policy,
max_inflight_rollouts: int,
max_inflight_episodes: int,
tasks_per_minute: float | None,
max_off_policy_steps: int,
) -> None:
@@ -143,7 +145,7 @@ class RolloutDispatcher:
self.eval_source = eval_source
self.max_off_policy_steps = max_off_policy_steps
self.max_inflight = max_inflight_rollouts
self.max_inflight = max_inflight_episodes
self.inflight_permits = 0
self.rate_limiter: AsyncLimiter | None = (
AsyncLimiter(tasks_per_minute, time_period=60) if tasks_per_minute else None
@@ -493,7 +495,7 @@ class RolloutDispatcher:
self.inflight_permits -= n
async def handle_completed_rollout(self, task: asyncio.Task) -> None:
"""Emit every dispatched env-rollout exactly once to ``out_q``: a ``run``
"""Emit every dispatched episode exactly once to ``out_q``: a ``run``
result as one episode, a legacy ``run_group`` result as ``rollout_count``
single-trace episodes. Task exceptions synthesize ``rollout_count``
error-marker episodes so the sink's count-to-``group_size`` finalization
@@ -519,11 +521,14 @@ class RolloutDispatcher:
get_logger().warning(f"Rollout task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
task_idx = group.task_idx if group is not None else -1
rollouts = [
Rollout(task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)))
Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
agent=vf.AgentInfo(config=vf.AgentConfig()),
)
for _ in range(meta.rollout_count)
]
for r in rollouts:
r.capture_error(exc)
r.record_error(exc)
is_synth_exception = True
for r in rollouts:
@@ -535,9 +540,9 @@ class RolloutDispatcher:
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
if r.has_error:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if not is_synth_exception and r.error is not None:
if not is_synth_exception and r.last_error is not None:
get_logger().warning(
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — {r.error.type}: {r.error.message}"
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — {r.last_error.type}: {r.last_error.message}"
)
if meta.rollout_count == 1:
# A ``run`` task: the whole result is one episode.
@@ -599,6 +604,7 @@ class RolloutDispatcher:
for _ in range(meta.rollout_count):
trace = Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
agent=vf.AgentInfo(config=vf.AgentConfig()),
ok=False,
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
stop_condition="error",
@@ -626,6 +632,7 @@ class RolloutDispatcher:
for _ in range(unscheduled_cancelled):
trace = Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
agent=vf.AgentInfo(config=vf.AgentConfig()),
ok=False,
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
stop_condition="error",
+50 -153
View File
@@ -1,10 +1,12 @@
"""Env wrappers over a v1 env server.
Each ``Env`` owns a v1 ``EnvServer`` (spawned as a child process, or an
external one given by ``config.address``) and an ``EnvClient`` to drive it. The
Each ``Env`` is an ``EnvClient`` onto its source's env server. Each server's address
is derived from the source's position in the config
(``OrchestratorConfig.env_addresses``); the launcher runs the servers at
exactly those addresses, and the orchestrator connects. The
orchestrator never *runs* an environment — the agents and their runtimes live only
in the server — but it does own the *taskset*: a v1 env's tasks are loaded here,
once, and each dispatched env-rollout ships its task's data on the request
once, and each dispatched episode ships its task's data on the request
(``task_data``); the server pydantic-validates it into the taskset's declared
``TaskData`` type and runs it. That keeps the server (and every worker in its
pool) stateless about data — no per-worker dataset loads, no idx-addressed task
@@ -12,7 +14,7 @@ cache — and gives the orchestrator real tasks to cycle, shuffle, and filter. O
the legacy (v0) bridge, whose dataset genuinely lives server-side, is still driven
by ``task_idx`` (its count comes from ``info``).
The server answers one ``Episode`` per env-rollout, whose traces we validate into
The server answers one ``Episode`` per run request, whose traces we validate into
``Trace[WireTaskData]`` — real ``vf.Trace``\\ s (never loose dicts) whose task
keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
"""
@@ -20,21 +22,14 @@ keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
from __future__ import annotations
import asyncio
import atexit
import multiprocessing as mp
import os
import queue
import sys
from collections.abc import Iterator, Sequence
from itertools import islice
from multiprocessing.process import BaseProcess
from pathlib import Path
from typing import Generic, TypeVar
import verifiers.v1 as vf
from verifiers.v1.serve import EnvClient, env_config_data
from verifiers.v1.serve import EnvClient
from prime_rl.configs.orchestrator import EnvConfig, EvalEnvConfig, TrainEnvConfig
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
@@ -45,48 +40,19 @@ from prime_rl.utils.logger import get_logger
# task.idx + task.model_dump).
ROLLOUT_TYPE = Rollout[vf.WireTaskData]
# Max wait for a spawned env server to bind and report its address. A legacy
# child loads its dataset before reporting, so this is generous.
ENV_SERVER_SPAWN_TIMEOUT = 600.0
def _run_env_server(
*,
log_file: str,
log_level: str,
json_logging: bool,
legacy: bool = False,
**kwargs,
) -> None:
"""Spawned-process entry point: redirect this process's output to ``log_file`` (the
server's logging + any subprocess-runtime output), then serve via ``serve_env``. The
worker-pool sizing arrives in ``kwargs`` (``max_workers`` / ``multiplex`` / ``elastic``
from the env's ``pool``). ``serve_env`` applies ``log_setup`` here and in every spawned
worker; a worker inherits this process's redirected stdout/stderr, so its per-rollout
logs reach ``log_file`` too. Top-level so it stays picklable for the ``spawn`` start
method. ``legacy`` picks the v0 bridge."""
from functools import partial
from verifiers.v1.serve import serve_env
from prime_rl.orchestrator.utils import setup_env_server_logging
fh = open(log_file, "w", buffering=1)
os.dup2(fh.fileno(), sys.stdout.fileno())
os.dup2(fh.fileno(), sys.stderr.fileno())
serve_env(
legacy=legacy,
log_setup=partial(setup_env_server_logging, log_level, json_logging),
**kwargs,
)
# Max wait for the env server to answer health. Generous because the launcher spawns
# servers concurrently with the orchestrator, and a legacy server loads its dataset
# before serving.
ENV_SERVER_STARTUP_TIMEOUT = 600.0
class Env:
"""Wraps a v1 env server + client. The orchestrator owns the taskset (loaded once,
"""Client onto a v1 env server. The orchestrator owns the taskset (loaded once,
client-side); the server owns agent/harness execution."""
def __init__(self, config: EnvConfig):
def __init__(self, config: EnvConfig, address: str):
self.config = config
self.address = address
self.sampling_args: dict = {}
self.num_tasks: int | None = 0
"""Task count; ``None`` means the taskset is infinite."""
@@ -97,7 +63,6 @@ class Env:
count) and iterated from there; an infinite one streams off its generator.
Consumed once — by ``TrainSource`` (train) or ``EvalEnv.start`` (eval)."""
self._env_client: EnvClient | None = None
self._env_server_process: BaseProcess | None = None
@property
def name(self) -> str:
@@ -109,17 +74,14 @@ class Env:
raise RuntimeError(f"Env {self.name} not started — call start() first.")
return self._env_client
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
"""Spawn the env server (if needed), connect, and load the taskset client-side
(legacy instead asks the server for ``info`` — its dataset is server-side)."""
external = self.config.address is not None
address = self.config.address or await self._spawn(log_dir, log_level or "INFO", json_logging)
get_logger().debug(f"Connecting {self.name} to env server {address}")
self._env_client = EnvClient(address=address)
# A spawned server already reported its address *after* binding, so it's up. An
# external server has no such handshake, so poll until it answers.
if external:
await self.env_client.wait_for_server_startup()
async def start(self) -> None:
"""Connect to the env server and load the taskset client-side (legacy instead
asks the server for ``info`` — its dataset is server-side)."""
get_logger().debug(f"Connecting {self.name} to env server {self.address}")
self._env_client = EnvClient(address=self.address)
# The server may still be coming up (the launcher spawns it concurrently with
# the orchestrator), so poll until it answers.
await self.env_client.wait_for_server_startup(timeout=ENV_SERVER_STARTUP_TIMEOUT)
if self.config.is_legacy:
info = await self.env_client.info()
self.num_tasks = info.num_tasks
@@ -137,53 +99,6 @@ class Env:
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks} group_scoring={self.requires_group_scoring}")
async def _spawn(self, log_dir: Path, log_level: str, json_logging: bool) -> str:
"""Spawn a v1 EnvServer child process (it runs the agents; the tasks come from
us). The server binds an OS-assigned port (``:0``) and reports the concrete
address back over a queue — no free-port guess, no TOCTOU race. Its output
goes to ``<log_dir>/<name>.log`` (``log_dir`` is already the train/eval-split
``.../logs/envs/{train,eval}`` the orchestrator passes in)."""
ctx = mp.get_context("spawn")
address_queue: mp.Queue = ctx.Queue()
log_file = log_dir / f"{self.name}.log"
log_file.parent.mkdir(parents=True, exist_ok=True)
get_logger().debug(f"Spawning env server {self.name} (id={self.config.env_id}, log={log_file})")
server_kwargs = (
dict(
legacy=True,
env_id=self.config.env_id,
env_args=self.config.args,
extra_env_kwargs=self.config.extra_env_kwargs,
)
if self.config.is_legacy
# Picklable dict — the narrowed config class doesn't survive the spawn.
else dict(legacy=False, config_data=env_config_data(self.config.env))
)
process = ctx.Process(
target=_run_env_server,
kwargs=dict(
log_file=str(log_file),
log_level=log_level,
json_logging=json_logging,
**vf.pool_serve_kwargs(self.config.pool),
address="tcp://127.0.0.1:0",
address_queue=address_queue,
**server_kwargs,
),
daemon=False,
)
process.start()
self._env_server_process = process
try:
address = await asyncio.to_thread(address_queue.get, timeout=ENV_SERVER_SPAWN_TIMEOUT)
except queue.Empty:
raise RuntimeError(f"Env server {self.name} did not report its address within {ENV_SERVER_SPAWN_TIMEOUT}s")
finally:
address_queue.close()
address_queue.join_thread()
get_logger().debug(f"Env server {self.name} bound at {address}")
return address
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
sampling = {**self.sampling_args}
if cache_salt is not None:
@@ -211,14 +126,14 @@ class Env:
sampling=self._sampling(cache_salt),
)
if not episode.traces:
error = episode.error
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"env-rollout failed before any trace was minted — {detail}")
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:
error = episode.error or vf.Error(
error = episode.last_error or vf.Error(
type="EpisodeFailed", message="A sibling trace in this episode failed"
)
rollout.errors = [*rollout.errors, error]
@@ -238,33 +153,27 @@ class Env:
)
return [ROLLOUT_TYPE.model_construct(**dict(wire)) for wire in wires]
def shutdown(self) -> None:
if self._env_server_process is None:
return
self._env_server_process.terminate()
self._env_server_process = None
class TrainEnv(Env):
config: TrainEnvConfig
config: TrainSourceConfig
def __init__(self, config: TrainEnvConfig, sampler: Sampler, algorithm: Algorithm):
super().__init__(config)
def __init__(self, config: TrainSourceConfig, address: str, sampler: Sampler, algorithm: Algorithm):
super().__init__(config, address)
self.sampler = sampler
self.algorithm = algorithm
self.sampling_args = sampler.sampling_args(config.sampling.to_sampling_args())
class EvalEnv(Env):
config: EvalEnvConfig
config: EvalSourceConfig
def __init__(self, config: EvalEnvConfig):
super().__init__(config)
def __init__(self, config: EvalSourceConfig, address: str):
super().__init__(config, address)
self.sampling_args = config.sampling.to_sampling_args()
self.examples: list[dict] = []
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
await super().start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
async def start(self) -> None:
await super().start()
n = self.config.num_examples
if self.tasks is None: # legacy: the dataset lives on the server — address it by row
count = self.num_tasks if n < 0 else min(n, self.num_tasks)
@@ -302,30 +211,10 @@ class Envs(Generic[EnvT]):
def __len__(self) -> int:
return len(self._envs)
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
"""Spawn env servers (where needed) and connect, one at a time. Each server
binds an OS-assigned port and reports it back, so there's no port race."""
for env in self:
await env.start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
atexit.register(self.shutdown)
def shutdown(self) -> None:
"""Terminate all spawned env server processes."""
processes = [env._env_server_process for env in self if env._env_server_process is not None]
if not processes:
return
logger = get_logger()
logger.debug(f"Shutting down {len(processes)} env server(s)")
for p in processes:
p.terminate()
for p in processes:
p.join(timeout=25)
if p.is_alive():
logger.warning(f"Env server {p.pid} did not exit after 25s, force killing")
p.kill()
p.join(timeout=5)
for env in self:
env._env_server_process = None
async def start(self) -> None:
"""Connect to all env servers in parallel — every address is known up front,
so there's nothing to serialize on."""
await asyncio.gather(*(env.start() for env in self))
class TrainEnvs(Envs[TrainEnv]):
@@ -333,12 +222,20 @@ class TrainEnvs(Envs[TrainEnv]):
:class:`Sampler` and runtime :class:`Algorithm`, built from the env's
resolved algorithm config."""
def __init__(self, configs: Sequence[TrainEnvConfig], *, policy_pool, renderer_config=None):
def __init__(
self,
configs: Sequence[TrainSourceConfig],
addresses: dict[tuple[str, str], str],
*,
policy_pool,
renderer_config=None,
):
self._envs: dict[str, TrainEnv] = {}
for config in configs:
assert config.algo is not None, "TrainEnvConfig.algo must be resolved before env construction"
assert config.algo is not None, "TrainSourceConfig.algo must be resolved before env construction"
env = TrainEnv(
config,
addresses[("train", config.resolved_name)],
Sampler(config.algo.sampling, policy_pool, renderer_config),
build_algorithm(config.algo, policy_pool),
)
@@ -348,8 +245,8 @@ class TrainEnvs(Envs[TrainEnv]):
class EvalEnvs(Envs[EvalEnv]):
"""Collection of evaluation environments."""
def __init__(self, configs: Sequence[EvalEnvConfig]):
def __init__(self, configs: Sequence[EvalSourceConfig], addresses: dict[tuple[str, str], str]):
self._envs: dict[str, EvalEnv] = {}
for config in configs:
env = EvalEnv(config)
env = EvalEnv(config, addresses[("eval", config.resolved_name)])
self._envs[env.name] = env
+184 -123
View File
@@ -6,13 +6,22 @@ A rollout container (``TrainRollouts`` / ``EvalRollouts``) owns the rollout list
``rollouts.metrics.num_input_tokens.mean()`` works — and assembles the full
``{prefix}/{subset}/<metric>/<stat>`` wandb dict via ``.to_wandb(...)``.
No I/O, no pandas — plain Python over the ``vf.Trace`` properties each rollout exposes. Aggregation
is flat over the rollout list except the solve rates, which group by ``group_id``.
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.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Iterator, Literal
from typing import TYPE_CHECKING, Any, Callable, Iterator, Literal
from prime_rl.orchestrator.utils import compute_pass_metrics
@@ -90,26 +99,26 @@ 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", "generation", "finalize", "scoring")
PHASES = ("setup", "agent", "finalize", "scoring")
@property
def setup(self) -> Stat:
return Stat([r.timing.setup.duration for r in self.rollouts])
@property
def generation(self) -> Stat:
return Stat([r.timing.generation.duration for r in self.rollouts])
def agent(self) -> Stat:
return Stat([r.timing.agent.duration for r in self.rollouts])
@property
def generation_model(self) -> Stat:
"""The share of the generation phase spent inside model calls (inference)."""
return Stat([r.timing.generation.model.duration for r in self.rollouts])
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])
@property
def generation_harness(self) -> Stat:
"""The share of the generation phase spent outside model calls (harness, tools,
def agent_harness(self) -> Stat:
"""The share of the agent phase spent outside model calls (harness, tools,
user simulation)."""
return Stat([r.timing.generation.harness.duration for r in self.rollouts])
return Stat([r.timing.agent.harness.duration for r in self.rollouts])
@property
def finalize(self) -> Stat:
@@ -126,56 +135,52 @@ class TimingMetrics(StatGroup):
def stats(self) -> dict[str, Stat]:
return {
**{phase: getattr(self, phase) for phase in self.PHASES},
"generation/model": self.generation_model,
"generation/harness": self.generation_harness,
"agent/model": self.agent_model,
"agent/harness": self.agent_harness,
"total": self.total,
}
class CustomMetrics(StatGroup):
"""Per-key ``Stat``s over a dynamic per-rollout dict attribute (env ``@metric``s or reward
components), each averaged over the rollouts that report the key."""
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) -> None:
def __init__(self, rollouts: list[Rollout], attr: str, value: Callable[[Any], float] = float) -> None:
super().__init__(rollouts)
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)})
return {
name: Stat([getattr(r, self.attr)[name] for r in self.rollouts if name in getattr(r, self.attr)])
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 name in names
}
class RolloutMetrics:
"""Metrics shared by train and eval over a rollout list. Distributional metrics are ``Stat``s
(mean/max/min); boolean metrics are ``Stat``s of 0/1 (use ``.mean()`` for the rate). ``to_wandb``
assembles the full ``{prefix}/{subset}/...`` dict; ``TrainMetrics`` / ``EvalMetrics`` extend it."""
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."""
def __init__(self, rollouts: list[Rollout]) -> None:
self.rollouts = rollouts
DISTRIBUTIONS = ("reward", "num_total_tokens", "num_input_tokens", "num_output_tokens", "num_turns", "num_branches")
RATES = ("is_truncated", "is_completed")
# Distributional metrics
@property
def num_total_tokens(self) -> Stat:
return Stat([float(r.num_total_tokens) for r in self.rollouts])
@property
def num_input_tokens(self) -> Stat:
return Stat([float(r.num_input_tokens) for r in self.rollouts])
@property
def num_output_tokens(self) -> Stat:
return Stat([float(r.num_output_tokens) for r in self.rollouts])
@property
def num_turns(self) -> Stat:
return Stat([float(r.num_turns) for r in self.rollouts])
@property
def num_branches(self) -> Stat:
return Stat([float(r.num_branches) for r in self.rollouts])
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)
}
@property
def timing(self) -> TimingMetrics:
@@ -183,30 +188,22 @@ class RolloutMetrics:
@property
def metrics(self) -> CustomMetrics:
"""Env custom ``@metric`` outputs, keyed by name (``metrics.metrics["acc"].mean()``)."""
"""Env custom ``@metric`` outputs, keyed by name."""
return CustomMetrics(self.rollouts, "metrics")
@property
def rewards(self) -> CustomMetrics:
"""Per-component reward breakdown, keyed by name (summed into the scalar ``reward``)."""
return CustomMetrics(self.rollouts, "rewards")
# Boolean rate metrics (0/1 distributions — ``.mean()`` is the rate)
@property
def is_truncated(self) -> Stat:
return Stat([float(r.is_truncated) for r in self.rollouts])
@property
def is_completed(self) -> Stat:
return Stat([float(r.is_completed) for r in self.rollouts])
"""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)
@property
def has_error(self) -> Stat:
return Stat([float(r.has_error) for r in self.rollouts])
def stop_conditions(self) -> dict[str, float]:
"""``generation_truncated`` over all rollouts, then each recorded ``stop_condition``'s rate
over the rollouts that recorded one."""
"""``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"
@@ -219,15 +216,16 @@ class RolloutMetrics:
return out
def error_types(self) -> dict[str, int]:
"""Count of errored rollouts by error type (the rollout's last error — e.g. ``Cancelled``,
"""Count of errored traces by error type (the trace's last error — e.g. ``Cancelled``,
``ProviderError``)."""
types = [r.error.type for r in self.rollouts if r.has_error]
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))}
def solve_rates(self) -> dict[str, float]:
"""Per-group solve rates, assuming binary 0/1 rewards (unspecified for other reward ranges):
``solved_none`` (the group earned no reward), ``solved_all`` (every rollout scored 1.0), and
``solved_some`` (the mixed remainder — the GRPO-signal groups)."""
"""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)
@@ -240,6 +238,84 @@ class RolloutMetrics:
"solved_some": 1 - (solved_none + solved_all) / n_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:
out |= stats[name].to_dict(f"{prefix}/{name}")
for name in self.RATES:
out[f"{prefix}/{name}/mean"] = stats[name].mean()
out |= self.timing.to_dict(f"{prefix}/timing")
out |= self.metrics.to_dict(f"{prefix}/metrics")
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()}
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`` (legacy envs, 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 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())}
# 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()])
@property
def num_input_tokens(self) -> Stat:
return Stat([float(sum(r.num_input_tokens for r in episode)) for episode in self.episodes()])
@property
def num_output_tokens(self) -> Stat:
return Stat([float(sum(r.num_output_tokens for r in episode)) for episode in self.episodes()])
@property
def num_turns(self) -> Stat:
return Stat([float(sum(r.num_turns for r in episode)) for episode in self.episodes()])
@property
def num_branches(self) -> Stat:
return Stat([float(sum(r.num_branches for r in episode)) for episode in self.episodes()])
# 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])
@property
def has_error(self) -> Stat:
return Stat([float(r.has_error) for r in self.rollouts])
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:
@@ -251,59 +327,55 @@ class RolloutMetrics:
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")
out |= self.timing.to_dict(f"{p}/timing")
out |= self.metrics.to_dict(f"{p}/metrics")
out |= self.rewards.to_dict(f"{p}/rewards")
out[f"{p}/is_truncated/mean"] = self.is_truncated.mean()
out[f"{p}/is_completed/mean"] = self.is_completed.mean()
# errors live only on the `all` subset (effective drops them), so emit the rate + the
# per-type counts there only
if subset == "all":
out[f"{p}/has_error/mean"] = self.has_error.mean()
out |= {f"{p}/error/{t}": float(count) for t, count in self.error_types().items()}
out |= {f"{p}/stop_condition/{k}": v for k, v in self.stop_conditions().items()}
out |= {f"{p}/{k}": v for k, v in self.solve_rates().items()}
for agent, agent_metrics in self.by_agent().items():
out |= agent_metrics.to_dict(f"{p}/{agent}", subset=subset)
return out
class TrainMetrics(RolloutMetrics):
"""Common metrics plus the reward distribution and filter-pipeline rates."""
class TrainMetrics(EpisodeMetrics):
"""Common metrics plus the per-agent filter-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])
@property
def is_trainable(self) -> Stat:
return Stat([float(r.is_trainable) for r in self.rollouts])
@property
def is_filtered(self) -> Stat:
return Stat([float(r.is_filtered) for r in self.rollouts])
def filter_rates(self) -> dict[str, float]:
"""Per-filter detection rate over all rollouts."""
names = sorted({name for r in self.rollouts for name in r.filter_results})
return {
name: sum(1 for r in self.rollouts if r.filter_results.get(name)) / len(self.rollouts) for name in names
}
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
out = super().to_wandb(prefix=prefix, subset=subset)
if not self.rollouts:
return out
p = f"{prefix}/{subset}"
out |= self.reward.to_dict(f"{p}/reward")
out[f"{p}/is_trainable/mean"] = self.is_trainable.mean()
out[f"{p}/is_filtered/mean"] = self.is_filtered.mean()
out |= {f"{p}/filters/{k}/mean": v for k, v in self.filter_rates().items()}
# The pipeline verdicts are per-trace (an untrainable seat is 0.0 throughout, and filters
# only ever run on trainable survivors), 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_filtered/mean"] = sum(float(r.is_filtered) for r in rollouts) / len(rollouts)
names = sorted({name for r in rollouts for name in r.filter_results})
out |= {
f"{p}/filters/{name}/mean": sum(1 for r in rollouts if r.filter_results.get(name)) / len(rollouts)
for name in names
}
return out
class EvalMetrics(RolloutMetrics):
"""Common metrics plus the ``avg@<group_size>`` score and (on the effective subset, for
binary-reward tasks) pass@k / pass^k. ``group_size`` (the ``avg@k`` k) is supplied by the
container so the ``all`` and ``effective`` subsets share one stable key."""
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]
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}
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)
@@ -313,26 +385,13 @@ class EvalMetrics(RolloutMetrics):
def reward(self) -> Stat:
return Stat([float(r.reward) for r in self.rollouts])
def pass_at_k(self) -> dict[str, float]:
"""pass@k / pass^k averaged over examples; ``{}`` for non-binary rewards."""
rewards = [r.reward for r in self.rollouts]
if not set(rewards).issubset({0.0, 1.0}):
return {}
by_example: dict = {}
for r in self.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}
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
out = super().to_wandb(prefix=prefix, subset=subset)
if not self.rollouts:
return out
p = f"{prefix}/{subset}"
out[f"{p}/avg@{self.group_size}"] = self.reward.mean()
if subset == "effective":
out |= {f"{p}/{k}": v for k, v in self.pass_at_k().items()}
for agent, traces in self.by_agent().items():
p = f"{prefix}/{subset}/{agent}"
out[f"{p}/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()}
return out
@@ -355,7 +414,7 @@ class TrainRollouts:
@property
def effective(self) -> TrainRollouts:
return TrainRollouts([r for r in self.rollouts if not r.has_error and not r.is_filtered and r.trainable])
return TrainRollouts([r for r in self.rollouts if not r.has_error and not r.is_filtered and r.agent.trainable])
def by_env(self) -> dict[str, TrainRollouts]:
grouped: dict[str, list[Rollout]] = {}
@@ -394,13 +453,15 @@ class EvalRollouts:
return self._group_size
counts: dict = {}
for r in self.rollouts:
if r.trainable:
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.trainable], group_size=self.group_size)
return EvalRollouts(
[r for r in self.rollouts if not r.has_error and r.agent.trainable], group_size=self.group_size
)
@property
def metrics(self) -> EvalMetrics:
+45 -42
View File
@@ -24,6 +24,7 @@ from __future__ import annotations
import asyncio
import os
import time
import uuid
from typing import TYPE_CHECKING
import tomli_w
@@ -80,7 +81,7 @@ from prime_rl.utils.config import to_toml_dict
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.monitor import setup_monitor
from prime_rl.utils.pathing import get_log_dir, get_trace_path
from prime_rl.utils.pathing import get_trace_path
from prime_rl.utils.usage_reporter import UsageReporter
from prime_rl.utils.utils import (
clean_exit,
@@ -156,7 +157,7 @@ class Orchestrator:
# Route the in-process v1 library logging through our handler. The
# env server runs in a child process, so its logging is separate.
intercept_vf_logging(logger="verifiers.v1", level="WARN")
algorithms = sorted({env.algo.type for env in config.train.env if env.algo is not None})
algorithms = sorted({env.algo.type for env in config.train.source if env.algo is not None})
get_logger().info(f"Starting orchestrator (algorithm: {', '.join(algorithms)})")
if config.bench:
@@ -238,9 +239,12 @@ class Orchestrator:
tokenizer=self.tokenizer,
run_config=config,
keep_full_history=config.bench,
train_env_names=[env.resolved_name for env in config.train.env],
eval_env_names=[env.resolved_name for env in config.eval.env] if config.eval is not None else [],
train_env_names=[env.resolved_name for env in config.train.source],
eval_env_names=[source.resolved_name for source in config.eval.source] if config.eval is not None else [],
)
# ``RunInfo.id`` is required on the trace: fall back to a run-local uuid
# when no external monitor identity (W&B) exists.
self.run_id = self.monitor.run_id or uuid.uuid4().hex
if config.heartbeat is not None:
self.heart = Heartbeat(config.heartbeat.url)
@@ -256,27 +260,22 @@ class Orchestrator:
get_logger().info("Loading training environments")
self.train_envs = TrainEnvs(
config.train.env, policy_pool=self.policy_inference, renderer_config=config.renderer
config.train.source,
config.env_addresses,
policy_pool=self.policy_inference,
renderer_config=config.renderer,
)
get_logger().debug(
f"Loaded {len(self.train_envs)} training environment(s) ({', '.join(self.train_envs.names)})"
)
await self.train_envs.start(
log_dir=get_log_dir(config.output_dir.parent) / "envs" / "train",
log_level=config.log.vf_level,
json_logging=config.log.json_logging,
)
await self.train_envs.start()
get_logger().success("Train environment(s) ready")
if config.eval is not None:
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.eval.env)
self.eval_envs = EvalEnvs(config.eval.source, config.env_addresses)
get_logger().debug(f"Loaded {len(self.eval_envs)} eval environment(s) ({', '.join(self.eval_envs.names)})")
await self.eval_envs.start(
log_dir=get_log_dir(config.output_dir.parent) / "envs" / "eval",
log_level=config.log.vf_level,
json_logging=config.log.json_logging,
)
await self.eval_envs.start()
get_logger().success("Eval environment(s) ready")
if config.ckpt is not None and config.ckpt.resume_step is not None and self.ckpt_manager is not None:
@@ -339,8 +338,10 @@ class Orchestrator:
self.lora_name = config.model.lora.name if config.model.lora else None
self.train_source = TrainSource(self.train_envs)
if self.resume_step is not None and self.ckpt_manager is not None:
self.ckpt_manager.load(self.progress, step=self.resume_step)
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step)
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
@@ -380,7 +381,6 @@ class Orchestrator:
self.policy.model_name = self.lora_name
self.policy.version = sync_version
self.train_source = TrainSource(self.train_envs, seed=42)
self.eval_source: EvalSource | None = (
EvalSource(
self.eval_envs,
@@ -391,7 +391,7 @@ class Orchestrator:
else None
)
assert config.max_inflight_rollouts is not None, "max_inflight_rollouts must be resolved before dispatcher init"
assert config.max_inflight_episodes is not None, "max_inflight_episodes must be resolved before dispatcher init"
log_interval = config.log.interval
wandb_enabled = config.wandb is not None
self.dispatcher = RolloutDispatcher(
@@ -401,7 +401,7 @@ class Orchestrator:
eval_source=self.eval_source,
policy_pool=self.policy_inference,
policy=self.policy,
max_inflight_rollouts=config.max_inflight_rollouts,
max_inflight_episodes=config.max_inflight_episodes,
tasks_per_minute=config.tasks_per_minute,
max_off_policy_steps=config.max_off_policy_steps,
)
@@ -470,7 +470,11 @@ class Orchestrator:
]
# Base-model eval (policy v0) — fires before any train rollouts, logged at the first
# step, unless ``eval.skip_first_step=True`` (or this is a resume)
# step, unless ``eval.skip_first_step=True``. On resume, defaults to assuming a clean
# exit (evals already completed); set ``eval.retrigger_on_resume=True`` to also re-fire
# interval-aligned evals at the checkpoint step (e.g. after a crash).
if config.eval is not None and config.eval.retrigger_on_resume and self.resume_step is not None:
self.maybe_trigger_eval(self.resume_step)
self.maybe_trigger_eval(self.progress.step)
# Anchor step-time clock so the first step measures startup → first batch
@@ -496,7 +500,7 @@ class Orchestrator:
if self.ckpt_manager is not None and self.progress.step > 1:
self.progress.step -= 1
get_logger().info("Writing final checkpoint")
self.ckpt_manager.save(self.progress, step=self.progress.step)
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
await self.stop()
if clean_exit:
get_logger().success("Orchestrator finished.")
@@ -527,12 +531,12 @@ class Orchestrator:
step = episode[0].eval_step if kind == "eval" else self.progress.step
assert step is not None
run: vf.RunInfo = (
vf.EvalRunInfo(id=self.monitor.run_id, step=step)
vf.EvalRunInfo(id=self.run_id, step=step)
if kind == "eval"
else vf.TrainRunInfo(id=self.monitor.run_id, step=step)
else vf.TrainRunInfo(id=self.run_id, step=step)
)
for rollout in episode:
rollout.stamp(
rollout.record_run(
run,
env_name=rollout.env_name,
group_id=str(rollout.group_id),
@@ -597,11 +601,12 @@ class Orchestrator:
)
return
self.consecutive_empty_batches = 0
n_trainable = sum(1 for r in batch.rollouts if r.is_trainable)
if n_trainable / len(batch.rollouts) <= 0.1:
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:
get_logger().warning(
f"Only {n_trainable}/{len(batch.rollouts)} generated rollouts are trainable "
f"({n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
f"Only {n_trainable}/{len(effective)} effective rollouts are trainable "
f"({n_trainable / len(effective):.1%}) — consider reviewing task difficulty / filter config"
)
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
@@ -637,7 +642,6 @@ class Orchestrator:
# at ship time; the full arrival window already streamed into ``all`` on arrival.
# to_record drops the per-node training tensors — they're for training, not the rollout
# record, and can't round-trip json (raw numpy bytes).
effective = batch.rollouts.effective
records = [r.to_record() for r in effective]
await asyncio.to_thread(save_rollouts, records, get_trace_path(config.output_dir, step, "train", "effective"))
@@ -805,19 +809,19 @@ 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; ``Trainable`` is
relative to all generated rollouts."""
the quality metrics are over the effective (clean, trained-on) subset, as is ``Trainable``."""
rollouts = batch.rollouts
effective = rollouts.effective
eff = effective.metrics
n_generated = len(rollouts)
n_trainable = sum(1 for r in rollouts if r.is_trainable)
trainable_rate = (n_trainable / n_generated) if n_generated else 0.0
n_effective = len(effective)
n_trainable = sum(1 for r in effective if r.is_trainable)
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)
head = (
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
f"Trainable {n_trainable}/{n_generated} ({trainable_rate:.1%}) | "
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%}"
@@ -875,15 +879,15 @@ class Orchestrator:
metrics["step"] = float(batch.step)
self.monitor.log(metrics, step=batch.step)
# Success line — reward / turns / truncation over the effective set, error rate + branches
# over the full returned cohort. ``Stat.mean()`` is 0.0 for an empty set.
# 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
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"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {full.num_branches.mean():.1f} | "
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%}"
)
@@ -900,7 +904,9 @@ class Orchestrator:
return 0.0
get_logger().info(f"Saving checkpoint at step {step}")
t = time.perf_counter()
await asyncio.to_thread(self.ckpt_manager.save, self.progress, step)
# Synchronous on purpose: the payload is tiny, and snapshotting on the
# event loop keeps the dispatcher from mutating TrainSource mid-save
self.ckpt_manager.save(self.progress, self.train_source, step)
return time.perf_counter() - t
def update_dispatch_gate(self) -> None:
@@ -977,9 +983,6 @@ class Orchestrator:
for env in self.train_envs:
for pool in (*env.sampler.connected_pools, *env.algorithm.connected_pools):
await pool.stop()
self.train_envs.shutdown()
if self.eval_envs is not None:
self.eval_envs.shutdown()
if self.usage_reporter is not None:
self.usage_reporter.close()
+2 -2
View File
@@ -155,7 +155,7 @@ class TrainSink:
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.trainable:
if rollout.has_error or not rollout.agent.trainable:
return
samples = await asyncio.to_thread(
trace_to_samples,
@@ -198,7 +198,7 @@ class TrainSink:
)
return
# Untrainable traces carry no samples and must not skew the group baseline.
survivors = [r for r in survivors if r.trainable]
survivors = [r for r in survivors if r.agent.trainable]
if not survivors:
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
+74 -17
View File
@@ -2,10 +2,11 @@
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
per env). A v1 env serves the tasks the orchestrator loaded client-side: a
finite one as a shuffled table (reshuffled on cursor exhaustion), an
infinite one (``num_tasks is None``) straight off its generator — every
pull is a fresh task and there are no epochs to shuffle. A legacy env's
dataset lives on its server, so it serves shuffled task *indices*."""
finite one as a shuffled table (reshuffled with ``seed=epoch`` on cursor
exhaustion), an infinite one (``num_tasks is None``) straight off its
generator — every pull is a fresh task and there are no epochs to shuffle.
A legacy env's dataset lives on its server, so it serves shuffled task
*indices*."""
from __future__ import annotations
@@ -22,51 +23,107 @@ class TrainSource:
returns its next example (or ``None`` when the env's per-call permit
cost doesn't fit — the dispatch loop retries when permits free up).
Returned dicts carry ``env_name`` + ``task_idx`` (+ ``task`` for v1 envs,
whose data is shipped to the env server at dispatch)."""
whose data is shipped to the env server at dispatch).
def __init__(self, train_envs: TrainEnvs, *, seed: int | None) -> None:
self.rng = random.Random(seed)
The data position round-trips through a checkpoint via ``state_dict()``
/ ``load_state_dict()``: per-env ``{epoch, cursor}`` plus the env-choice
RNG state, making the dispatch sequence reproducible across resumes. For
a finite env, epochs are 1-indexed and seed that epoch's shuffle; for an
infinite env the epoch stays 1 and the cursor counts generator pulls,
replayed on restore by fast-forwarding the generator (exact iff it's
deterministic). Cursors advance at dispatch time (ahead of shipped
batches), so a resume skips the tasks that were in flight at checkpoint
time."""
def __init__(self, train_envs: TrainEnvs) -> None:
self.rng = random.Random(42)
# The drawn-but-undispatched env. A draw whose permit cost doesn't fit
# is held here (head-of-line) rather than redrawn, so the choice stream
# advances exactly once per dispatched example and stays reproducible.
self.pending_env: str | None = None
self.envs = list(train_envs)
if not self.envs:
raise ValueError("TrainSource needs at least one train env")
# A finite env's shuffled example table; ``None`` for an infinite env,
# whose generator (``self.iters``) is pulled per example.
# A finite env's example table in canonical order (each epoch's shuffle
# starts from this); ``None`` for an infinite env, whose generator
# (``self.iters``) is pulled per example.
self.base_rows: dict[str, list[dict] | None] = {}
self.examples: dict[str, list[dict] | None] = {}
self.iters: dict[str, Iterator[vf.Task]] = {}
self.epochs: dict[str, int] = {}
self.cursors: dict[str, int] = {}
# Group-scoring envs reserve ``group_size`` permits up front;
# per-rollout envs need 1
self.env_costs: dict[str, int] = {}
for env in self.envs:
if env.tasks is None: # legacy: sample over the index range from info()
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
self.rng.shuffle(rows)
self.examples[env.name] = rows
rows: list[dict] | None = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
elif env.num_tasks is None: # infinite: pull the generator per example
self.examples[env.name] = None
rows = None
self.iters[env.name] = env.tasks
else:
rows = [{"task_idx": task.data.idx, "task": task, "env_name": env.name} for task in env.tasks]
self.rng.shuffle(rows)
self.examples[env.name] = rows
self.base_rows[env.name] = rows
self.epochs[env.name] = 1
self.cursors[env.name] = 0
self.examples[env.name] = self._shuffle(env.name)
self.env_costs[env.name] = env.config.group_size if env.requires_group_scoring else 1
self.env_names = [e.name for e in self.envs]
self.weights: list[float] = [float(e.config.ratio) for e in self.envs]
def _shuffle(self, env_name: str) -> list[dict] | None:
"""The env's example table shuffled for its current epoch — a pure
function of (canonical order, epoch), so a restored position replays
the exact epoch permutation."""
rows = self.base_rows[env_name]
if rows is None:
return None
rows = rows.copy()
random.Random(self.epochs[env_name]).shuffle(rows)
return rows
def state_dict(self) -> dict:
"""Env-choice RNG state + pending draw + per-env ``{epoch, cursor}``."""
return {
"rng": self.rng.getstate(),
"pending_env": self.pending_env,
"envs": {name: {"epoch": self.epochs[name], "cursor": self.cursors[name]} for name in self.epochs},
}
def load_state_dict(self, state_dict: dict) -> None:
self.rng.setstate(state_dict["rng"])
pending = state_dict["pending_env"]
self.pending_env = pending if pending in self.env_costs else None
for name, position in state_dict["envs"].items():
if name not in self.base_rows:
continue
self.epochs[name] = position["epoch"]
self.cursors[name] = position["cursor"]
if self.base_rows[name] is None:
for _ in range(position["cursor"]):
next(self.iters[name])
else:
self.examples[name] = self._shuffle(name)
def next_example(self, available_permits: int) -> dict | None:
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
if self.pending_env is None:
self.pending_env = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
env_name = self.pending_env
if self.env_costs[env_name] > available_permits:
return None
self.pending_env = None
rows = self.examples[env_name]
cursor = self.cursors[env_name]
if rows is None: # infinite env: pull the next generated task
task = next(self.iters[env_name])
self.cursors[env_name] = cursor + 1
return {"task_idx": task.data.idx, "task": task, "env_name": env_name}
if cursor >= len(rows):
self.rng.shuffle(rows)
self.epochs[env_name] += 1
rows = self._shuffle(env_name)
self.examples[env_name] = rows
cursor = 0
example = rows[cursor]
self.cursors[env_name] = cursor + 1
+2 -2
View File
@@ -77,7 +77,7 @@ class Rollout(vf.Trace[DataT], Generic[DataT]):
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.stamp`` (``kind`` as
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.
@@ -146,7 +146,7 @@ class TrainBatch:
finalized in that span (errored + filtered included; rollouts of still-incomplete groups wait
for a later window). Its ``.effective`` / ``.metrics`` views drive logging. ``samples`` is the
trainer-bound payload (the shipped cohort's post-filter survivors) — an empty list means nothing
ships, which would stall the trainer. Trainable counts derive from ``rollouts``
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."""
rollouts: TrainRollouts
-1
View File
@@ -45,7 +45,6 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
train_client_type="renderer",
eval_client_type="openai_chat_completions",
renderer_config=config.renderer,
pool_size=config.pool_size,
)
return renderer, inference_pool
+34 -18
View File
@@ -1,21 +1,23 @@
{# Shared router launch helper, included once per template and called by the
replica-head rank. The router backend (vllm-router vs llm-d EPP+Envoy) is
chosen here via router.type, so the call sites stay router-agnostic.
node_base/node_count locate this replica's nodes in HOSTNAMES for llm-d
endpoint discovery (disagg uses NUM_PREFILL_NODES/NUM_DECODE_NODES). #}
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log> <replica_idx> <node_base> [node_count]
{# Shared launch helper for the single global router, included once per template
and called by inference node 0. The router backend (vllm-router vs llm-d
EPP+Envoy) is chosen here via router.type, so the call sites stay
router-agnostic. llm-d endpoint discovery enumerates every inference node:
all nodes for regular mode; for disaggregated mode all prefill nodes across
replicas, then all decode nodes (matching the logical node order in
endpoints.yaml). #}
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log>
launch_router() {
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-0}" node_base="${7:-0}" node_count="${8:-0}"
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5"
{%- if router.type == "llm-d" %}
echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port for replica $replica" | tee "$log"
echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port" | tee "$log"
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
local LLMD_DIR="$OUTPUT_DIR/logs/inference/llmd_${replica}"
local LLMD_DIR="$OUTPUT_DIR/logs/inference/llmd"
mkdir -p "$LLMD_DIR"
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
{%- if is_disaggregated %}
{%- set ep_disaggregated = true %}
{%- set ep_num_prefill = num_prefill_nodes %}
{%- set ep_num_decode = num_decode_nodes %}
{%- set ep_num_prefill = num_prefill_nodes * (num_infer_replicas | default(1)) %}
{%- set ep_num_decode = num_decode_nodes * (num_infer_replicas | default(1)) %}
{%- set ep_dp = dp_per_node %}
{%- set ep_prefill_port = prefill_port %}
{%- set ep_sidecar_port = router.decode_sidecar_port %}
@@ -25,12 +27,22 @@ LLMD_EOF
cat > "$LLMD_DIR/endpoints.yaml" <<LLMD_EOF
{% include 'llmd/endpoints.yaml.j2' %}
LLMD_EOF
local node=0 ip
for ((p=0; p<NUM_PREFILL_NODES; p++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + p))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
for ((d=0; d<NUM_DECODE_NODES; d++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + NUM_PREFILL_NODES + d))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
local node=0 ip reps=${NUM_INFER_REPLICAS:-1} span=${NODES_PER_INFER_REPLICA:-$((NUM_PREFILL_NODES + NUM_DECODE_NODES))}
for ((rr=0; rr<reps; rr++)); do
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
ip=$(getent hosts "${HOSTNAMES[$((rr * span + p))]}" | awk "{print \$1}")
sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1))
done
done
for ((rr=0; rr<reps; rr++)); do
for ((d=0; d<NUM_DECODE_NODES; d++)); do
ip=$(getent hosts "${HOSTNAMES[$((rr * span + NUM_PREFILL_NODES + d))]}" | awk "{print \$1}")
sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1))
done
done
{%- else %}
{%- set ep_disaggregated = false %}
{%- set ep_num_nodes = infer_nodes_per_replica %}
{%- set ep_num_nodes = num_infer_nodes | default(num_nodes) %}
{%- set ep_dp = dp_per_node %}
{%- set ep_backend_port = backend_port %}
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
@@ -40,13 +52,16 @@ LLMD_EOF
{% include 'llmd/endpoints.yaml.j2' %}
LLMD_EOF
local ip
for ((n=0; n<node_count; n++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + n))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${n}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; done
for ((n=0; n<{{ ep_num_nodes }}; n++)); do
ip=$(getent hosts "${HOSTNAMES[$n]}" | awk "{print \$1}")
sed -i "s|__LLMD_ADDR_${n}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"
done
{%- endif %}
cat > "$LLMD_DIR/envoy.yaml" <<LLMD_EOF
{% include 'llmd/envoy.yaml.j2' %}
LLMD_EOF
# grpc-health-port avoids 9003: mooncake_master runs its metrics server on 9003 and
# shares the replica-head node with the EPP, so 9003 would fail to bind and kill the EPP.
# shares node 0 with the EPP, so 9003 would fail to bind and kill the EPP.
epp --pool-name prime-rl --pool-namespace slurm \
--config-file "$LLMD_DIR/epp.yaml" \
--grpc-port 9002 --grpc-health-port 9013 --metrics-port 9090 \
@@ -55,9 +70,10 @@ LLMD_EOF
envoy -c "$LLMD_DIR/envoy.yaml" >> "$log" 2>&1 &
{%- else %}
local tag="vllm-router"; [ "$mode" = pd ] && tag="vllm-router (PD)"
echo "Starting $tag on $LOCAL_IP:$port${replica:+ for replica $replica}" | tee "$log"
echo "Starting $tag on $LOCAL_IP:$port" | tee "$log"
local -a cmd=(vllm-router --policy "$policy" --host 0.0.0.0 --port "$port"
--request-id-headers x-session-id
--prometheus-port "$((port + 21000))"
--worker-startup-timeout-secs 4200 --log-level debug)
if [ "$mode" = pd ]; then
cmd+=(--vllm-pd-disaggregation $worker_args)
+26 -31
View File
@@ -38,13 +38,13 @@ export NODES_PER_PREFILL_REPLICA={{ prefill_nodes_per_replica }}
export NODES_PER_DECODE_REPLICA={{ decode_nodes_per_replica }}
export PREFILL_PORT={{ prefill_port }}
export DECODE_PORT={{ decode_port }}
export ROUTER_PORT={{ router.port }}
export ROUTER_PORT={{ router_port }}
export RPC_PORT={{ data_parallel_rpc_port }}
{%- if router.type == "llm-d" %}
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
{%- endif %}
{%- elif num_nodes > 1 %}
export ROUTER_PORT={{ router.port }}
export ROUTER_PORT={{ router_port }}
export BACKEND_PORT={{ backend_port }}
export RPC_PORT={{ data_parallel_rpc_port }}
{%- endif %}
@@ -77,32 +77,24 @@ uv sync --all-extras --all-packages
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
export HOSTNAMES_STR="${HOSTNAMES[*]}"
{% if is_disaggregated -%}
# Build per-replica router URLs
INFER_URLS=""
ALL_ROUTER_ARGS=""
for ((r=0; r<NUM_NODES/NODES_PER_REPLICA; r++)); do
replica_base=$((r * NODES_PER_REPLICA))
router_host="${HOSTNAMES[$replica_base]}"
INFER_URLS="${INFER_URLS:+$INFER_URLS,}http://${router_host}:${ROUTER_PORT}/v1"
REPLICA_ROUTER_ARGS=""
# External-LB: one --prefill/--decode endpoint per DP rank (PORT + k) on each node.
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
host="${HOSTNAMES[$((replica_base + p))]}"
for ((k=0; k<{{ dp_per_node }}; k++)); do
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
done
# Single global router on node 0 fronts every per-rank endpoint.
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
ROUTER_ARGS=""
# External-LB: one --prefill/--decode endpoint per DP rank (PORT + k) on each node.
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
host="${HOSTNAMES[$p]}"
for ((k=0; k<{{ dp_per_node }}; k++)); do
ROUTER_ARGS="$ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
done
for ((d=0; d<NUM_DECODE_NODES; d++)); do
host="${HOSTNAMES[$((replica_base + NUM_PREFILL_NODES + d))]}"
for ((k=0; k<{{ dp_per_node }}; k++)); do
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
done
done
for ((d=0; d<NUM_DECODE_NODES; d++)); do
host="${HOSTNAMES[$((NUM_PREFILL_NODES + d))]}"
for ((k=0; k<{{ dp_per_node }}; k++)); do
ROUTER_ARGS="$ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
done
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
done
export INFER_URLS
export ALL_ROUTER_ARGS
export ROUTER_ARGS
{%- elif num_nodes > 1 %}
# External LB: one router on node 0; one endpoint per DP rank (BACKEND_PORT + dp_local) on every node.
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
@@ -273,10 +265,9 @@ srun --kill-on-bad-exit=1 bash -c '
echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT LOCAL_IP=$LOCAL_IP" \
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
# Start the router on the first prefill node of each replica (external LB across per-rank endpoints)
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
# Start the single global router on node 0 (external LB across all per-rank endpoints)
if [ "$INFER_NODE_RANK" -eq 0 ]; then
launch_router pd "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
fi
{%- if router.type == "llm-d" %}
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
@@ -318,9 +309,9 @@ srun --kill-on-bad-exit=1 bash -c '
TP=$((GPUS_PER_NODE / DP_PER_NODE))
EP={{ "1" if enable_expert_parallel else "0" }}
# Start the router on node 0 (balances across per-rank endpoints — no intra-node DP header)
# Start the single global router on node 0 (balances across per-rank endpoints — no intra-node DP header)
if [ "$INFER_NODE_RANK" -eq 0 ]; then
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log" 0 0 "$NUM_NODES"
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
fi
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
@@ -329,10 +320,14 @@ srun --kill-on-bad-exit=1 bash -c '
for ((d=0; d<DP_PER_NODE; d++)); do
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
if [ "$EP" -eq 1 ]; then
if [ "$EP" -eq 1 ] && [ "$DP_PER_NODE" -gt 1 ]; then
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
else
# Dense or single-DP-rank EP (dp=1, e.g. EP within one tp=8 group):
# independent single-engine servers. vLLM rejects the external-LB DP
# args when data_parallel_size == 1; enable_expert_parallel in the
# inference config alone shards experts across the TP group.
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
fi
done

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